Repository navigation
feat(labeler): notification delivery table + CSPRNG token + gated send-core (W10.5 slice 1) - #2076
Conversation
…10.5 slice 1) Migration 0008 adds the publisher-facing `notifications` delivery table (polymorphic issuance/operator source, confirmation|notice kind, pending/sent/failed/undeliverable state, plaintext cleared on success) and a per-DID `notification_confirm_ledger` for distinct-recipient rate limiting. `generateConfirmToken` draws a 256-bit base64url token from `crypto.getRandomValues`; only its SHA-256 digest is persisted via the existing `recordConfirmSent`. `sendNotification` orchestrates one delivery against an injected `NotificationSender`: fresh contact resolve, recipient hash, atomic suppression-guarded claim, and a confirm-state gate (never `seeded:true`) — confirmed => substantive notice; unconfirmed => a confirmation mail only when both the per-address and per-DID limits pass; declined/suppressed/no-contact => undeliverable, no send. The real email adapter and triggers are slice 2.
…(W10.5 slice 1 review) Adversary-pass fixes: - recordConfirmSent is now a compare-and-set: the UPDATE re-checks the per-address interval in SQL (last_confirm_sent IS NULL OR <= epochMs - minIntervalMs), so two triggers racing for the same unconfirmed address off a stale canSendConfirm snapshot can no longer both mail the victim. minIntervalMs is an optional param (default 0 for seeding callers); the send path passes CONFIRM_MIN_INTERVAL_MS. - Per-DID ledger: count and ledger-write moved adjacent to narrow the overshoot window (best-effort, bounded; exact serialization deferred to slice 2). The gate still returns before any write, so a sustained DID email-bomb costs no rows. - Migration: CHECK (state = 'undeliverable' OR recipient_hash IS NOT NULL); a sendable row must carry a hash. - finalizeSend / markRowUndeliverable UPDATEs gated on state = 'pending' — one-shot terminal transition, no double-finalize. - NotificationSender doc: slice-2 impls must not leak confirmUrl/token into the returned error string (persisted verbatim in last_error). New concurrency test proves the CAS: two Promise.all sends to one unconfirmed victim yield exactly one confirmation (mail once, loser row undeliverable).
… slice 1) Supersedes the interval-CAS: a confirmation mail now reaches an address at most ONCE EVER. The confirmation claimSend gains a second guard in the same INSERT...SELECT — AND NOT EXISTS (a prior notifications row for the hash with kind='confirmation' AND state != 'undeliverable'). This one atomic statement enforces suppression, the lifetime cap, and the concurrency race (of two racing sends exactly one inserts; the loser writes no row). An undeliverable prior (race loser / suppressed-at-claim that never mailed) never blocks a later send. - recordConfirmSent reverts to its state-only guard (drops the minIntervalMs param); it only stamps the token now. - Per-address interval gating removed from the send path; CONFIRM_MIN_INTERVAL_MS deleted (unreferenced). canSendConfirm left as-is (slice-B/C utility). - Ledger write moved after a successful claim, so a repeat trigger for an already-mailed address writes nothing and cannot bloat the per-DID ledger. - New outcome `already_mailed` for a claim blocked by the lifetime cap (suppression re-checked cheaply first for audit precision). Tests prove it: concurrent Promise.all sends mail exactly once (loser row-less); no second mail after a sent OR failed confirmation; an undeliverable-only prior still mails. All three fail with the guard removed.
|
Scope checkThis PR changes 1,183 lines across 6 files. Large PRs are harder to review and more likely to be closed without review. If this scope is intentional, no action needed. A maintainer will review it. If not, please consider splitting this into smaller PRs. See CONTRIBUTING.md for contribution guidelines. |
Deploying with
|
| Status | Name | Latest Commit | Updated (UTC) |
|---|---|---|---|
| ✅ Deployment successful! View logs |
emdash-demo-cache | 8ca97d1 | Jul 16 2026, 03:37 PM |
Deploying with
|
| Status | Name | Latest Commit | Updated (UTC) |
|---|---|---|---|
| ✅ Deployment successful! View logs |
emdash-demo-do | 8ca97d1 | Jul 16 2026, 03:38 PM |
Deploying with
|
| Status | Name | Latest Commit | Updated (UTC) |
|---|---|---|---|
| ✅ Deployment successful! View logs |
emdash-playground | 8ca97d1 | Jul 16 2026, 03:38 PM |
There was a problem hiding this comment.
This PR lands W10.5 slice 1 exactly as ratified in the implementation plan: the notifications delivery table, a CSPRNG confirmation-token helper, and the gated send core with an injected NotificationSender. The overall approach is right for the integration branch—atomic lifetime-cap claim via INSERT ... SELECT, separation of the per-DID best-effort ledger, and never gating on seeded:true.
I reviewed statically against the diff, full files, the W10.5 plan, and notification-contacts.ts / notification-endpoints.ts. The tests cover the headline lifetime, concurrency, undeliverable-prior, and per-DID-cap cases well. I did not run the test suite locally.
Two logic bugs need fixing:
-
False per-DID cap consumption on theskipped
contact_state_changedrace.sendConfirmationMail()writes anotification_confirm_ledgerrow right after the atomic claim but beforerecordConfirmSent()verifies the contact is stillunconfirmed. If the contact flips todeclined/confirmedbetween the state read and the stamp, no mail is sent, yet the ledger row remains—silently eating a distinct-recipient slot for that DID. The surrounding comment explicitly says the ledger is written only after an actual first-ever mail, so the code currently contradicts its own contract. -
markRowUndeliverable()populatessent_atfor a never-sent row.sent_atsemantically means “provider accepted the mail” (the success path uses it withprovider_id). Marking a rowundeliverablebecause the contact leftunconfirmedshould not setsent_at;created_at_epoch_msalready captures the row lifetime.
A smaller suggestion: move the isSuppressed() check before ensureContact() so suppressed addresses are not seeded with an unconfirmed row, matching seedPublisherContact in publisher-contact.ts.
With those two fixes and a covering test for the contact_state_changed path, this is good to merge.
| // cap guarantees that — so it admits a few extra distinct victims, it never | ||
| // bombs anyone). Exact enforcement needs a serialized claim (a Durable Object) | ||
| // and is deferred to slice 2. The gate returns before any write, so a sustained | ||
| // DID email-bomb costs no rows; the ledger is written only after a successful | ||
| // claim (an actual first-ever mail), so a repeat trigger for an already-mailed | ||
| // address writes nothing and cannot bloat the ledger or falsely trip the cap. | ||
| const sinceMs = now.ms - CONFIRM_DID_WINDOW_MS; | ||
| const distinctRecipients = await countDistinctConfirmRecipients( | ||
| ctx.db, | ||
| request.target.did, | ||
| sinceMs, | ||
| ); | ||
| if (distinctRecipients >= CONFIRM_DID_MAX_DISTINCT_RECIPIENTS) { | ||
| logSend(request.target.did, "rate_limited:did", hash); | ||
| return { status: "rate_limited", recipientHash: hash, scope: "did" }; | ||
| } | ||
|
|
||
| // Atomic claim: suppression + lifetime "mail once ever" cap + concurrency, all | ||
| // in one INSERT...SELECT (see claimSend). A false means one of those fired. | ||
| const id = newNotificationId(); | ||
| const claimed = await claimSend( | ||
| ctx.db, | ||
| id, | ||
| request.source, | ||
| "confirmation", | ||
| hash, | ||
| email, | ||
| now.date, | ||
| ); | ||
| if (!claimed) { | ||
| // Suppression is pre-checked upstream, so a false here is almost always the | ||
| // lifetime cap. The cheap re-check only distinguishes a suppression that | ||
| // landed in the pre-check→claim window — an audit nicety, not correctness. | ||
| if (await isSuppressed(ctx.db, hash)) { | ||
| logSend(request.target.did, "suppressed", hash); | ||
| return { status: "suppressed", recipientHash: hash }; | ||
| } | ||
| logSend(request.target.did, "already_mailed", hash); | ||
| return { status: "already_mailed", recipientHash: hash }; | ||
| } | ||
|
|
||
| await recordConfirmLedgerEntry(ctx.db, request.target.did, hash, now.ms); | ||
|
|
||
| const token = generateConfirmToken(); | ||
| const tokenHash = await hashConfirmToken(token); | ||
| const recorded = await recordConfirmSent(ctx.db, hash, tokenHash, now.ms); | ||
| if (!recorded) { | ||
| // The claim already enforced the lifetime cap and concurrency; a false here | ||
| // is only the contact leaving `unconfirmed` between the state read and this | ||
| // stamp. Retire the claimed row rather than mail a dead-token confirmation. | ||
| await markRowUndeliverable(ctx.db, id, "contact_state_changed", now.date); | ||
| logSend(request.target.did, "skipped:contact_state_changed", hash); | ||
| return { status: "skipped", recipientHash: hash, reason: "contact_state_changed" }; | ||
| } | ||
|
|
||
| const result = await ctx.sender.sendConfirmation({ | ||
| to: email, |
There was a problem hiding this comment.
[needs fixing] recordConfirmLedgerEntry(...) is written immediately after the atomic claim, but the code then calls recordConfirmSent(...) and can still bail out with status: "skipped" / reason: "contact_state_changed" if the contact left unconfirmed in the race. In that case no confirmation mail is sent, yet the per-DID ledger row remains, falsely consuming one of the CONFIRM_DID_MAX_DISTINCT_RECIPIENTS slots. The block comment at line 241 says the ledger is written only after an actual first-ever mail, so the implementation does not match its own contract.
Move the ledger write to after recordConfirmSent succeeds (the mail is about to go out), and add a regression test for the contact_state_changed skipped path to lock in cap accuracy.
| // cap guarantees that — so it admits a few extra distinct victims, it never | |
| // bombs anyone). Exact enforcement needs a serialized claim (a Durable Object) | |
| // and is deferred to slice 2. The gate returns before any write, so a sustained | |
| // DID email-bomb costs no rows; the ledger is written only after a successful | |
| // claim (an actual first-ever mail), so a repeat trigger for an already-mailed | |
| // address writes nothing and cannot bloat the ledger or falsely trip the cap. | |
| const sinceMs = now.ms - CONFIRM_DID_WINDOW_MS; | |
| const distinctRecipients = await countDistinctConfirmRecipients( | |
| ctx.db, | |
| request.target.did, | |
| sinceMs, | |
| ); | |
| if (distinctRecipients >= CONFIRM_DID_MAX_DISTINCT_RECIPIENTS) { | |
| logSend(request.target.did, "rate_limited:did", hash); | |
| return { status: "rate_limited", recipientHash: hash, scope: "did" }; | |
| } | |
| // Atomic claim: suppression + lifetime "mail once ever" cap + concurrency, all | |
| // in one INSERT...SELECT (see claimSend). A false means one of those fired. | |
| const id = newNotificationId(); | |
| const claimed = await claimSend( | |
| ctx.db, | |
| id, | |
| request.source, | |
| "confirmation", | |
| hash, | |
| email, | |
| now.date, | |
| ); | |
| if (!claimed) { | |
| // Suppression is pre-checked upstream, so a false here is almost always the | |
| // lifetime cap. The cheap re-check only distinguishes a suppression that | |
| // landed in the pre-check→claim window — an audit nicety, not correctness. | |
| if (await isSuppressed(ctx.db, hash)) { | |
| logSend(request.target.did, "suppressed", hash); | |
| return { status: "suppressed", recipientHash: hash }; | |
| } | |
| logSend(request.target.did, "already_mailed", hash); | |
| return { status: "already_mailed", recipientHash: hash }; | |
| } | |
| await recordConfirmLedgerEntry(ctx.db, request.target.did, hash, now.ms); | |
| const token = generateConfirmToken(); | |
| const tokenHash = await hashConfirmToken(token); | |
| const recorded = await recordConfirmSent(ctx.db, hash, tokenHash, now.ms); | |
| if (!recorded) { | |
| // The claim already enforced the lifetime cap and concurrency; a false here | |
| // is only the contact leaving `unconfirmed` between the state read and this | |
| // stamp. Retire the claimed row rather than mail a dead-token confirmation. | |
| await markRowUndeliverable(ctx.db, id, "contact_state_changed", now.date); | |
| logSend(request.target.did, "skipped:contact_state_changed", hash); | |
| return { status: "skipped", recipientHash: hash, reason: "contact_state_changed" }; | |
| } | |
| const result = await ctx.sender.sendConfirmation({ | |
| to: email, | |
| const token = generateConfirmToken(); | |
| const tokenHash = await hashConfirmToken(token); | |
| const recorded = await recordConfirmSent(ctx.db, hash, tokenHash, now.ms); | |
| if (!recorded) { | |
| // The claim already enforced the lifetime cap and concurrency; a false here | |
| // is only the contact leaving `unconfirmed` between the state read and this | |
| // stamp. Retire the claimed row rather than mail a dead-token confirmation. | |
| await markRowUndeliverable(ctx.db, id, "contact_state_changed", now.date); | |
| logSend(request.target.did, "skipped:contact_state_changed", hash); | |
| return { status: "skipped", recipientHash: hash, reason: "contact_state_changed" }; | |
| } | |
| await recordConfirmLedgerEntry(ctx.db, request.target.did, hash, now.ms); | |
| const result = await ctx.sender.sendConfirmation({ | |
| to: email, | |
| confirmUrl: buildActionUrl(ctx.origin, "confirm", hash, token), | |
| unsubscribeUrl: buildActionUrl(ctx.origin, "unsubscribe", hash), | |
| notMeUrl: buildActionUrl(ctx.origin, "not-me", hash), | |
| }); |
| async function markRowUndeliverable( | ||
| db: D1Database, | ||
| id: string, | ||
| reason: string, | ||
| now: Date, | ||
| ): Promise<void> { | ||
| await db | ||
| .prepare( | ||
| `UPDATE notifications | ||
| SET state = 'undeliverable', last_error = ?, plaintext_email = NULL, sent_at = ? | ||
| WHERE id = ? AND state = 'pending'`, | ||
| ) | ||
| .bind(reason, now.toISOString(), id) |
There was a problem hiding this comment.
[needs fixing] markRowUndeliverable() transitions a row to state = 'undeliverable' because the contact left unconfirmed and the confirmation was never mailed. Yet it also sets sent_at to the current time. Semantically, sent_at belongs to successfully handed-off rows (used together with provider_id); a never-sent undeliverable row should not carry a send timestamp. Future sweeps or analytics that treat sent_at IS NOT NULL as a successful-send indicator will be misled, and created_at_epoch_ms already records the row’s lifetime.
Drop sent_at from this transition.
| async function markRowUndeliverable( | |
| db: D1Database, | |
| id: string, | |
| reason: string, | |
| now: Date, | |
| ): Promise<void> { | |
| await db | |
| .prepare( | |
| `UPDATE notifications | |
| SET state = 'undeliverable', last_error = ?, plaintext_email = NULL, sent_at = ? | |
| WHERE id = ? AND state = 'pending'`, | |
| ) | |
| .bind(reason, now.toISOString(), id) | |
| async function markRowUndeliverable( | |
| db: D1Database, | |
| id: string, | |
| reason: string, | |
| now: Date, | |
| ): Promise<void> { | |
| await db | |
| .prepare( | |
| `UPDATE notifications | |
| SET state = 'undeliverable', last_error = ?, plaintext_email = NULL | |
| WHERE id = ? AND state = 'pending'`, | |
| ) | |
| .bind(reason, id) | |
| .run(); | |
| } |
| const hash = await recipientHash(ctx.pepper, resolution.email); | ||
| const nowDate = now(); | ||
| const nowIso = nowDate.toISOString(); | ||
| const nowMs = nowDate.getTime(); | ||
|
|
||
| await ensureContact(ctx.db, hash, nowIso); | ||
| const state = await getContactState(ctx.db, hash); | ||
|
|
||
| if (await isSuppressed(ctx.db, hash)) { |
There was a problem hiding this comment.
[suggestion] The send path ensureContacts every resolved address before checking suppression, which inserts an unconfirmed row for suppressed addresses (which already have a row in notification_suppressions). In publisher-contact.ts, seedPublisherContact() checks isSuppressed first and avoids seeding those addresses; doing the same here keeps suppressed addresses off the contact ledger entirely and reduces an avoidable privacy/abuse inconsistency.
| const hash = await recipientHash(ctx.pepper, resolution.email); | |
| const nowDate = now(); | |
| const nowIso = nowDate.toISOString(); | |
| const nowMs = nowDate.getTime(); | |
| await ensureContact(ctx.db, hash, nowIso); | |
| const state = await getContactState(ctx.db, hash); | |
| if (await isSuppressed(ctx.db, hash)) { | |
| const hash = await recipientHash(ctx.pepper, resolution.email); | |
| const nowDate = now(); | |
| const nowIso = nowDate.toISOString(); | |
| const nowMs = nowDate.getTime(); | |
| if (await isSuppressed(ctx.db, hash)) { | |
| await recordUndeliverable(ctx.db, request.source, "notice", hash, "suppressed", nowDate); | |
| logSend(request.target.did, "suppressed", hash); | |
| return { status: "suppressed", recipientHash: hash }; | |
| } | |
| await ensureContact(ctx.db, hash, nowIso); | |
| const state = await getContactState(ctx.db, hash); | |
| if (state === null || state.confirmState === "declined") { |
…t_at, suppress order) - Move recordConfirmLedgerEntry to after recordConfirmSent succeeds (still before send). A contact_state_changed abort now writes no ledger row, so it no longer eats a distinct-recipient slot — matching the comment's own contract. A failed SEND still consumes budget (the conservative fail-safe). - markRowUndeliverable no longer sets sent_at: a never-sent undeliverable row must not carry a provider-accepted timestamp (dropped the now param too). - Check isSuppressed before ensureContact in sendNotification (matching seedPublisherContact), so a suppressed address is never seeded with an unconfirmed contact row. New test drives the contact_state_changed abort via a DB proxy that flips the contact to declined during the per-DID count (after the state read, before the stamp) and asserts no ledger row + an undeliverable row with sent_at NULL; it fails if the ledger write is moved back before the stamp.
There was a problem hiding this comment.
Re-review of W10.5 slice 1. The integration-branch approach remains sound: CSPRNG confirm token, atomic lifetime-cap claim, per-DID best-effort gate, injected NotificationSender, and no seeded:true gating.
I verified the two blocking issues from the prior review and the suggestion are all addressed in the current head:
- Per-DID ledger no longer consumed on
contact_state_changedabort.recordConfirmLedgerEntryis now written only afterrecordConfirmSentsucceeds, and the abort path marks the claimed rowundeliverablewithout touching the ledger. markRowUndeliverableno longer setssent_at. The helper only flips state/plainslast_errorand clearsplaintext_email, matching the "never handed to a provider" semantics.isSuppressed()now runs beforeensureContact. Suppressed addresses are not seeded with anunconfirmedcontact row.
A covering test for the mid-send decline race has been added and asserts both the zero ledger count and the sent_at = NULL retired row.
I also re-checked the new code against AGENTS.md conventions:
- SQL safety: all dynamic values are bound; identifiers are hardcoded. No
sql.raw()-style interpolation in the migration or the send core. - Indexes: migration
0008adds partialpending/failed, source, recipient, and sweep indexes plus the correct per-DID ledger indexes. - Envelope shape / authorization / locale filtering: not applicable; these are internal labeler helpers with no new API routes or content-table queries.
- Changesets: n/a — the labeler app is private (
0.0.0) and its migrations are unpublished.
Everything in the diff is consistent with the ratified W10.5 contracts recorded in the implementation plan. LGTM.
738f94e
into
feat/plugin-registry-labelling-service
What does this PR do?
W10.5 slice 1 of the publisher-notification subsystem: the security-critical send-orchestration core, plus its delivery table and CSPRNG confirm token. Builds on the merged W10.4 contact/confirm infrastructure (slices A/B/C).
What lands here:
0008_notifications.sql— the publisher-facingnotificationsdelivery table (mutable outbox: polymorphicissuance|operatorsource with no cross-table FK,confirmation|noticekind,pending|sent|failed|undeliverablestate,attempts/provider_id/last_error, and a nullableplaintext_emailset on claim and cleared on successful send) plus a per-DIDnotification_confirm_ledgerfor distinct-recipient rate limiting. ACHECK (state = 'undeliverable' OR recipient_hash IS NOT NULL)keeps every sendable row hash-bearing.generateConfirmToken()draws 256 bits fromcrypto.getRandomValues, base64url, single-use; only its SHA-256 digest is persisted (via the existingrecordConfirmSent), the raw token travels only in the confirm link. This is the hard requirement from the W10.4 slice-C adversary pass (the pepper-less, rate-limit-free confirm endpoint rests entirely on token unguessability).sendNotification(ctx, request)against an injectedNotificationSender(the real Cloudflare Email Sending adapter is slice 2, exercised here with a fake). Fresh contact resolve → recipient hash → atomic suppression re-check → confirm-state gate (neverseeded:true):confirmed→ substantive notice;unconfirmed→ a content-neutral confirmation mail subject to the caps;declined/suppressed/no-contact →undeliverable, no send.Lifetime-cap decision (ratified). A confirmation mail reaches an address at most once ever — no re-nudge after any interval. This is enforced atomically inside the confirmation claim: one
INSERT ... SELECT ... WHERE NOT EXISTS (suppression) AND NOT EXISTS (prior non-undeliverable confirmation row for the hash). That single statement enforces all three of not-suppressed, the lifetime cap, and the concurrency race (of two racing sends exactly one inserts; the loser writes no row). Anundeliverableprior never mailed, so it is deliberately excluded and cannot foreclose a later legitimate confirmation. A separate per-DID cap (distinct recipients in a rolling window) throttles a hostile DID naming many distinctvictim@xaddresses — the amplification the per-address cap cannot see.Out of scope (slice 2): the real Cloudflare Email Sending adapter + templates, the five issuance-point triggers, verified-publisher confirmation-skip, and the cron retry/cleanup sweep. Three slice-2 contracts (source ref, verified-skip, and the sweep re-driving stuck
pendingrows / retiring terminally-abandoned rows) are recorded in.opencode/plans/plugin-registry-labelling-service/implementation-plan.mdunder W10.5.Base is the integration branch
feat/plugin-registry-labelling-service, notmain.Type of change
Checklist
pnpm typecheckpassespnpm lintpasses — 0 diagnostics in the files this PR touches (the repo has pre-existing diagnostics in unrelatedregistry-verification/calibrationfiles, untouched here)pnpm testpasses — full labeler suite green (707 tests, 37 files), including the newnotification-send/notification-contactscoveragepnpm formathas been run (oxfmt, tabs).opencode/plans/plugin-registry-labelling-service/implementation-plan.md), targeting the integration branch rather thanmainAI-generated code disclosure
Screenshots / test output
Full labeler suite: 707 passed (37 files). Gate-specific proofs for the anti-abuse core:
Promise.all([sendNotification, sendNotification])for one unconfirmed address → the fake sender receives exactly one confirmation, exactly onesentrow, the other call returnsalready_mailedwith no row.undeliverableis still mailed.NOT EXISTSguard temporarily removed, the concurrency and both lifetime tests fail (two mails / re-mails); the undeliverable-prior test still passes. Guard restored.Try this PR
Open a fresh playground →
A full working EmDash site, deployed from this branch. Each visit gets its own session-scoped sandbox: no login needed and no shared state. Try the admin, edit content, hit the public site.
Tracks
feat/labeler-notification-send. Updated automatically when the playground redeploys.