@lunora/notify 1.0.0-alpha.1 → 1.0.0-alpha.100
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 +154 -17
- package/dist/index.d.mts +623 -49
- package/dist/index.d.ts +623 -49
- package/dist/index.mjs +1 -8
- package/dist/packem_shared/FCM_ENV_KEYS-BbhPScGH.mjs +1 -0
- package/dist/packem_shared/buildEngine-x7r_sr3M.mjs +1 -0
- package/dist/packem_shared/createNotify-hH_Y5OJQ.mjs +1 -0
- package/dist/packem_shared/d1SubscriptionStore-D80r22Vc.mjs +1 -0
- package/dist/packem_shared/defineNotify-DVPpVkU0.mjs +1 -0
- package/dist/packem_shared/enqueuePushBroadcast-C9tO0BZj.mjs +1 -0
- package/dist/packem_shared/fcmId-o_liCQKp.mjs +1 -0
- package/dist/packem_shared/memorySubscriptionStore-Ccr3ErTV.mjs +1 -0
- package/dist/packem_shared/normalize-B5B9QUol.mjs +1 -0
- package/dist/web.d.mts +48 -18
- package/dist/web.d.ts +48 -18
- 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-Gg40Htm-.mjs +0 -128
- 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/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
|
|
@@ -75,8 +102,58 @@ type RegisterInput = {
|
|
|
75
102
|
};
|
|
76
103
|
/** Filter narrowing which stored subscriptions a `list`/`broadcast` targets. */
|
|
77
104
|
interface SubscriptionFilter {
|
|
105
|
+
/**
|
|
106
|
+
* Keyset pagination cursor: return only rows with `id` strictly GREATER
|
|
107
|
+
* than this value, ordered ascending by `id`. `id` is a stable,
|
|
108
|
+
* content-derived hash (see `webPushId`/`fcmId`), so ordering by it is
|
|
109
|
+
* immune to concurrent inserts/deletes elsewhere in the table — a page
|
|
110
|
+
* already walked never re-delivers or skips a row when another device
|
|
111
|
+
* registers mid-broadcast (the reviewer-flagged "stable under concurrent
|
|
112
|
+
* registers" property). `broadcastPage`/`broadcast` set this internally to
|
|
113
|
+
* walk pages; a direct `list()` caller may also page through results with
|
|
114
|
+
* it.
|
|
115
|
+
*
|
|
116
|
+
* OPTIONAL for a reason: `SubscriptionStore` is implementable outside this
|
|
117
|
+
* package. An external store that does not support cursoring may ignore
|
|
118
|
+
* `after` entirely and keep returning its (from-the-top) unpaged result —
|
|
119
|
+
* `broadcastPage` defensively re-filters whatever the store returns down
|
|
120
|
+
* to `id > after` itself, so a non-cursoring store can never cause a
|
|
121
|
+
* double-send or an infinite page-walk (each page's result only ever
|
|
122
|
+
* contains ids the previous page didn't already deliver), but it also
|
|
123
|
+
* cannot deliver the FULL matched audience beyond whatever the store's own
|
|
124
|
+
* (unpaged) response window happens to contain — implement `after`
|
|
125
|
+
* (ordered ascending by `id`, exclusive) to get real, complete pagination
|
|
126
|
+
* over a large audience.
|
|
127
|
+
*/
|
|
128
|
+
after?: string;
|
|
78
129
|
/** Restrict to a delivery kind. */
|
|
79
130
|
kind?: SubscriptionKind;
|
|
131
|
+
/**
|
|
132
|
+
* Cap the number of rows returned (a `LIMIT`). Applied server-side by the
|
|
133
|
+
* store, so a large audience never materializes wholesale in the isolate.
|
|
134
|
+
* A non-positive/absent value means "no cap"; a fractional value is truncated.
|
|
135
|
+
*
|
|
136
|
+
* For `list`/admin reads this bounds the returned page as before. For
|
|
137
|
+
* `broadcast`, this is now an OVERALL cap on the total number of
|
|
138
|
+
* subscriptions reached across every internally-walked page (still
|
|
139
|
+
* deliberately left unset by default — it must reach every matched
|
|
140
|
+
* device); the PER-PAGE batch size is a separate, independent knob (see
|
|
141
|
+
* `defineNotify`'s `broadcastPageSize`, default 250) so a caller
|
|
142
|
+
* that sets `limit` to bound the audience doesn't also have to reason
|
|
143
|
+
* about page sizing.
|
|
144
|
+
*
|
|
145
|
+
* The non-positive sentinel means something different at each layer: at
|
|
146
|
+
* the STORE layer (`list`, and the `d1-store`/`memory-store` fetch-size
|
|
147
|
+
* hint) a non-positive `limit` means "no cap" — fetch everything. At the
|
|
148
|
+
* `broadcast`/`broadcastPage` layer, where `limit` is an AUDIENCE cap, a
|
|
149
|
+
* non-positive value instead means "no deliveries" — `broadcast({ limit: 0
|
|
150
|
+
* })` reaches nobody, not everybody. This asymmetry is deliberate: the two
|
|
151
|
+
* layers answer different questions ("how many rows to fetch" vs. "how
|
|
152
|
+
* many recipients to reach"), and unifying them would either break `list`
|
|
153
|
+
* callers relying on "no cap" or reintroduce the over-delivery this
|
|
154
|
+
* distinction fixes (see `broadcastPage`'s doc comment).
|
|
155
|
+
*/
|
|
156
|
+
limit?: number;
|
|
80
157
|
/** Restrict to a single owning user. */
|
|
81
158
|
userId?: string | null;
|
|
82
159
|
}
|
|
@@ -86,15 +163,78 @@ interface SubscriptionFilter {
|
|
|
86
163
|
* and a D1-backed store (durable, edge-safe).
|
|
87
164
|
*/
|
|
88
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>;
|
|
89
173
|
/** Remove a subscription by id (idempotent). */
|
|
90
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>;
|
|
91
199
|
/** Read a subscription by id, or `undefined`. */
|
|
92
200
|
get: (id: string) => Promise<StoredSubscription | undefined>;
|
|
93
|
-
/**
|
|
201
|
+
/**
|
|
202
|
+
* List subscriptions, optionally filtered. When `filter.after` is set,
|
|
203
|
+
* results are keyset-paginated: only rows with `id` strictly greater than
|
|
204
|
+
* `filter.after` are returned, ordered ascending by `id`. Implementing
|
|
205
|
+
* `after` is OPTIONAL (see {@link SubscriptionFilter.after}) — a store
|
|
206
|
+
* that ignores it may keep returning its unpaged result.
|
|
207
|
+
*/
|
|
94
208
|
list: (filter?: SubscriptionFilter) => Promise<StoredSubscription[]>;
|
|
95
209
|
/** Record the latest delivery outcome for a subscription (best-effort). */
|
|
96
210
|
markStatus: (id: string, status: SubscriptionStatus, error?: string) => Promise<void>;
|
|
97
|
-
/**
|
|
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
|
+
*/
|
|
98
238
|
put: (subscription: StoredSubscription) => Promise<StoredSubscription>;
|
|
99
239
|
}
|
|
100
240
|
/** Per-recipient outcome from a fan-out `broadcast`. */
|
|
@@ -119,6 +259,61 @@ interface BroadcastResult {
|
|
|
119
259
|
/** Total subscriptions attempted. */
|
|
120
260
|
total: number;
|
|
121
261
|
}
|
|
262
|
+
/**
|
|
263
|
+
* Result of `broadcastPage` — one bounded page of a fan-out, plus the cursor
|
|
264
|
+
* to fetch the next page. `nextCursor` is `undefined` when this was the last
|
|
265
|
+
* page (or the store doesn't support cursoring — see
|
|
266
|
+
* {@link SubscriptionFilter.after}'s documented unpaged fallback).
|
|
267
|
+
*/
|
|
268
|
+
interface BroadcastPageResult {
|
|
269
|
+
/** Cursor for the next page (pass as `filter.after`), or `undefined` when done. */
|
|
270
|
+
nextCursor?: string;
|
|
271
|
+
/** The delivery outcome for just this page. */
|
|
272
|
+
result: BroadcastResult;
|
|
273
|
+
}
|
|
274
|
+
/**
|
|
275
|
+
* The compact, stable delivery-status vocabulary emitted on notify observability
|
|
276
|
+
* signals — the `status` dimension on the `notify.send` metric and the failure
|
|
277
|
+
* log line. Modeled on Novu's execution status, but honest to edge push:
|
|
278
|
+
*
|
|
279
|
+
* - `accepted` — the provider took the message (a `Receipt.successful` send).
|
|
280
|
+
* - `failed` — a provider error; the log line carries the `error` text.
|
|
281
|
+
* - `gone` — the endpoint is unregistered (Web Push 404/410, FCM's `NOT_FOUND` for a dead token) and pruned; push-only.
|
|
282
|
+
*
|
|
283
|
+
* Web Push and FCM give no delivery/open receipts, so the vocabulary stops at the
|
|
284
|
+
* send attempt: a `delivered`/`opened` status would be a lie for these channels.
|
|
285
|
+
* The one place a later `seen`/`read` is real is the in-app inbox, where the
|
|
286
|
+
* client posts a read receipt back — out of scope here.
|
|
287
|
+
*/
|
|
288
|
+
type NotifyDeliveryStatus = "accepted" | "failed" | "gone";
|
|
289
|
+
/**
|
|
290
|
+
* Why a send fanned out to nobody — the "sent 0 because…" signal (mirrors Novu's
|
|
291
|
+
* pre-send `DetailEnum` reasons). Emitted as the `reason` dimension on a
|
|
292
|
+
* `notify.skipped` metric so a no-op is visible in the Studio metric/trend view
|
|
293
|
+
* instead of silent.
|
|
294
|
+
*
|
|
295
|
+
* - `no-subscriptions-matched` — the store held no device for the broadcast filter.
|
|
296
|
+
* - `channel-not-configured` — the target channel was never wired in `defineNotify`.
|
|
297
|
+
*/
|
|
298
|
+
type NotifySkipReason = "channel-not-configured" | "no-subscriptions-matched";
|
|
299
|
+
/**
|
|
300
|
+
* The minimal structural slice of `ctx.log` the notify facade emits through — just
|
|
301
|
+
* the `warn` severity it uses for a failed delivery. Structural (rather than a
|
|
302
|
+
* dependency on `@lunora/server`'s `LunoraLogger`) so codegen passes the real
|
|
303
|
+
* `ctx.log` and a test passes a spy — the D1-store `D1Like` pattern, applied to
|
|
304
|
+
* observability.
|
|
305
|
+
*/
|
|
306
|
+
interface NotifyLogger {
|
|
307
|
+
warn: (message: string, fields?: Record<string, unknown>) => void;
|
|
308
|
+
}
|
|
309
|
+
/**
|
|
310
|
+
* The minimal structural slice of `ctx.metrics` the notify facade emits through —
|
|
311
|
+
* the `count` instrument backing the `notify.send` / `notify.skipped` series.
|
|
312
|
+
* Structural for the same reason as {@link NotifyLogger}.
|
|
313
|
+
*/
|
|
314
|
+
interface NotifyMetrics {
|
|
315
|
+
count: (name: string, value?: number, attributes?: Record<string, unknown>) => void;
|
|
316
|
+
}
|
|
122
317
|
/**
|
|
123
318
|
* The push sub-facade — spliced onto ctx as `ctx.push` (and reachable as
|
|
124
319
|
* `ctx.notify.push`). Owns the device-subscription lifecycle plus targeted and
|
|
@@ -128,20 +323,96 @@ interface LunoraPush {
|
|
|
128
323
|
/**
|
|
129
324
|
* Fan-out a push to every stored subscription matching `filter` (default: all).
|
|
130
325
|
* Reuses the engine's retry/circuit-breaker middleware; prunes subscriptions
|
|
131
|
-
* the push service reports as gone (
|
|
326
|
+
* the push service reports as gone (Web Push 404/410, FCM's `NOT_FOUND` for a dead token). The `to`
|
|
132
327
|
* target is derived from each subscription, so it is omitted from the payload.
|
|
328
|
+
*
|
|
329
|
+
* Internally walks the audience in bounded pages (via {@link LunoraPush.broadcastPage},
|
|
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.
|
|
133
338
|
*/
|
|
134
339
|
broadcast: (payload: PushContent, filter?: SubscriptionFilter) => Promise<BroadcastResult>;
|
|
135
|
-
/**
|
|
136
|
-
|
|
137
|
-
|
|
340
|
+
/**
|
|
341
|
+
* Fan-out a push to ONE bounded page of stored subscriptions matching
|
|
342
|
+
* `filter` (page size: `defineNotify`'s `broadcastPageSize`, default
|
|
343
|
+
* 250, capped by `filter.limit` when set). Same delivery semantics as
|
|
344
|
+
* {@link LunoraPush.broadcast} (retry/circuit-breaker, gone-pruning) but
|
|
345
|
+
* scoped to a single page; returns the page's own {@link BroadcastResult}
|
|
346
|
+
* plus a `nextCursor` to fetch the next page (`undefined` when done).
|
|
347
|
+
* Backs `runPushBroadcastPage` so one queue message does bounded work
|
|
348
|
+
* regardless of audience size — most app code should call
|
|
349
|
+
* {@link LunoraPush.broadcast} instead.
|
|
350
|
+
*/
|
|
351
|
+
broadcastPage: (payload: PushContent, filter?: SubscriptionFilter) => Promise<BroadcastPageResult>;
|
|
352
|
+
/**
|
|
353
|
+
* List stored subscriptions (optionally filtered), with the delivery
|
|
354
|
+
* **secrets** stripped — the Web Push `keys` (RFC 8291 `auth`/`p256dh`) and the
|
|
355
|
+
* FCM `token`. Those, plus the endpoint, are enough to deliver arbitrary push to
|
|
356
|
+
* a device, so no READ on this facade returns them; the raw rows are otherwise
|
|
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.
|
|
362
|
+
*/
|
|
363
|
+
list: (filter?: SubscriptionFilter) => Promise<PushSubscriptionDevice[]>;
|
|
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
|
+
*/
|
|
138
376
|
register: (input: RegisterInput) => Promise<StoredSubscription>;
|
|
139
377
|
/** Send a push to a single stored subscription (by id or record); `to` is derived from it. */
|
|
140
378
|
send: (target: StoredSubscription | string, payload: PushContent) => Promise<Receipt>;
|
|
141
|
-
/**
|
|
142
|
-
|
|
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>;
|
|
143
402
|
}
|
|
144
|
-
/**
|
|
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;
|
|
410
|
+
}
|
|
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
|
+
*/
|
|
145
416
|
type PushContent = Omit<PushPayload, "to">;
|
|
146
417
|
/**
|
|
147
418
|
* The multi-channel notification facade — spliced onto ctx as `ctx.notify`.
|
|
@@ -150,7 +421,7 @@ type PushContent = Omit<PushPayload, "to">;
|
|
|
150
421
|
* single-channel convenience senders for the edge-safe channels.
|
|
151
422
|
*/
|
|
152
423
|
interface LunoraNotify {
|
|
153
|
-
/**
|
|
424
|
+
/** Post to a chat channel (Slack/Discord/Teams/Telegram). */
|
|
154
425
|
chat: (payload: ChatPayload) => Promise<Receipt>;
|
|
155
426
|
/** Deliver an in-app inbox notification. */
|
|
156
427
|
inApp: (payload: InAppPayload) => Promise<Receipt>;
|
|
@@ -158,7 +429,7 @@ interface LunoraNotify {
|
|
|
158
429
|
push: LunoraPush;
|
|
159
430
|
/** Deliver a multi-channel message (one payload per channel). */
|
|
160
431
|
send: (message: NotificationMessage) => Promise<Receipt[]>;
|
|
161
|
-
/**
|
|
432
|
+
/** Send an outbound webhook. */
|
|
162
433
|
webhook: (payload: WebhookPayload) => Promise<Receipt>;
|
|
163
434
|
}
|
|
164
435
|
/**
|
|
@@ -170,11 +441,48 @@ type WebPushConfigFactory = (env: NotifyEnv) => WebPushConfig | undefined;
|
|
|
170
441
|
type FcmConfigFactory = (env: NotifyEnv) => FcmConfig | undefined;
|
|
171
442
|
/** Options accepted by `defineNotify`. */
|
|
172
443
|
interface NotifyConfig {
|
|
444
|
+
/**
|
|
445
|
+
* Exact origins (`https://host[:port]`) a client-supplied Web Push `endpoint`
|
|
446
|
+
* may register from. When set (non-empty), `register()` requires the endpoint's
|
|
447
|
+
* origin to be one of these — the strongest anti-SSRF posture, and the way to
|
|
448
|
+
* close DNS rebinding for a facade that accepts client-controlled endpoints.
|
|
449
|
+
*
|
|
450
|
+
* When unset, the default posture applies: an endpoint must be `https:` with a
|
|
451
|
+
* host a STRING classifier does not flag as private / loopback / link-local.
|
|
452
|
+
* That classifier does NOT resolve DNS, so a public hostname resolving to a
|
|
453
|
+
* private/internal IP (e.g. `https://127.0.0.1.nip.io/…`) is NOT blocked by it
|
|
454
|
+
* — `register()` also emits a one-shot dev warning in this case. Set this to the
|
|
455
|
+
* push services your app actually uses (e.g. `["https://fcm.googleapis.com",
|
|
456
|
+
* "https://updates.push.services.mozilla.com"]` — exact origins only, no
|
|
457
|
+
* wildcards) to hard-pin the boundary and close DNS rebinding.
|
|
458
|
+
*/
|
|
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;
|
|
173
475
|
/**
|
|
174
476
|
* Optional chat provider factory (Slack/Discord/Teams/Telegram). Wire with a
|
|
175
477
|
* provider from `@visulima/notification/providers/*`. Edge-safe (fetch-based).
|
|
176
478
|
*/
|
|
177
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;
|
|
178
486
|
/** FCM (Firebase Cloud Messaging HTTP v1) config. Edge-safe — supply an OAuth2 token. */
|
|
179
487
|
fcm?: FcmConfig | FcmConfigFactory;
|
|
180
488
|
/** Optional in-app inbox provider factory. Edge-safe. */
|
|
@@ -260,7 +568,21 @@ declare const defineNotify: (config: NotifyConfig) => NotifyDefinition;
|
|
|
260
568
|
declare const isNotifyDefinition: (value: unknown) => value is NotifyDefinition;
|
|
261
569
|
/** Options for {@link createNotify}. */
|
|
262
570
|
interface CreateNotifyOptions {
|
|
263
|
-
/**
|
|
571
|
+
/**
|
|
572
|
+
* Page size for `push.broadcast`'s internal keyset pagination over the
|
|
573
|
+
* subscription store (default {@link DEFAULT_BROADCAST_PAGE_SIZE}, 250).
|
|
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.
|
|
579
|
+
*/
|
|
580
|
+
broadcastPageSize?: number;
|
|
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
|
+
*/
|
|
264
586
|
concurrency?: number;
|
|
265
587
|
/**
|
|
266
588
|
* Override the assembled `@visulima/notification` engine. Advanced/testing
|
|
@@ -268,6 +590,22 @@ interface CreateNotifyOptions {
|
|
|
268
590
|
* config resolution entirely.
|
|
269
591
|
*/
|
|
270
592
|
engine?: Notification;
|
|
593
|
+
/**
|
|
594
|
+
* The request's `ctx.log` (structural {@link NotifyLogger}). Codegen threads
|
|
595
|
+
* `ctx.log` in; when present the facade emits one `warn` line per FAILED
|
|
596
|
+
* delivery — trace-correlated to the enclosing action and durably archived by
|
|
597
|
+
* the log sink. Successes and prunes stay off the log to keep the archive
|
|
598
|
+
* clean; they are counted on `metrics` instead. Absent ⇒ no log emits.
|
|
599
|
+
*/
|
|
600
|
+
log?: NotifyLogger;
|
|
601
|
+
/**
|
|
602
|
+
* The request's `ctx.metrics` (structural {@link NotifyMetrics}). Codegen
|
|
603
|
+
* threads `ctx.metrics` in; when present the facade counts every send on the
|
|
604
|
+
* `notify.send` series (dimensions `channel` / `provider` / `status`) and every
|
|
605
|
+
* no-op on `notify.skipped` (`channel` / `reason`) — feeding the durable metric
|
|
606
|
+
* history + trend charts. Absent ⇒ no metric emits.
|
|
607
|
+
*/
|
|
608
|
+
metrics?: NotifyMetrics;
|
|
271
609
|
/** Suppress the in-memory-store dev warning (tests set this). */
|
|
272
610
|
silent?: boolean;
|
|
273
611
|
}
|
|
@@ -288,7 +626,19 @@ declare const createNotify: (definition: NotifyDefinition, env: NotifyEnv, optio
|
|
|
288
626
|
};
|
|
289
627
|
/** Options for {@link routingPushProvider}. */
|
|
290
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[];
|
|
291
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;
|
|
292
642
|
webPush?: Provider<unknown, PushPayload>;
|
|
293
643
|
}
|
|
294
644
|
/**
|
|
@@ -301,6 +651,8 @@ interface RoutingPushOptions {
|
|
|
301
651
|
declare const routingPushProvider: (options: RoutingPushOptions) => Provider<unknown, PushPayload>;
|
|
302
652
|
/** A resolved, ready-to-wire set of channel configs (edge-safe channels only). */
|
|
303
653
|
interface ResolvedProviders {
|
|
654
|
+
/** The definition's `allowedPushOrigins`, threaded to the push router's send-time SSRF guard. */
|
|
655
|
+
allowedPushOrigins?: string[];
|
|
304
656
|
chat?: Provider;
|
|
305
657
|
fcm?: FcmConfig;
|
|
306
658
|
inApp?: Provider;
|
|
@@ -318,47 +670,154 @@ declare const buildEngine: (resolved: ResolvedProviders) => Notification;
|
|
|
318
670
|
* A broadcast job body — the JSON-serialisable payload enqueued for off-request
|
|
319
671
|
* fan-out. Shaped to travel through a `@lunora/queue` producer/consumer without
|
|
320
672
|
* `@lunora/notify` depending on `@lunora/queue` (the seam stays structural).
|
|
673
|
+
* `filter.after`, when set, resumes a broadcast partway through (see
|
|
674
|
+
* {@link runPushBroadcastPage}'s continuation semantics).
|
|
321
675
|
*/
|
|
322
676
|
interface PushBroadcastJob {
|
|
323
|
-
/** Subscription filter (which devices/users to target). */
|
|
677
|
+
/** Subscription filter (which devices/users to target; `filter.after` resumes a paged broadcast). */
|
|
324
678
|
filter?: SubscriptionFilter;
|
|
325
679
|
/** The push payload to deliver (the `to` target is derived per subscription). */
|
|
326
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[];
|
|
327
688
|
/** Discriminator so a shared queue can multiplex message kinds. */
|
|
328
689
|
type: "lunora.push.broadcast";
|
|
329
690
|
}
|
|
330
|
-
/**
|
|
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
|
+
}
|
|
722
|
+
/** The structural slice of a `@lunora/queue` producer (`ctx.queues.<name>`) used here. */
|
|
331
723
|
interface QueueProducerLike {
|
|
332
724
|
send: (body: PushBroadcastJob) => Promise<void>;
|
|
333
725
|
}
|
|
334
726
|
/**
|
|
335
727
|
* Enqueue a fan-out broadcast for background delivery through a `@lunora/queue`
|
|
336
|
-
* queue instead of blocking the request. Pair with {@link
|
|
337
|
-
* the queue consumer
|
|
728
|
+
* queue instead of blocking the request. Pair with {@link runPushBroadcastPage} in
|
|
729
|
+
* the queue consumer — see its doc comment for how a large audience continues
|
|
730
|
+
* across MULTIPLE messages (one bounded page per message), not one.
|
|
338
731
|
*
|
|
339
732
|
* ```ts
|
|
340
|
-
* //
|
|
341
|
-
*
|
|
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";
|
|
737
|
+
*
|
|
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);
|
|
742
|
+
*
|
|
743
|
+
* if (nextFilter !== undefined) {
|
|
744
|
+
* // More pages remain — enqueue the continuation. Each message still
|
|
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 });
|
|
748
|
+
* }
|
|
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
|
+
* });
|
|
342
767
|
*
|
|
343
|
-
* // in
|
|
344
|
-
*
|
|
345
|
-
* for (const message of batch.messages) await runPushBroadcastJob(ctx.push, message.body);
|
|
346
|
-
* }});
|
|
768
|
+
* // in a mutation/action, to start it:
|
|
769
|
+
* await enqueuePushBroadcast(ctx.queues.push, { payload: { body: "…", title: "New drop" } });
|
|
347
770
|
* ```
|
|
348
771
|
*/
|
|
349
772
|
declare const enqueuePushBroadcast: (queue: QueueProducerLike, job: Omit<PushBroadcastJob, "type">) => Promise<void>;
|
|
350
773
|
/**
|
|
351
|
-
* Run an enqueued broadcast job on the consumer side,
|
|
352
|
-
*
|
|
353
|
-
* gone
|
|
774
|
+
* Run ONE bounded page of an enqueued broadcast job on the consumer side,
|
|
775
|
+
* delivering through the push facade's {@link LunoraPush.broadcastPage} (which
|
|
776
|
+
* reuses the engine's retry + circuit-breaker middleware and prunes gone
|
|
777
|
+
* subscriptions).
|
|
778
|
+
*
|
|
779
|
+
* RETRY / CONTINUATION SEMANTICS:
|
|
780
|
+
*
|
|
781
|
+
* - A job processes exactly ONE bounded page (see `defineNotify`'s
|
|
782
|
+
* `broadcastPageSize`, default 250, or `job.filter.limit` when smaller),
|
|
783
|
+
* keyset-paginated on the subscription `id` (see `SubscriptionFilter.after`)
|
|
784
|
+
* — so per-message work is bounded regardless of total audience size.
|
|
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.
|
|
354
812
|
*/
|
|
355
|
-
declare const
|
|
813
|
+
declare const runPushBroadcastPage: (push: LunoraPush, job: PushBroadcastJob) => Promise<PushBroadcastPageOutcome>;
|
|
356
814
|
/**
|
|
357
815
|
* The minimal structural slice of Cloudflare's `D1Database` this store uses. A
|
|
358
816
|
* structural type (rather than importing `@cloudflare/workers-types`) keeps the
|
|
359
817
|
* store runtime-agnostic and trivially fakeable in tests.
|
|
360
818
|
*/
|
|
361
819
|
interface D1Like {
|
|
820
|
+
batch: (statements: D1PreparedLike[]) => Promise<unknown>;
|
|
362
821
|
prepare: (query: string) => D1PreparedLike;
|
|
363
822
|
}
|
|
364
823
|
interface D1PreparedLike {
|
|
@@ -374,18 +833,6 @@ interface D1StoreOptions {
|
|
|
374
833
|
/** Table name (default `lunora_push_subscriptions`). Must be a bare identifier. */
|
|
375
834
|
tableName?: string;
|
|
376
835
|
}
|
|
377
|
-
/**
|
|
378
|
-
* A D1-backed {@link SubscriptionStore}. Edge-safe (D1 is a Worker binding). The
|
|
379
|
-
* backing table is created lazily on first use (`CREATE TABLE IF NOT EXISTS`), so
|
|
380
|
-
* no migration step is required for the subscription table itself.
|
|
381
|
-
*
|
|
382
|
-
* ```ts
|
|
383
|
-
* export default defineNotify({
|
|
384
|
-
* webPush: (env) => webPushFromEnv(env),
|
|
385
|
-
* store: (env) => d1SubscriptionStore(env.DB),
|
|
386
|
-
* });
|
|
387
|
-
* ```
|
|
388
|
-
*/
|
|
389
836
|
declare const d1SubscriptionStore: (database: D1Like, options?: D1StoreOptions) => SubscriptionStore;
|
|
390
837
|
/**
|
|
391
838
|
* An in-memory {@link SubscriptionStore} — the zero-dependency default. Suitable
|
|
@@ -394,16 +841,57 @@ declare const d1SubscriptionStore: (database: D1Like, options?: D1StoreOptions)
|
|
|
394
841
|
* (or another backing store) for production so subscriptions survive restarts.
|
|
395
842
|
*/
|
|
396
843
|
declare const memorySubscriptionStore: () => SubscriptionStore;
|
|
397
|
-
/**
|
|
844
|
+
/**
|
|
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.
|
|
860
|
+
*
|
|
861
|
+
* The `wp2_` prefix is a version tag (see also {@link fcmId}'s `fcm2_`): it marks
|
|
862
|
+
* the 64-bit-id revision so the pre-existing 32-bit `wp_` rows stay readable and a
|
|
863
|
+
* returning device simply re-registers under the new id, its stale `wp_` row aging
|
|
864
|
+
* out via normal gone-pruning. A future third revision must mint `wp3_` and repeat
|
|
865
|
+
* the lazy migration — NEVER reuse a prefix.
|
|
866
|
+
*/
|
|
398
867
|
declare const webPushId: (endpoint: string) => string;
|
|
399
|
-
/** Stable store id for an FCM device token. */
|
|
868
|
+
/** Stable store id for an FCM device token. See {@link webPushId} for the `_2` version-prefix contract. */
|
|
400
869
|
declare const fcmId: (token: string) => string;
|
|
870
|
+
/** Options threaded into {@link normalizeRegisterInput} from the notify definition. */
|
|
871
|
+
interface NormalizeOptions {
|
|
872
|
+
/**
|
|
873
|
+
* Exact origins (`https://host[:port]`) a web-push endpoint may register from.
|
|
874
|
+
* When set (non-empty), the endpoint's origin must be one of these — the
|
|
875
|
+
* strongest anti-SSRF posture, and the ONLY way to close DNS rebinding for a
|
|
876
|
+
* facade that accepts client-controlled endpoints.
|
|
877
|
+
*
|
|
878
|
+
* When unset, the default posture applies: `https:` scheme + a host the
|
|
879
|
+
* {@link assertPushEndpoint} STRING classifier does not flag as
|
|
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.
|
|
884
|
+
*/
|
|
885
|
+
allowedPushOrigins?: string[];
|
|
886
|
+
}
|
|
401
887
|
/**
|
|
402
888
|
* Normalise a `register(...)` input into a {@link StoredSubscription}. Validates
|
|
403
889
|
* the shape (a web-push subscription needs `endpoint` + `keys.{p256dh,auth}`; an
|
|
404
|
-
* FCM entry needs a non-empty `token`)
|
|
890
|
+
* FCM entry needs a non-empty `token`), enforces the anti-SSRF endpoint boundary
|
|
891
|
+
* (see {@link assertPushEndpoint}), validates `metadata` (see
|
|
892
|
+
* {@link validateMetadata}), and stamps `createdAt`/`lastSeenAt`.
|
|
405
893
|
*/
|
|
406
|
-
declare const normalizeRegisterInput: (input: RegisterInput, now?: number) => StoredSubscription;
|
|
894
|
+
declare const normalizeRegisterInput: (input: RegisterInput, now?: number, options?: NormalizeOptions) => StoredSubscription;
|
|
407
895
|
/**
|
|
408
896
|
* The provider `to` target for a stored subscription: the W3C Push subscription
|
|
409
897
|
* (JSON-stringified) for web-push, or the raw device token for FCM. Matches the
|
|
@@ -415,11 +903,97 @@ declare const targetOf: (subscription: StoredSubscription) => string;
|
|
|
415
903
|
* (the browser/device unsubscribed) and should be pruned — as opposed to a
|
|
416
904
|
* transient failure worth retrying.
|
|
417
905
|
*
|
|
418
|
-
* Gates on STRUCTURED signals first:
|
|
419
|
-
*
|
|
420
|
-
*
|
|
421
|
-
*
|
|
422
|
-
*
|
|
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
|
|
423
998
|
*/
|
|
424
|
-
|
|
425
|
-
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 NotifyEnv, 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 };
|