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

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.mts 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. */
@@ -416,14 +571,18 @@ interface CreateNotifyOptions {
416
571
  /**
417
572
  * Page size for `push.broadcast`'s internal keyset pagination over the
418
573
  * 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.
574
+ *
575
+ * A test/tuning seam only. **Apps set `broadcastPageSize` on `defineNotify`
576
+ * instead** — the sole production call is codegen's fixed
577
+ * `createNotify(definition, env, { log, metrics })`, so nothing an app writes
578
+ * reaches this object. Set here it wins over the definition's value.
424
579
  */
425
580
  broadcastPageSize?: number;
426
- /** Max concurrent sends during a `broadcast` (default 10). */
581
+ /**
582
+ * Max concurrent sends during a `broadcast` (default 10). Test/tuning seam;
583
+ * apps set `concurrency` on `defineNotify` — see
584
+ * {@link CreateNotifyOptions.broadcastPageSize}.
585
+ */
427
586
  concurrency?: number;
428
587
  /**
429
588
  * Override the assembled `@visulima/notification` engine. Advanced/testing
@@ -467,7 +626,19 @@ declare const createNotify: (definition: NotifyDefinition, env: NotifyEnv, optio
467
626
  };
468
627
  /** Options for {@link routingPushProvider}. */
469
628
  interface RoutingPushOptions {
629
+ /**
630
+ * The definition's exact-origin allowlist, when configured. Its presence
631
+ * disables the send-time rebinding re-check (see {@link assertPushTargetResolvable}).
632
+ */
633
+ allowedPushOrigins?: string[];
470
634
  fcm?: Provider<unknown, PushPayload>;
635
+ /**
636
+ * Backoff base for the in-router group retry, in ms (default 250 — the
637
+ * engine's own). Only a TEST double passes anything else, for the same
638
+ * reason {@link ResilienceOptions.retryBaseDelay} exists: a mock that fails
639
+ * on purpose would otherwise spend the real ~1 s of backoff per partial.
640
+ */
641
+ retryBaseDelay?: number;
471
642
  webPush?: Provider<unknown, PushPayload>;
472
643
  }
473
644
  /**
@@ -480,6 +651,8 @@ interface RoutingPushOptions {
480
651
  declare const routingPushProvider: (options: RoutingPushOptions) => Provider<unknown, PushPayload>;
481
652
  /** A resolved, ready-to-wire set of channel configs (edge-safe channels only). */
482
653
  interface ResolvedProviders {
654
+ /** The definition's `allowedPushOrigins`, threaded to the push router's send-time SSRF guard. */
655
+ allowedPushOrigins?: string[];
483
656
  chat?: Provider;
484
657
  fcm?: FcmConfig;
485
658
  inApp?: Provider;
@@ -498,45 +671,102 @@ declare const buildEngine: (resolved: ResolvedProviders) => Notification;
498
671
  * fan-out. Shaped to travel through a `@lunora/queue` producer/consumer without
499
672
  * `@lunora/notify` depending on `@lunora/queue` (the seam stays structural).
500
673
  * `filter.after`, when set, resumes a broadcast partway through (see
501
- * {@link runPushBroadcastJob}'s continuation semantics).
674
+ * {@link runPushBroadcastPage}'s continuation semantics).
502
675
  */
503
676
  interface PushBroadcastJob {
504
677
  /** Subscription filter (which devices/users to target; `filter.after` resumes a paged broadcast). */
505
678
  filter?: SubscriptionFilter;
506
679
  /** The push payload to deliver (the `to` target is derived per subscription). */
507
680
  payload: PushContent;
681
+ /**
682
+ * Redeliver to exactly these subscription ids instead of walking a page —
683
+ * an earlier page's {@link PushBroadcastPageOutcome.failedIds}. Set by the
684
+ * consumer when it re-enqueues a page's transient failures; `filter` is
685
+ * ignored on such a job. See {@link runPushBroadcastPage}.
686
+ */
687
+ retryIds?: string[];
508
688
  /** Discriminator so a shared queue can multiplex message kinds. */
509
689
  type: "lunora.push.broadcast";
510
690
  }
691
+ /**
692
+ * One page's outcome plus the ids that need redelivering.
693
+ *
694
+ * The consumer MUST act on BOTH fields: `nextFilter` continues the broadcast and
695
+ * `failedIds` redelivers the recipients this page missed. Acking a message while
696
+ * ignoring either silently drops part of the audience.
697
+ */
698
+ interface PushBroadcastPageOutcome {
699
+ /**
700
+ * Subscriptions that failed transiently on this run (gone/pruned devices are
701
+ * NOT here — they are deleted, not retried). Re-enqueue a job carrying these
702
+ * as `retryIds` to redeliver to just them.
703
+ */
704
+ failedIds: string[];
705
+ /**
706
+ * The filter for the CONTINUATION job, or `undefined` when the broadcast is
707
+ * finished (no further pages, or `filter.limit` is spent). Enqueue it
708
+ * verbatim — it carries the next page's cursor AND, when the job set
709
+ * `filter.limit`, the REMAINING budget.
710
+ *
711
+ * This replaces the raw `nextCursor` the runner used to return. Rebuilding
712
+ * the filter at the call site (`{ ...job.filter, after: nextCursor }`)
713
+ * forwarded the ORIGINAL `limit` to every message, so a `limit` documented
714
+ * as an overall audience cap (see {@link SubscriptionFilter.limit}, which
715
+ * `broadcast` honours as one) became a per-message cap and the walk reached
716
+ * the entire audience anyway.
717
+ */
718
+ nextFilter?: SubscriptionFilter;
719
+ /** This page's delivery result. */
720
+ result: BroadcastResult;
721
+ }
511
722
  /** The structural slice of a `@lunora/queue` producer (`ctx.queues.<name>`) used here. */
512
723
  interface QueueProducerLike {
513
724
  send: (body: PushBroadcastJob) => Promise<void>;
514
725
  }
515
726
  /**
516
727
  * Enqueue a fan-out broadcast for background delivery through a `@lunora/queue`
517
- * queue instead of blocking the request. Pair with {@link runPushBroadcastJob} in
728
+ * queue instead of blocking the request. Pair with {@link runPushBroadcastPage} in
518
729
  * the queue consumer — see its doc comment for how a large audience continues
519
730
  * across MULTIPLE messages (one bounded page per message), not one.
520
731
  *
521
732
  * ```ts
522
- * // in a mutation/action:
523
- * await enqueuePushBroadcast(ctx.queues.push, { payload: { title: "New drop", body: "…" } });
733
+ * // lunora/notify-fanout.ts — an INTERNAL ACTION, because that is where
734
+ * // `ctx.push` and `ctx.queues` exist.
735
+ * import { internalAction, v } from "./_generated/server";
736
+ * import { enqueuePushBroadcast, runPushBroadcastPage } from "@lunora/notify";
524
737
  *
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);
738
+ * export const deliverPage = internalAction
739
+ * .input({ job: v.any() })
740
+ * .action(async ({ args: { job }, ctx }) => {
741
+ * const { failedIds, nextFilter } = await runPushBroadcastPage(ctx.push, job);
529
742
  *
530
- * if (nextCursor !== undefined) {
743
+ * if (nextFilter !== undefined) {
531
744
  * // 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
- * });
745
+ * // does only ONE bounded page of work. Pass `nextFilter` VERBATIM:
746
+ * // it carries the cursor and the remaining `limit` budget.
747
+ * await enqueuePushBroadcast(ctx.queues.push, { filter: nextFilter, payload: job.payload });
537
748
  * }
538
- * }
539
- * }});
749
+ *
750
+ * if (failedIds.length > 0) {
751
+ * // Redeliver ONLY the recipients that failed — never the whole page.
752
+ * await enqueuePushBroadcast(ctx.queues.push, { payload: job.payload, retryIds: failedIds });
753
+ * }
754
+ * });
755
+ *
756
+ * // lunora/queues.ts — the consumer itself has NO ctx.push / ctx.queues: a
757
+ * // `QueueRunContext` is exactly `{ env, log, run }` (handler signature
758
+ * // `(context, batch)`, in that order). It hands each message to the action above.
759
+ * export const push = defineQueue<PushBroadcastJob>({
760
+ * handler: async (context, batch) => {
761
+ * for (const message of batch.messages) {
762
+ * await message.run(internal.notifyFanout.deliverPage, { job: message.body });
763
+ * message.ack();
764
+ * }
765
+ * },
766
+ * });
767
+ *
768
+ * // in a mutation/action, to start it:
769
+ * await enqueuePushBroadcast(ctx.queues.push, { payload: { body: "…", title: "New drop" } });
540
770
  * ```
541
771
  */
542
772
  declare const enqueuePushBroadcast: (queue: QueueProducerLike, job: Omit<PushBroadcastJob, "type">) => Promise<void>;
@@ -546,43 +776,48 @@ declare const enqueuePushBroadcast: (queue: QueueProducerLike, job: Omit<PushBro
546
776
  * reuses the engine's retry + circuit-breaker middleware and prunes gone
547
777
  * subscriptions).
548
778
  *
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):
779
+ * RETRY / CONTINUATION SEMANTICS:
553
780
  *
554
- * - A job now processes exactly ONE bounded page (see `CreateNotifyOptions`'s
555
- * page-size option, default 250, or `job.filter.limit` when smaller),
781
+ * - A job processes exactly ONE bounded page (see `defineNotify`'s
782
+ * `broadcastPageSize`, default 250, or `job.filter.limit` when smaller),
556
783
  * keyset-paginated on the subscription `id` (see `SubscriptionFilter.after`)
557
784
  * — 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>;
785
+ * - A page NEVER throws for a partial failure. Throwing discarded the page's
786
+ * continuation, which is the only way the broadcast advances: one device that
787
+ * fails permanently (a rotated VAPID keypair leaves a stale device answering
788
+ * `403 VapidPkHashMismatch` forever) would then stall the cursor, re-POST
789
+ * every already-delivered recipient on each retry, dead-letter, and leave
790
+ * every LATER page unreached. The page's `nextFilter` and its `failedIds`
791
+ * both come back instead.
792
+ * - The CALLER re-enqueues: `filter: nextFilter` while more pages remain, and a
793
+ * `retryIds: failedIds` job when any recipient failed. `@lunora/notify` cannot
794
+ * do it itself — it has no `@lunora/queue` dependency (the seam stays
795
+ * structural) and no reference to the producer that enqueued this message. See
796
+ * the consumer example on {@link enqueuePushBroadcast}.
797
+ * - `job.filter.limit` is spent across messages, not re-granted to each one:
798
+ * `nextFilter` carries the REMAINING budget and is `undefined` once it runs
799
+ * out, so `limit` caps the whole audience here exactly as it does on
800
+ * {@link LunoraPush.broadcast}.
801
+ * - A `retryIds` job redelivers to exactly those ids and throws only while ALL
802
+ * of them still fail, so the queue's backoff/dead-letter bounds a device that
803
+ * never recovers. Once any recipient recovers the run resolves and reports the
804
+ * rest in `failedIds`, so the narrower retry never re-sends to a device this
805
+ * message already reached. A recipient that turns out to be GONE — a 404/410
806
+ * receipt, or an id whose row no longer exists at all — counts as `pruned` here
807
+ * too, never as a failure: there is nothing left to redeliver to, so retrying it
808
+ * could only burn the queue's budget and dead-letter an unsubscribe.
809
+ * - Gone subscriptions (Web Push 404/410, FCM's `NOT_FOUND` for a dead token) are pruned by the page and
810
+ * never appear in `failedIds` — an all-`pruned` page is a success, not a
811
+ * failure, as is an empty page.
812
+ */
813
+ declare const runPushBroadcastPage: (push: LunoraPush, job: PushBroadcastJob) => Promise<PushBroadcastPageOutcome>;
580
814
  /**
581
815
  * The minimal structural slice of Cloudflare's `D1Database` this store uses. A
582
816
  * structural type (rather than importing `@cloudflare/workers-types`) keeps the
583
817
  * store runtime-agnostic and trivially fakeable in tests.
584
818
  */
585
819
  interface D1Like {
820
+ batch: (statements: D1PreparedLike[]) => Promise<unknown>;
586
821
  prepare: (query: string) => D1PreparedLike;
587
822
  }
588
823
  interface D1PreparedLike {
@@ -598,27 +833,6 @@ interface D1StoreOptions {
598
833
  /** Table name (default `lunora_push_subscriptions`). Must be a bare identifier. */
599
834
  tableName?: string;
600
835
  }
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
836
  declare const d1SubscriptionStore: (database: D1Like, options?: D1StoreOptions) => SubscriptionStore;
623
837
  /**
624
838
  * An in-memory {@link SubscriptionStore} — the zero-dependency default. Suitable
@@ -628,7 +842,21 @@ declare const d1SubscriptionStore: (database: D1Like, options?: D1StoreOptions)
628
842
  */
629
843
  declare const memorySubscriptionStore: () => SubscriptionStore;
630
844
  /**
631
- * Stable store id for a web-push endpoint.
845
+ * Stable store id for a web-push endpoint — `fnv1a64Hex` of the (long) endpoint,
846
+ * so re-registering the same device upserts rather than duplicates.
847
+ *
848
+ * The digest comes from the canonical `shared/fnv1a`, not a local copy. This id
849
+ * is a PERSISTED primary key: a digest that drifts in one copy silently re-keys
850
+ * every existing subscription — the old row goes dark and the device
851
+ * re-registers as a duplicate — so the implementation must have exactly one
852
+ * home. `shared/fnv1a`'s is bit-verified against a BigInt reference in
853
+ * `packages/replica/__tests__/apply-diff.test.ts`.
854
+ *
855
+ * Widened from the previous 32-bit FNV-1a (8 hex): at 100K devices a 32-bit key
856
+ * collides with ~68% probability (birthday bound), and a collision silently
857
+ * overwrites another device's row under the store's `ON CONFLICT(id) DO UPDATE` —
858
+ * so the wrong user gets the push and the victim goes dark. 64 bits drops that to
859
+ * negligible at any realistic device count.
632
860
  *
633
861
  * The `wp2_` prefix is a version tag (see also {@link fcmId}'s `fcm2_`): it marks
634
862
  * the 64-bit-id revision so the pre-existing 32-bit `wp_` rows stay readable and a
@@ -649,9 +877,10 @@ interface NormalizeOptions {
649
877
  *
650
878
  * When unset, the default posture applies: `https:` scheme + a host the
651
879
  * {@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.
880
+ * private/loopback, plus a resolved-address re-check at send time. Setting
881
+ * this allowlist replaces both with an exact-origin match — the hard
882
+ * guarantee, and the only one that also covers an internal push service you
883
+ * deliberately want to reach.
655
884
  */
656
885
  allowedPushOrigins?: string[];
657
886
  }
@@ -674,11 +903,97 @@ declare const targetOf: (subscription: StoredSubscription) => string;
674
903
  * (the browser/device unsubscribed) and should be pruned — as opposed to a
675
904
  * transient failure worth retrying.
676
905
  *
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.
906
+ * Gates on STRUCTURED signals first: an `HTTP 404/410` status (both providers
907
+ * answer one for a dead endpoint/token, though FCM's is usually replaced by its
908
+ * error body before it reaches here) or, for FCM only, an
909
+ * `UNREGISTERED`/`NOT_REGISTERED` code or the `NOT_FOUND` prose that is the one
910
+ * signal its provider actually forwards (see {@link FCM_GONE_PATTERN}). The
911
+ * free-text {@link GONE_TEXT_FALLBACK} is a tightened last resort only, so a
912
+ * transient error that happens to contain `expired` (a cert/session expiry) can
913
+ * never permanently drop a valid subscription.
914
+ *
915
+ * `kind` scopes the PROVIDER-SPECIFIC patterns to the provider that emits them.
916
+ * The web-push provider echoes the push service's response body into
917
+ * `HTTP ${status}: ${body}`, so a 4xx whose prose merely contains "not
918
+ * registered" matched the FCM-only codes and permanently deleted a live
919
+ * subscription. Omit `kind` (the third-party/unknown-provider case) to test
920
+ * every pattern, as before.
921
+ */
922
+ declare const isGoneError: (message: string | undefined, kind?: StoredSubscription["kind"]) => boolean;
923
+ export { type BroadcastOutcome, type BroadcastResult, type CreateNotifyOptions, type D1Like, type D1PreparedLike, type D1StoreOptions,
924
+ /**
925
+ * `@lunora/notify`
926
+ *
927
+ * Multi-channel notifications for Lunora, wrapping the `@visulima/notification`
928
+ * engine. `defineNotify` in `lunora/notify.ts` configures the edge-safe channels
929
+ * (Web Push + FCM, plus chat / in-app inbox / webhook); codegen wires `ctx.notify`
930
+ * and its `ctx.push` alias onto every handler ctx from it (mirroring `defineFlags`
931
+ * → `ctx.flags`).
932
+ *
933
+ * Edge-safety: Web Push (VAPID + RFC 8291) and FCM (HTTP v1) run on `fetch` + Web
934
+ * Crypto under workerd. APNs (`node:http2`) and SMS / Node-only queue adapters are
935
+ * deliberately **not** on the edge facade — route heavy fan-out through
936
+ * `@lunora/queue` (`enqueuePushBroadcast` / `runPushBroadcastPage`).
937
+ *
938
+ * - `@lunora/notify` — `defineNotify`, `createNotify`, config resolvers, subscription stores and types.
939
+ * - `@lunora/notify/web` — the browser `subscribeToPush` service-worker helper.
940
+ * @packageDocumentation
941
+ */
942
+ 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,
943
+ /**
944
+ * `@lunora/notify`
945
+ *
946
+ * Multi-channel notifications for Lunora, wrapping the `@visulima/notification`
947
+ * engine. `defineNotify` in `lunora/notify.ts` configures the edge-safe channels
948
+ * (Web Push + FCM, plus chat / in-app inbox / webhook); codegen wires `ctx.notify`
949
+ * and its `ctx.push` alias onto every handler ctx from it (mirroring `defineFlags`
950
+ * → `ctx.flags`).
951
+ *
952
+ * Edge-safety: Web Push (VAPID + RFC 8291) and FCM (HTTP v1) run on `fetch` + Web
953
+ * Crypto under workerd. APNs (`node:http2`) and SMS / Node-only queue adapters are
954
+ * deliberately **not** on the edge facade — route heavy fan-out through
955
+ * `@lunora/queue` (`enqueuePushBroadcast` / `runPushBroadcastPage`).
956
+ *
957
+ * - `@lunora/notify` — `defineNotify`, `createNotify`, config resolvers, subscription stores and types.
958
+ * - `@lunora/notify/web` — the browser `subscribeToPush` service-worker helper.
959
+ * @packageDocumentation
960
+ */
961
+ WEB_PUSH_ENV_KEYS, type WebPushConfigFactory, buildEngine, createNotify, d1SubscriptionStore, defineNotify, enqueuePushBroadcast,
962
+ /**
963
+ * `@lunora/notify`
964
+ *
965
+ * Multi-channel notifications for Lunora, wrapping the `@visulima/notification`
966
+ * engine. `defineNotify` in `lunora/notify.ts` configures the edge-safe channels
967
+ * (Web Push + FCM, plus chat / in-app inbox / webhook); codegen wires `ctx.notify`
968
+ * and its `ctx.push` alias onto every handler ctx from it (mirroring `defineFlags`
969
+ * → `ctx.flags`).
970
+ *
971
+ * Edge-safety: Web Push (VAPID + RFC 8291) and FCM (HTTP v1) run on `fetch` + Web
972
+ * Crypto under workerd. APNs (`node:http2`) and SMS / Node-only queue adapters are
973
+ * deliberately **not** on the edge facade — route heavy fan-out through
974
+ * `@lunora/queue` (`enqueuePushBroadcast` / `runPushBroadcastPage`).
975
+ *
976
+ * - `@lunora/notify` — `defineNotify`, `createNotify`, config resolvers, subscription stores and types.
977
+ * - `@lunora/notify/web` — the browser `subscribeToPush` service-worker helper.
978
+ * @packageDocumentation
979
+ */
980
+ fcmFromEnv, fcmId, isGoneError, isNotifyDefinition, memorySubscriptionStore, normalizeRegisterInput, routingPushProvider, runPushBroadcastPage, targetOf,
981
+ /**
982
+ * `@lunora/notify`
983
+ *
984
+ * Multi-channel notifications for Lunora, wrapping the `@visulima/notification`
985
+ * engine. `defineNotify` in `lunora/notify.ts` configures the edge-safe channels
986
+ * (Web Push + FCM, plus chat / in-app inbox / webhook); codegen wires `ctx.notify`
987
+ * and its `ctx.push` alias onto every handler ctx from it (mirroring `defineFlags`
988
+ * → `ctx.flags`).
989
+ *
990
+ * Edge-safety: Web Push (VAPID + RFC 8291) and FCM (HTTP v1) run on `fetch` + Web
991
+ * Crypto under workerd. APNs (`node:http2`) and SMS / Node-only queue adapters are
992
+ * deliberately **not** on the edge facade — route heavy fan-out through
993
+ * `@lunora/queue` (`enqueuePushBroadcast` / `runPushBroadcastPage`).
994
+ *
995
+ * - `@lunora/notify` — `defineNotify`, `createNotify`, config resolvers, subscription stores and types.
996
+ * - `@lunora/notify/web` — the browser `subscribeToPush` service-worker helper.
997
+ * @packageDocumentation
682
998
  */
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 };
999
+ webPushFromEnv, webPushId };