@lunora/notify 1.0.0-alpha.3 → 1.0.0-alpha.31
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/README.md +63 -13
- package/dist/index.d.mts +385 -23
- package/dist/index.d.ts +385 -23
- package/dist/index.mjs +1 -8
- package/dist/packem_shared/FCM_ENV_KEYS-BbhPScGH.mjs +1 -0
- package/dist/packem_shared/buildEngine-oDWs9Pom.mjs +1 -0
- package/dist/packem_shared/createNotify-B27o09vm.mjs +1 -0
- package/dist/packem_shared/d1SubscriptionStore-B7f20Nqr.mjs +1 -0
- package/dist/packem_shared/defineNotify-DVPpVkU0.mjs +1 -0
- package/dist/packem_shared/enqueuePushBroadcast-B6v3DLLp.mjs +1 -0
- package/dist/packem_shared/fcmId-DNM-rzkd.mjs +1 -0
- package/dist/packem_shared/memorySubscriptionStore-DdVxq2zI.mjs +1 -0
- package/dist/packem_shared/ssrf-host-BCpHorGa.mjs +1 -0
- package/dist/web.d.mts +0 -15
- package/dist/web.d.ts +0 -15
- package/dist/web.mjs +1 -44
- package/package.json +3 -3
- package/dist/packem_shared/FCM_ENV_KEYS-DY4-A717.mjs +0 -32
- package/dist/packem_shared/buildEngine-DlmjvnNk.mjs +0 -65
- package/dist/packem_shared/createNotify-bDWs4qBm.mjs +0 -191
- package/dist/packem_shared/d1SubscriptionStore-Dv3VPMI_.mjs +0 -107
- package/dist/packem_shared/defineNotify-B6S_47C2.mjs +0 -18
- package/dist/packem_shared/enqueuePushBroadcast-DiK7Hyja.mjs +0 -4
- package/dist/packem_shared/fcmId-B-YPgHi7.mjs +0 -68
- package/dist/packem_shared/memorySubscriptionStore-DhS-YnLe.mjs +0 -46
package/README.md
CHANGED
|
@@ -45,11 +45,8 @@ await client.mutation("registerDevice", { subscription });
|
|
|
45
45
|
|
|
46
46
|
```ts
|
|
47
47
|
// lunora/registerDevice.ts (a mutation — storage write is fine here)
|
|
48
|
-
export const registerDevice = mutation({
|
|
49
|
-
|
|
50
|
-
handler: async (ctx, { subscription }) => {
|
|
51
|
-
await ctx.push.register({ subscription, userId: ctx.auth?.userId });
|
|
52
|
-
},
|
|
48
|
+
export const registerDevice = mutation.input({ subscription: v.any() }).mutation(async ({ ctx, args: { subscription } }) => {
|
|
49
|
+
await ctx.push.register({ subscription, userId: ctx.auth?.userId });
|
|
53
50
|
});
|
|
54
51
|
```
|
|
55
52
|
|
|
@@ -58,12 +55,9 @@ export const registerDevice = mutation({
|
|
|
58
55
|
Notification sends are external I/O, so they belong in **actions** (the `notify_send_outside_action` advisor lint enforces this):
|
|
59
56
|
|
|
60
57
|
```ts
|
|
61
|
-
export const announce = action({
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
const result = await ctx.push.broadcast({ title, body });
|
|
65
|
-
// result: { total, sent, pruned, failed, outcomes }
|
|
66
|
-
},
|
|
58
|
+
export const announce = action.input({ title: v.string(), body: v.string() }).action(async ({ ctx, args: { title, body } }) => {
|
|
59
|
+
const result = await ctx.push.broadcast({ title, body });
|
|
60
|
+
// result: { total, sent, pruned, failed, outcomes }
|
|
67
61
|
});
|
|
68
62
|
```
|
|
69
63
|
|
|
@@ -90,14 +84,70 @@ Move a large broadcast off the request path with `@lunora/queue`:
|
|
|
90
84
|
// producer (mutation/action)
|
|
91
85
|
await enqueuePushBroadcast(ctx.queues.push, { payload: { title: "New drop", body: "…" } });
|
|
92
86
|
|
|
93
|
-
//
|
|
94
|
-
|
|
87
|
+
// lunora/notify-fanout.ts — an INTERNAL ACTION, because that is where
|
|
88
|
+
// `ctx.push` and `ctx.queues` exist.
|
|
89
|
+
export const deliverPage = internalAction.input({ job: v.any() }).action(async ({ args: { job }, ctx }) => {
|
|
90
|
+
const { failedIds, nextCursor } = await runPushBroadcastPage(ctx.push, job);
|
|
91
|
+
|
|
92
|
+
// One message = ONE bounded page. Discarding `nextCursor` delivers only the
|
|
93
|
+
// first page (default 250 devices) and reports success for the whole audience.
|
|
94
|
+
if (nextCursor !== undefined) {
|
|
95
|
+
await enqueuePushBroadcast(ctx.queues.push, { payload: job.payload, filter: { ...job.filter, after: nextCursor } });
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
// Redeliver ONLY the recipients that failed — a retry of the whole page would
|
|
99
|
+
// re-POST everyone it already reached.
|
|
100
|
+
if (failedIds.length > 0) {
|
|
101
|
+
await enqueuePushBroadcast(ctx.queues.push, { payload: job.payload, retryIds: failedIds });
|
|
102
|
+
}
|
|
103
|
+
});
|
|
104
|
+
|
|
105
|
+
// lunora/queues.ts — a `QueueRunContext` is exactly `{ env, log, run }`: no
|
|
106
|
+
// `ctx.push`, no `ctx.queues`. The consumer hands each message to the action above.
|
|
107
|
+
// (Note the handler signature: `(context, batch)`, in that order.)
|
|
108
|
+
export const push = defineQueue<PushBroadcastJob>({
|
|
109
|
+
handler: async (context, batch) => {
|
|
110
|
+
for (const message of batch.messages) {
|
|
111
|
+
await message.run(internal.notifyFanout.deliverPage, { job: message.body });
|
|
112
|
+
message.ack();
|
|
113
|
+
}
|
|
114
|
+
},
|
|
115
|
+
});
|
|
95
116
|
```
|
|
96
117
|
|
|
97
118
|
## Subscription storage
|
|
98
119
|
|
|
99
120
|
`SubscriptionStore` implementations: `memorySubscriptionStore()` (non-durable default, tests/dev) and `d1SubscriptionStore(db)` (durable, edge-safe, lazy table creation). Lifecycle: register (upsert), list/filter (by kind or user), status marking, and automatic prune of gone subscriptions on send/broadcast.
|
|
100
121
|
|
|
122
|
+
## Security
|
|
123
|
+
|
|
124
|
+
`ctx.push.register(...)` and the browser `subscribeToPush` helper both accept
|
|
125
|
+
client-supplied data, so the facade enforces two boundaries:
|
|
126
|
+
|
|
127
|
+
- **Endpoint validation (anti-SSRF).** Every later `send`/`broadcast` POSTs to a
|
|
128
|
+
subscription's stored Web Push `endpoint`, so a hostile `endpoint` would turn the
|
|
129
|
+
worker into an SSRF / amplification primitive. `register()` validates the endpoint
|
|
130
|
+
**at storage time** (the durable boundary): it must be an absolute `https:` URL
|
|
131
|
+
with a non-private / non-loopback / non-link-local / non-CGNAT host. To hard-pin
|
|
132
|
+
the boundary to the push services you actually use, set `allowedPushOrigins` on
|
|
133
|
+
`defineNotify` — when present, an endpoint's origin must match one of the listed
|
|
134
|
+
origins **exactly** (no wildcards), which also closes DNS rebinding:
|
|
135
|
+
|
|
136
|
+
```ts
|
|
137
|
+
export default defineNotify({
|
|
138
|
+
webPush: (env) => webPushFromEnv(env),
|
|
139
|
+
allowedPushOrigins: ["https://fcm.googleapis.com", "https://updates.push.services.mozilla.com"],
|
|
140
|
+
store: (env) => d1SubscriptionStore(env.DB),
|
|
141
|
+
});
|
|
142
|
+
```
|
|
143
|
+
|
|
144
|
+
- **No secrets on the app facade.** `ctx.push.list()`
|
|
145
|
+
returns the registered devices with the delivery **secrets stripped** — the Web
|
|
146
|
+
Push `keys` (`auth`/`p256dh`) and the FCM `token`, which together with the
|
|
147
|
+
endpoint are enough to deliver arbitrary push to a device. The raw rows are
|
|
148
|
+
reachable only through the internal `SubscriptionStore` (which handlers never
|
|
149
|
+
hold); the broadcast path uses the store directly.
|
|
150
|
+
|
|
101
151
|
## Delivery observability
|
|
102
152
|
|
|
103
153
|
Every send is counted onto `ctx.metrics` and failures onto `ctx.log` for you — codegen threads the request's logger/metrics into `ctx.notify` (`createNotify(notifyConfig, env, { log, metrics })`), so there is nothing to wire. Two low-cardinality metric series feed the durable metric history + trend charts:
|
package/dist/index.d.mts
CHANGED
|
@@ -75,8 +75,58 @@ type RegisterInput = {
|
|
|
75
75
|
};
|
|
76
76
|
/** Filter narrowing which stored subscriptions a `list`/`broadcast` targets. */
|
|
77
77
|
interface SubscriptionFilter {
|
|
78
|
+
/**
|
|
79
|
+
* Keyset pagination cursor: return only rows with `id` strictly GREATER
|
|
80
|
+
* than this value, ordered ascending by `id`. `id` is a stable,
|
|
81
|
+
* content-derived hash (see `webPushId`/`fcmId`), so ordering by it is
|
|
82
|
+
* immune to concurrent inserts/deletes elsewhere in the table — a page
|
|
83
|
+
* already walked never re-delivers or skips a row when another device
|
|
84
|
+
* registers mid-broadcast (the reviewer-flagged "stable under concurrent
|
|
85
|
+
* registers" property). `broadcastPage`/`broadcast` set this internally to
|
|
86
|
+
* walk pages; a direct `list()` caller may also page through results with
|
|
87
|
+
* it.
|
|
88
|
+
*
|
|
89
|
+
* OPTIONAL for a reason: `SubscriptionStore` is implementable outside this
|
|
90
|
+
* package. An external store that does not support cursoring may ignore
|
|
91
|
+
* `after` entirely and keep returning its (from-the-top) unpaged result —
|
|
92
|
+
* `broadcastPage` defensively re-filters whatever the store returns down
|
|
93
|
+
* to `id > after` itself, so a non-cursoring store can never cause a
|
|
94
|
+
* double-send or an infinite page-walk (each page's result only ever
|
|
95
|
+
* contains ids the previous page didn't already deliver), but it also
|
|
96
|
+
* cannot deliver the FULL matched audience beyond whatever the store's own
|
|
97
|
+
* (unpaged) response window happens to contain — implement `after`
|
|
98
|
+
* (ordered ascending by `id`, exclusive) to get real, complete pagination
|
|
99
|
+
* over a large audience.
|
|
100
|
+
*/
|
|
101
|
+
after?: string;
|
|
78
102
|
/** Restrict to a delivery kind. */
|
|
79
103
|
kind?: SubscriptionKind;
|
|
104
|
+
/**
|
|
105
|
+
* Cap the number of rows returned (a `LIMIT`). Applied server-side by the
|
|
106
|
+
* store, so a large audience never materializes wholesale in the isolate.
|
|
107
|
+
* A non-positive/absent value means "no cap"; a fractional value is truncated.
|
|
108
|
+
*
|
|
109
|
+
* For `list`/admin reads this bounds the returned page as before. For
|
|
110
|
+
* `broadcast`, this is now an OVERALL cap on the total number of
|
|
111
|
+
* subscriptions reached across every internally-walked page (still
|
|
112
|
+
* deliberately left unset by default — it must reach every matched
|
|
113
|
+
* device); the PER-PAGE batch size is a separate, independent knob (see
|
|
114
|
+
* `defineNotify`'s `broadcastPageSize`, default 250) so a caller
|
|
115
|
+
* that sets `limit` to bound the audience doesn't also have to reason
|
|
116
|
+
* about page sizing.
|
|
117
|
+
*
|
|
118
|
+
* The non-positive sentinel means something different at each layer: at
|
|
119
|
+
* the STORE layer (`list`, and the `d1-store`/`memory-store` fetch-size
|
|
120
|
+
* hint) a non-positive `limit` means "no cap" — fetch everything. At the
|
|
121
|
+
* `broadcast`/`broadcastPage` layer, where `limit` is an AUDIENCE cap, a
|
|
122
|
+
* non-positive value instead means "no deliveries" — `broadcast({ limit: 0
|
|
123
|
+
* })` reaches nobody, not everybody. This asymmetry is deliberate: the two
|
|
124
|
+
* layers answer different questions ("how many rows to fetch" vs. "how
|
|
125
|
+
* many recipients to reach"), and unifying them would either break `list`
|
|
126
|
+
* callers relying on "no cap" or reintroduce the over-delivery this
|
|
127
|
+
* distinction fixes (see `broadcastPage`'s doc comment).
|
|
128
|
+
*/
|
|
129
|
+
limit?: number;
|
|
80
130
|
/** Restrict to a single owning user. */
|
|
81
131
|
userId?: string | null;
|
|
82
132
|
}
|
|
@@ -90,7 +140,13 @@ interface SubscriptionStore {
|
|
|
90
140
|
delete: (id: string) => Promise<void>;
|
|
91
141
|
/** Read a subscription by id, or `undefined`. */
|
|
92
142
|
get: (id: string) => Promise<StoredSubscription | undefined>;
|
|
93
|
-
/**
|
|
143
|
+
/**
|
|
144
|
+
* List subscriptions, optionally filtered. When `filter.after` is set,
|
|
145
|
+
* results are keyset-paginated: only rows with `id` strictly greater than
|
|
146
|
+
* `filter.after` are returned, ordered ascending by `id`. Implementing
|
|
147
|
+
* `after` is OPTIONAL (see {@link SubscriptionFilter.after}) — a store
|
|
148
|
+
* that ignores it may keep returning its unpaged result.
|
|
149
|
+
*/
|
|
94
150
|
list: (filter?: SubscriptionFilter) => Promise<StoredSubscription[]>;
|
|
95
151
|
/** Record the latest delivery outcome for a subscription (best-effort). */
|
|
96
152
|
markStatus: (id: string, status: SubscriptionStatus, error?: string) => Promise<void>;
|
|
@@ -119,6 +175,18 @@ interface BroadcastResult {
|
|
|
119
175
|
/** Total subscriptions attempted. */
|
|
120
176
|
total: number;
|
|
121
177
|
}
|
|
178
|
+
/**
|
|
179
|
+
* Result of `broadcastPage` — one bounded page of a fan-out, plus the cursor
|
|
180
|
+
* to fetch the next page. `nextCursor` is `undefined` when this was the last
|
|
181
|
+
* page (or the store doesn't support cursoring — see
|
|
182
|
+
* {@link SubscriptionFilter.after}'s documented unpaged fallback).
|
|
183
|
+
*/
|
|
184
|
+
interface BroadcastPageResult {
|
|
185
|
+
/** Cursor for the next page (pass as `filter.after`), or `undefined` when done. */
|
|
186
|
+
nextCursor?: string;
|
|
187
|
+
/** The delivery outcome for just this page. */
|
|
188
|
+
result: BroadcastResult;
|
|
189
|
+
}
|
|
122
190
|
/**
|
|
123
191
|
* The compact, stable delivery-status vocabulary emitted on notify observability
|
|
124
192
|
* signals — the `status` dimension on the `notify.send` metric and the failure
|
|
@@ -173,10 +241,36 @@ interface LunoraPush {
|
|
|
173
241
|
* Reuses the engine's retry/circuit-breaker middleware; prunes subscriptions
|
|
174
242
|
* the push service reports as gone (HTTP 404/410, FCM `UNREGISTERED`). The `to`
|
|
175
243
|
* target is derived from each subscription, so it is omitted from the payload.
|
|
244
|
+
*
|
|
245
|
+
* 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 `defineNotify`'s
|
|
248
|
+
* `broadcastPageSize`. This call still processes the WHOLE matched
|
|
249
|
+
* audience in one request/queue message; use {@link LunoraPush.broadcastPage}
|
|
250
|
+
* directly (as `runPushBroadcastPage` does) to bound a single queue message
|
|
251
|
+
* to one page.
|
|
176
252
|
*/
|
|
177
253
|
broadcast: (payload: PushContent, filter?: SubscriptionFilter) => Promise<BroadcastResult>;
|
|
178
|
-
/**
|
|
179
|
-
|
|
254
|
+
/**
|
|
255
|
+
* Fan-out a push to ONE bounded page of stored subscriptions matching
|
|
256
|
+
* `filter` (page size: `defineNotify`'s `broadcastPageSize`, default
|
|
257
|
+
* 250, capped by `filter.limit` when set). Same delivery semantics as
|
|
258
|
+
* {@link LunoraPush.broadcast} (retry/circuit-breaker, gone-pruning) but
|
|
259
|
+
* scoped to a single page; returns the page's own {@link BroadcastResult}
|
|
260
|
+
* plus a `nextCursor` to fetch the next page (`undefined` when done).
|
|
261
|
+
* Backs `runPushBroadcastPage` so one queue message does bounded work
|
|
262
|
+
* regardless of audience size — most app code should call
|
|
263
|
+
* {@link LunoraPush.broadcast} instead.
|
|
264
|
+
*/
|
|
265
|
+
broadcastPage: (payload: PushContent, filter?: SubscriptionFilter) => Promise<BroadcastPageResult>;
|
|
266
|
+
/**
|
|
267
|
+
* List stored subscriptions (optionally filtered), with the delivery
|
|
268
|
+
* **secrets** stripped — the Web Push `keys` (RFC 8291 `auth`/`p256dh`) and the
|
|
269
|
+
* 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
|
|
271
|
+
* reachable only through the internal `SubscriptionStore`.
|
|
272
|
+
*/
|
|
273
|
+
list: (filter?: SubscriptionFilter) => Promise<PushSubscriptionDevice[]>;
|
|
180
274
|
/** Register (upsert) a device subscription and return the stored record. */
|
|
181
275
|
register: (input: RegisterInput) => Promise<StoredSubscription>;
|
|
182
276
|
/** Send a push to a single stored subscription (by id or record); `to` is derived from it. */
|
|
@@ -213,11 +307,48 @@ type WebPushConfigFactory = (env: NotifyEnv) => WebPushConfig | undefined;
|
|
|
213
307
|
type FcmConfigFactory = (env: NotifyEnv) => FcmConfig | undefined;
|
|
214
308
|
/** Options accepted by `defineNotify`. */
|
|
215
309
|
interface NotifyConfig {
|
|
310
|
+
/**
|
|
311
|
+
* Exact origins (`https://host[:port]`) a client-supplied Web Push `endpoint`
|
|
312
|
+
* may register from. When set (non-empty), `register()` requires the endpoint's
|
|
313
|
+
* origin to be one of these — the strongest anti-SSRF posture, and the way to
|
|
314
|
+
* close DNS rebinding for a facade that accepts client-controlled endpoints.
|
|
315
|
+
*
|
|
316
|
+
* When unset, the default posture applies: an endpoint must be `https:` with a
|
|
317
|
+
* host a STRING classifier does not flag as private / loopback / link-local.
|
|
318
|
+
* That classifier does NOT resolve DNS, so a public hostname resolving to a
|
|
319
|
+
* private/internal IP (e.g. `https://127.0.0.1.nip.io/…`) is NOT blocked by it
|
|
320
|
+
* — `register()` also emits a one-shot dev warning in this case. Set this to the
|
|
321
|
+
* push services your app actually uses (e.g. `["https://fcm.googleapis.com",
|
|
322
|
+
* "https://updates.push.services.mozilla.com"]` — exact origins only, no
|
|
323
|
+
* wildcards) to hard-pin the boundary and close DNS rebinding.
|
|
324
|
+
*/
|
|
325
|
+
allowedPushOrigins?: string[];
|
|
326
|
+
/**
|
|
327
|
+
* Page size for `push.broadcast`'s internal keyset pagination over the
|
|
328
|
+
* subscription store (default 250, minimum 1). Each page is fetched,
|
|
329
|
+
* delivered, and counted before the next page's store round trip, so a huge
|
|
330
|
+
* audience is never materialized wholesale in the isolate. Also the
|
|
331
|
+
* per-message bound `push.broadcastPage` (and `runPushBroadcastPage`) uses.
|
|
332
|
+
*
|
|
333
|
+
* Declared here, and not only on `createNotify`'s third argument, because
|
|
334
|
+
* this file is the only handle an app has: the sole production constructor is
|
|
335
|
+
* codegen's fixed `createNotify(definition, env, { log, metrics })`, so a knob
|
|
336
|
+
* that lives only on those options is unsettable by every Lunora app —
|
|
337
|
+
* while {@link SubscriptionFilter.limit}'s own docs point at it as the way to
|
|
338
|
+
* size pages.
|
|
339
|
+
*/
|
|
340
|
+
broadcastPageSize?: number;
|
|
216
341
|
/**
|
|
217
342
|
* Optional chat provider factory (Slack/Discord/Teams/Telegram). Wire with a
|
|
218
343
|
* provider from `@visulima/notification/providers/*`. Edge-safe (fetch-based).
|
|
219
344
|
*/
|
|
220
345
|
chat?: (env: NotifyEnv) => unknown;
|
|
346
|
+
/**
|
|
347
|
+
* Max concurrent sends during a `push.broadcast` (default 10, minimum 1).
|
|
348
|
+
* Same reasoning as {@link NotifyConfig.broadcastPageSize}: this is where an
|
|
349
|
+
* app can reach it.
|
|
350
|
+
*/
|
|
351
|
+
concurrency?: number;
|
|
221
352
|
/** FCM (Firebase Cloud Messaging HTTP v1) config. Edge-safe — supply an OAuth2 token. */
|
|
222
353
|
fcm?: FcmConfig | FcmConfigFactory;
|
|
223
354
|
/** Optional in-app inbox provider factory. Edge-safe. */
|
|
@@ -303,7 +434,21 @@ declare const defineNotify: (config: NotifyConfig) => NotifyDefinition;
|
|
|
303
434
|
declare const isNotifyDefinition: (value: unknown) => value is NotifyDefinition;
|
|
304
435
|
/** Options for {@link createNotify}. */
|
|
305
436
|
interface CreateNotifyOptions {
|
|
306
|
-
/**
|
|
437
|
+
/**
|
|
438
|
+
* Page size for `push.broadcast`'s internal keyset pagination over the
|
|
439
|
+
* subscription store (default {@link DEFAULT_BROADCAST_PAGE_SIZE}, 250).
|
|
440
|
+
*
|
|
441
|
+
* A test/tuning seam only. **Apps set `broadcastPageSize` on `defineNotify`
|
|
442
|
+
* instead** — the sole production call is codegen's fixed
|
|
443
|
+
* `createNotify(definition, env, { log, metrics })`, so nothing an app writes
|
|
444
|
+
* reaches this object. Set here it wins over the definition's value.
|
|
445
|
+
*/
|
|
446
|
+
broadcastPageSize?: number;
|
|
447
|
+
/**
|
|
448
|
+
* Max concurrent sends during a `broadcast` (default 10). Test/tuning seam;
|
|
449
|
+
* apps set `concurrency` on `defineNotify` — see
|
|
450
|
+
* {@link CreateNotifyOptions.broadcastPageSize}.
|
|
451
|
+
*/
|
|
307
452
|
concurrency?: number;
|
|
308
453
|
/**
|
|
309
454
|
* Override the assembled `@visulima/notification` engine. Advanced/testing
|
|
@@ -347,6 +492,11 @@ declare const createNotify: (definition: NotifyDefinition, env: NotifyEnv, optio
|
|
|
347
492
|
};
|
|
348
493
|
/** Options for {@link routingPushProvider}. */
|
|
349
494
|
interface RoutingPushOptions {
|
|
495
|
+
/**
|
|
496
|
+
* The definition's exact-origin allowlist, when configured. Its presence
|
|
497
|
+
* disables the send-time rebinding re-check (see {@link assertPushTargetResolvable}).
|
|
498
|
+
*/
|
|
499
|
+
allowedPushOrigins?: string[];
|
|
350
500
|
fcm?: Provider<unknown, PushPayload>;
|
|
351
501
|
webPush?: Provider<unknown, PushPayload>;
|
|
352
502
|
}
|
|
@@ -360,6 +510,8 @@ interface RoutingPushOptions {
|
|
|
360
510
|
declare const routingPushProvider: (options: RoutingPushOptions) => Provider<unknown, PushPayload>;
|
|
361
511
|
/** A resolved, ready-to-wire set of channel configs (edge-safe channels only). */
|
|
362
512
|
interface ResolvedProviders {
|
|
513
|
+
/** The definition's `allowedPushOrigins`, threaded to the push router's send-time SSRF guard. */
|
|
514
|
+
allowedPushOrigins?: string[];
|
|
363
515
|
chat?: Provider;
|
|
364
516
|
fcm?: FcmConfig;
|
|
365
517
|
inApp?: Provider;
|
|
@@ -377,41 +529,125 @@ declare const buildEngine: (resolved: ResolvedProviders) => Notification;
|
|
|
377
529
|
* A broadcast job body — the JSON-serialisable payload enqueued for off-request
|
|
378
530
|
* fan-out. Shaped to travel through a `@lunora/queue` producer/consumer without
|
|
379
531
|
* `@lunora/notify` depending on `@lunora/queue` (the seam stays structural).
|
|
532
|
+
* `filter.after`, when set, resumes a broadcast partway through (see
|
|
533
|
+
* {@link runPushBroadcastPage}'s continuation semantics).
|
|
380
534
|
*/
|
|
381
535
|
interface PushBroadcastJob {
|
|
382
|
-
/** Subscription filter (which devices/users to target). */
|
|
536
|
+
/** Subscription filter (which devices/users to target; `filter.after` resumes a paged broadcast). */
|
|
383
537
|
filter?: SubscriptionFilter;
|
|
384
538
|
/** The push payload to deliver (the `to` target is derived per subscription). */
|
|
385
539
|
payload: PushContent;
|
|
540
|
+
/**
|
|
541
|
+
* Redeliver to exactly these subscription ids instead of walking a page —
|
|
542
|
+
* an earlier page's {@link PushBroadcastPageOutcome.failedIds}. Set by the
|
|
543
|
+
* consumer when it re-enqueues a page's transient failures; `filter` is
|
|
544
|
+
* ignored on such a job. See {@link runPushBroadcastPage}.
|
|
545
|
+
*/
|
|
546
|
+
retryIds?: string[];
|
|
386
547
|
/** Discriminator so a shared queue can multiplex message kinds. */
|
|
387
548
|
type: "lunora.push.broadcast";
|
|
388
549
|
}
|
|
389
|
-
/**
|
|
550
|
+
/**
|
|
551
|
+
* One page's outcome plus the ids that need redelivering.
|
|
552
|
+
*
|
|
553
|
+
* The consumer MUST act on BOTH fields: `nextCursor` continues the broadcast and
|
|
554
|
+
* `failedIds` redelivers the recipients this page missed. Acking a message while
|
|
555
|
+
* ignoring either silently drops part of the audience.
|
|
556
|
+
*/
|
|
557
|
+
interface PushBroadcastPageOutcome extends BroadcastPageResult {
|
|
558
|
+
/**
|
|
559
|
+
* Subscriptions that failed transiently on this run (gone/pruned devices are
|
|
560
|
+
* NOT here — they are deleted, not retried). Re-enqueue a job carrying these
|
|
561
|
+
* as `retryIds` to redeliver to just them.
|
|
562
|
+
*/
|
|
563
|
+
failedIds: string[];
|
|
564
|
+
}
|
|
565
|
+
/** The structural slice of a `@lunora/queue` producer (`ctx.queues.<name>`) used here. */
|
|
390
566
|
interface QueueProducerLike {
|
|
391
567
|
send: (body: PushBroadcastJob) => Promise<void>;
|
|
392
568
|
}
|
|
393
569
|
/**
|
|
394
570
|
* Enqueue a fan-out broadcast for background delivery through a `@lunora/queue`
|
|
395
|
-
* queue instead of blocking the request. Pair with {@link
|
|
396
|
-
* the queue consumer
|
|
571
|
+
* queue instead of blocking the request. Pair with {@link runPushBroadcastPage} in
|
|
572
|
+
* the queue consumer — see its doc comment for how a large audience continues
|
|
573
|
+
* across MULTIPLE messages (one bounded page per message), not one.
|
|
397
574
|
*
|
|
398
575
|
* ```ts
|
|
399
|
-
* //
|
|
400
|
-
*
|
|
576
|
+
* // lunora/notify-fanout.ts — an INTERNAL ACTION, because that is where
|
|
577
|
+
* // `ctx.push` and `ctx.queues` exist.
|
|
578
|
+
* import { internalAction, v } from "./_generated/server";
|
|
579
|
+
* import { enqueuePushBroadcast, runPushBroadcastPage } from "@lunora/notify";
|
|
580
|
+
*
|
|
581
|
+
* export const deliverPage = internalAction
|
|
582
|
+
* .input({ job: v.any() })
|
|
583
|
+
* .action(async ({ args: { job }, ctx }) => {
|
|
584
|
+
* const { failedIds, nextCursor } = await runPushBroadcastPage(ctx.push, job);
|
|
401
585
|
*
|
|
402
|
-
*
|
|
403
|
-
*
|
|
404
|
-
*
|
|
405
|
-
*
|
|
586
|
+
* if (nextCursor !== undefined) {
|
|
587
|
+
* // More pages remain — enqueue the continuation. Each message still
|
|
588
|
+
* // does only ONE bounded page of work.
|
|
589
|
+
* await enqueuePushBroadcast(ctx.queues.push, {
|
|
590
|
+
* filter: { ...job.filter, after: nextCursor },
|
|
591
|
+
* payload: job.payload,
|
|
592
|
+
* });
|
|
593
|
+
* }
|
|
594
|
+
*
|
|
595
|
+
* if (failedIds.length > 0) {
|
|
596
|
+
* // Redeliver ONLY the recipients that failed — never the whole page.
|
|
597
|
+
* await enqueuePushBroadcast(ctx.queues.push, { payload: job.payload, retryIds: failedIds });
|
|
598
|
+
* }
|
|
599
|
+
* });
|
|
600
|
+
*
|
|
601
|
+
* // lunora/queues.ts — the consumer itself has NO ctx.push / ctx.queues: a
|
|
602
|
+
* // `QueueRunContext` is exactly `{ env, log, run }` (handler signature
|
|
603
|
+
* // `(context, batch)`, in that order). It hands each message to the action above.
|
|
604
|
+
* export const push = defineQueue<PushBroadcastJob>({
|
|
605
|
+
* handler: async (context, batch) => {
|
|
606
|
+
* for (const message of batch.messages) {
|
|
607
|
+
* await message.run(internal.notifyFanout.deliverPage, { job: message.body });
|
|
608
|
+
* message.ack();
|
|
609
|
+
* }
|
|
610
|
+
* },
|
|
611
|
+
* });
|
|
612
|
+
*
|
|
613
|
+
* // in a mutation/action, to start it:
|
|
614
|
+
* await enqueuePushBroadcast(ctx.queues.push, { payload: { body: "…", title: "New drop" } });
|
|
406
615
|
* ```
|
|
407
616
|
*/
|
|
408
617
|
declare const enqueuePushBroadcast: (queue: QueueProducerLike, job: Omit<PushBroadcastJob, "type">) => Promise<void>;
|
|
409
618
|
/**
|
|
410
|
-
* Run an enqueued broadcast job on the consumer side,
|
|
411
|
-
*
|
|
412
|
-
* gone
|
|
619
|
+
* Run ONE bounded page of an enqueued broadcast job on the consumer side,
|
|
620
|
+
* delivering through the push facade's {@link LunoraPush.broadcastPage} (which
|
|
621
|
+
* reuses the engine's retry + circuit-breaker middleware and prunes gone
|
|
622
|
+
* subscriptions).
|
|
623
|
+
*
|
|
624
|
+
* RETRY / CONTINUATION SEMANTICS:
|
|
625
|
+
*
|
|
626
|
+
* - A job processes exactly ONE bounded page (see `defineNotify`'s
|
|
627
|
+
* `broadcastPageSize`, default 250, or `job.filter.limit` when smaller),
|
|
628
|
+
* keyset-paginated on the subscription `id` (see `SubscriptionFilter.after`)
|
|
629
|
+
* — so per-message work is bounded regardless of total audience size.
|
|
630
|
+
* - A page NEVER throws for a partial failure. Throwing discarded the page's
|
|
631
|
+
* `nextCursor`, which is the only way the broadcast advances: one device that
|
|
632
|
+
* fails permanently (a rotated VAPID keypair leaves a stale device answering
|
|
633
|
+
* `403 VapidPkHashMismatch` forever) would then stall the cursor, re-POST
|
|
634
|
+
* every already-delivered recipient on each retry, dead-letter, and leave
|
|
635
|
+
* every LATER page unreached. The page's `nextCursor` and its `failedIds`
|
|
636
|
+
* both come back instead.
|
|
637
|
+
* - The CALLER re-enqueues: `filter.after:
|
|
638
|
+
* nextCursor` while more pages remain, and a `retryIds: failedIds` job when
|
|
639
|
+
* any recipient failed. `@lunora/notify` cannot do it itself — it has no
|
|
640
|
+
* `@lunora/queue` dependency (the seam stays structural) and no reference to
|
|
641
|
+
* the producer that enqueued this message. See the consumer example on
|
|
642
|
+
* {@link enqueuePushBroadcast}.
|
|
643
|
+
* - A `retryIds` job redelivers to exactly those ids and DOES throw while any
|
|
644
|
+
* of them still fails, so the queue's backoff/dead-letter bounds it. That
|
|
645
|
+
* message contains no already-delivered recipient, so nothing is re-sent.
|
|
646
|
+
* - Gone subscriptions (404/410, FCM `UNREGISTERED`) are pruned by the page and
|
|
647
|
+
* never appear in `failedIds` — an all-`pruned` page is a success, not a
|
|
648
|
+
* failure, as is an empty page.
|
|
413
649
|
*/
|
|
414
|
-
declare const
|
|
650
|
+
declare const runPushBroadcastPage: (push: LunoraPush, job: PushBroadcastJob) => Promise<PushBroadcastPageOutcome>;
|
|
415
651
|
/**
|
|
416
652
|
* The minimal structural slice of Cloudflare's `D1Database` this store uses. A
|
|
417
653
|
* structural type (rather than importing `@cloudflare/workers-types`) keeps the
|
|
@@ -438,6 +674,15 @@ interface D1StoreOptions {
|
|
|
438
674
|
* backing table is created lazily on first use (`CREATE TABLE IF NOT EXISTS`), so
|
|
439
675
|
* no migration step is required for the subscription table itself.
|
|
440
676
|
*
|
|
677
|
+
* ID SCHEME / LAZY MIGRATION: `id` (the `PRIMARY KEY`, upserted via `ON
|
|
678
|
+
* CONFLICT(id) DO UPDATE`) is a version-prefixed digest of the endpoint/token —
|
|
679
|
+
* currently `wp2_`/`fcm2_` (64-bit FNV-1a; see `normalize.ts`). No table migration
|
|
680
|
+
* runs when the id scheme is revised: a returning device re-registers under its new
|
|
681
|
+
* id and upserts a fresh row, while its old-prefix row (`wp_`/`fcm_`) ages out via
|
|
682
|
+
* the normal gone-pruning on the next failed send. So a table can transiently hold
|
|
683
|
+
* both an old- and new-prefix row for one device — expected, self-healing, and the
|
|
684
|
+
* reason a prefix must NEVER be reused for a different scheme.
|
|
685
|
+
*
|
|
441
686
|
* ```ts
|
|
442
687
|
* export default defineNotify({
|
|
443
688
|
* webPush: (env) => webPushFromEnv(env),
|
|
@@ -453,16 +698,57 @@ declare const d1SubscriptionStore: (database: D1Like, options?: D1StoreOptions)
|
|
|
453
698
|
* (or another backing store) for production so subscriptions survive restarts.
|
|
454
699
|
*/
|
|
455
700
|
declare const memorySubscriptionStore: () => SubscriptionStore;
|
|
456
|
-
/**
|
|
701
|
+
/**
|
|
702
|
+
* Stable store id for a web-push endpoint — `fnv1a64Hex` of the (long) endpoint,
|
|
703
|
+
* so re-registering the same device upserts rather than duplicates.
|
|
704
|
+
*
|
|
705
|
+
* The digest comes from the canonical `shared/fnv1a`, not a local copy. This id
|
|
706
|
+
* is a PERSISTED primary key: a digest that drifts in one copy silently re-keys
|
|
707
|
+
* every existing subscription — the old row goes dark and the device
|
|
708
|
+
* re-registers as a duplicate — so the implementation must have exactly one
|
|
709
|
+
* home. `shared/fnv1a`'s is bit-verified against a BigInt reference in
|
|
710
|
+
* `packages/replica/__tests__/apply-diff.test.ts`.
|
|
711
|
+
*
|
|
712
|
+
* Widened from the previous 32-bit FNV-1a (8 hex): at 100K devices a 32-bit key
|
|
713
|
+
* collides with ~68% probability (birthday bound), and a collision silently
|
|
714
|
+
* overwrites another device's row under the store's `ON CONFLICT(id) DO UPDATE` —
|
|
715
|
+
* so the wrong user gets the push and the victim goes dark. 64 bits drops that to
|
|
716
|
+
* negligible at any realistic device count.
|
|
717
|
+
*
|
|
718
|
+
* The `wp2_` prefix is a version tag (see also {@link fcmId}'s `fcm2_`): it marks
|
|
719
|
+
* the 64-bit-id revision so the pre-existing 32-bit `wp_` rows stay readable and a
|
|
720
|
+
* returning device simply re-registers under the new id, its stale `wp_` row aging
|
|
721
|
+
* out via normal gone-pruning. A future third revision must mint `wp3_` and repeat
|
|
722
|
+
* the lazy migration — NEVER reuse a prefix.
|
|
723
|
+
*/
|
|
457
724
|
declare const webPushId: (endpoint: string) => string;
|
|
458
|
-
/** Stable store id for an FCM device token. */
|
|
725
|
+
/** Stable store id for an FCM device token. See {@link webPushId} for the `_2` version-prefix contract. */
|
|
459
726
|
declare const fcmId: (token: string) => string;
|
|
727
|
+
/** Options threaded into {@link normalizeRegisterInput} from the notify definition. */
|
|
728
|
+
interface NormalizeOptions {
|
|
729
|
+
/**
|
|
730
|
+
* Exact origins (`https://host[:port]`) a web-push endpoint may register from.
|
|
731
|
+
* When set (non-empty), the endpoint's origin must be one of these — the
|
|
732
|
+
* strongest anti-SSRF posture, and the ONLY way to close DNS rebinding for a
|
|
733
|
+
* facade that accepts client-controlled endpoints.
|
|
734
|
+
*
|
|
735
|
+
* When unset, the default posture applies: `https:` scheme + a host the
|
|
736
|
+
* {@link assertPushEndpoint} STRING classifier does not flag as
|
|
737
|
+
* private/loopback, plus a resolved-address re-check at send time. Setting
|
|
738
|
+
* this allowlist replaces both with an exact-origin match — the hard
|
|
739
|
+
* guarantee, and the only one that also covers an internal push service you
|
|
740
|
+
* deliberately want to reach.
|
|
741
|
+
*/
|
|
742
|
+
allowedPushOrigins?: string[];
|
|
743
|
+
}
|
|
460
744
|
/**
|
|
461
745
|
* Normalise a `register(...)` input into a {@link StoredSubscription}. Validates
|
|
462
746
|
* the shape (a web-push subscription needs `endpoint` + `keys.{p256dh,auth}`; an
|
|
463
|
-
* FCM entry needs a non-empty `token`)
|
|
747
|
+
* FCM entry needs a non-empty `token`), enforces the anti-SSRF endpoint boundary
|
|
748
|
+
* (see {@link assertPushEndpoint}), validates `metadata` (see
|
|
749
|
+
* {@link validateMetadata}), and stamps `createdAt`/`lastSeenAt`.
|
|
464
750
|
*/
|
|
465
|
-
declare const normalizeRegisterInput: (input: RegisterInput, now?: number) => StoredSubscription;
|
|
751
|
+
declare const normalizeRegisterInput: (input: RegisterInput, now?: number, options?: NormalizeOptions) => StoredSubscription;
|
|
466
752
|
/**
|
|
467
753
|
* The provider `to` target for a stored subscription: the W3C Push subscription
|
|
468
754
|
* (JSON-stringified) for web-push, or the raw device token for FCM. Matches the
|
|
@@ -481,4 +767,80 @@ declare const targetOf: (subscription: StoredSubscription) => string;
|
|
|
481
767
|
* (a cert/session expiry) can never permanently drop a valid subscription.
|
|
482
768
|
*/
|
|
483
769
|
declare const isGoneError: (message: string | undefined) => boolean;
|
|
484
|
-
export { type BroadcastOutcome, type BroadcastResult, type CreateNotifyOptions, type D1Like, type D1PreparedLike, type D1StoreOptions,
|
|
770
|
+
export { type BroadcastOutcome, type BroadcastResult, type CreateNotifyOptions, type D1Like, type D1PreparedLike, type D1StoreOptions,
|
|
771
|
+
/**
|
|
772
|
+
* `@lunora/notify`
|
|
773
|
+
*
|
|
774
|
+
* Multi-channel notifications for Lunora, wrapping the `@visulima/notification`
|
|
775
|
+
* engine. `defineNotify` in `lunora/notify.ts` configures the edge-safe channels
|
|
776
|
+
* (Web Push + FCM, plus chat / in-app inbox / webhook); codegen wires `ctx.notify`
|
|
777
|
+
* and its `ctx.push` alias onto every handler ctx from it (mirroring `defineFlags`
|
|
778
|
+
* → `ctx.flags`).
|
|
779
|
+
*
|
|
780
|
+
* Edge-safety: Web Push (VAPID + RFC 8291) and FCM (HTTP v1) run on `fetch` + Web
|
|
781
|
+
* Crypto under workerd. APNs (`node:http2`) and SMS / Node-only queue adapters are
|
|
782
|
+
* deliberately **not** on the edge facade — route heavy fan-out through
|
|
783
|
+
* `@lunora/queue` (`enqueuePushBroadcast` / `runPushBroadcastPage`).
|
|
784
|
+
*
|
|
785
|
+
* - `@lunora/notify` — `defineNotify`, `createNotify`, config resolvers, subscription stores and types.
|
|
786
|
+
* - `@lunora/notify/web` — the browser `subscribeToPush` service-worker helper.
|
|
787
|
+
* @packageDocumentation
|
|
788
|
+
*/
|
|
789
|
+
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 PushSubscriptionDevice, type PushSubscriptionsResult, type QueueProducerLike, type RegisterInput, type ResolvedProviders, type RoutingPushOptions, type StoredSubscription, type SubscriptionFilter, type SubscriptionKind, type SubscriptionStatus, type SubscriptionStore,
|
|
790
|
+
/**
|
|
791
|
+
* `@lunora/notify`
|
|
792
|
+
*
|
|
793
|
+
* Multi-channel notifications for Lunora, wrapping the `@visulima/notification`
|
|
794
|
+
* engine. `defineNotify` in `lunora/notify.ts` configures the edge-safe channels
|
|
795
|
+
* (Web Push + FCM, plus chat / in-app inbox / webhook); codegen wires `ctx.notify`
|
|
796
|
+
* and its `ctx.push` alias onto every handler ctx from it (mirroring `defineFlags`
|
|
797
|
+
* → `ctx.flags`).
|
|
798
|
+
*
|
|
799
|
+
* Edge-safety: Web Push (VAPID + RFC 8291) and FCM (HTTP v1) run on `fetch` + Web
|
|
800
|
+
* Crypto under workerd. APNs (`node:http2`) and SMS / Node-only queue adapters are
|
|
801
|
+
* deliberately **not** on the edge facade — route heavy fan-out through
|
|
802
|
+
* `@lunora/queue` (`enqueuePushBroadcast` / `runPushBroadcastPage`).
|
|
803
|
+
*
|
|
804
|
+
* - `@lunora/notify` — `defineNotify`, `createNotify`, config resolvers, subscription stores and types.
|
|
805
|
+
* - `@lunora/notify/web` — the browser `subscribeToPush` service-worker helper.
|
|
806
|
+
* @packageDocumentation
|
|
807
|
+
*/
|
|
808
|
+
WEB_PUSH_ENV_KEYS, type WebPushConfigFactory, buildEngine, createNotify, d1SubscriptionStore, defineNotify, enqueuePushBroadcast,
|
|
809
|
+
/**
|
|
810
|
+
* `@lunora/notify`
|
|
811
|
+
*
|
|
812
|
+
* Multi-channel notifications for Lunora, wrapping the `@visulima/notification`
|
|
813
|
+
* engine. `defineNotify` in `lunora/notify.ts` configures the edge-safe channels
|
|
814
|
+
* (Web Push + FCM, plus chat / in-app inbox / webhook); codegen wires `ctx.notify`
|
|
815
|
+
* and its `ctx.push` alias onto every handler ctx from it (mirroring `defineFlags`
|
|
816
|
+
* → `ctx.flags`).
|
|
817
|
+
*
|
|
818
|
+
* Edge-safety: Web Push (VAPID + RFC 8291) and FCM (HTTP v1) run on `fetch` + Web
|
|
819
|
+
* Crypto under workerd. APNs (`node:http2`) and SMS / Node-only queue adapters are
|
|
820
|
+
* deliberately **not** on the edge facade — route heavy fan-out through
|
|
821
|
+
* `@lunora/queue` (`enqueuePushBroadcast` / `runPushBroadcastPage`).
|
|
822
|
+
*
|
|
823
|
+
* - `@lunora/notify` — `defineNotify`, `createNotify`, config resolvers, subscription stores and types.
|
|
824
|
+
* - `@lunora/notify/web` — the browser `subscribeToPush` service-worker helper.
|
|
825
|
+
* @packageDocumentation
|
|
826
|
+
*/
|
|
827
|
+
fcmFromEnv, fcmId, isGoneError, isNotifyDefinition, memorySubscriptionStore, normalizeRegisterInput, routingPushProvider, runPushBroadcastPage, targetOf,
|
|
828
|
+
/**
|
|
829
|
+
* `@lunora/notify`
|
|
830
|
+
*
|
|
831
|
+
* Multi-channel notifications for Lunora, wrapping the `@visulima/notification`
|
|
832
|
+
* engine. `defineNotify` in `lunora/notify.ts` configures the edge-safe channels
|
|
833
|
+
* (Web Push + FCM, plus chat / in-app inbox / webhook); codegen wires `ctx.notify`
|
|
834
|
+
* and its `ctx.push` alias onto every handler ctx from it (mirroring `defineFlags`
|
|
835
|
+
* → `ctx.flags`).
|
|
836
|
+
*
|
|
837
|
+
* Edge-safety: Web Push (VAPID + RFC 8291) and FCM (HTTP v1) run on `fetch` + Web
|
|
838
|
+
* Crypto under workerd. APNs (`node:http2`) and SMS / Node-only queue adapters are
|
|
839
|
+
* deliberately **not** on the edge facade — route heavy fan-out through
|
|
840
|
+
* `@lunora/queue` (`enqueuePushBroadcast` / `runPushBroadcastPage`).
|
|
841
|
+
*
|
|
842
|
+
* - `@lunora/notify` — `defineNotify`, `createNotify`, config resolvers, subscription stores and types.
|
|
843
|
+
* - `@lunora/notify/web` — the browser `subscribeToPush` service-worker helper.
|
|
844
|
+
* @packageDocumentation
|
|
845
|
+
*/
|
|
846
|
+
webPushFromEnv, webPushId };
|