@lunora/notify 1.0.0-alpha.11 → 1.0.0-alpha.111

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -1,3 +1,21 @@
1
+ /**
2
+ * `@lunora/notify`
3
+ *
4
+ * Multi-channel notifications for Lunora, wrapping the `@visulima/notification`
5
+ * engine. `defineNotify` in `lunora/notify.ts` configures the edge-safe channels
6
+ * (Web Push + FCM, plus chat / in-app inbox / webhook); codegen wires `ctx.notify`
7
+ * and its `ctx.push` alias onto every handler ctx from it (mirroring `defineFlags`
8
+ * → `ctx.flags`).
9
+ *
10
+ * Edge-safety: Web Push (VAPID + RFC 8291) and FCM (HTTP v1) run on `fetch` + Web
11
+ * Crypto under workerd. APNs (`node:http2`) and SMS / Node-only queue adapters are
12
+ * deliberately **not** on the edge facade — route heavy fan-out through
13
+ * `@lunora/queue` (`enqueuePushBroadcast` / `runPushBroadcastPage`).
14
+ *
15
+ * - `@lunora/notify` — `defineNotify`, `createNotify`, config resolvers, subscription stores and types.
16
+ * - `@lunora/notify/web` — the browser `subscribeToPush` service-worker helper.
17
+ * @packageDocumentation
18
+ */
1
19
  import { FcmConfig } from '@visulima/notification/providers/fcm';
2
20
  export type { FcmConfig } from '@visulima/notification/providers/fcm';
3
21
  import { PushSubscriptionLike, WebPushConfig } from '@visulima/notification/providers/web-push';
@@ -15,6 +33,15 @@ type NotifyEnv = Record<string, unknown>;
15
33
  type SubscriptionKind = "fcm" | "web-push";
16
34
  /** The last-known delivery outcome recorded on a subscription. */
17
35
  type SubscriptionStatus = "expired" | "failed" | "ok";
36
+ /** The delivery outcomes of one broadcast page, grouped for {@link SubscriptionStore.applyOutcomes}. */
37
+ interface SubscriptionOutcomes {
38
+ failed: {
39
+ error?: string;
40
+ id: string;
41
+ }[];
42
+ gone: string[];
43
+ ok: string[];
44
+ }
18
45
  /**
19
46
  * A registered device/browser subscription. Web Push carries a W3C Push API
20
47
  * `endpoint` + `keys`; FCM carries a device registration `token`. `id` is a
@@ -111,7 +138,7 @@ interface SubscriptionFilter {
111
138
  * subscriptions reached across every internally-walked page (still
112
139
  * deliberately left unset by default — it must reach every matched
113
140
  * device); the PER-PAGE batch size is a separate, independent knob (see
114
- * `CreateNotifyOptions`'s `broadcastPageSize`, default 250) so a caller
141
+ * `defineNotify`'s `broadcastPageSize`, default 250) so a caller
115
142
  * that sets `limit` to bound the audience doesn't also have to reason
116
143
  * about page sizing.
117
144
  *
@@ -136,8 +163,39 @@ interface SubscriptionFilter {
136
163
  * and a D1-backed store (durable, edge-safe).
137
164
  */
138
165
  interface SubscriptionStore {
166
+ /**
167
+ * Apply a whole broadcast page's delivery outcomes at once (best-effort):
168
+ * `ok` ids are marked ok, `failed` ids marked failed with their error, `gone`
169
+ * ids deleted. OPTIONAL — when absent, `broadcast` calls `markStatus` /
170
+ * `delete` per id.
171
+ */
172
+ applyOutcomes?: (outcomes: SubscriptionOutcomes) => Promise<void>;
139
173
  /** Remove a subscription by id (idempotent). */
140
174
  delete: (id: string) => Promise<void>;
175
+ /**
176
+ * Remove a subscription by id ONLY if it is owned by `userId`, and report
177
+ * whether it was.
178
+ *
179
+ * Separate from {@link SubscriptionStore.delete} because the caller-facing
180
+ * `unregister` must not be a read followed by a write: between a `get` that
181
+ * checks the owner and a `delete` that acts on it, a re-registration can
182
+ * replace the row, so the check passes for one owner and the removal lands on
183
+ * another's subscription.
184
+ *
185
+ * **The predicate and the removal must be ONE operation.** A store that
186
+ * cannot do that atomically should say so in its own documentation rather
187
+ * than implement this as a get-then-delete, which reintroduces the race this
188
+ * method exists to remove. Both shipped stores manage it: the in-memory one
189
+ * because a `Map` check-and-delete has no await between the two, and the D1
190
+ * one with a single `DELETE … WHERE id = ? AND user_id = ? RETURNING id`.
191
+ *
192
+ * `userId` is `null` for an anonymous subscription, and matches only a row
193
+ * that is itself unowned.
194
+ * @param id The subscription id.
195
+ * @param userId The owner the row must carry, or `null` for unowned.
196
+ * @returns `true` when a row was removed.
197
+ */
198
+ deleteOwned: (id: string, userId: string | null) => Promise<boolean>;
141
199
  /** Read a subscription by id, or `undefined`. */
142
200
  get: (id: string) => Promise<StoredSubscription | undefined>;
143
201
  /**
@@ -150,7 +208,33 @@ interface SubscriptionStore {
150
208
  list: (filter?: SubscriptionFilter) => Promise<StoredSubscription[]>;
151
209
  /** Record the latest delivery outcome for a subscription (best-effort). */
152
210
  markStatus: (id: string, status: SubscriptionStatus, error?: string) => Promise<void>;
153
- /** Insert or update a subscription (upsert by id). */
211
+ /**
212
+ * Insert or update a subscription (upsert by id), refusing to move an
213
+ * existing row to a DIFFERENT owner.
214
+ *
215
+ * The ownership predicate is the same one {@link SubscriptionStore.deleteOwned}
216
+ * carries, and for the same reason: the id is derived from the endpoint or the
217
+ * FCM token, so it is a **caller-controlled key**. An unguarded upsert let any
218
+ * caller who could guess or observe another user's endpoint re-register it
219
+ * under their own `userId` with keys of their choosing — the victim's device
220
+ * then fails every send (an encryption failure is not a gone signal, so it is
221
+ * never pruned either) and the attacker can `unregister` it as their own. The
222
+ * `unregister` guard alone closed exactly half of that (CWE-639).
223
+ *
224
+ * A row with no owner is claimable (the device signed in), and a row the caller
225
+ * already owns is theirs to refresh — that is the routine service-worker
226
+ * re-registration. Anything else must REJECT (`FORBIDDEN`), not silently
227
+ * no-op: unlike `unregister` there is nothing safe to return, since a caller
228
+ * gets the stored record back and it would be someone else's delivery keys.
229
+ * A shared device that legitimately changes hands is handled by its current
230
+ * owner calling `unregister` first.
231
+ *
232
+ * **The predicate and the write must be ONE operation**, as for `deleteOwned`:
233
+ * between a read that checks the owner and the write that acts on it, another
234
+ * registration can replace the row. The D1 store puts the predicate in the
235
+ * `ON CONFLICT … DO UPDATE`'s own `WHERE`; the in-memory one has no `await`
236
+ * between the two.
237
+ */
154
238
  put: (subscription: StoredSubscription) => Promise<StoredSubscription>;
155
239
  }
156
240
  /** Per-recipient outcome from a fan-out `broadcast`. */
@@ -194,7 +278,7 @@ interface BroadcastPageResult {
194
278
  *
195
279
  * - `accepted` — the provider took the message (a `Receipt.successful` send).
196
280
  * - `failed` — a provider error; the log line carries the `error` text.
197
- * - `gone` — the endpoint is unregistered (404/410, FCM `UNREGISTERED`) and pruned; push-only.
281
+ * - `gone` — the endpoint is unregistered (Web Push 404/410, FCM's `NOT_FOUND` for a dead token) and pruned; push-only.
198
282
  *
199
283
  * Web Push and FCM give no delivery/open receipts, so the vocabulary stops at the
200
284
  * send attempt: a `delivered`/`opened` status would be a lie for these channels.
@@ -239,26 +323,28 @@ interface LunoraPush {
239
323
  /**
240
324
  * Fan-out a push to every stored subscription matching `filter` (default: all).
241
325
  * Reuses the engine's retry/circuit-breaker middleware; prunes subscriptions
242
- * the push service reports as gone (HTTP 404/410, FCM `UNREGISTERED`). The `to`
326
+ * the push service reports as gone (Web Push 404/410, FCM's `NOT_FOUND` for a dead token). The `to`
243
327
  * target is derived from each subscription, so it is omitted from the payload.
244
328
  *
245
329
  * Internally walks the audience in bounded pages (via {@link LunoraPush.broadcastPage},
246
- * keyset-paginated on the subscription `id`) so a huge audience is never
247
- * materialized wholesale in the isolate — see `CreateNotifyOptions`'s
248
- * `broadcastPageSize`. This call still processes the WHOLE matched
249
- * audience in one request/queue message; use {@link LunoraPush.broadcastPage}
250
- * directly (as `runPushBroadcastJob` does) to bound a single queue message
251
- * to one page.
330
+ * keyset-paginated on the subscription `id`) so the audience ROWS are never
331
+ * materialized wholesale in the isolate — see `defineNotify`'s
332
+ * `broadcastPageSize`. The returned `outcomes` ARE whole-audience, though: one
333
+ * `{ id, status }` per recipient accumulates across every page, so this call is
334
+ * bounded in rows held but not in outcomes reported. It also processes the WHOLE
335
+ * matched audience in one request/queue message; use {@link LunoraPush.broadcastPage}
336
+ * directly (as `runPushBroadcastPage` does) to bound a single queue message —
337
+ * and its result — to one page.
252
338
  */
253
339
  broadcast: (payload: PushContent, filter?: SubscriptionFilter) => Promise<BroadcastResult>;
254
340
  /**
255
341
  * Fan-out a push to ONE bounded page of stored subscriptions matching
256
- * `filter` (page size: `CreateNotifyOptions`'s `broadcastPageSize`, default
342
+ * `filter` (page size: `defineNotify`'s `broadcastPageSize`, default
257
343
  * 250, capped by `filter.limit` when set). Same delivery semantics as
258
344
  * {@link LunoraPush.broadcast} (retry/circuit-breaker, gone-pruning) but
259
345
  * scoped to a single page; returns the page's own {@link BroadcastResult}
260
346
  * plus a `nextCursor` to fetch the next page (`undefined` when done).
261
- * Backs `runPushBroadcastJob` so one queue message does bounded work
347
+ * Backs `runPushBroadcastPage` so one queue message does bounded work
262
348
  * regardless of audience size — most app code should call
263
349
  * {@link LunoraPush.broadcast} instead.
264
350
  */
@@ -267,18 +353,66 @@ interface LunoraPush {
267
353
  * List stored subscriptions (optionally filtered), with the delivery
268
354
  * **secrets** stripped — the Web Push `keys` (RFC 8291 `auth`/`p256dh`) and the
269
355
  * FCM `token`. Those, plus the endpoint, are enough to deliver arbitrary push to
270
- * a device, so they never cross the app-facing facade; the raw rows are
356
+ * a device, so no READ on this facade returns them; the raw rows are otherwise
271
357
  * reachable only through the internal `SubscriptionStore`.
358
+ *
359
+ * {@link LunoraPush.register} is the one exception, and deliberately so: it
360
+ * echoes back the record the caller just supplied, so it discloses nothing
361
+ * the caller did not already hold and never another device's row.
272
362
  */
273
363
  list: (filter?: SubscriptionFilter) => Promise<PushSubscriptionDevice[]>;
274
- /** Register (upsert) a device subscription and return the stored record. */
364
+ /**
365
+ * Register (upsert) a device subscription and return the stored record (the
366
+ * caller's own row, secrets included).
367
+ *
368
+ * Owner-scoped, exactly as {@link LunoraPush.unregister} is: registering an
369
+ * endpoint that is already another user's row is REFUSED (`FORBIDDEN`) rather
370
+ * than re-owning it. Pass `ctx.auth?.userId` so the check has something to
371
+ * separate; an app that registers every device anonymously gets no separation
372
+ * from it (every row is unowned, and unowned rows stay claimable). A device
373
+ * that legitimately changes hands — one browser profile, two accounts —
374
+ * unregisters as its current owner first.
375
+ */
275
376
  register: (input: RegisterInput) => Promise<StoredSubscription>;
276
377
  /** Send a push to a single stored subscription (by id or record); `to` is derived from it. */
277
378
  send: (target: StoredSubscription | string, payload: PushContent) => Promise<Receipt>;
278
- /** Remove a subscription by id (idempotent). */
279
- unregister: (id: string) => Promise<void>;
379
+ /**
380
+ * Remove ONE of `owner`'s subscriptions by id (idempotent).
381
+ *
382
+ * `owner` is not optional, and the removal happens only when the stored row
383
+ * carries that same owner. A subscription id is derived from the endpoint
384
+ * (`webPushId`) or the FCM token, so it is a **caller-controlled key**: the
385
+ * intended call is a mutation forwarding `subscribeToPush`'s
386
+ * `replacedEndpoint` after a VAPID rotation, and nothing about that argument
387
+ * proves the browser sending it ever held the subscription it names.
388
+ * Deleting by id alone let any caller that could guess or observe another
389
+ * user's endpoint silence that device's notifications (CWE-639).
390
+ *
391
+ * A row belonging to someone else is left alone SILENTLY rather than
392
+ * refused, so the call cannot be used to probe which endpoints exist — the
393
+ * same answer, and the same absence of a write, as an id that was never
394
+ * registered.
395
+ *
396
+ * `{ userId: null }` (or `undefined`, which normalises to it) addresses the
397
+ * anonymous rows — those registered with no `userId`. An app that registers
398
+ * every device anonymously therefore gets no separation from this check;
399
+ * pass `ctx.auth?.userId` and register with it to get any.
400
+ */
401
+ unregister: (id: string, owner: PushOwner) => Promise<void>;
402
+ }
403
+ /** Who a {@link LunoraPush.unregister} call is acting as. */
404
+ interface PushOwner {
405
+ /**
406
+ * The authenticated caller (`ctx.auth?.userId`), or `null`/`undefined` for
407
+ * an anonymous registration. Required — see {@link LunoraPush.unregister}.
408
+ */
409
+ userId: string | null | undefined;
280
410
  }
281
- /** A push payload without its `to` target — the facade derives `to` from the stored subscription. */
411
+ /**
412
+ * A push payload without its `to` target — the facade derives `to` from the
413
+ * stored subscription. Its `ttl` / `urgency` override the channel defaults per
414
+ * message on every push transport (Web Push, FCM, APNs, Expo).
415
+ */
282
416
  type PushContent = Omit<PushPayload, "to">;
283
417
  /**
284
418
  * The multi-channel notification facade — spliced onto ctx as `ctx.notify`.
@@ -287,7 +421,7 @@ type PushContent = Omit<PushPayload, "to">;
287
421
  * single-channel convenience senders for the edge-safe channels.
288
422
  */
289
423
  interface LunoraNotify {
290
- /** Send an outbound webhook. */
424
+ /** Post to a chat channel (Slack/Discord/Teams/Telegram). */
291
425
  chat: (payload: ChatPayload) => Promise<Receipt>;
292
426
  /** Deliver an in-app inbox notification. */
293
427
  inApp: (payload: InAppPayload) => Promise<Receipt>;
@@ -295,7 +429,7 @@ interface LunoraNotify {
295
429
  push: LunoraPush;
296
430
  /** Deliver a multi-channel message (one payload per channel). */
297
431
  send: (message: NotificationMessage) => Promise<Receipt[]>;
298
- /** Post to a chat channel (Slack/Discord/Teams/Telegram). */
432
+ /** Send an outbound webhook. */
299
433
  webhook: (payload: WebhookPayload) => Promise<Receipt>;
300
434
  }
301
435
  /**
@@ -323,11 +457,32 @@ interface NotifyConfig {
323
457
  * wildcards) to hard-pin the boundary and close DNS rebinding.
324
458
  */
325
459
  allowedPushOrigins?: string[];
460
+ /**
461
+ * Page size for `push.broadcast`'s internal keyset pagination over the
462
+ * subscription store (default 250, minimum 1). Each page is fetched,
463
+ * delivered, and counted before the next page's store round trip, so a huge
464
+ * audience is never materialized wholesale in the isolate. Also the
465
+ * per-message bound `push.broadcastPage` (and `runPushBroadcastPage`) uses.
466
+ *
467
+ * Declared here, and not only on `createNotify`'s third argument, because
468
+ * this file is the only handle an app has: the sole production constructor is
469
+ * codegen's fixed `createNotify(definition, env, { log, metrics })`, so a knob
470
+ * that lives only on those options is unsettable by every Lunora app —
471
+ * while {@link SubscriptionFilter.limit}'s own docs point at it as the way to
472
+ * size pages.
473
+ */
474
+ broadcastPageSize?: number;
326
475
  /**
327
476
  * Optional chat provider factory (Slack/Discord/Teams/Telegram). Wire with a
328
477
  * provider from `@visulima/notification/providers/*`. Edge-safe (fetch-based).
329
478
  */
330
479
  chat?: (env: NotifyEnv) => unknown;
480
+ /**
481
+ * Max concurrent sends during a `push.broadcast` (default 10, minimum 1).
482
+ * Same reasoning as {@link NotifyConfig.broadcastPageSize}: this is where an
483
+ * app can reach it.
484
+ */
485
+ concurrency?: number;
331
486
  /** FCM (Firebase Cloud Messaging HTTP v1) config. Edge-safe — supply an OAuth2 token. */
332
487
  fcm?: FcmConfig | FcmConfigFactory;
333
488
  /** Optional in-app inbox provider factory. Edge-safe. */
@@ -364,6 +519,7 @@ declare const WEB_PUSH_ENV_KEYS: {
364
519
  declare const FCM_ENV_KEYS: {
365
520
  readonly accessToken: "FCM_ACCESS_TOKEN";
366
521
  readonly projectId: "FCM_PROJECT_ID";
522
+ readonly serviceAccount: "FCM_SERVICE_ACCOUNT";
367
523
  };
368
524
  /**
369
525
  * Resolve a {@link WebPushConfig} from the Worker `env` VAPID secrets
@@ -376,13 +532,19 @@ declare const FCM_ENV_KEYS: {
376
532
  */
377
533
  declare const webPushFromEnv: (env: NotifyEnv, overrides?: Partial<WebPushConfig>) => WebPushConfig | undefined;
378
534
  /**
379
- * Resolve an {@link FcmConfig} from the Worker `env` (`FCM_PROJECT_ID` plus a
380
- * static `FCM_ACCESS_TOKEN`). Returns `undefined` when the project id is missing.
535
+ * Resolve an {@link FcmConfig} from the Worker `env`.
381
536
  *
382
- * The static token is convenient for local dev but expires; in production prefer
383
- * passing your own `getAccessToken` (e.g. wrapping `google-auth-library`) via
384
- * `defineNotify({ fcm: (env) => ({ ...fcmFromEnv(env), getAccessToken }) })` —
385
- * that keeps the provider edge-safe (no Google SDK / `node:crypto` bundled).
537
+ * Production: `FCM_SERVICE_ACCOUNT` holds the Google service-account key file, as JSON or
538
+ * base64 of it. The access token is minted from it on demand and cached until shortly
539
+ * before it expires, so `defineNotify({ fcm: (env) => fcmFromEnv(env) })` is correct as written.
540
+ * `FCM_PROJECT_ID` overrides the project id in the key file.
541
+ *
542
+ * Dev: a static `FCM_ACCESS_TOKEN` is accepted when no service account is set. It
543
+ * expires within the hour, so it is only a stopgap for local work.
544
+ *
545
+ * Returns `undefined` when no project id can be resolved. A malformed key does not throw
546
+ * here: the token source rejects with the parse error instead, so only FCM sends fail, not
547
+ * the other channels that share this engine.
386
548
  */
387
549
  declare const fcmFromEnv: (env: NotifyEnv, overrides?: Partial<FcmConfig>) => FcmConfig | undefined;
388
550
  /**
@@ -398,7 +560,7 @@ declare const fcmFromEnv: (env: NotifyEnv, overrides?: Partial<FcmConfig>) => Fc
398
560
  *
399
561
  * export default defineNotify({
400
562
  * webPush: (env) => webPushFromEnv(env), // VAPID_* from .dev.vars
401
- * fcm: (env) => fcmFromEnv(env), // FCM_PROJECT_ID / FCM_ACCESS_TOKEN
563
+ * fcm: (env) => fcmFromEnv(env), // FCM_SERVICE_ACCOUNT (+ FCM_PROJECT_ID)
402
564
  * store: (env) => d1SubscriptionStore(env.DB),
403
565
  * });
404
566
  * ```
@@ -416,14 +578,18 @@ interface CreateNotifyOptions {
416
578
  /**
417
579
  * Page size for `push.broadcast`'s internal keyset pagination over the
418
580
  * subscription store (default {@link DEFAULT_BROADCAST_PAGE_SIZE}, 250).
419
- * Each page is fetched, delivered, and counted independently before the
420
- * next page's store round trip, so a huge audience is never materialized
421
- * wholesale in the isolate. Also the per-message bound `push.broadcastPage`
422
- * (and so `runPushBroadcastJob`) uses. A test/tuning seam — most apps never
423
- * need to set this.
581
+ *
582
+ * A test/tuning seam only. **Apps set `broadcastPageSize` on `defineNotify`
583
+ * instead** — the sole production call is codegen's fixed
584
+ * `createNotify(definition, env, { log, metrics })`, so nothing an app writes
585
+ * reaches this object. Set here it wins over the definition's value.
424
586
  */
425
587
  broadcastPageSize?: number;
426
- /** Max concurrent sends during a `broadcast` (default 10). */
588
+ /**
589
+ * Max concurrent sends during a `broadcast` (default 10). Test/tuning seam;
590
+ * apps set `concurrency` on `defineNotify` — see
591
+ * {@link CreateNotifyOptions.broadcastPageSize}.
592
+ */
427
593
  concurrency?: number;
428
594
  /**
429
595
  * Override the assembled `@visulima/notification` engine. Advanced/testing
@@ -467,7 +633,19 @@ declare const createNotify: (definition: NotifyDefinition, env: NotifyEnv, optio
467
633
  };
468
634
  /** Options for {@link routingPushProvider}. */
469
635
  interface RoutingPushOptions {
636
+ /**
637
+ * The definition's exact-origin allowlist, when configured. Its presence
638
+ * disables the send-time rebinding re-check (see {@link assertPushTargetResolvable}).
639
+ */
640
+ allowedPushOrigins?: string[];
470
641
  fcm?: Provider<unknown, PushPayload>;
642
+ /**
643
+ * Backoff base for the in-router group retry, in ms (default 250 — the
644
+ * engine's own). Only a TEST double passes anything else, for the same
645
+ * reason {@link ResilienceOptions.retryBaseDelay} exists: a mock that fails
646
+ * on purpose would otherwise spend the real ~1 s of backoff per partial.
647
+ */
648
+ retryBaseDelay?: number;
471
649
  webPush?: Provider<unknown, PushPayload>;
472
650
  }
473
651
  /**
@@ -480,6 +658,8 @@ interface RoutingPushOptions {
480
658
  declare const routingPushProvider: (options: RoutingPushOptions) => Provider<unknown, PushPayload>;
481
659
  /** A resolved, ready-to-wire set of channel configs (edge-safe channels only). */
482
660
  interface ResolvedProviders {
661
+ /** The definition's `allowedPushOrigins`, threaded to the push router's send-time SSRF guard. */
662
+ allowedPushOrigins?: string[];
483
663
  chat?: Provider;
484
664
  fcm?: FcmConfig;
485
665
  inApp?: Provider;
@@ -498,45 +678,102 @@ declare const buildEngine: (resolved: ResolvedProviders) => Notification;
498
678
  * fan-out. Shaped to travel through a `@lunora/queue` producer/consumer without
499
679
  * `@lunora/notify` depending on `@lunora/queue` (the seam stays structural).
500
680
  * `filter.after`, when set, resumes a broadcast partway through (see
501
- * {@link runPushBroadcastJob}'s continuation semantics).
681
+ * {@link runPushBroadcastPage}'s continuation semantics).
502
682
  */
503
683
  interface PushBroadcastJob {
504
684
  /** Subscription filter (which devices/users to target; `filter.after` resumes a paged broadcast). */
505
685
  filter?: SubscriptionFilter;
506
686
  /** The push payload to deliver (the `to` target is derived per subscription). */
507
687
  payload: PushContent;
688
+ /**
689
+ * Redeliver to exactly these subscription ids instead of walking a page —
690
+ * an earlier page's {@link PushBroadcastPageOutcome.failedIds}. Set by the
691
+ * consumer when it re-enqueues a page's transient failures; `filter` is
692
+ * ignored on such a job. See {@link runPushBroadcastPage}.
693
+ */
694
+ retryIds?: string[];
508
695
  /** Discriminator so a shared queue can multiplex message kinds. */
509
696
  type: "lunora.push.broadcast";
510
697
  }
698
+ /**
699
+ * One page's outcome plus the ids that need redelivering.
700
+ *
701
+ * The consumer MUST act on BOTH fields: `nextFilter` continues the broadcast and
702
+ * `failedIds` redelivers the recipients this page missed. Acking a message while
703
+ * ignoring either silently drops part of the audience.
704
+ */
705
+ interface PushBroadcastPageOutcome {
706
+ /**
707
+ * Subscriptions that failed transiently on this run (gone/pruned devices are
708
+ * NOT here — they are deleted, not retried). Re-enqueue a job carrying these
709
+ * as `retryIds` to redeliver to just them.
710
+ */
711
+ failedIds: string[];
712
+ /**
713
+ * The filter for the CONTINUATION job, or `undefined` when the broadcast is
714
+ * finished (no further pages, or `filter.limit` is spent). Enqueue it
715
+ * verbatim — it carries the next page's cursor AND, when the job set
716
+ * `filter.limit`, the REMAINING budget.
717
+ *
718
+ * This replaces the raw `nextCursor` the runner used to return. Rebuilding
719
+ * the filter at the call site (`{ ...job.filter, after: nextCursor }`)
720
+ * forwarded the ORIGINAL `limit` to every message, so a `limit` documented
721
+ * as an overall audience cap (see {@link SubscriptionFilter.limit}, which
722
+ * `broadcast` honours as one) became a per-message cap and the walk reached
723
+ * the entire audience anyway.
724
+ */
725
+ nextFilter?: SubscriptionFilter;
726
+ /** This page's delivery result. */
727
+ result: BroadcastResult;
728
+ }
511
729
  /** The structural slice of a `@lunora/queue` producer (`ctx.queues.<name>`) used here. */
512
730
  interface QueueProducerLike {
513
731
  send: (body: PushBroadcastJob) => Promise<void>;
514
732
  }
515
733
  /**
516
734
  * Enqueue a fan-out broadcast for background delivery through a `@lunora/queue`
517
- * queue instead of blocking the request. Pair with {@link runPushBroadcastJob} in
735
+ * queue instead of blocking the request. Pair with {@link runPushBroadcastPage} in
518
736
  * the queue consumer — see its doc comment for how a large audience continues
519
737
  * across MULTIPLE messages (one bounded page per message), not one.
520
738
  *
521
739
  * ```ts
522
- * // in a mutation/action:
523
- * await enqueuePushBroadcast(ctx.queues.push, { payload: { title: "New drop", body: "…" } });
740
+ * // lunora/notify-fanout.ts — an INTERNAL ACTION, because that is where
741
+ * // `ctx.push` and `ctx.queues` exist.
742
+ * import { internalAction, v } from "./_generated/server";
743
+ * import { enqueuePushBroadcast, runPushBroadcastPage } from "@lunora/notify";
524
744
  *
525
- * // in lunora/queues.ts consumer:
526
- * export const push = defineQueue({ async handler(batch, ctx) {
527
- * for (const message of batch.messages) {
528
- * const { nextCursor } = await runPushBroadcastJob(ctx.push, message.body);
745
+ * export const deliverPage = internalAction
746
+ * .input({ job: v.any() })
747
+ * .action(async ({ args: { job }, ctx }) => {
748
+ * const { failedIds, nextFilter } = await runPushBroadcastPage(ctx.push, job);
529
749
  *
530
- * if (nextCursor !== undefined) {
750
+ * if (nextFilter !== undefined) {
531
751
  * // More pages remain — enqueue the continuation. Each message still
532
- * // does only ONE bounded page of work.
533
- * await enqueuePushBroadcast(ctx.queues.push, {
534
- * payload: message.body.payload,
535
- * filter: { ...message.body.filter, after: nextCursor },
536
- * });
752
+ * // does only ONE bounded page of work. Pass `nextFilter` VERBATIM:
753
+ * // it carries the cursor and the remaining `limit` budget.
754
+ * await enqueuePushBroadcast(ctx.queues.push, { filter: nextFilter, payload: job.payload });
537
755
  * }
538
- * }
539
- * }});
756
+ *
757
+ * if (failedIds.length > 0) {
758
+ * // Redeliver ONLY the recipients that failed — never the whole page.
759
+ * await enqueuePushBroadcast(ctx.queues.push, { payload: job.payload, retryIds: failedIds });
760
+ * }
761
+ * });
762
+ *
763
+ * // lunora/queues.ts — the consumer itself has NO ctx.push / ctx.queues: a
764
+ * // `QueueRunContext` is exactly `{ env, log, run }` (handler signature
765
+ * // `(context, batch)`, in that order). It hands each message to the action above.
766
+ * export const push = defineQueue<PushBroadcastJob>({
767
+ * handler: async (context, batch) => {
768
+ * for (const message of batch.messages) {
769
+ * await message.run(internal.notifyFanout.deliverPage, { job: message.body });
770
+ * message.ack();
771
+ * }
772
+ * },
773
+ * });
774
+ *
775
+ * // in a mutation/action, to start it:
776
+ * await enqueuePushBroadcast(ctx.queues.push, { payload: { body: "…", title: "New drop" } });
540
777
  * ```
541
778
  */
542
779
  declare const enqueuePushBroadcast: (queue: QueueProducerLike, job: Omit<PushBroadcastJob, "type">) => Promise<void>;
@@ -546,43 +783,48 @@ declare const enqueuePushBroadcast: (queue: QueueProducerLike, job: Omit<PushBro
546
783
  * reuses the engine's retry + circuit-breaker middleware and prunes gone
547
784
  * subscriptions).
548
785
  *
549
- * RETRY / CONTINUATION SEMANTICS (rewritten for plan 222 / NOTIFY-01 — a
550
- * broadcast job used to process the WHOLE audience in one message, which could
551
- * exceed Worker CPU/wall limits for a large audience and made a retry re-run
552
- * everything):
786
+ * RETRY / CONTINUATION SEMANTICS:
553
787
  *
554
- * - A job now processes exactly ONE bounded page (see `CreateNotifyOptions`'s
555
- * page-size option, default 250, or `job.filter.limit` when smaller),
788
+ * - A job processes exactly ONE bounded page (see `defineNotify`'s
789
+ * `broadcastPageSize`, default 250, or `job.filter.limit` when smaller),
556
790
  * keyset-paginated on the subscription `id` (see `SubscriptionFilter.after`)
557
791
  * — so per-message work is bounded regardless of total audience size.
558
- * - Retry is still gated on `result.failed` — the count of TRANSIENT delivery
559
- * errors (a provider 5xx / network fault worth another attempt). When at
560
- * least one recipient in THIS PAGE `failed`, the job is RE-THROWN so the
561
- * queue does NOT ack it and its normal retry/backoff (and, on exhaustion,
562
- * dead-letter) applies — to just this page, not the whole broadcast.
563
- * - A page with zero `failed` resolves and is acked — this includes the
564
- * all-`pruned` case (every device on the page had unsubscribed:
565
- * `sent:0`, `failed:0`, `pruned:N`), which is a SUCCESSFUL prune, not a
566
- * failure, so throwing on it would spuriously retry and pressure the DLQ;
567
- * and the empty-page case (zero `total`), which has nothing to retry.
568
- * - The returned `nextCursor` is set when more pages remain. `@lunora/notify`
569
- * does NOT enqueue the continuation itself — it has no `@lunora/queue`
570
- * dependency (the seam stays structural) and no reference to the producer
571
- * that enqueued this message — so the CALLER (the `lunora/queues.ts`
572
- * consumer) is responsible for re-enqueueing with `filter.after: nextCursor`
573
- * when present. See the consumer example on {@link enqueuePushBroadcast}.
574
- * - A retry of a page redelivers only that page's already-delivered recipients
575
- * on a transient partial failure (a page is not individually idempotent) —
576
- * the accepted cost of getting the transiently failed ones redelivered, now
577
- * scoped to one page instead of the whole broadcast.
578
- */
579
- declare const runPushBroadcastJob: (push: LunoraPush, job: PushBroadcastJob) => Promise<BroadcastPageResult>;
792
+ * - A page NEVER throws for a partial failure. Throwing discarded the page's
793
+ * continuation, which is the only way the broadcast advances: one device that
794
+ * fails permanently (a rotated VAPID keypair leaves a stale device answering
795
+ * `403 VapidPkHashMismatch` forever) would then stall the cursor, re-POST
796
+ * every already-delivered recipient on each retry, dead-letter, and leave
797
+ * every LATER page unreached. The page's `nextFilter` and its `failedIds`
798
+ * both come back instead.
799
+ * - The CALLER re-enqueues: `filter: nextFilter` while more pages remain, and a
800
+ * `retryIds: failedIds` job when any recipient failed. `@lunora/notify` cannot
801
+ * do it itself — it has no `@lunora/queue` dependency (the seam stays
802
+ * structural) and no reference to the producer that enqueued this message. See
803
+ * the consumer example on {@link enqueuePushBroadcast}.
804
+ * - `job.filter.limit` is spent across messages, not re-granted to each one:
805
+ * `nextFilter` carries the REMAINING budget and is `undefined` once it runs
806
+ * out, so `limit` caps the whole audience here exactly as it does on
807
+ * {@link LunoraPush.broadcast}.
808
+ * - A `retryIds` job redelivers to exactly those ids and throws only while ALL
809
+ * of them still fail, so the queue's backoff/dead-letter bounds a device that
810
+ * never recovers. Once any recipient recovers the run resolves and reports the
811
+ * rest in `failedIds`, so the narrower retry never re-sends to a device this
812
+ * message already reached. A recipient that turns out to be GONE — a 404/410
813
+ * receipt, or an id whose row no longer exists at all — counts as `pruned` here
814
+ * too, never as a failure: there is nothing left to redeliver to, so retrying it
815
+ * could only burn the queue's budget and dead-letter an unsubscribe.
816
+ * - Gone subscriptions (Web Push 404/410, FCM's `NOT_FOUND` for a dead token) are pruned by the page and
817
+ * never appear in `failedIds` — an all-`pruned` page is a success, not a
818
+ * failure, as is an empty page.
819
+ */
820
+ declare const runPushBroadcastPage: (push: LunoraPush, job: PushBroadcastJob) => Promise<PushBroadcastPageOutcome>;
580
821
  /**
581
822
  * The minimal structural slice of Cloudflare's `D1Database` this store uses. A
582
823
  * structural type (rather than importing `@cloudflare/workers-types`) keeps the
583
824
  * store runtime-agnostic and trivially fakeable in tests.
584
825
  */
585
826
  interface D1Like {
827
+ batch: (statements: D1PreparedLike[]) => Promise<unknown>;
586
828
  prepare: (query: string) => D1PreparedLike;
587
829
  }
588
830
  interface D1PreparedLike {
@@ -598,27 +840,6 @@ interface D1StoreOptions {
598
840
  /** Table name (default `lunora_push_subscriptions`). Must be a bare identifier. */
599
841
  tableName?: string;
600
842
  }
601
- /**
602
- * A D1-backed {@link SubscriptionStore}. Edge-safe (D1 is a Worker binding). The
603
- * backing table is created lazily on first use (`CREATE TABLE IF NOT EXISTS`), so
604
- * no migration step is required for the subscription table itself.
605
- *
606
- * ID SCHEME / LAZY MIGRATION: `id` (the `PRIMARY KEY`, upserted via `ON
607
- * CONFLICT(id) DO UPDATE`) is a version-prefixed digest of the endpoint/token —
608
- * currently `wp2_`/`fcm2_` (64-bit FNV-1a; see `normalize.ts`). No table migration
609
- * runs when the id scheme is revised: a returning device re-registers under its new
610
- * id and upserts a fresh row, while its old-prefix row (`wp_`/`fcm_`) ages out via
611
- * the normal gone-pruning on the next failed send. So a table can transiently hold
612
- * both an old- and new-prefix row for one device — expected, self-healing, and the
613
- * reason a prefix must NEVER be reused for a different scheme.
614
- *
615
- * ```ts
616
- * export default defineNotify({
617
- * webPush: (env) => webPushFromEnv(env),
618
- * store: (env) => d1SubscriptionStore(env.DB),
619
- * });
620
- * ```
621
- */
622
843
  declare const d1SubscriptionStore: (database: D1Like, options?: D1StoreOptions) => SubscriptionStore;
623
844
  /**
624
845
  * An in-memory {@link SubscriptionStore} — the zero-dependency default. Suitable
@@ -628,7 +849,21 @@ declare const d1SubscriptionStore: (database: D1Like, options?: D1StoreOptions)
628
849
  */
629
850
  declare const memorySubscriptionStore: () => SubscriptionStore;
630
851
  /**
631
- * Stable store id for a web-push endpoint.
852
+ * Stable store id for a web-push endpoint — `fnv1a64Hex` of the (long) endpoint,
853
+ * so re-registering the same device upserts rather than duplicates.
854
+ *
855
+ * The digest comes from the canonical `shared/fnv1a`, not a local copy. This id
856
+ * is a PERSISTED primary key: a digest that drifts in one copy silently re-keys
857
+ * every existing subscription — the old row goes dark and the device
858
+ * re-registers as a duplicate — so the implementation must have exactly one
859
+ * home. `shared/fnv1a`'s is bit-verified against a BigInt reference in
860
+ * `packages/replica/__tests__/apply-diff.test.ts`.
861
+ *
862
+ * Widened from the previous 32-bit FNV-1a (8 hex): at 100K devices a 32-bit key
863
+ * collides with ~68% probability (birthday bound), and a collision silently
864
+ * overwrites another device's row under the store's `ON CONFLICT(id) DO UPDATE` —
865
+ * so the wrong user gets the push and the victim goes dark. 64 bits drops that to
866
+ * negligible at any realistic device count.
632
867
  *
633
868
  * The `wp2_` prefix is a version tag (see also {@link fcmId}'s `fcm2_`): it marks
634
869
  * the 64-bit-id revision so the pre-existing 32-bit `wp_` rows stay readable and a
@@ -649,9 +884,10 @@ interface NormalizeOptions {
649
884
  *
650
885
  * When unset, the default posture applies: `https:` scheme + a host the
651
886
  * {@link assertPushEndpoint} STRING classifier does not flag as
652
- * private/loopback. That classifier does NOT resolve DNS, so a public hostname
653
- * resolving to a private/internal IP (e.g. `https://127.0.0.1.nip.io/…`) is NOT
654
- * blocked by it — set this allowlist to close that gap.
887
+ * private/loopback, plus a resolved-address re-check at send time. Setting
888
+ * this allowlist replaces both with an exact-origin match — the hard
889
+ * guarantee, and the only one that also covers an internal push service you
890
+ * deliberately want to reach.
655
891
  */
656
892
  allowedPushOrigins?: string[];
657
893
  }
@@ -674,11 +910,97 @@ declare const targetOf: (subscription: StoredSubscription) => string;
674
910
  * (the browser/device unsubscribed) and should be pruned — as opposed to a
675
911
  * transient failure worth retrying.
676
912
  *
677
- * Gates on STRUCTURED signals first: a Web Push `HTTP 404/410` status or an FCM
678
- * `UNREGISTERED`/`NOT_REGISTERED` code, both of which the providers surface in
679
- * their failure receipts. The free-text {@link GONE_TEXT_FALLBACK} is a tightened
680
- * last resort only, so a transient error that happens to contain `expired`
681
- * (a cert/session expiry) can never permanently drop a valid subscription.
913
+ * Gates on STRUCTURED signals first: an `HTTP 404/410` status (both providers
914
+ * answer one for a dead endpoint/token, though FCM's is usually replaced by its
915
+ * error body before it reaches here) or, for FCM only, an
916
+ * `UNREGISTERED`/`NOT_REGISTERED` code or the `NOT_FOUND` prose that is the one
917
+ * signal its provider actually forwards (see {@link FCM_GONE_PATTERN}). The
918
+ * free-text {@link GONE_TEXT_FALLBACK} is a tightened last resort only, so a
919
+ * transient error that happens to contain `expired` (a cert/session expiry) can
920
+ * never permanently drop a valid subscription.
921
+ *
922
+ * `kind` scopes the PROVIDER-SPECIFIC patterns to the provider that emits them.
923
+ * The web-push provider echoes the push service's response body into
924
+ * `HTTP ${status}: ${body}`, so a 4xx whose prose merely contains "not
925
+ * registered" matched the FCM-only codes and permanently deleted a live
926
+ * subscription. Omit `kind` (the third-party/unknown-provider case) to test
927
+ * every pattern, as before.
928
+ */
929
+ declare const isGoneError: (message: string | undefined, kind?: StoredSubscription["kind"]) => boolean;
930
+ export { type BroadcastOutcome, type BroadcastResult, type CreateNotifyOptions, type D1Like, type D1PreparedLike, type D1StoreOptions,
931
+ /**
932
+ * `@lunora/notify`
933
+ *
934
+ * Multi-channel notifications for Lunora, wrapping the `@visulima/notification`
935
+ * engine. `defineNotify` in `lunora/notify.ts` configures the edge-safe channels
936
+ * (Web Push + FCM, plus chat / in-app inbox / webhook); codegen wires `ctx.notify`
937
+ * and its `ctx.push` alias onto every handler ctx from it (mirroring `defineFlags`
938
+ * → `ctx.flags`).
939
+ *
940
+ * Edge-safety: Web Push (VAPID + RFC 8291) and FCM (HTTP v1) run on `fetch` + Web
941
+ * Crypto under workerd. APNs (`node:http2`) and SMS / Node-only queue adapters are
942
+ * deliberately **not** on the edge facade — route heavy fan-out through
943
+ * `@lunora/queue` (`enqueuePushBroadcast` / `runPushBroadcastPage`).
944
+ *
945
+ * - `@lunora/notify` — `defineNotify`, `createNotify`, config resolvers, subscription stores and types.
946
+ * - `@lunora/notify/web` — the browser `subscribeToPush` service-worker helper.
947
+ * @packageDocumentation
948
+ */
949
+ FCM_ENV_KEYS, type FcmConfigFactory, type LunoraNotify, type LunoraPush, type NotifyConfig, type NotifyDefinition, type NotifyDeliveryStatus, type NotifyEnv, type NotifyLogger, type NotifyMetrics, type NotifySkipReason, type PushBroadcastJob, type PushBroadcastPageOutcome, type PushOwner, type PushSubscriptionDevice, type PushSubscriptionsResult, type QueueProducerLike, type RegisterInput, type ResolvedProviders, type RoutingPushOptions, type StoredSubscription, type SubscriptionFilter, type SubscriptionKind, type SubscriptionOutcomes, type SubscriptionStatus, type SubscriptionStore,
950
+ /**
951
+ * `@lunora/notify`
952
+ *
953
+ * Multi-channel notifications for Lunora, wrapping the `@visulima/notification`
954
+ * engine. `defineNotify` in `lunora/notify.ts` configures the edge-safe channels
955
+ * (Web Push + FCM, plus chat / in-app inbox / webhook); codegen wires `ctx.notify`
956
+ * and its `ctx.push` alias onto every handler ctx from it (mirroring `defineFlags`
957
+ * → `ctx.flags`).
958
+ *
959
+ * Edge-safety: Web Push (VAPID + RFC 8291) and FCM (HTTP v1) run on `fetch` + Web
960
+ * Crypto under workerd. APNs (`node:http2`) and SMS / Node-only queue adapters are
961
+ * deliberately **not** on the edge facade — route heavy fan-out through
962
+ * `@lunora/queue` (`enqueuePushBroadcast` / `runPushBroadcastPage`).
963
+ *
964
+ * - `@lunora/notify` — `defineNotify`, `createNotify`, config resolvers, subscription stores and types.
965
+ * - `@lunora/notify/web` — the browser `subscribeToPush` service-worker helper.
966
+ * @packageDocumentation
967
+ */
968
+ WEB_PUSH_ENV_KEYS, type WebPushConfigFactory, buildEngine, createNotify, d1SubscriptionStore, defineNotify, enqueuePushBroadcast,
969
+ /**
970
+ * `@lunora/notify`
971
+ *
972
+ * Multi-channel notifications for Lunora, wrapping the `@visulima/notification`
973
+ * engine. `defineNotify` in `lunora/notify.ts` configures the edge-safe channels
974
+ * (Web Push + FCM, plus chat / in-app inbox / webhook); codegen wires `ctx.notify`
975
+ * and its `ctx.push` alias onto every handler ctx from it (mirroring `defineFlags`
976
+ * → `ctx.flags`).
977
+ *
978
+ * Edge-safety: Web Push (VAPID + RFC 8291) and FCM (HTTP v1) run on `fetch` + Web
979
+ * Crypto under workerd. APNs (`node:http2`) and SMS / Node-only queue adapters are
980
+ * deliberately **not** on the edge facade — route heavy fan-out through
981
+ * `@lunora/queue` (`enqueuePushBroadcast` / `runPushBroadcastPage`).
982
+ *
983
+ * - `@lunora/notify` — `defineNotify`, `createNotify`, config resolvers, subscription stores and types.
984
+ * - `@lunora/notify/web` — the browser `subscribeToPush` service-worker helper.
985
+ * @packageDocumentation
986
+ */
987
+ fcmFromEnv, fcmId, isGoneError, isNotifyDefinition, memorySubscriptionStore, normalizeRegisterInput, routingPushProvider, runPushBroadcastPage, targetOf,
988
+ /**
989
+ * `@lunora/notify`
990
+ *
991
+ * Multi-channel notifications for Lunora, wrapping the `@visulima/notification`
992
+ * engine. `defineNotify` in `lunora/notify.ts` configures the edge-safe channels
993
+ * (Web Push + FCM, plus chat / in-app inbox / webhook); codegen wires `ctx.notify`
994
+ * and its `ctx.push` alias onto every handler ctx from it (mirroring `defineFlags`
995
+ * → `ctx.flags`).
996
+ *
997
+ * Edge-safety: Web Push (VAPID + RFC 8291) and FCM (HTTP v1) run on `fetch` + Web
998
+ * Crypto under workerd. APNs (`node:http2`) and SMS / Node-only queue adapters are
999
+ * deliberately **not** on the edge facade — route heavy fan-out through
1000
+ * `@lunora/queue` (`enqueuePushBroadcast` / `runPushBroadcastPage`).
1001
+ *
1002
+ * - `@lunora/notify` — `defineNotify`, `createNotify`, config resolvers, subscription stores and types.
1003
+ * - `@lunora/notify/web` — the browser `subscribeToPush` service-worker helper.
1004
+ * @packageDocumentation
682
1005
  */
683
- declare const isGoneError: (message: string | undefined) => boolean;
684
- export { type BroadcastOutcome, type BroadcastResult, type CreateNotifyOptions, type D1Like, type D1PreparedLike, type D1StoreOptions, FCM_ENV_KEYS, type FcmConfigFactory, type LunoraNotify, type LunoraPush, type NotifyConfig, type NotifyDefinition, type NotifyDeliveryStatus, type NotifyEnv, type NotifyLogger, type NotifyMetrics, type NotifySkipReason, type PushBroadcastJob, type PushSubscriptionDevice, type PushSubscriptionsResult, type QueueProducerLike, type RegisterInput, type ResolvedProviders, type RoutingPushOptions, type StoredSubscription, type SubscriptionFilter, type SubscriptionKind, type SubscriptionStatus, type SubscriptionStore, WEB_PUSH_ENV_KEYS, type WebPushConfigFactory, buildEngine, createNotify, d1SubscriptionStore, defineNotify, enqueuePushBroadcast, fcmFromEnv, fcmId, isGoneError, isNotifyDefinition, memorySubscriptionStore, normalizeRegisterInput, routingPushProvider, runPushBroadcastJob, targetOf, webPushFromEnv, webPushId };
1006
+ webPushFromEnv, webPushId };