diff --git a/pm-stack/aggregator/src/config.ts b/pm-stack/aggregator/src/config.ts index 30980f9ed7..08cab65073 100644 --- a/pm-stack/aggregator/src/config.ts +++ b/pm-stack/aggregator/src/config.ts @@ -212,6 +212,18 @@ export interface Config { ackWindowMin: number; tickMs: number; }; + /** Notify relay (#8569 Phase 2 step 1): the Cloudflare edge + * dead-man's switch the aggregator heartbeats to and mirrors + * its push subscriptions into. `url` is null until the relay is + * deployed and PM_AGG_NOTIFY_RELAY_URL is set — the client is a + * no-op while unset, so this config is safe to ship ahead of + * the deploy. `stateFile` persists the subscription snapshot + * seq (the edge keeps only the highest; a lost counter would + * regress loudly, and the client re-adopts from /status). */ + notifyRelay: { + url: string | null; + stateFile: string; + }; } function parseAggregatorSource(env: Record): "fixtures" | "live" { @@ -402,5 +414,12 @@ export function loadConfig(env: Record = process.env ackWindowMin: parseAggregatorCount(env.ALERT_ACK_WINDOW_MIN, "ALERT_ACK_WINDOW_MIN", "15"), tickMs: 60_000, }, + notifyRelay: { + url: env.PM_AGG_NOTIFY_RELAY_URL?.trim() ? env.PM_AGG_NOTIFY_RELAY_URL.trim().replace(/\/+$/, "") : null, + stateFile: s( + env.PM_AGG_NOTIFY_RELAY_STATE_FILE, + join(homedir(), ".local", "state", "pm-aggregator", "notify-relay.json"), + ), + }, }; } diff --git a/pm-stack/aggregator/src/notify-relay.ts b/pm-stack/aggregator/src/notify-relay.ts new file mode 100644 index 0000000000..df03abc7bb --- /dev/null +++ b/pm-stack/aggregator/src/notify-relay.ts @@ -0,0 +1,273 @@ +// Notify-relay client (#8569 Phase 2 step 1): the laptop half of +// the pm-notify dead-man's switch, per design record +// doc/2026-11-17_design_pm8569_notifications_phase2.md §1. +// +// Two flows out of the aggregator, both authenticated with the +// relay shared secret (Bitwarden by name, resolved at send time +// through the same secrets layer as the VAPID key): +// +// - Heartbeat: POST {stackEpoch, seq, at} every ~60s. The +// stackEpoch is minted per aggregator start; the edge treats +// an epoch change after silence as the recovery boundary. +// The response carries the pending-answer count (step 3's +// drain; this client only reads it, the drain itself is +// step 3). +// - Subscription mirror: on any subscription-store change (the +// server routes call requestNotifyRelaySubscriptionSync) the +// COMPLETE mirrored set is POSTed as one snapshot under a +// monotonically increasing snapshotSeq persisted in the +// relay state file. The edge keeps only the highest seq; a +// failed POST is retried with the same seq on the next beat, +// and a 409 (our counter fell behind the edge's, e.g. the +// state file was lost) re-adopts the edge's seq from /status. +// +// Everything here is fail-soft: the relay is a mirror of the +// throat, never a dependency of it. A down edge, a missing +// secret, or an unavailable alerts store must never break the +// aggregator's own sends — every public entry point swallows its +// errors after recording them on the client for /status-style +// inspection. +import { mkdir, readFile, writeFile } from "node:fs/promises"; +import { dirname } from "node:path"; +import type { AlertsStore, PushSubscriptionRow } from "./alerts.ts"; +import type { Config } from "./config.ts"; +import { resolveBwsSecret } from "./secrets.ts"; + +/** Bitwarden name of the throat<->Worker shared secret (design + * §4: by name on the laptop side; the Worker holds the same value + * as its RELAY_SHARED_SECRET). */ +export const NOTIFY_RELAY_SECRET_NAME = "pm-aggregator.notify-relay-shared-secret"; +export const NOTIFY_RELAY_HEARTBEAT_MS = 60_000; + +export interface MirroredSubscription { + endpoint: string; + p256dh: string; + auth: string; + classes: Record; + quiet: PushSubscriptionRow["quiet"]; +} + +/** The design §1 snapshot body: the complete mirrored set + * (endpoints, keys, class map, quiet hours) under one seq. Only + * delivery-relevant row fields cross — the store's bookkeeping + * (ids, user agent, gone counts) stays home. */ +export function buildSnapshotBody(rows: PushSubscriptionRow[], snapshotSeq: number) { + return { + snapshotSeq, + subscriptions: rows.map( + (row): MirroredSubscription => ({ + endpoint: row.endpoint, + p256dh: row.p256dh, + auth: row.auth, + classes: row.classes, + quiet: row.quiet, + }), + ), + }; +} + +export function buildHeartbeatBody(stackEpoch: string, seq: number, at: string) { + return { stackEpoch, seq, at }; +} + +export interface NotifyRelayDeps { + url: string; + stateFile: string; + getStore: () => Promise | null>; + resolveSecret?: (name: string) => Promise; + fetchImpl?: typeof fetch; + now?: () => number; + mintEpoch?: () => string; +} + +export class NotifyRelayClient { + readonly stackEpoch: string; + private readonly resolveSecret: (name: string) => Promise; + private readonly fetchImpl: typeof fetch; + private readonly now: () => number; + private beatSeq = 0; + /** Highest snapshot seq this process has assigned (persisted). */ + private snapshotSeq = 0; + /** The snapshot content awaiting an ack, with the seq it was + * assigned. A retry reuses both — the edge acks an equal seq + * as a duplicate. */ + private pending: { seq: number; json: string } | null = null; + /** The last snapshot content the edge acked. */ + private ackedJson: string | null = null; + private syncDirty = true; + private syncInFlight: Promise | null = null; + private timer: ReturnType | null = null; + lastError: string | null = null; + lastHeartbeatAt: string | null = null; + lastPendingAnswers: number | null = null; + + constructor(private readonly deps: NotifyRelayDeps) { + this.stackEpoch = (deps.mintEpoch ?? (() => crypto.randomUUID()))(); + this.resolveSecret = deps.resolveSecret ?? resolveBwsSecret; + this.fetchImpl = deps.fetchImpl ?? fetch; + this.now = deps.now ?? Date.now; + } + + async start(): Promise { + await this.loadSnapshotSeq(); + await this.beat(); + if (!this.timer) { + this.timer = setInterval(() => void this.beat(), NOTIFY_RELAY_HEARTBEAT_MS); + this.timer.unref?.(); + } + } + + stop(): void { + if (this.timer) clearInterval(this.timer); + this.timer = null; + } + + /** Called by the subscription routes after a store mutation: + * mark the mirror stale and kick a sync now (the beat retries + * until it lands). */ + requestSubscriptionSync(): void { + this.syncDirty = true; + void this.syncSubscriptions(); + } + + /** One contact: sync the mirror first if it owes one (so a + * recovery beat doesn't close an episode before the snapshot + * that authorizes its push has landed), then heartbeat. */ + async beat(): Promise { + try { + if (this.syncDirty || this.pending) await this.syncSubscriptions(); + await this.postHeartbeat(); + } catch (err) { + this.lastError = err instanceof Error ? err.message : String(err); + } + } + + async syncSubscriptions(): Promise { + if (this.syncInFlight) return this.syncInFlight; + const run = (async () => { + try { + await this.syncOnce(); + this.lastError = null; + } catch (err) { + this.lastError = err instanceof Error ? err.message : String(err); + } finally { + this.syncInFlight = null; + } + })(); + this.syncInFlight = run; + return run; + } + + private async syncOnce(): Promise { + const store = await this.deps.getStore(); + if (!store) return; // alerts store unavailable (fixtures): nothing to mirror yet + const rows = await store.listSubscriptions(); + const contentJson = JSON.stringify(buildSnapshotBody(rows, 0).subscriptions); + if (!this.pending && contentJson === this.ackedJson) { + this.syncDirty = false; + return; + } + if (!this.pending || this.pending.json !== contentJson) { + const seq = this.snapshotSeq + 1; + await this.saveSnapshotSeq(seq); + this.snapshotSeq = seq; + this.pending = { seq, json: contentJson }; + } + const secret = await this.resolveSecret(NOTIFY_RELAY_SECRET_NAME); + if (!secret) throw new Error(`relay shared secret unavailable (bws: ${NOTIFY_RELAY_SECRET_NAME})`); + const res = await this.fetchImpl(`${this.deps.url}/mirror/subscriptions`, { + method: "POST", + headers: { "content-type": "application/json", authorization: `Bearer ${secret}` }, + body: JSON.stringify({ snapshotSeq: this.pending.seq, subscriptions: JSON.parse(this.pending.json) }), + signal: AbortSignal.timeout(10_000), + }); + if (res.status === 409) { + // Our counter fell behind the edge's (state file lost or + // restored from backup): adopt the edge's seq from /status + // and let the next attempt re-assign above it. + await this.adoptEdgeSnapshotSeq(); + this.pending = null; + this.syncDirty = true; + return; + } + if (!res.ok) throw new Error(`relay snapshot POST failed: HTTP ${res.status}`); + this.ackedJson = this.pending.json; + this.pending = null; + this.syncDirty = false; + } + + private async adoptEdgeSnapshotSeq(): Promise { + const res = await this.fetchImpl(`${this.deps.url}/status`, { signal: AbortSignal.timeout(10_000) }); + if (!res.ok) throw new Error(`relay /status failed: HTTP ${res.status}`); + const status = (await res.json()) as { snapshotSeq?: unknown }; + if (typeof status.snapshotSeq === "number" && status.snapshotSeq > this.snapshotSeq) { + this.snapshotSeq = status.snapshotSeq; + await this.saveSnapshotSeq(status.snapshotSeq); + } + } + + private async postHeartbeat(): Promise { + const secret = await this.resolveSecret(NOTIFY_RELAY_SECRET_NAME); + if (!secret) throw new Error(`relay shared secret unavailable (bws: ${NOTIFY_RELAY_SECRET_NAME})`); + this.beatSeq += 1; + const res = await this.fetchImpl(`${this.deps.url}/heartbeat`, { + method: "POST", + headers: { "content-type": "application/json", authorization: `Bearer ${secret}` }, + body: JSON.stringify(buildHeartbeatBody(this.stackEpoch, this.beatSeq, new Date(this.now()).toISOString())), + signal: AbortSignal.timeout(10_000), + }); + if (!res.ok) throw new Error(`relay heartbeat POST failed: HTTP ${res.status}`); + const body = (await res.json().catch(() => null)) as { pendingAnswers?: unknown } | null; + this.lastHeartbeatAt = new Date(this.now()).toISOString(); + this.lastPendingAnswers = typeof body?.pendingAnswers === "number" ? body.pendingAnswers : null; + this.lastError = null; + } + + private async loadSnapshotSeq(): Promise { + try { + const parsed = JSON.parse(await readFile(this.deps.stateFile, "utf8")) as { snapshotSeq?: unknown }; + if (typeof parsed.snapshotSeq === "number" && Number.isSafeInteger(parsed.snapshotSeq) && parsed.snapshotSeq > 0) { + this.snapshotSeq = parsed.snapshotSeq; + } + } catch { + // No state file yet (first run) or unreadable: start at 0; + // a collision with the edge's stored seq surfaces as a 409 + // and re-adopts (see syncOnce). + } + } + + private async saveSnapshotSeq(seq: number): Promise { + await mkdir(dirname(this.deps.stateFile), { recursive: true }); + await writeFile(this.deps.stateFile, JSON.stringify({ snapshotSeq: seq }), "utf8"); + } +} + +// ------------------------------------------------------ singleton wiring + +let singleton: NotifyRelayClient | null = null; + +/** Start the relay client if (and only if) a relay URL is + * configured. Returns the client, or null when the relay is not + * deployed/configured yet — the aggregator runs exactly as + * before in that case. Called once from server.ts startup, + * beside startAlertEngine. */ +export function startNotifyRelay( + cfg: Config, + getStore: () => Promise | null>, +): NotifyRelayClient | null { + if (!cfg.notifyRelay.url) return null; + if (singleton) return singleton; + singleton = new NotifyRelayClient({ url: cfg.notifyRelay.url, stateFile: cfg.notifyRelay.stateFile, getStore }); + void singleton.start().catch(() => { + // start() records its own errors; the catch only keeps an + // early rejection from surfacing as an unhandled rejection. + }); + return singleton; +} + +/** The subscription routes' hook: after any successful store + * mutation, ask the relay to re-mirror. A no-op until the relay + * is configured and started. */ +export function requestNotifyRelaySubscriptionSync(): void { + singleton?.requestSubscriptionSync(); +} diff --git a/pm-stack/aggregator/src/server.ts b/pm-stack/aggregator/src/server.ts index 78101155d6..d014576e63 100644 --- a/pm-stack/aggregator/src/server.ts +++ b/pm-stack/aggregator/src/server.ts @@ -247,6 +247,7 @@ import { } from "./alerts.ts"; import { recordSwProbe, sendPush, swProbeSummary, VAPID_PUBLIC_KEY } from "./push.ts"; import { notifyPromptCompletion, promptCompletionTransition } from "./prompt-notify.ts"; +import { requestNotifyRelaySubscriptionSync, startNotifyRelay } from "./notify-relay.ts"; import { resolveBwsSecret, resolveBwsSecretLookup } from "./secrets.ts"; import { openMetadataStore, type EpicSlugMap, type IngestionItem } from "./metadata-ingestion.ts"; import { createMetadataWebhookHandler } from "./webhook-listener.ts"; @@ -4476,7 +4477,9 @@ async function handler(req: Request, remoteAddress?: string): Promise try { const parsed = validateNewSubscription(await readJsonBody(req)); if (!parsed.ok) return json({ error: parsed.error }, 400); - return json({ subscription: toPublicSubscription(await store.upsertSubscription(parsed.value)) }, 201); + const row = await store.upsertSubscription(parsed.value); + requestNotifyRelaySubscriptionSync(); + return json({ subscription: toPublicSubscription(row) }, 201); } catch (err) { return json({ error: `invalid subscription: ${err instanceof Error ? err.message : err}` }, 400); } @@ -4486,6 +4489,7 @@ async function handler(req: Request, remoteAddress?: string): Promise const body = (await readJsonBody(req)) as { endpoint?: unknown }; if (typeof body.endpoint !== "string") return json({ error: "endpoint required" }, 400); const deleted = await store.deleteSubscription(body.endpoint); + if (deleted) requestNotifyRelaySubscriptionSync(); return deleted ? json({ deleted: true }) : json({ error: "no such subscription" }, 404); } catch (err) { return json({ error: `invalid delete: ${err instanceof Error ? err.message : err}` }, 400); @@ -5748,3 +5752,11 @@ startAlertEngine(cfg, async (): Promise => { stackHealthStates, }; }); + +// The notify relay's laptop half (#8569 Phase 2 step 1): ~60s +// heartbeats to the pm-notify edge Durable Object + the +// subscription mirror that authorizes its sends. A no-op until +// PM_AGG_NOTIFY_RELAY_URL is set (the deploy is a separate leg), +// and fail-soft once running — the edge is a mirror of this +// stack, never a dependency of it. +startNotifyRelay(cfg, () => getAlertsStore()); diff --git a/pm-stack/aggregator/test/notify-relay.test.ts b/pm-stack/aggregator/test/notify-relay.test.ts new file mode 100644 index 0000000000..2ab1dfb33a --- /dev/null +++ b/pm-stack/aggregator/test/notify-relay.test.ts @@ -0,0 +1,210 @@ +// #8569 Phase 2 step 1 — oracles for the notify-relay client +// (design record doc/2026-11-17_design_pm8569_notifications_phase2.md +// §1): +// - the mirror is the COMPLETE set under a monotonic seq, and +// only delivery fields cross (store bookkeeping stays home); +// - an unchanged set is not re-posted; a changed set takes the +// next seq; a failed POST retries with the SAME seq (the edge +// acks an equal seq as a duplicate); +// - a 409 (our counter fell behind the edge's) re-adopts the +// edge's seq from /status and the next sync lands above it; +// - everything is fail-soft: no secret, no store, or a dead +// edge never throws into the aggregator. +import { afterEach, describe, expect, test } from "bun:test"; +import { mkdtemp, readFile, rm } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import type { PushSubscriptionRow } from "../src/alerts.ts"; +import { buildHeartbeatBody, buildSnapshotBody, NotifyRelayClient } from "../src/notify-relay.ts"; + +const row = (over: Partial = {}): PushSubscriptionRow => ({ + id: "sub-1", + endpoint: "https://fcm.googleapis.com/fcm/send/fixture", + p256dh: "p256dh-fixture", + auth: "auth-fixture", + classes: { incident: true, "needs-drew": true }, + quiet: { start: "23:00", end: "07:00", tz: "America/Chicago", enabled: true }, + user_agent: "fixture-agent", + created_at: "2026-11-20T00:00:00Z", + last_seen_at: "2026-11-20T00:00:00Z", + gone_count: 0, + ...over, +}); + +interface RecordedCall { + url: string; + method: string; + authorization: string | null; + body: Record | null; +} + +const clients: NotifyRelayClient[] = []; +const dirs: string[] = []; +afterEach(async () => { + for (const client of clients.splice(0)) client.stop(); + for (const dir of dirs.splice(0)) await rm(dir, { recursive: true, force: true }); +}); + +async function makeClient( + handler: (call: RecordedCall) => { status: number; body?: unknown }, + opts: { + rows?: PushSubscriptionRow[]; + storeNull?: boolean; + secret?: string | null; + } = {}, +) { + const dir = await mkdtemp(join(tmpdir(), "notify-relay-test-")); + dirs.push(dir); + const calls: RecordedCall[] = []; + const rows = opts.rows ?? [row()]; + const client = new NotifyRelayClient({ + url: "https://pm-notify.example.workers.dev", + stateFile: join(dir, "notify-relay.json"), + getStore: async () => (opts.storeNull ? null : { listSubscriptions: async () => rows }), + resolveSecret: async () => (opts.secret === undefined ? "test-secret" : opts.secret), + fetchImpl: (async (url: string, init: RequestInit) => { + const call: RecordedCall = { + url, + method: init.method ?? "GET", + authorization: new Headers(init.headers).get("authorization"), + body: typeof init.body === "string" ? JSON.parse(init.body) : null, + }; + calls.push(call); + const out = handler(call); + return { + status: out.status, + ok: out.status >= 200 && out.status < 300, + json: async () => out.body ?? {}, + } as Response; + }) as typeof fetch, + mintEpoch: () => "epoch-test", + now: () => Date.parse("2026-11-23T12:00:00Z"), + }); + clients.push(client); + return { client, calls, rows, stateFile: join(dir, "notify-relay.json") }; +} + +const okHandler = (call: RecordedCall) => + call.url.endsWith("/heartbeat") ? { status: 200, body: { ok: true, pendingAnswers: 0 } } : { status: 200, body: { ok: true } }; + +describe("snapshot + heartbeat bodies (design §1 shapes)", () => { + test("the snapshot carries only delivery fields, under the given seq", () => { + const body = buildSnapshotBody([row()], 4); + expect(body.snapshotSeq).toBe(4); + expect(body.subscriptions).toEqual([ + { + endpoint: "https://fcm.googleapis.com/fcm/send/fixture", + p256dh: "p256dh-fixture", + auth: "auth-fixture", + classes: { incident: true, "needs-drew": true }, + quiet: { start: "23:00", end: "07:00", tz: "America/Chicago", enabled: true }, + }, + ]); + }); + + test("the heartbeat body is {stackEpoch, seq, at}", () => { + expect(buildHeartbeatBody("epoch-x", 3, "2026-11-23T12:00:00Z")).toEqual({ + stackEpoch: "epoch-x", + seq: 3, + at: "2026-11-23T12:00:00Z", + }); + }); +}); + +describe("the client's contact discipline", () => { + test("first beat: snapshot seq 1 lands before the heartbeat, both Bearer-authed; the seq persists", async () => { + const { client, calls, stateFile } = await makeClient(okHandler); + await client.start(); + expect(calls.map((c) => new URL(c.url).pathname)).toEqual(["/mirror/subscriptions", "/heartbeat"]); + expect(calls[0].body?.snapshotSeq).toBe(1); + expect(calls[0].authorization).toBe("Bearer test-secret"); + expect(calls[1].body).toEqual({ stackEpoch: "epoch-test", seq: 1, at: "2026-11-23T12:00:00.000Z" }); + expect(JSON.parse(await readFile(stateFile, "utf8"))).toEqual({ snapshotSeq: 1 }); + expect(client.lastPendingAnswers).toBe(0); + }); + + test("an unchanged set is not re-posted on the next beat", async () => { + const { client, calls } = await makeClient(okHandler); + await client.start(); + await client.beat(); + const snapshots = calls.filter((c) => c.url.endsWith("/mirror/subscriptions")); + const beats = calls.filter((c) => c.url.endsWith("/heartbeat")); + expect(snapshots).toHaveLength(1); + expect(beats).toHaveLength(2); + expect(beats[1].body?.seq).toBe(2); + }); + + test("a changed set takes the next seq after requestSubscriptionSync", async () => { + const { client, calls, rows } = await makeClient(okHandler); + await client.start(); + rows.push(row({ id: "sub-2", endpoint: "https://fcm.googleapis.com/fcm/send/other" })); + client.requestSubscriptionSync(); + // The kick is async; wait for the second snapshot POST. + for (let i = 0; i < 50 && calls.filter((c) => c.url.endsWith("/mirror/subscriptions")).length < 2; i++) { + await new Promise((r) => setTimeout(r, 10)); + } + const snapshots = calls.filter((c) => c.url.endsWith("/mirror/subscriptions")); + expect(snapshots).toHaveLength(2); + expect(snapshots[1].body?.snapshotSeq).toBe(2); + expect((snapshots[1].body?.subscriptions as unknown[]).length).toBe(2); + }); + + test("a failed snapshot POST retries with the SAME seq on the next beat", async () => { + let snapshotAttempts = 0; + const { client, calls } = await makeClient((call) => { + if (call.url.endsWith("/mirror/subscriptions")) { + snapshotAttempts += 1; + return snapshotAttempts === 1 ? { status: 500 } : { status: 200, body: { ok: true } }; + } + return { status: 200, body: { ok: true, pendingAnswers: 0 } }; + }); + await client.start(); + await client.beat(); + const snapshots = calls.filter((c) => c.url.endsWith("/mirror/subscriptions")); + expect(snapshots.map((c) => c.body?.snapshotSeq)).toEqual([1, 1]); + // The heartbeat still went out on the failed beat — the mirror + // owing a retry must not mute the dead-man's switch input. + expect(calls.filter((c) => c.url.endsWith("/heartbeat"))).toHaveLength(2); + }); + + test("a 409 re-adopts the edge's seq from /status; the next sync lands above it", async () => { + let snapshotAttempts = 0; + const { client, calls, rows, stateFile } = await makeClient((call) => { + if (call.url.endsWith("/mirror/subscriptions")) { + snapshotAttempts += 1; + return snapshotAttempts === 1 ? { status: 409 } : { status: 200, body: { ok: true } }; + } + if (call.url.endsWith("/status")) return { status: 200, body: { snapshotSeq: 7 } }; + return { status: 200, body: { ok: true, pendingAnswers: 0 } }; + }); + await client.start(); + expect(JSON.parse(await readFile(stateFile, "utf8"))).toEqual({ snapshotSeq: 7 }); + rows.push(row({ id: "sub-2", endpoint: "https://fcm.googleapis.com/fcm/send/other" })); + client.requestSubscriptionSync(); + for (let i = 0; i < 50 && snapshotAttempts < 2; i++) await new Promise((r) => setTimeout(r, 10)); + const snapshots = calls.filter((c) => c.url.endsWith("/mirror/subscriptions")); + expect(snapshots.map((c) => c.body?.snapshotSeq)).toEqual([1, 8]); + }); +}); + +describe("fail-soft (the relay never breaks the throat)", () => { + test("a dead edge: beats resolve, the error is recorded, nothing throws", async () => { + const { client } = await makeClient(() => ({ status: 500 })); + await client.start(); + await client.beat(); + expect(client.lastError).toContain("500"); + }); + + test("no secret resolvable: nothing is posted, nothing throws", async () => { + const { client, calls } = await makeClient(okHandler, { secret: null }); + await client.start(); + expect(calls).toHaveLength(0); + expect(client.lastError).toContain("unavailable"); + }); + + test("no alerts store: the sync is skipped, the heartbeat still posts", async () => { + const { client, calls } = await makeClient(okHandler, { storeNull: true }); + await client.start(); + expect(calls.map((c) => c.url)).toEqual(["https://pm-notify.example.workers.dev/heartbeat"]); + }); +}); diff --git a/pm-stack/notify-relay/README.md b/pm-stack/notify-relay/README.md new file mode 100644 index 0000000000..34eaabe04c --- /dev/null +++ b/pm-stack/notify-relay/README.md @@ -0,0 +1,98 @@ +# pm-notify relay — the pm-stack dead-man's switch at the edge + +Phase 2 of the pm-stack notifications program +([#8569](https://github.com/developing-today/code/issues/8569)), +built to the design record +`doc/2026-11-17_design_pm8569_notifications_phase2.md`. +**This package is step 1 of the design's ordered split: the relay +skeleton + dead-man's switch.** Steps 2 (event mirror), 3 (edge +answer intake) and 4 (cron narrowing) are separate issues; their +routes are deliberately not routed yet. + +## What it does + +The aggregator on the laptop POSTs a heartbeat every ~60s and +mirrors its push-subscription set here. A single Durable Object +(`PmNotify`, singleton) holds that mirror and one alarm: + +- Every heartbeat re-arms the alarm at last-beat + 150s. +- An alarm fire with no intervening beat opens a **silent + episode** and sends exactly one `stack.silent` Web Push ("PM + stack is down", with the silence start) to the mirrored + subscriptions — no cron, no laptop, no Muse in the path. +- The first heartbeat after silence closes the episode and sends + exactly one **recovered** push naming the downtime. + +The edge sends only this one class (design invariant 2), riding +the `incident` preference class (default-on, breakthrough — quiet +hours never hold it). The board never moves to the edge (the +NO-GO half of the ruling); the only read surface is `GET /status`. + +## Routes (closed list) + +| Route | Auth | Lands in | +| -------------------------- | ----------------- | -------- | +| `POST /mirror/subscriptions` | shared secret | step 1 (this package) | +| `POST /heartbeat` | shared secret | step 1 (this package) | +| `GET /status` | none (minimal) | step 1 (this package) | +| `POST /mirror/event` | shared secret | step 2 | +| `GET /answer/:ledgerId`, `POST /api/needs-drew/:ledgerId/answer` | per-question token | step 3 | + +Everything else 404s. The heartbeat response carries +`pendingAnswers` — step 3's drain count, always 0 in step 1, so +the client contract is stable from the first beat. + +## Recorded deviation from the design letter + +Design §3 names an epoch change as the recovery signal, on the +stated ground that a same-epoch heartbeat after silence "cannot +occur". A suspended laptop is the counterexample: it stops +beating without dying and resumes with the same epoch. This +implementation closes the episode on the **first beat after +silence, epoch change or not** — the design's invariant (exactly +one down push, exactly one recovered push per episode) holds +under both signals, and a same-epoch resume can never strand an +episode open (which would suppress the next episode's down +push). The heartbeat state records both epochs so the two cases +stay distinguishable in the delivery record. + +## Secrets — by name only + +No secret value lives in this repo. Custody (design §4): + +| Secret | Role | Where it lives | +| ------ | ---- | -------------- | +| Relay shared secret | Authenticates the laptop → edge POSTs | Bitwarden `pm-aggregator.notify-relay-shared-secret`; set on the Worker as `RELAY_SHARED_SECRET` | +| VAPID private key | Signs the edge's Web Push sends | The existing aggregator keypair (custody moves, the keypair does not change): Bitwarden `pm-aggregator.vapid-private-key`; set on the Worker as `VAPID_PRIVATE_KEY` | +| Cloudflare API token | Deploys (wrangler) | Bitwarden, the existing day-to-day CF token; deploy-time only | + +## Deploy (the step-1 remainder, not done by the build PR) + +From this directory, with the day-to-day CF API token available +to wrangler: + +```sh +bunx wrangler deploy +bunx wrangler secret put RELAY_SHARED_SECRET # value: the Bitwarden-named secret above +bunx wrangler secret put VAPID_PRIVATE_KEY # value: the Bitwarden-named key above +``` + +Then point the aggregator at it: set `PM_AGG_NOTIFY_RELAY_URL` +to the deployed Worker URL in the aggregator's environment and +restart the aggregator. Until both halves exist, each side is +inert: the relay with no heartbeats never opens an episode (an +alarm with no beat ever seen opens nothing), and the aggregator +with no URL configured never sends. + +Acceptance after deploy (Drew's terms, #8569): stop the laptop +stack (or kill the tunnel) → the down push reaches the phone in +under 2 minutes; restart → exactly one recovered push naming +the downtime. + +## Development + +```sh +bun test # oracle tests for the state machine + push crypto +bun run typecheck +bun run dev # wrangler dev (local DO + alarm) +``` diff --git a/pm-stack/notify-relay/package.json b/pm-stack/notify-relay/package.json new file mode 100644 index 0000000000..dcfa07c0e2 --- /dev/null +++ b/pm-stack/notify-relay/package.json @@ -0,0 +1 @@ +{"description":"pm-stack notifications Phase 2 (#8569) step 1: the pm-notify edge relay — one Worker + one Durable Object holding the mirrored push subscriptions and the heartbeat dead-man's switch (stack.silent / recovered).","devDependencies":{"@cloudflare/workers-types":"^4.20251011.0","typescript":"^5.6.0","wrangler":"4.44.0"},"name":"pm-notify-relay","private":true,"scripts":{"deploy":"wrangler deploy","dev":"wrangler dev","test":"bun test","typecheck":"tsc --noEmit"},"type":"module","version":"0.1.0"} \ No newline at end of file diff --git a/pm-stack/notify-relay/src/index.ts b/pm-stack/notify-relay/src/index.ts new file mode 100644 index 0000000000..49a94d0018 --- /dev/null +++ b/pm-stack/notify-relay/src/index.ts @@ -0,0 +1,187 @@ +// pm-notify relay Worker (#8569 Phase 2 step 1): the Cloudflare +// half of the pm-stack dead-man's switch, per design record +// doc/2026-11-17_design_pm8569_notifications_phase2.md. +// +// POST /mirror/subscriptions (shared-secret auth, laptop -> edge) +// Full-snapshot replace of the mirrored push subscriptions +// under a monotonic seq (design §1). Step 1 of the split. +// POST /heartbeat (shared-secret auth, laptop -> edge) +// The aggregator's ~60s beat {stackEpoch, seq, at}. Each beat +// re-arms the Durable Object's alarm at last-beat + 150s; the +// response carries the pending-answer count (step 3's drain — +// always 0 in step 1). +// GET /status (unauthenticated, deliberately +// minimal: up/silent + since, snapshot seq, subscription +// count, last delivery — never board data, never endpoints.) +// +// Everything else 404s — the route list is closed (design §2). +// POST /mirror/event arrives with step 2 and the answer routes +// with step 3; they are not routed yet. +// +// The Durable Object (singleton, idFromName("pm-notify")) owns the +// episode state machine in src/relay.ts: an alarm fire with no +// intervening beat opens the silent episode and sends exactly one +// stack.silent push; the first beat after silence sends exactly +// one recovered push naming the downtime. The alarm is the only +// scheduler — no cron anywhere (design invariant 3). +import { sendPush } from "./push.ts"; +import { + applyAlarm, + applyHeartbeat, + applySnapshot, + buildRecoveredPayload, + buildSilentPayload, + emptyRelayState, + isAuthorized, + takesSilentClass, + validateHeartbeat, + validateSnapshot, + type DeliveryRecord, + type RelayState, +} from "./relay.ts"; + +export interface Env { + PM_NOTIFY: DurableObjectNamespace; + /** Shared secret for the laptop -> edge POSTs (wrangler secret + * put; Bitwarden name `pm-aggregator.notify-relay-shared-secret`). */ + RELAY_SHARED_SECRET?: string; + /** The aggregator VAPID keypair's private key (wrangler secret + * put; Bitwarden name `pm-aggregator.vapid-private-key`). */ + VAPID_PRIVATE_KEY?: string; +} + +const SINGLETON = "pm-notify"; +const STATE_KEY = "relay-state"; + +const json = (body: unknown, status = 200): Response => + new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } }); + +export default { + async fetch(req: Request, env: Env): Promise { + const url = new URL(req.url); + const stub = env.PM_NOTIFY.get(env.PM_NOTIFY.idFromName(SINGLETON)); + if (req.method === "POST" && (url.pathname === "/mirror/subscriptions" || url.pathname === "/heartbeat")) { + if (!isAuthorized(req.headers, env.RELAY_SHARED_SECRET)) return json({ error: "unauthorized" }, 401); + // The DO learns the Worker's public origin from the request + // itself (for the /status deep link in push payloads) — no + // configured URL to drift. + const forwarded = new Request(req); + forwarded.headers.set("X-Relay-Origin", url.origin); + return stub.fetch(forwarded); + } + if (req.method === "GET" && url.pathname === "/status") return stub.fetch(req); + return new Response("not found", { status: 404 }); + }, +}; + +export class PmNotify { + constructor( + private state: DurableObjectState, + private env: Env, + ) {} + + private async load(): Promise { + return (await this.state.storage.get(STATE_KEY)) ?? emptyRelayState(); + } + + private async save(state: RelayState): Promise { + await this.state.storage.put(STATE_KEY, state); + } + + /** Send one episode payload to every mirrored subscription that + * takes the incident class, and record the outcome on the state. + * A missing VAPID secret is recorded, never thrown — the episode + * transition has already happened and must not wedge. */ + private async deliver(state: RelayState, kind: DeliveryRecord["kind"], payload: unknown): Promise { + const targets = (state.snapshot?.subscriptions ?? []).filter(takesSilentClass); + let record: DeliveryRecord; + if (!this.env.VAPID_PRIVATE_KEY) { + record = { kind, at: new Date().toISOString(), sent: 0, gone: 0, failed: 0, error: "VAPID_PRIVATE_KEY not configured" }; + } else { + try { + const summary = await sendPush(targets, payload, { vapidPrivateKey: this.env.VAPID_PRIVATE_KEY }); + record = { kind, at: new Date().toISOString(), sent: summary.sent, gone: summary.gone, failed: summary.failed }; + } catch (err) { + record = { + kind, + at: new Date().toISOString(), + sent: 0, + gone: 0, + failed: 0, + error: err instanceof Error ? err.message : String(err), + }; + } + } + return { ...state, lastDelivery: record }; + } + + async fetch(req: Request): Promise { + const url = new URL(req.url); + let state = await this.load(); + const origin = req.headers.get("X-Relay-Origin"); + if (origin && origin !== state.origin) { + state = { ...state, origin }; + await this.save(state); + } + + if (req.method === "POST" && url.pathname === "/mirror/subscriptions") { + const parsed = validateSnapshot(await req.json().catch(() => null)); + if (!parsed.ok) return json({ error: parsed.error }, 400); + const applied = applySnapshot(state, parsed.value); + if (applied.outcome === "regression") { + return json( + { error: `snapshotSeq ${parsed.value.snapshotSeq} regresses the stored seq ${state.snapshot?.snapshotSeq}` }, + 409, + ); + } + await this.save(applied.state); + return json({ + ok: true, + outcome: applied.outcome, + snapshotSeq: parsed.value.snapshotSeq, + subscriptions: parsed.value.subscriptions.length, + }); + } + + if (req.method === "POST" && url.pathname === "/heartbeat") { + const parsed = validateHeartbeat(await req.json().catch(() => null)); + if (!parsed.ok) return json({ error: parsed.error }, 400); + const outcome = applyHeartbeat(state, parsed.value, Date.now()); + state = outcome.state; + if (outcome.recovered) { + state = await this.deliver(state, "recovered", buildRecoveredPayload(state, outcome.recovered.downtimeMs)); + } + await this.save(state); + await this.state.storage.setAlarm(outcome.alarmAt); + // pendingAnswers is step 3's drain count; the field exists + // from the first heartbeat so the client contract is stable. + return json({ ok: true, silent: state.heartbeat.silentSince !== null, pendingAnswers: 0 }); + } + + if (req.method === "GET" && url.pathname === "/status") { + const hb = state.heartbeat; + return json({ + up: hb.lastBeatAt !== null && hb.silentSince === null, + silent: hb.silentSince !== null, + silentSince: hb.silentSince ? new Date(hb.silentSince).toISOString() : null, + lastBeatAt: hb.lastBeatAt ? new Date(hb.lastBeatAt).toISOString() : null, + stackEpoch: hb.stackEpoch, + snapshotSeq: state.snapshot?.snapshotSeq ?? null, + subscriptions: state.snapshot?.subscriptions.length ?? 0, + lastDelivery: state.lastDelivery, + }); + } + + return new Response("not found", { status: 404 }); + } + + /** The dead-man's switch itself: no beat inside the window => + * open the episode and send the one stack.silent push. */ + async alarm(): Promise { + const loaded = await this.load(); + const outcome = applyAlarm(loaded, Date.now()); + if (!outcome.opened) return; + const delivered = await this.deliver(outcome.state, "silent", buildSilentPayload(outcome.state)); + await this.save(delivered); + } +} diff --git a/pm-stack/notify-relay/src/push.ts b/pm-stack/notify-relay/src/push.ts new file mode 100644 index 0000000000..294daf98ed --- /dev/null +++ b/pm-stack/notify-relay/src/push.ts @@ -0,0 +1,213 @@ +// Web Push sending for the pm-notify relay (#8569 Phase 2, design +// record doc/2026-11-17_design_pm8569_notifications_phase2.md §2/§4). +// +// Same construction as pm-stack/console/src/push.ts (RFC 8291 +// aes128gcm payload encryption + RFC 8292 VAPID signing, WebCrypto +// only — the `web-push` package the laptop uses is Node-only), with +// one custody difference the design mandates: the keypair is NOT +// generated at the edge. It is the aggregator's existing VAPID +// keypair, so subscriptions registered with the laptop keep working +// when the edge sends. The public key ships here (it is public by +// design — the same constant as pm-stack/aggregator/src/push.ts); +// the private key arrives as the Worker secret VAPID_PRIVATE_KEY, +// in the base64url raw-scalar form the laptop fetches from +// Bitwarden by name `pm-aggregator.vapid-private-key`. + +/** The aggregator's VAPID public key (uncompressed P-256 point, + * base64url). Public by design; identical to the key the laptop's + * subscriptions were registered against. */ +export const VAPID_PUBLIC_KEY = + "BNBCc8IjMrerQY8aGviwq71OoJwf6BCnVOJd0UMAnSwRuXJ8nlIkfh2TFEmAPyPGKU2OOpDEnqdhIGTcBv4Jb2E"; +export const VAPID_SUBJECT = "mailto:drewrypope@gmail.com"; + +const enc = new TextEncoder(); + +export function b64uEncode(bytes: Uint8Array | ArrayBuffer): string { + const view = bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes); + let binary = ""; + for (const byte of view) binary += String.fromCharCode(byte); + return btoa(binary).replaceAll("+", "-").replaceAll("/", "_").replace(/=+$/, ""); +} + +export function b64uDecode(text: string): Uint8Array { + const padded = text.replaceAll("-", "+").replaceAll("_", "/") + "=".repeat((4 - (text.length % 4)) % 4); + const binary = atob(padded); + const out = new Uint8Array(binary.length); + for (let i = 0; i < binary.length; i++) out[i] = binary.charCodeAt(i); + return out; +} + +const concat = (...parts: Uint8Array[]) => { + const out = new Uint8Array(parts.reduce((n, p) => n + p.length, 0)); + let at = 0; + for (const p of parts) { + out.set(p, at); + at += p.length; + } + return out; +}; + +export interface PushTarget { + endpoint: string; + p256dh: string; + auth: string; +} + +async function hkdf(salt: Uint8Array, ikm: Uint8Array, info: Uint8Array, length: number): Promise { + const key = await crypto.subtle.importKey("raw", ikm, "HKDF", false, ["deriveBits"]); + return new Uint8Array(await crypto.subtle.deriveBits({ name: "HKDF", hash: "SHA-256", salt, info }, key, length * 8)); +} + +/** Encrypt one message for one subscription (RFC 8291, aes128gcm). */ +export async function encryptPayload(target: PushTarget, plaintext: Uint8Array): Promise { + const uaPublic = b64uDecode(target.p256dh); + const authSecret = b64uDecode(target.auth); + const local = (await crypto.subtle.generateKey({ name: "ECDH", namedCurve: "P-256" }, true, [ + "deriveBits", + ])) as CryptoKeyPair; + const localPublic = new Uint8Array( + (await crypto.subtle.exportKey("raw", local.publicKey)) as ArrayBuffer, + ); + // The casts in this function are for the workers-types surface: + // its exportKey returns an ArrayBuffer|JsonWebKey union and its + // deriveBits params type predates the standard ECDH params + // shape. Every call is the standard one at runtime. + const peer = await crypto.subtle.importKey("raw", uaPublic.slice(), { name: "ECDH", namedCurve: "P-256" }, false, []); + const shared = new Uint8Array( + await crypto.subtle.deriveBits( + { name: "ECDH", public: peer } as Parameters[0], + local.privateKey, + 256, + ), + ); + const ikm = await hkdf(authSecret, shared, concat(enc.encode("WebPush: info\0"), uaPublic, localPublic), 32); + const salt = crypto.getRandomValues(new Uint8Array(16)); + const cek = await hkdf(salt, ikm, enc.encode("Content-Encoding: aes128gcm\0"), 16); + const nonce = await hkdf(salt, ikm, enc.encode("Content-Encoding: nonce\0"), 12); + const key = await crypto.subtle.importKey("raw", cek, "AES-GCM", false, ["encrypt"]); + // One record: the message, then the delimiter that marks the last record. + const sealed = new Uint8Array( + await crypto.subtle.encrypt({ name: "AES-GCM", iv: nonce }, key, concat(plaintext, new Uint8Array([2]))), + ); + const header = new Uint8Array(16 + 4 + 1 + localPublic.length); + header.set(salt, 0); + new DataView(header.buffer).setUint32(16, 4096); + header[20] = localPublic.length; + header.set(localPublic, 21); + return concat(header, sealed); +} + +/** Import the VAPID signing key from the raw private scalar (the + * Worker secret's form). The JWK's x/y come from the public point — + * the pair is only usable together: WebCrypto validates the JWK + * as a set, so a secret that does not match the public key is + * rejected at import, loudly, before any send. The public key is + * a parameter (defaulting to the production key) so tests can + * sign with a generated pair. */ +export async function importVapidSigner( + privateKeyB64u: string, + publicKeyB64u: string = VAPID_PUBLIC_KEY, +): Promise { + const point = b64uDecode(publicKeyB64u); + if (point.length !== 65 || point[0] !== 4) throw new Error("VAPID public key is not an uncompressed P-256 point"); + const jwk: JsonWebKey = { + kty: "EC", + crv: "P-256", + x: b64uEncode(point.subarray(1, 33)), + y: b64uEncode(point.subarray(33, 65)), + d: privateKeyB64u, + }; + return crypto.subtle.importKey("jwk", jwk, { name: "ECDSA", namedCurve: "P-256" }, false, ["sign"]); +} + +/** The RFC 8292 Authorization header value for one push endpoint. */ +export async function vapidAuthorization( + endpoint: string, + signer: CryptoKey, + now: number, + publicKeyB64u: string = VAPID_PUBLIC_KEY, +): Promise { + const head = b64uEncode(enc.encode(JSON.stringify({ typ: "JWT", alg: "ES256" }))); + const body = b64uEncode( + enc.encode( + JSON.stringify({ + aud: new URL(endpoint).origin, + exp: Math.floor(now / 1000) + 12 * 3600, + sub: VAPID_SUBJECT, + }), + ), + ); + const sig = await crypto.subtle.sign({ name: "ECDSA", hash: "SHA-256" }, signer, enc.encode(`${head}.${body}`)); + return `vapid t=${head}.${body}.${b64uEncode(sig)}, k=${publicKeyB64u}`; +} + +export type Poster = ( + url: string, + init: { method: string; headers: Record; body: Uint8Array; signal?: AbortSignal }, +) => Promise<{ status: number }>; + +export interface SendSummary { + sent: number; + /** Endpoints the push service reports gone (404/410). The relay's + * snapshot is a mirror — the caller records the count but never + * edits the mirror locally (design invariant 1). */ + gone: number; + failed: number; + refused: { host: string; status: number }[]; +} + +export interface SendOptions { + vapidPrivateKey: string; + /** The public half of the vapidPrivateKey pair; defaults to the + * production VAPID_PUBLIC_KEY. Tests pass a generated pair. */ + vapidPublicKey?: string; + poster?: Poster; + now?: () => number; + /** Matches the laptop's incident sends (aggregator push.ts). */ + ttlSeconds?: number; +} + +/** Send one payload to every target. Never throws: per-target + * failures are counted in the summary. */ +export async function sendPush(targets: PushTarget[], payload: unknown, opts: SendOptions): Promise { + const poster: Poster = opts.poster ?? ((url, init) => fetch(url, init as RequestInit)); + const now = opts.now ?? Date.now; + const signer = await importVapidSigner(opts.vapidPrivateKey, opts.vapidPublicKey ?? VAPID_PUBLIC_KEY); + const body = enc.encode(JSON.stringify(payload)); + const summary: SendSummary = { sent: 0, gone: 0, failed: 0, refused: [] }; + for (const target of targets) { + const host = (() => { + try { + return new URL(target.endpoint).hostname; + } catch { + return "invalid-endpoint"; + } + })(); + try { + const authorization = await vapidAuthorization(target.endpoint, signer, now(), opts.vapidPublicKey ?? VAPID_PUBLIC_KEY); + const res = await poster(target.endpoint, { + method: "POST", + headers: { + Authorization: authorization, + "Content-Encoding": "aes128gcm", + "Content-Type": "application/octet-stream", + TTL: String(opts.ttlSeconds ?? 3600), + Urgency: "high", + }, + body: await encryptPayload(target, body), + signal: AbortSignal.timeout(15_000), + }); + if (res.status === 404 || res.status === 410) summary.gone++; + else if (res.status >= 200 && res.status < 300) summary.sent++; + else { + summary.failed++; + summary.refused.push({ host, status: res.status }); + } + } catch { + summary.failed++; + summary.refused.push({ host, status: 0 }); + } + } + summary.refused = summary.refused.slice(0, 5); + return summary; +} diff --git a/pm-stack/notify-relay/src/relay.ts b/pm-stack/notify-relay/src/relay.ts new file mode 100644 index 0000000000..4b8d280b74 --- /dev/null +++ b/pm-stack/notify-relay/src/relay.ts @@ -0,0 +1,328 @@ +// The pm-notify relay's pure core (#8569 Phase 2, design record +// doc/2026-11-17_design_pm8569_notifications_phase2.md): payload +// validation, the subscription-snapshot seq rules, and the +// dead-man's-switch episode state machine. Everything here is a +// pure function of (state, input, now) so the oracle tests in +// test/relay.test.ts exercise the exact transitions the Durable +// Object performs; src/index.ts is only storage + scheduling +// around this module. + +/** A heartbeat every ~60s; the alarm sits at last-beat + 150s + * (~2 missed beats + margin, design §2). The alarm is the only + * scheduler in the design. */ +export const ALARM_AFTER_MS = 150_000; + +/** The class the edge's two sends carry, per design §3: the + * stack.silent episode rides the `incident` preference class + * (default-on, breakthrough — quiet hours never hold it). */ +export const SILENT_CLASS = "incident"; +export const SILENT_OBJECT_REF = "stack:silent"; + +/** One mirrored subscription: the DO's send authority, mirrored in + * full from the aggregator's alerts store (design §1). Mirrors + * PushSubscriptionRow's delivery-relevant fields. */ +export interface MirroredSubscription { + endpoint: string; + p256dh: string; + auth: string; + classes: Record; + quiet: { start: string; end: string; tz: string; enabled?: boolean }; +} + +export interface SubscriptionSnapshot { + snapshotSeq: number; + subscriptions: MirroredSubscription[]; +} + +export interface Heartbeat { + stackEpoch: string; + seq: number; + /** The sender's clock, informational only — the DO's own clock + * is authoritative for lastBeatAt and the alarm. */ + at?: string; +} + +export interface HeartbeatState { + stackEpoch: string | null; + lastSeq: number | null; + lastBeatAt: number | null; + /** When the current silent episode began (= the last beat before + * the silence, so downtime measures the true silent span), or + * null when no episode is open. */ + silentSince: number | null; +} + +export interface DeliveryRecord { + kind: "silent" | "recovered"; + at: string; + sent: number; + gone: number; + failed: number; + error?: string; +} + +export interface RelayState { + snapshot: SubscriptionSnapshot | null; + heartbeat: HeartbeatState; + /** The Worker origin learned from forwarded laptop requests; + * the push payloads' /status deep link. */ + origin: string | null; + lastDelivery: DeliveryRecord | null; +} + +export const emptyRelayState = (): RelayState => ({ + snapshot: null, + heartbeat: { stackEpoch: null, lastSeq: null, lastBeatAt: null, silentSince: null }, + origin: null, + lastDelivery: null, +}); + +// ---------------------------------------------------------------- auth + +/** Constant-time string compare over the encoded bytes (same shape + * as decision-events-worker's timingSafeEqual). */ +export function timingSafeEqual(a: string, b: string): boolean { + const enc = new TextEncoder(); + const ab = enc.encode(a); + const bb = enc.encode(b); + if (ab.length !== bb.length) return false; + let diff = 0; + for (let i = 0; i < ab.length; i++) diff |= ab[i] ^ bb[i]; + return diff === 0; +} + +/** Shared-secret auth for the laptop -> edge POSTs: Bearer token or + * the X-Relay-Secret header, mirroring the decision-events + * worker's isAuthorized. No secret configured => nothing is + * authorized (fail closed). */ +export function isAuthorized(headers: Headers, secret: string | undefined): boolean { + if (!secret) return false; + const auth = headers.get("Authorization"); + if (auth?.startsWith("Bearer ") && timingSafeEqual(auth.slice("Bearer ".length), secret)) return true; + const headerSecret = headers.get("X-Relay-Secret"); + if (headerSecret && timingSafeEqual(headerSecret, secret)) return true; + return false; +} + +// ---------------------------------------------------------- validation + +const MAX_SUBSCRIPTIONS = 32; +const MAX_CLASS_KEYS = 16; + +export type Validation = { ok: true; value: T } | { ok: false; error: string }; + +const isRecord = (v: unknown): v is Record => typeof v === "object" && v !== null && !Array.isArray(v); + +function isBase64UrlOfLength(text: string, bytes: number): boolean { + if (!/^[A-Za-z0-9_-]+$/.test(text)) return false; + try { + const padded = text.replaceAll("-", "+").replaceAll("_", "/") + "=".repeat((4 - (text.length % 4)) % 4); + return atob(padded).length === bytes; + } catch { + return false; + } +} + +function validateSubscription(raw: unknown, index: number): Validation { + if (!isRecord(raw)) return { ok: false, error: `subscriptions[${index}] must be an object` }; + const { endpoint, p256dh, auth, classes, quiet } = raw; + if (typeof endpoint !== "string" || endpoint.length > 1024) { + return { ok: false, error: `subscriptions[${index}].endpoint must be a string of at most 1024 chars` }; + } + let url: URL; + try { + url = new URL(endpoint); + } catch { + return { ok: false, error: `subscriptions[${index}].endpoint is not a URL` }; + } + if (url.protocol !== "https:" || url.username || url.password) { + return { ok: false, error: `subscriptions[${index}].endpoint must be an https URL without credentials` }; + } + // An uncompressed P-256 point is 65 bytes; the auth secret is 16. + if (typeof p256dh !== "string" || !isBase64UrlOfLength(p256dh, 65)) { + return { ok: false, error: `subscriptions[${index}].p256dh must be a base64url 65-byte point` }; + } + if (typeof auth !== "string" || !isBase64UrlOfLength(auth, 16)) { + return { ok: false, error: `subscriptions[${index}].auth must be a base64url 16-byte secret` }; + } + if (!isRecord(classes)) return { ok: false, error: `subscriptions[${index}].classes must be an object` }; + const classKeys = Object.keys(classes); + if (classKeys.length > MAX_CLASS_KEYS || classKeys.some((k) => typeof classes[k] !== "boolean")) { + return { ok: false, error: `subscriptions[${index}].classes must map at most ${MAX_CLASS_KEYS} keys to booleans` }; + } + if (!isRecord(quiet)) return { ok: false, error: `subscriptions[${index}].quiet must be an object` }; + const { start, end, tz, enabled } = quiet; + if (typeof start !== "string" || typeof end !== "string" || typeof tz !== "string") { + return { ok: false, error: `subscriptions[${index}].quiet needs string start/end/tz` }; + } + if (enabled !== undefined && typeof enabled !== "boolean") { + return { ok: false, error: `subscriptions[${index}].quiet.enabled must be a boolean when present` }; + } + return { + ok: true, + value: { + endpoint: url.href, + p256dh, + auth, + classes: { ...classes } as Record, + quiet: { start, end, tz, ...(enabled !== undefined ? { enabled } : {}) }, + }, + }; +} + +/** Validate a POST /mirror/subscriptions body (design §1: a + * full-snapshot replace under a monotonically increasing seq). */ +export function validateSnapshot(body: unknown): Validation { + if (!isRecord(body)) return { ok: false, error: "body must be an object" }; + const { snapshotSeq, subscriptions } = body; + if (typeof snapshotSeq !== "number" || !Number.isSafeInteger(snapshotSeq) || snapshotSeq < 1) { + return { ok: false, error: "snapshotSeq must be a positive integer" }; + } + if (!Array.isArray(subscriptions)) return { ok: false, error: "subscriptions must be an array" }; + if (subscriptions.length > MAX_SUBSCRIPTIONS) { + return { ok: false, error: `subscriptions is capped at ${MAX_SUBSCRIPTIONS} entries` }; + } + const validated: MirroredSubscription[] = []; + for (let i = 0; i < subscriptions.length; i++) { + const one = validateSubscription(subscriptions[i], i); + if (!one.ok) return one; + validated.push(one.value); + } + return { ok: true, value: { snapshotSeq, subscriptions: validated } }; +} + +/** Validate a POST /heartbeat body (design §1). */ +export function validateHeartbeat(body: unknown): Validation { + if (!isRecord(body)) return { ok: false, error: "body must be an object" }; + const { stackEpoch, seq, at } = body; + if (typeof stackEpoch !== "string" || stackEpoch.length === 0 || stackEpoch.length > 64) { + return { ok: false, error: "stackEpoch must be a non-empty string of at most 64 chars" }; + } + if (typeof seq !== "number" || !Number.isSafeInteger(seq) || seq < 0) { + return { ok: false, error: "seq must be a non-negative integer" }; + } + if (at !== undefined && typeof at !== "string") return { ok: false, error: "at must be a string when present" }; + return { ok: true, value: { stackEpoch, seq, ...(at !== undefined ? { at } : {}) } }; +} + +// -------------------------------------------------------- state machine + +export type SnapshotOutcome = "stored" | "duplicate" | "regression"; + +/** Apply a validated snapshot under the design §1 seq rules: the + * DO keeps only the highest seq; an equal seq is an idempotent + * retry of the same snapshot (ack it, change nothing); a lower + * seq is a regression, rejected loudly by the caller. */ +export function applySnapshot(state: RelayState, snapshot: SubscriptionSnapshot): { state: RelayState; outcome: SnapshotOutcome } { + const current = state.snapshot?.snapshotSeq ?? 0; + if (snapshot.snapshotSeq < current) return { state, outcome: "regression" }; + if (snapshot.snapshotSeq === current) return { state, outcome: "duplicate" }; + return { state: { ...state, snapshot }, outcome: "stored" }; +} + +export interface HeartbeatOutcome { + state: RelayState; + /** Set when this beat closes a silent episode: the caller owes + * exactly one recovered push naming this downtime. */ + recovered: { downtimeMs: number; epochChanged: boolean } | null; + /** The alarm instant the caller must set (design §2). */ + alarmAt: number; +} + +/** Apply one heartbeat. Episode close: the design names an epoch + * change as the recovery signal ("a heartbeat with the same epoch + * after a silent episode cannot occur — a live process keeps + * beating"). A suspended laptop is the real-world exception: it + * stops beating without dying and resumes with the same epoch. + * Any first beat after silence therefore closes the episode — + * the design's invariant (exactly one down push, exactly one + * recovered push per episode) holds under both signals, and a + * same-epoch resume can never strand an episode open. Recorded + * as a deliberate widening in the package README. */ +export function applyHeartbeat(state: RelayState, beat: Heartbeat, now: number): HeartbeatOutcome { + const hb = state.heartbeat; + let recovered: HeartbeatOutcome["recovered"] = null; + let silentSince = hb.silentSince; + if (silentSince !== null) { + recovered = { downtimeMs: Math.max(0, now - silentSince), epochChanged: beat.stackEpoch !== hb.stackEpoch }; + silentSince = null; + } + return { + state: { + ...state, + heartbeat: { stackEpoch: beat.stackEpoch, lastSeq: beat.seq, lastBeatAt: now, silentSince }, + }, + recovered, + alarmAt: now + ALARM_AFTER_MS, + }; +} + +export interface AlarmOutcome { + state: RelayState; + /** True when this alarm fire opens a new silent episode: the + * caller owes exactly one stack.silent push. */ + opened: boolean; +} + +/** Apply an alarm fire. Opens an episode only when beats have + * actually stopped for the full window — an alarm that races a + * fresh beat, or fires with no beat ever seen, opens nothing. */ +export function applyAlarm(state: RelayState, now: number): AlarmOutcome { + const hb = state.heartbeat; + if (hb.silentSince !== null || hb.lastBeatAt === null) return { state, opened: false }; + if (now < hb.lastBeatAt + ALARM_AFTER_MS) return { state, opened: false }; + return { + state: { ...state, heartbeat: { ...hb, silentSince: hb.lastBeatAt } }, + opened: true, + }; +} + +/** Whether a mirrored subscription takes the edge's sends: the + * incident class is enabled unless explicitly toggled off (the + * aggregator's mergeClasses default), and incident breakthrough + * means quiet hours never hold it — so quiet is not consulted. */ +export function takesSilentClass(sub: MirroredSubscription): boolean { + return sub.classes[SILENT_CLASS] !== false; +} + +// ------------------------------------------------------------ payloads + +export function formatDuration(ms: number): string { + const totalSeconds = Math.round(ms / 1000); + if (totalSeconds < 60) return `${totalSeconds}s`; + const minutes = Math.floor(totalSeconds / 60); + if (minutes < 60) return `${minutes}m`; + const hours = Math.floor(minutes / 60); + const rest = minutes % 60; + return rest > 0 ? `${hours}h ${rest}m` : `${hours}h`; +} + +const statusUrl = (origin: string | null): string => (origin ? `${origin}/status` : "/status"); + +/** The stack.silent push payload, in the aggregator's PushPayload + * shape (pm-stack/aggregator/src/alerts.ts) so the phone's service + * worker renders it exactly like a laptop-sent incident. */ +export function buildSilentPayload(state: RelayState) { + const since = state.heartbeat.silentSince; + return { + class: SILENT_CLASS, + objectRef: SILENT_OBJECT_REF, + url: statusUrl(state.origin), + title: "PM stack is down", + body: since + ? `No heartbeat since ${new Date(since).toISOString()}. The laptop stack is unreachable — the board and answers are paused until it returns.` + : "No heartbeat from the laptop stack. It is unreachable — the board and answers are paused until it returns.", + }; +} + +/** The recovered push payload: exactly one per episode, naming + * the downtime (design §3). */ +export function buildRecoveredPayload(state: RelayState, downtimeMs: number) { + return { + class: SILENT_CLASS, + objectRef: SILENT_OBJECT_REF, + url: statusUrl(state.origin), + title: "PM stack recovered", + body: `The laptop stack is back after ${formatDuration(downtimeMs)} of silence.`, + }; +} diff --git a/pm-stack/notify-relay/test/push.test.ts b/pm-stack/notify-relay/test/push.test.ts new file mode 100644 index 0000000000..0b5a6f227a --- /dev/null +++ b/pm-stack/notify-relay/test/push.test.ts @@ -0,0 +1,152 @@ +// Oracles for the relay's Web Push sender (#8569): +// - RFC 8291: only the subscribed browser can read the payload — +// proven by decrypting with the receiver's private key and auth +// secret, through the RFC's own HKDF chain. +// - RFC 8292: the VAPID JWT is signed by the keypair's private +// half, names the push service's origin as audience, and +// carries the production public key in `k=`. +// - Delivery accounting: 2xx = sent, 404/410 = gone, anything +// else (or a throw) = failed — and a failure never throws. +import { describe, expect, test } from "bun:test"; +import { b64uDecode, b64uEncode, encryptPayload, sendPush, vapidAuthorization, VAPID_PUBLIC_KEY, type PushTarget } from "../src/push.ts"; + +const enc = new TextEncoder(); +const concat = (...parts: Uint8Array[]) => { + const out = new Uint8Array(parts.reduce((n, p) => n + p.length, 0)); + let at = 0; + for (const p of parts) { + out.set(p, at); + at += p.length; + } + return out; +}; + +async function hkdf(salt: Uint8Array, ikm: Uint8Array, info: Uint8Array, length: number): Promise { + const key = await crypto.subtle.importKey("raw", ikm, "HKDF", false, ["deriveBits"]); + return new Uint8Array(await crypto.subtle.deriveBits({ name: "HKDF", hash: "SHA-256", salt, info }, key, length * 8)); +} + +/** A fresh receiver: an ECDH keypair + auth secret, as a browser + * would hand to the subscription store. */ +async function makeReceiver() { + const pair = (await crypto.subtle.generateKey({ name: "ECDH", namedCurve: "P-256" }, true, [ + "deriveBits", + ])) as CryptoKeyPair; + const publicRaw = new Uint8Array(await crypto.subtle.exportKey("raw", pair.publicKey)); + const auth = crypto.getRandomValues(new Uint8Array(16)); + const target: PushTarget = { + endpoint: "https://fcm.googleapis.com/fcm/send/fixture", + p256dh: b64uEncode(publicRaw), + auth: b64uEncode(auth), + }; + return { pair, publicRaw, auth, target }; +} + +/** Decrypt an aes128gcm body the way the browser's push service + * client would (RFC 8291 §3.3 in reverse). */ +async function decrypt(receiver: Awaited>, body: Uint8Array): Promise { + const salt = body.subarray(0, 16); + const idLen = body[20]; + const senderPublic = body.subarray(21, 21 + idLen); + const sealed = body.subarray(21 + idLen); + const senderKey = await crypto.subtle.importKey("raw", senderPublic, { name: "ECDH", namedCurve: "P-256" }, false, []); + const shared = new Uint8Array(await crypto.subtle.deriveBits({ name: "ECDH", public: senderKey }, receiver.pair.privateKey, 256)); + const ikm = await hkdf(receiver.auth, shared, concat(enc.encode("WebPush: info\0"), receiver.publicRaw, senderPublic), 32); + const cek = await hkdf(salt, ikm, enc.encode("Content-Encoding: aes128gcm\0"), 16); + const nonce = await hkdf(salt, ikm, enc.encode("Content-Encoding: nonce\0"), 12); + const key = await crypto.subtle.importKey("raw", cek, "AES-GCM", false, ["decrypt"]); + const plain = new Uint8Array(await crypto.subtle.decrypt({ name: "AES-GCM", iv: nonce }, key, sealed)); + return plain; +} + +describe("RFC 8291 payload encryption", () => { + test("only the subscribed browser can read it; the last-record delimiter rides along", async () => { + const receiver = await makeReceiver(); + const message = enc.encode(JSON.stringify({ title: "PM stack is down" })); + const body = await encryptPayload(receiver.target, message); + const plain = await decrypt(receiver, body); + expect(plain[plain.length - 1]).toBe(2); + expect(new TextDecoder().decode(plain.subarray(0, plain.length - 1))).toBe(new TextDecoder().decode(message)); + }); + + test("a different auth secret cannot read it", async () => { + const receiver = await makeReceiver(); + const body = await encryptPayload(receiver.target, enc.encode("secret")); + const impostor = { ...receiver, auth: crypto.getRandomValues(new Uint8Array(16)) }; + await expect(decrypt(impostor, body)).rejects.toThrow(); + }); +}); + +describe("RFC 8292 VAPID signing", () => { + test("the JWT verifies against the keypair and names the push origin", async () => { + const pair = (await crypto.subtle.generateKey({ name: "ECDSA", namedCurve: "P-256" }, true, [ + "sign", + "verify", + ])) as CryptoKeyPair; + const now = 1_700_000_000_000; + const header = await vapidAuthorization("https://fcm.googleapis.com/fcm/send/x", pair.privateKey, now); + expect(header.startsWith("vapid t=")).toBe(true); + expect(header.endsWith(`, k=${VAPID_PUBLIC_KEY}`)).toBe(true); + const jwt = header.slice("vapid t=".length, header.indexOf(", k=")); + const [head, bodyPart, sig] = jwt.split("."); + const claims = JSON.parse(new TextDecoder().decode(b64uDecode(bodyPart))); + expect(claims.aud).toBe("https://fcm.googleapis.com"); + expect(claims.exp).toBe(Math.floor(now / 1000) + 12 * 3600); + expect(claims.sub).toBe("mailto:drewrypope@gmail.com"); + const ok = await crypto.subtle.verify( + { name: "ECDSA", hash: "SHA-256" }, + pair.publicKey, + b64uDecode(sig), + enc.encode(`${head}.${bodyPart}`), + ); + expect(ok).toBe(true); + }); +}); + +describe("delivery accounting", () => { + /** A throwaway VAPID keypair for the sender under test (the + * production pair is a secret and never appears in tests; + * WebCrypto validates the JWK as a set, so the pair must be + * consistent — private scalar + its own public point). */ + const testKeyPair = async (): Promise<{ vapidPrivateKey: string; vapidPublicKey: string }> => { + const pair = (await crypto.subtle.generateKey({ name: "ECDSA", namedCurve: "P-256" }, true, ["sign"])) as CryptoKeyPair; + const jwk = await crypto.subtle.exportKey("jwk", pair.privateKey); + const raw = new Uint8Array(await crypto.subtle.exportKey("raw", pair.publicKey)); + return { vapidPrivateKey: jwk.d as string, vapidPublicKey: b64uEncode(raw) }; + }; + + test("2xx counts sent and the posted body is the sealed payload", async () => { + const receiver = await makeReceiver(); + let posted: { url: string; body: Uint8Array; headers: Record } | null = null; + const summary = await sendPush([receiver.target], { title: "down" }, { + ...(await testKeyPair()), + poster: async (url, init) => { + posted = { url, body: init.body, headers: init.headers }; + return { status: 201 }; + }, + }); + expect(summary).toMatchObject({ sent: 1, gone: 0, failed: 0 }); + expect(posted!.headers["Content-Encoding"]).toBe("aes128gcm"); + expect(posted!.headers.Authorization.startsWith("vapid t=")).toBe(true); + const plain = await decrypt(receiver, posted!.body); + expect(new TextDecoder().decode(plain.subarray(0, plain.length - 1))).toBe(JSON.stringify({ title: "down" })); + }); + + test("410 counts gone; a 500 and a throw count failed; sendPush never throws", async () => { + const a = (await makeReceiver()).target; + const b = (await makeReceiver()).target; + const c = (await makeReceiver()).target; + const statuses = [410, 500]; + const summary = await sendPush([a, b, c], { title: "x" }, { + ...(await testKeyPair()), + poster: async () => { + const status = statuses.shift(); + if (status === undefined) throw new Error("network down"); + return { status }; + }, + }); + expect(summary.sent).toBe(0); + expect(summary.gone).toBe(1); + expect(summary.failed).toBe(2); + }); +}); diff --git a/pm-stack/notify-relay/test/relay.test.ts b/pm-stack/notify-relay/test/relay.test.ts new file mode 100644 index 0000000000..460c0c5d6d --- /dev/null +++ b/pm-stack/notify-relay/test/relay.test.ts @@ -0,0 +1,189 @@ +// Oracles for the pm-notify relay core (#8569, design record +// doc/2026-11-17_design_pm8569_notifications_phase2.md): +// - §1 seq rules: the DO keeps only the highest snapshot seq; an +// equal seq is an idempotent retry; a lower seq is a regression. +// - §2/§3 episode mechanics: the alarm at last-beat + 150s opens +// exactly one silent episode; the first beat after silence +// closes it with exactly one recovered owed, naming the +// downtime; a fresh silence opens a fresh episode. +// - §3 payload terms: the silent push rides class `incident` +// with the since-when in the body; the recovered push names +// the downtime length. +import { describe, expect, test } from "bun:test"; +import { + ALARM_AFTER_MS, + applyAlarm, + applyHeartbeat, + applySnapshot, + buildRecoveredPayload, + buildSilentPayload, + emptyRelayState, + formatDuration, + isAuthorized, + takesSilentClass, + validateHeartbeat, + validateSnapshot, + type MirroredSubscription, + type RelayState, +} from "../src/relay.ts"; + +// A syntactically valid subscription: 65-byte point + 16-byte auth, +// base64url. Values are fixtures, not any real device's. +const point65 = Buffer.from(new Uint8Array(65).fill(7)).toString("base64url"); +const auth16 = Buffer.from(new Uint8Array(16).fill(9)).toString("base64url"); +const sub = (over: Partial = {}): MirroredSubscription => ({ + endpoint: "https://fcm.googleapis.com/fcm/send/fixture", + p256dh: point65, + auth: auth16, + classes: { incident: true }, + quiet: { start: "23:00", end: "07:00", tz: "America/Chicago", enabled: true }, + ...over, +}); + +const beat = (state: RelayState, epoch: string, seq: number, now: number) => + applyHeartbeat(state, { stackEpoch: epoch, seq }, now).state; + +describe("subscription snapshot seq rules (design §1)", () => { + test("first snapshot stores; a higher seq replaces it whole", () => { + const first = applySnapshot(emptyRelayState(), { snapshotSeq: 1, subscriptions: [sub()] }); + expect(first.outcome).toBe("stored"); + const second = applySnapshot(first.state, { snapshotSeq: 2, subscriptions: [] }); + expect(second.outcome).toBe("stored"); + expect(second.state.snapshot?.subscriptions).toEqual([]); + }); + + test("an equal seq is a duplicate: acked, state untouched", () => { + const stored = applySnapshot(emptyRelayState(), { snapshotSeq: 5, subscriptions: [sub()] }).state; + const dup = applySnapshot(stored, { snapshotSeq: 5, subscriptions: [] }); + expect(dup.outcome).toBe("duplicate"); + expect(dup.state.snapshot?.subscriptions).toHaveLength(1); + }); + + test("a lower seq is a regression: state untouched", () => { + const stored = applySnapshot(emptyRelayState(), { snapshotSeq: 5, subscriptions: [sub()] }).state; + const reg = applySnapshot(stored, { snapshotSeq: 4, subscriptions: [] }); + expect(reg.outcome).toBe("regression"); + expect(reg.state.snapshot?.snapshotSeq).toBe(5); + }); +}); + +describe("the dead-man's switch (design §2/§3)", () => { + const t0 = 1_700_000_000_000; + + test("a heartbeat records the beat and re-arms the alarm at +150s", () => { + const out = applyHeartbeat(emptyRelayState(), { stackEpoch: "epoch-a", seq: 1 }, t0); + expect(out.state.heartbeat.lastBeatAt).toBe(t0); + expect(out.state.heartbeat.stackEpoch).toBe("epoch-a"); + expect(out.alarmAt).toBe(t0 + ALARM_AFTER_MS); + expect(out.recovered).toBeNull(); + }); + + test("an alarm inside the window opens nothing; at the window it opens the episode, once", () => { + const state = beat(emptyRelayState(), "epoch-a", 1, t0); + expect(applyAlarm(state, t0 + ALARM_AFTER_MS - 1).opened).toBe(false); + const opened = applyAlarm(state, t0 + ALARM_AFTER_MS); + expect(opened.opened).toBe(true); + // Silence is measured from the last beat, not the alarm fire. + expect(opened.state.heartbeat.silentSince).toBe(t0); + // A second fire while the episode is open opens nothing new. + expect(applyAlarm(opened.state, t0 + ALARM_AFTER_MS + 60_000).opened).toBe(false); + }); + + test("an alarm with no beat ever seen opens nothing", () => { + expect(applyAlarm(emptyRelayState(), t0).opened).toBe(false); + }); + + test("the first beat after silence closes the episode and owes one recovered, naming the downtime", () => { + let state = beat(emptyRelayState(), "epoch-a", 1, t0); + state = applyAlarm(state, t0 + ALARM_AFTER_MS).state; + const back = t0 + 42 * 60_000; + const out = applyHeartbeat(state, { stackEpoch: "epoch-b", seq: 1 }, back); + expect(out.recovered).toEqual({ downtimeMs: 42 * 60_000, epochChanged: true }); + expect(out.state.heartbeat.silentSince).toBeNull(); + // And the beat after that owes nothing. + expect(applyHeartbeat(out.state, { stackEpoch: "epoch-b", seq: 2 }, back + 60_000).recovered).toBeNull(); + }); + + test("a same-epoch resume (laptop slept, did not die) also closes the episode", () => { + let state = beat(emptyRelayState(), "epoch-a", 7, t0); + state = applyAlarm(state, t0 + ALARM_AFTER_MS).state; + const out = applyHeartbeat(state, { stackEpoch: "epoch-a", seq: 8 }, t0 + 10 * 60_000); + expect(out.recovered).toEqual({ downtimeMs: 10 * 60_000, epochChanged: false }); + expect(out.state.heartbeat.silentSince).toBeNull(); + }); + + test("a second silence opens a second episode (the switch re-arms)", () => { + let state = beat(emptyRelayState(), "epoch-a", 1, t0); + state = applyAlarm(state, t0 + ALARM_AFTER_MS).state; + state = applyHeartbeat(state, { stackEpoch: "epoch-b", seq: 1 }, t0 + 20 * 60_000).state; + const t1 = t0 + 20 * 60_000; + expect(applyAlarm(state, t1 + ALARM_AFTER_MS).opened).toBe(true); + }); +}); + +describe("payloads (design §3 terms)", () => { + test("the silent payload is an incident naming the silence start", () => { + const t0 = 1_700_000_000_000; + let state = beat(emptyRelayState(), "epoch-a", 1, t0); + state = { ...applyAlarm(state, t0 + ALARM_AFTER_MS).state, origin: "https://pm-notify.example.workers.dev" }; + const payload = buildSilentPayload(state); + expect(payload.class).toBe("incident"); + expect(payload.objectRef).toBe("stack:silent"); + expect(payload.title).toBe("PM stack is down"); + expect(payload.body).toContain(new Date(t0).toISOString()); + expect(payload.url).toBe("https://pm-notify.example.workers.dev/status"); + }); + + test("the recovered payload names the downtime length", () => { + const payload = buildRecoveredPayload(emptyRelayState(), 42 * 60_000); + expect(payload.title).toBe("PM stack recovered"); + expect(payload.body).toContain("42m"); + }); + + test("formatDuration reads like the stack's other durations", () => { + expect(formatDuration(45_000)).toBe("45s"); + expect(formatDuration(5 * 60_000)).toBe("5m"); + expect(formatDuration(60 * 60_000)).toBe("1h"); + expect(formatDuration((2 * 60 + 5) * 60_000)).toBe("2h 5m"); + }); + + test("the incident class gate: default on, explicit off respected, quiet never consulted", () => { + expect(takesSilentClass(sub({ classes: {} }))).toBe(true); + expect(takesSilentClass(sub({ classes: { incident: false } }))).toBe(false); + expect(takesSilentClass(sub({ quiet: { start: "00:00", end: "23:59", tz: "UTC", enabled: true } }))).toBe(true); + }); +}); + +describe("validation (design §1 shapes, rejected loudly)", () => { + test("a well-formed snapshot validates and normalizes the endpoint", () => { + const out = validateSnapshot({ snapshotSeq: 3, subscriptions: [sub()] }); + expect(out.ok).toBe(true); + }); + + test("snapshot rejects a bad seq, a non-https endpoint, and wrong key lengths", () => { + expect(validateSnapshot({ snapshotSeq: 0, subscriptions: [] }).ok).toBe(false); + expect(validateSnapshot({ snapshotSeq: 1, subscriptions: [sub({ endpoint: "http://fcm.googleapis.com/x" })] }).ok).toBe(false); + expect(validateSnapshot({ snapshotSeq: 1, subscriptions: [sub({ p256dh: "AAAA" })] }).ok).toBe(false); + expect(validateSnapshot({ snapshotSeq: 1, subscriptions: [sub({ auth: "AAAA" })] }).ok).toBe(false); + expect(validateSnapshot({ snapshotSeq: 1, subscriptions: [sub({ classes: { incident: "yes" } as never })] }).ok).toBe(false); + }); + + test("heartbeat rejects an empty epoch and a negative seq", () => { + expect(validateHeartbeat({ stackEpoch: "", seq: 1 }).ok).toBe(false); + expect(validateHeartbeat({ stackEpoch: "e", seq: -1 }).ok).toBe(false); + expect(validateHeartbeat({ stackEpoch: "e", seq: 0, at: "2026-11-23T00:00:00Z" }).ok).toBe(true); + }); +}); + +describe("shared-secret auth (fail closed)", () => { + const headers = (init: Record) => new Headers(init); + test("no configured secret authorizes nothing", () => { + expect(isAuthorized(headers({ Authorization: "Bearer x" }), undefined)).toBe(false); + }); + test("bearer and header forms match; wrong secrets do not", () => { + expect(isAuthorized(headers({ Authorization: "Bearer s3cret" }), "s3cret")).toBe(true); + expect(isAuthorized(headers({ "X-Relay-Secret": "s3cret" }), "s3cret")).toBe(true); + expect(isAuthorized(headers({ Authorization: "Bearer other" }), "s3cret")).toBe(false); + expect(isAuthorized(headers({}), "s3cret")).toBe(false); + }); +}); diff --git a/pm-stack/notify-relay/tsconfig.json b/pm-stack/notify-relay/tsconfig.json new file mode 100644 index 0000000000..4f66fb71bf --- /dev/null +++ b/pm-stack/notify-relay/tsconfig.json @@ -0,0 +1 @@ +{"compilerOptions":{"allowImportingTsExtensions":true,"lib":["ES2022"],"module":"ESNext","moduleResolution":"bundler","noEmit":true,"skipLibCheck":true,"strict":true,"target":"ES2022","types":["@cloudflare/workers-types"]},"include":["src"]} \ No newline at end of file diff --git a/pm-stack/notify-relay/wrangler.toml b/pm-stack/notify-relay/wrangler.toml new file mode 100644 index 0000000000..b15aa06ede --- /dev/null +++ b/pm-stack/notify-relay/wrangler.toml @@ -0,0 +1,28 @@ +# pm-notify relay Worker (#8569 Phase 2, design record +# doc/2026-11-17_design_pm8569_notifications_phase2.md): the edge half +# of the pm-stack dead-man's switch. One Worker + one singleton +# Durable Object (pm-notify) holding the mirrored subscription +# snapshot and the heartbeat alarm state. The DO alarm is the only +# scheduler — there is no cron anywhere in this design. +# +# Secrets (wrangler secret put; values never in this file): +# RELAY_SHARED_SECRET authenticates the laptop -> edge POSTs +# (/mirror/*, /heartbeat). Vaulted in Bitwarden by name +# `pm-aggregator.notify-relay-shared-secret`; the aggregator +# resolves the same name at send time. +# VAPID_PRIVATE_KEY signs the edge's Web Push sends. The existing +# aggregator VAPID keypair — custody moves, the keypair does not +# change (design §4): the value is the same one the laptop fetches +# from Bitwarden by name `pm-aggregator.vapid-private-key` +# (base64url raw private scalar, the web-push package's form). +name = "pm-notify" +main = "src/index.ts" +compatibility_date = "2025-09-15" +workers_dev = true + +[durable_objects] +bindings = [{ name = "PM_NOTIFY", class_name = "PmNotify" }] + +[[migrations]] +tag = "v1" +new_sqlite_classes = ["PmNotify"]