MassOutage API

A free, open-CORS JSON API for US power outages: live county status, municipalities, incidents and threshold alerts, plus a decade of history.

Recipes for sending MassOutage outage events into tools you already run. Each is code you deploy and own; MassOutage makes no ServiceNow, Slack or Teams app. Webhooks are part of the paid plans. Without one, the last recipe polls the free API and forwards the same events.

What a webhook sends

At dedicated.massoutage.com, add a webhook channel with your receiver’s URL (its whsec_ secret is shown once), then choose that channel on an alert rule. A channel gets two types of POST, told apart by type:

  • event: one outage event an alert rule matched, in { "id": "evt_<event id>", "type": "event", "created", "data" }. These recipes act on it.
  • dedicated.scope.changed: your plan’s whole live feed, each time a state it covers changes. The recipes answer it with a 2xx and drop it.

Every POST is signed: MassOutage-Signature: t=<unix seconds>,v1=<hex>, where v1 is HMAC-SHA256 of <t>.<raw body> keyed with the secret. Each recipe checks it over the raw body and refuses a timestamp more than 5 minutes off. Answer any 2xx within 10 seconds; anything else is retried after 1, 5, 15, 60, 180, 360, 720 minutes, and a 4xx other than 408 and 429 is not retried. A retry can arrive after a newer event, and an event two of your rules match is sent twice: de-duplicate on the envelope’s id and order by event.id. The full payload and headers are on alerts. Below, event is the envelope’s data, so event.data.subject is data.data.subject in the JSON. The fields the recipes use:

FieldMeaning
event.kindoutage_began, outage_grew, etr_changed, outage_improving, outage_restored, major_event, feed_stale or feed_recovered
event.scopecounty, municipality (a town), utility, or source (a data feed’s health)
event.titlee.g. “Outage began · Brielle Borough, Monmouth County NJ”; null for events stored before titles were kept
event.summarye.g. “JCP&L · 2,000 out (74.7%) · ETR 6:00 PM ET”; null as for title
event.urlthe place’s page on massoutage.com
event.area_name, event.utility_name, event.fips, event.state_fipsthe town (for a town event), the utility, the 5-digit county and 2-digit state FIPS
event.data.county_name, event.data.state_abbrthe county and state, as words
event.customers_out, event.pctcustomers out now and the percent of customers served
event.etrthe utility’s restoration estimate, ISO 8601 UTC, or null
event.ts, event.idwhen the event happened, and its id, which rises over time
event.data.subjectthe place being tracked (e.g. county:34025, or area:9726:34025:BRIELLE BOROUGH for a town), the same on every event of its outage
event.data.opened_at, event.data.peak_out, event.data.duration_minwhen the outage began, its peak customers out and, on a restore, how long it lasted

One storm, several outages. A rule on a county also matches that county’s towns and each utility in it, and each is tracked as its own outage with its own event.data.subject. So one storm in one county can send a county event, an event for every town out and one for a utility, each beginning, growing and being restored on its own. Every recipe here keeps only county events, set by SCOPES = ["county"] at its top. Add municipality for towns, utility for utilities or source for data feed health, knowing each adds its own incidents or messages. A rule that watches only towns or utilities needs their scope added, or nothing gets through.

ServiceNow: open, update and resolve incidents

A Scripted REST API resource receives the webhook, checks its signature and keeps one incident per outage of each place it tracks: with the default SCOPES, one per county. The first event opens it, later ones update it, and the restore resolves it.

  1. Add a system property massoutage.webhook_secret holding the channel’s secret, readable only by admins.
  2. Create a Scripted REST API in the global scope with a POST resource, and clear the resource’s Requires authentication: MassOutage sends no ServiceNow credentials, so the signature is the check.
  3. Paste the script below as the resource’s script.
  4. Add the resource’s URL, https://<instance>.service-now.com/api/<namespace>/<api id>/<path>, as the webhook channel.
Incident fieldFrom the event
correlation_idevent.data.subject, so later events find the open incident; correlation_display is MassOutage
short_descriptionevent.title, or event.kind when the title is null
descriptionplace (event.area_name, event.data.county_name, event.data.state_abbr), event.utility_name, event.customers_out and event.pct, event.etr, event.kind and event.ts, event.url
work_notesevent.title and event.summary, one note per event
state, close_code, close_notesResolved on outage_restored or feed_recovered, with event.data.peak_out
// A county rule also matches its towns' and utilities' events, each tracked as its own outage, so only county
// events make incidents. Add 'municipality' (towns), 'utility' (utilities) or 'source' (data feed health) for those.
var SCOPES = ['county'];

(function process(/*RESTAPIRequest*/ request, /*RESTAPIResponse*/ response) {
  var rawBody = request.body.dataString;
  var secret = gs.getProperty('massoutage.webhook_secret');
  if (!verifyMassOutage(secret, rawBody, request.getHeader('MassOutage-Signature') || '')) {
    response.setStatus(400);
    return;
  }
  var msg = JSON.parse(rawBody);
  // Acknowledge what isn't an alert-rule event in SCOPES (dedicated.scope.changed too) so it isn't retried.
  if (msg.type != 'event' || SCOPES.indexOf(msg.data.scope) == -1) {
    response.setStatus(204);
    return;
  }
  var e = msg.data;
  var d = e.data || {};
  var title = e.title || e.kind;
  var ends = e.kind == 'outage_restored' || e.kind == 'feed_recovered';

  // data.subject names the place being tracked; it has at most one open outage at a time.
  var inc = new GlideRecord('incident');
  inc.addQuery('correlation_display', 'MassOutage');
  inc.addQuery('correlation_id', d.subject);
  inc.addActiveQuery();
  inc.query();
  var exists = inc.next();
  if (!exists) {
    // Nothing to resolve; major_event only updates, since some places that send it never send a restored event.
    if (ends || e.kind == 'major_event') {
      response.setStatus(204);
      return;
    }
    inc.newRecord();
    inc.setValue('correlation_display', 'MassOutage');
    inc.setValue('correlation_id', d.subject);
  }

  inc.setValue('short_description', title);
  inc.setValue('description', [
    'Place: ' + [e.area_name, d.county_name, d.state_abbr].filter(Boolean).join(', '),
    'Utility: ' + (e.utility_name || 'n/a'),
    'Customers out: ' + (e.customers_out == null ? 'n/a' : e.customers_out) + (e.pct == null ? '' : ' (' + e.pct + '%)'),
    'Restoration estimate (UTC): ' + (e.etr || 'none given'),
    'Event: ' + e.kind + ' at ' + e.ts,
    e.url
  ].join('\n'));
  inc.work_notes = title + (e.summary ? '\n' + e.summary : '');
  if (ends) {
    inc.setValue('state', 6); // Resolved
    inc.setValue('close_code', 'Solved (Permanently)'); // a resolution code your instance offers
    inc.setValue('close_notes', title + (d.peak_out ? ', peak ' + d.peak_out + ' customers out' : ''));
  }
  if (exists) inc.update();
  else inc.insert();
  response.setStatus(204);
})(request, response);

function verifyMassOutage(secret, rawBody, header) {
  var t = (header.match(/(?:^|,)\s*t=(\d+)/) || [])[1];
  if (!t || Math.abs(new Date().getTime() / 1000 - Number(t)) > 300) return false;
  var mac = new GlideCertificateEncryption().generateMac(GlideStringUtil.base64Encode(secret), 'HmacSHA256', t + '.' + rawBody);
  var expected = base64ToHex(mac);
  var given = header.match(/v1=[0-9a-f]{64}/g) || [];
  for (var i = 0; i < given.length; i++) {
    if (sameHex(given[i].substring(3), expected)) return true;
  }
  return false;
}

// Compares every character, so the time taken doesn't reveal how much of a guess matched.
function sameHex(a, b) {
  if (a.length != b.length) return false;
  var diff = 0;
  for (var i = 0; i < a.length; i++) diff |= a.charCodeAt(i) ^ b.charCodeAt(i);
  return diff == 0;
}

function base64ToHex(b64) {
  var alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
  var bits = '';
  var hex = '';
  for (var i = 0; i < b64.length && b64.charAt(i) != '='; i++) {
    bits += ('00000' + alphabet.indexOf(b64.charAt(i)).toString(2)).slice(-6);
  }
  for (var j = 0; j + 8 <= bits.length; j += 8) {
    hex += ('0' + parseInt(bits.substring(j, j + 8), 2).toString(16)).slice(-2);
  }
  return hex;
}
  • A major_event only updates an open incident: some places that send it never send a restored event, so an incident it opened would stay open.
  • Set the assignment group, category, impact and urgency your instance uses, and a close_code from its resolution codes.
  • To keep a late retry from reopening a restored outage, store the highest event.id applied to each incident and skip lower ones.
  • Test with a real delivery: titles carry non-ASCII characters such as “·”, and the signature covers the body’s UTF-8 bytes.

Slack: post events to a channel

Slack’s incoming webhooks take Slack’s message format and can’t check MassOutage’s signature, so a small relay sits between them: it verifies the POST, turns the event into a Slack message and forwards it. Shown as a Cloudflare Worker; it uses only fetch, Request/Response and Web Crypto, so it ports to Deno, Bun or Node 18+ behind their own server. It posts county events only; see scopes to add towns or utilities.

  1. In a Slack app with Incoming Webhooks turned on, add a webhook for your channel and copy its URL.
  2. Deploy the relay with two secrets, MASSOUTAGE_SECRET (the channel’s whsec_) and SLACK_WEBHOOK_URL.
  3. Add the relay’s URL as the webhook channel.
// rawBody: the request body exactly as received, before JSON parsing.
async function verifyMassOutage(secret, rawBody, header, toleranceSec = 300) {
  const parts = Object.fromEntries(header.split(",").map((p) => p.trim().split("=")));
  const t = Number(parts.t);
  if (!Number.isFinite(t) || Math.abs(Date.now() / 1000 - t) > toleranceSec) return false;
  if (!/^[0-9a-f]{64}$/.test(parts.v1 ?? "")) return false;
  const enc = new TextEncoder();
  const key = await crypto.subtle.importKey("raw", enc.encode(secret), { name: "HMAC", hash: "SHA-256" }, false, ["verify"]);
  const signature = Uint8Array.from(parts.v1.match(/../g), (h) => parseInt(h, 16));
  return crypto.subtle.verify("HMAC", key, signature, enc.encode(t + "." + rawBody));
}

// A county rule also matches its towns' and utilities' events, each tracked as its own outage, so only county
// events are posted. Add "municipality" (towns), "utility" (utilities) or "source" (data feed health) for those.
const SCOPES = ["county"];

// Slack mrkdwn needs &, < and > escaped.
const esc = (s) => s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");

function message(e) {
  const lines = [`*${esc(e.title ?? e.kind)}*`, e.summary && esc(e.summary), `<${e.url}|View live status>`];
  return { text: lines.filter(Boolean).join("\n"), unfurl_links: false };
}

export default {
  async fetch(request, env) {
    if (request.method !== "POST") return new Response(null, { status: 405 });
    const rawBody = await request.text();
    const header = request.headers.get("MassOutage-Signature") ?? "";
    if (!(await verifyMassOutage(env.MASSOUTAGE_SECRET, rawBody, header))) return new Response(null, { status: 400 });

    const { type, data } = JSON.parse(rawBody);
    // Only alert-rule events in SCOPES become messages; acknowledge the rest (dedicated.scope.changed too) so they aren't retried.
    if (type !== "event" || !SCOPES.includes(data.scope)) return new Response(null, { status: 204 });

    const res = await fetch(env.SLACK_WEBHOOK_URL, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(message(data)),
    });
    // A 502 makes MassOutage retry the delivery on its schedule.
    return new Response(null, { status: res.ok ? 204 : 502 });
  },
};

Microsoft Teams: post events to a channel

The same relay, sending an Adaptive Card to a Teams workflow. In Teams, create a workflow from the template Post to a channel when a webhook request is received, pick the channel and copy the URL it gives you. Deploy the relay with MASSOUTAGE_SECRET and TEAMS_WORKFLOW_URL, and add the relay’s URL as the webhook channel. Like the Slack relay, it posts county events only unless you widen SCOPES.

// rawBody: the request body exactly as received, before JSON parsing.
async function verifyMassOutage(secret, rawBody, header, toleranceSec = 300) {
  const parts = Object.fromEntries(header.split(",").map((p) => p.trim().split("=")));
  const t = Number(parts.t);
  if (!Number.isFinite(t) || Math.abs(Date.now() / 1000 - t) > toleranceSec) return false;
  if (!/^[0-9a-f]{64}$/.test(parts.v1 ?? "")) return false;
  const enc = new TextEncoder();
  const key = await crypto.subtle.importKey("raw", enc.encode(secret), { name: "HMAC", hash: "SHA-256" }, false, ["verify"]);
  const signature = Uint8Array.from(parts.v1.match(/../g), (h) => parseInt(h, 16));
  return crypto.subtle.verify("HMAC", key, signature, enc.encode(t + "." + rawBody));
}

// A county rule also matches its towns' and utilities' events, each tracked as its own outage, so only county
// events are posted. Add "municipality" (towns), "utility" (utilities) or "source" (data feed health) for those.
const SCOPES = ["county"];

function message(e) {
  const body = [{ type: "TextBlock", text: e.title ?? e.kind, weight: "Bolder", wrap: true }];
  if (e.summary) body.push({ type: "TextBlock", text: e.summary, wrap: true });
  return {
    type: "message",
    attachments: [
      {
        contentType: "application/vnd.microsoft.card.adaptive",
        content: {
          $schema: "http://adaptivecards.io/schemas/adaptive-card.json",
          type: "AdaptiveCard",
          version: "1.4",
          body,
          actions: [{ type: "Action.OpenUrl", title: "View live status", url: e.url }],
        },
      },
    ],
  };
}

export default {
  async fetch(request, env) {
    if (request.method !== "POST") return new Response(null, { status: 405 });
    const rawBody = await request.text();
    const header = request.headers.get("MassOutage-Signature") ?? "";
    if (!(await verifyMassOutage(env.MASSOUTAGE_SECRET, rawBody, header))) return new Response(null, { status: 400 });

    const { type, data } = JSON.parse(rawBody);
    // Only alert-rule events in SCOPES become messages; acknowledge the rest (dedicated.scope.changed too) so they aren't retried.
    if (type !== "event" || !SCOPES.includes(data.scope)) return new Response(null, { status: 204 });

    const res = await fetch(env.TEAMS_WORKFLOW_URL, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(message(data)),
    });
    // A 502 makes MassOutage retry the delivery on its schedule.
    return new Response(null, { status: res.ok ? 204 : 502 });
  },
};

No plan: poll and forward

The public event stream /api/v1/events serves the events alert rules match, with the same fields as a webhook’s event, free and without a key (60 requests per minute per IP; poll every 5 minutes). Pass the last id you handled as after and you get only newer events, oldest first. This script keeps that cursor in a file and hands each new event to a forward function, where the message code from the Slack or Teams relay fits. Asking for a county’s fips returns its towns’ and utilities’ events too, so the script forwards county events only, set by SCOPES as in the relays:

// Node 18+. Run every 5 minutes (cron, a scheduled function, a CI schedule). No account or key needed.
import { readFile, writeFile } from "node:fs/promises";

const EVENTS = "https://massoutage.com/api/v1/events";
const FILTER = "fips=34025"; // also state, utility, kind; see the note on min_customers
const CURSOR_FILE = "massoutage-cursor.txt";
// A county's events come with its towns' and utilities', each tracked as its own outage, so only county events are
// forwarded. Add "municipality" (towns), "utility" (utilities) or "source" (data feed health) for those.
const SCOPES = ["county"];

async function forward(e) {
  // Post to your chat or ticketing system here; e has the same fields as a webhook's data.
  console.log(e.id, e.kind, e.title, e.url);
}

let after = (await readFile(CURSOR_FILE, "utf8").catch(() => "")).trim();
if (!after) {
  // First run: start at the newest event instead of forwarding the past.
  const { latest_id } = await (await fetch(EVENTS + "?limit=1")).json();
  after = String(latest_id ?? 0);
  await writeFile(CURSOR_FILE, after);
}
for (;;) {
  const res = await fetch(`${EVENTS}?${FILTER}&after=${after}&limit=100`);
  if (!res.ok) throw new Error(`MassOutage answered ${res.status}`);
  const page = await res.json();
  for (const e of page.data) {
    if (SCOPES.includes(e.scope)) await forward(e);
    await writeFile(CURSOR_FILE, String(e.id));
  }
  after = String(page.next_cursor);
  if (!page.has_more) break;
}
  • Filters are fips, state, utility, kind and min_customers, comma-separated. Use min_customers with care: it compares each event’s own event.customers_out, so it drops restores, which have few customers left out. To keep them, filter in forward and judge an outage_restored by event.data.peak_out.
  • For a yes-or-no threshold per county instead, poll the alerts endpoint and forward when its response’s data.county.above_threshold (or a utility’s) changes from your last poll:
curl -s "https://massoutage.com/api/v1/live/counties/34025/alerts?min_customers=1000&min_pct=5"

The JSON feed (also RSS and Atom) suits feed readers and no-code tools: it lists only outages that meet the events page’s listing line, folds repeats together and has no cursor, so remember the item ids you have forwarded.