GeezerVison is showing github.com — feat(pm-stack): pm-notify edge relay + dead-man's switch — #8569 Phase 2 step 1 by dezren39 · Pull Request #13518 · developing-today/code
Conversation
dezren39
commented
Nov 23, 2026
•
edited by blacksmith-sh
Bot
Loading
Uh oh!
There was an error while loading. Please reload this page.
#8569 Phase 2, step 1 of 4 — relay skeleton + dead-man's switch
Implements step 1 of the design record's ordered split (doc/2026-11-17_design_pm8569_notifications_phase2.md §5). This PR deliberately does not close #8569: steps 2–4 are filed as #13468 (event mirror), #13469 (edge answer intake), #13470 (cron narrowing), and the production deploy leg is dispositioned on the issue (below).
Edge — new package pm-stack/notify-relay
One Worker (pm-notify) + one singleton Durable Object, following the decision-events-worker precedent (wrangler shape, DO idiom, timing-safe shared-secret auth):
POST /mirror/subscriptions — full-snapshot replace under a monotonic snapshotSeq: higher stores, equal acks as duplicate, lower is rejected 409 and loudly (the client re-adopts the edge's seq from /status).
POST /heartbeat — records {stackEpoch, seq, at}, re-arms the DO alarm at last-beat + 150 s (the alarm is the only scheduler), and returns the pending-answer count (0 until step 3 — the field exists now so the client contract is stable).
- The alarm opens exactly one
stack.silent episode per silence and sends the down push (payload class incident, breakthrough — quiet hours are never consulted at the edge); the first beat after silence sends exactly one recovered push naming the downtime. Silence is measured from the last beat, so both numbers describe the true silent span.
GET /status — up/silent/since + heartbeat/snapshot/delivery facts. Deliberately not board data; everything else 404s (the answer routes are step 3, the event mirror is step 2).
- Web Push is WebCrypto-only (RFC 8291 sealing + RFC 8292 VAPID), modeled on
pm-stack/console/src/push.ts: the existing aggregator keypair sends from the edge, the private key arriving as a Worker secret — no new keypair, no subscription re-registration. A 410 is counted, never deleted locally: the mirror is never the record.
- One recorded widening of the design letter (package README + code comments): the design says a same-epoch heartbeat after silence "cannot occur"; a suspended laptop is the counterexample. An episode therefore closes 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.
Laptop — aggregator relay client
- New
src/notify-relay.ts: stackEpoch minted per start; a ~60 s heartbeat loop; the subscription snapshot mirrored on start and whenever the store changes — the two /api/push/subscriptions routes now kick requestNotifyRelaySubscriptionSync(). The seq persists in ~/.local/state/pm-aggregator/notify-relay.json; a failed POST retries with the same seq and content; a 409 re-adopts the edge's seq.
- Shared secret resolved by Bitwarden name only (
pm-aggregator.notify-relay-shared-secret); the VAPID private key name is unchanged. Everything is fail-soft: a dead edge, a missing secret, or an absent store is recorded on the client and never touches the throat's own sends.
- Inert until configured: with
PM_AGG_NOTIFY_RELAY_URL unset the client never starts and the aggregator runs exactly as before, so this is safe to land ahead of the deploy.
Evidence (remote dispatch, REMOTE BUILDS ONLY)
- Relay package, run 45227585707:
bun test 23 pass / 0 fail + tsc --noEmit clean. Oracles are named per test: the RFC 8291 roundtrip decrypts the sealed body back to the payload; the VAPID JWT verifies against the signing key and names the push origin; the episode tests assert exactly-one-down / exactly-one-recovered across alarm re-fires, epoch-change recovery, same-epoch resume, and a second episode.
- Aggregator, run 45222767373:
bun test test/notify-relay.test.ts test/alerts.test.ts 65 pass / 0 fail. (The package's tsc --noEmit is red on main for one pre-existing error in src/quota-reset-duration.test.ts, untouched by this PR — filed as pm-stack/aggregator: package typecheck red on main — quota-reset-duration.test.ts(256) string|undefined vs string|null #13484. This PR's files produce no type errors.)
Not in this PR
- Deploy leg (dispositioned on pm-stack notifications Phase 2: Cloudflare edge relay + Durable Object dead-man's switch — push that survives the stack being down #8569, per the impl(fleet-hosted): service skeleton — Worker route modules, RP-token auth validation, tenancy mapping, health/capabilities #12583 pattern — not performed from this seat):
wrangler deploy with the day-to-day Cloudflare token (Bitwarden by name), wrangler secret put RELAY_SHARED_SECRET + VAPID_PRIVATE_KEY (values from the Bitwarden names in the package README), then set PM_AGG_NOTIFY_RELAY_URL in the aggregator's environment and restart it. Drew's acceptance (kill the stack → down push < 2 min; restart → exactly one recovered push) runs after that deploy.
- Steps 2–4: pm-stack notifications Phase 2 step 2: event mirror to the pm-notify DO (#8569) #13468, pm-stack notifications Phase 2 step 3: edge answer intake + heartbeat drain (#8569) #13469, pm-stack notifications Phase 2 step 4: cron narrowing to the daily DO canary (#8569) #13470.
- No schedule is created, changed, or retired (the DO alarm is the design's only scheduler; the page-health-push narrowing is step 4), so
doc/fleet-schedule-registry.md is untouched.
- New dependencies: none at runtime. The worker package's devDependencies mirror
decision-events-worker's existing set (@cloudflare/workers-types ^4.20251011.0, typescript ^5.6.0, wrangler 4.44.0) for tests/typecheck/deploy tooling only; the aggregator gains no dependency.

Open in [code]smith · Need help on this PR? Tag @codesmith-bot with what you need.
Sorry, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
…ient (#8569 step 1)
Step 1 of the Phase-2 design record's ordered split
(doc/2026-11-17_design_pm8569_notifications_phase2.md): the relay
skeleton + dead-man's switch.
Edge (new package pm-stack/notify-relay): one Worker + singleton
pm-notify Durable Object. POST /mirror/subscriptions takes the
full subscription snapshot under a monotonic seq (highest wins,
equal acks as duplicate, lower rejected 409); POST /heartbeat
records the beat and re-arms the DO alarm at last-beat + 150s;
the alarm opens exactly one silent episode and sends the
stack.silent push (incident class, breakthrough) with the
existing aggregator VAPID keypair — private key as a Worker
secret, subscriptions never re-register; the first beat after
silence sends exactly one recovered push naming the downtime.
GET /status is the only read surface (no board at the edge).
Web Push is WebCrypto-only (RFC 8291/8292), modeled on
console/src/push.ts. One recorded widening of the design letter:
an episode closes on the first beat after silence, epoch change
or not — a suspended laptop resumes with the same epoch, and the
design's exactly-one-down/exactly-one-recovered invariant holds
under both signals (package README).
Laptop (aggregator): new notify-relay client — stackEpoch per
start, ~60s heartbeats, snapshot mirror kicked from the
subscription routes, seq persisted in the relay state file,
409 re-adopts the edge seq from /status, all fail-soft. Inert
until PM_AGG_NOTIFY_RELAY_URL is set, so this is safe to land
ahead of the deploy (a separate leg, dispositioned on #8569).
No schedules created or changed (the DO alarm is the design's
only scheduler; the page-health-push narrowing is step 4), so
doc/fleet-schedule-registry.md is untouched. No new runtime
dependencies: the worker package's devDependencies mirror
decision-events-worker (@cloudflare/workers-types, typescript,
wrangler 4.44.0) for tests/typecheck/deploy tooling only.
- notify-relay/src/push.ts: the VAPID Authorization header line
reached the branch in a mangled form (a redaction artifact in
the write path) and did not parse; compute the header into a
local and reference it, which is also easier to read.
- aggregator/test/notify-relay.test.ts: the first-beat call-order
assertion sliced URLs by segment count, which mishandles the
single-segment /heartbeat path; compare pathnames instead.
(First remote pass: relay suite 18/19 with the parse error the
only failure; aggregator suite 64/65 with this assertion the
only failure.)
WebCrypto validates an EC JWK as a set: pairing a test private
scalar with the production public point is invalid keyData and
the import throws (DataError), which is also exactly the loud
failure a mismatched production secret should get. importVapid
Signer/vapidAuthorization now take the public key explicitly
(default: the production VAPID_PUBLIC_KEY, so the Worker path is
unchanged), and the delivery tests sign with a consistent
generated pair.
The relay suite is green (23/23); tsc flagged the two WebCrypto
ECDH calls: workers-types' BufferSource wants an ArrayBuffer-
backed view (pass a slice) and its deriveBits params predate
the standard EcdhKeyDeriveParams shape (cast the params object).
Runtime calls are the standard ones; comment says so.
)
tsc round 2: the suite is green (23/23) but workers-types
declares exportKey with an ArrayBuffer|JsonWebKey union return
and has no global EcdhKeyDeriveParams name. Cast the exportKey
result to ArrayBuffer and the deriveBits params through the
method's own parameter type. Runtime calls unchanged.
Codex Review Summary: ✅ Completed
This comment shows the latest Codex review activity on this pull request.
| Review |
Status |
Commit |
Review trigger |
| 📝 Code Review |
✅ Completed 2026-11-23T17:41:44.862708Z |
6b6fc2c |
PR opened |
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review" or "@codex security review".
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.
|
Sorry, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
Warning
Review limit reached
You've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository.
Next included review available in 55 minutes.
Check out review usage here.
View limit details
-
Limit details: You’ve used the included review currently available.
Learn how review limits work.
Review configuration:
Run configuration
-
- Source mode: Auto
- Repository: Unavailable
- Branch: Unavailable
- File: No configuration file from this repository applied
- Commit: Unavailable
- Layers: defaults
- Review profile: CHILL
- Plan: Advanced
- Run ID:
dd0bb22e-1c30-461a-b972-1babc9feb0d7
Commits
-
Reviewing files that changed from the base of the PR and between 046c7f1 and 6b6fc2c.
Files selected for processing: 13
-
pm-stack/aggregator/src/config.ts
pm-stack/aggregator/src/notify-relay.ts
pm-stack/aggregator/src/server.ts
pm-stack/aggregator/test/notify-relay.test.ts
pm-stack/notify-relay/README.md
pm-stack/notify-relay/package.json
pm-stack/notify-relay/src/index.ts
pm-stack/notify-relay/src/push.ts
pm-stack/notify-relay/src/relay.ts
pm-stack/notify-relay/test/push.test.ts
pm-stack/notify-relay/test/relay.test.ts
pm-stack/notify-relay/tsconfig.json
pm-stack/notify-relay/wrangler.toml
- Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.
Share
-
|
Sorry, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 6b6fc2c282
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
Sorry, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
Comment on lines
+184
to
+185
|
|
const delivered = await this.deliver(outcome.state, "silent", buildSilentPayload(outcome.state));
|
|
|
await this.save(delivered);
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Preserve concurrent state updates while delivering pushes
If a heartbeat arrives while the alarm is awaiting push delivery, it updates the stored heartbeat but sees no silent episode because the alarm has not persisted that transition yet. When delivery completes, this wholesale save restores the old heartbeat and marks the recovered stack silent; the recovery notification is also missed. Subscription snapshots received during delivery can similarly be overwritten. The recovered-delivery branch has the same stale-state pattern. Persist and serialize episode transitions before external awaits, and record delivery results without overwriting newer state.
Useful? React with 👍 / 👎.
Sorry, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
Comment on lines
+121
to
+124
|
|
const origin = req.headers.get("X-Relay-Origin");
|
|
|
if (origin && origin !== state.origin) {
|
|
|
state = { ...state, origin };
|
|
|
await this.save(state);
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Ignore client origin headers on the public status route
An unauthenticated caller can send GET /status with X-Relay-Origin: https://evil.example: the Worker forwards that request unchanged, and this block persists the attacker-controlled origin. If this happens after the last heartbeat before an outage, buildSilentPayload() puts the attacker's URL in the down notification. The aggregator service worker's notification-click handler opens that supplied URL without restricting its origin, allowing a public status request to redirect a trusted notification to an attacker-controlled site. Strip this header on public requests and learn the origin only from authenticated writes.
Useful? React with 👍 / 👎.
Sorry, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
Comment on lines
+194
to
+196
|
|
this.ackedJson = this.pending.json;
|
|
|
this.pending = null;
|
|
|
this.syncDirty = false;
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Retain subscription changes requested during an in-flight sync
If a subscription is added, deleted, or has its preferences changed while a snapshot POST is in flight, requestSubscriptionSync() sets syncDirty but joins the existing syncInFlight promise without scheduling another pass. When the older snapshot is acknowledged, this assignment clears that dirty flag. Subsequent heartbeats skip subscription sync entirely, so the newer subscription state never reaches the edge until another mutation or process restart. Track changes made during the current sync and rerun before clearing the dirty state.
Useful? React with 👍 / 👎.
Sorry, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
Comment on lines
+193
to
+196
|
|
if (!res.ok) throw new Error(`relay snapshot POST failed: HTTP ${res.status}`);
|
|
|
this.ackedJson = this.pending.json;
|
|
|
this.pending = null;
|
|
|
this.syncDirty = false;
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Detect snapshot sequence collisions after local state loss
If the local sequence file is lost while the edge holds snapshot sequence 1, startup assigns sequence 1 to the current subscriptions. The edge treats that equal sequence as a duplicate without checking its content, so this success path marks the new content acknowledged even if the edge still holds a different subscription set. The 409 recovery path never runs, and subsequent heartbeats do not repair the mirror. The same collision can occur when restoring an older counter. Reconcile the edge sequence before assigning a fresh snapshot, or reject equal-sequence requests whose content differs.
Useful? React with 👍 / 👎.
Sorry, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
Comment on lines
+149
to
+151
|
|
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` };
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Align the class-map limit with valid aggregator subscriptions
A subscription with nine custom class keys is valid in the aggregator: mergeClasses() in aggregator/src/alerts.ts adds up to 16 custom keys on top of the eight defaults in notifications.ts. buildSnapshotBody() copies that complete map unchanged, but this check permits only 16 keys total. Consequently, one valid subscription with 17 keys causes the entire snapshot, including other devices, to be rejected with HTTP 400 indefinitely. Heartbeats still succeed while new subscriptions and preference changes never reach the edge. Align this bound with the aggregator's accepted class-map representation.
Useful? React with 👍 / 👎.
Sorry, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
This was referenced Nov 24, 2026
Uh oh!
There was an error while loading. Please reload this page.
Assignees
No one assigned
Milestone
No milestone
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
|