@lunora/notify 1.0.0-alpha.1 → 1.0.0-alpha.10
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 +43 -1
- package/dist/index.d.mts +274 -15
- package/dist/index.d.ts +274 -15
- package/dist/index.mjs +1 -8
- package/dist/packem_shared/FCM_ENV_KEYS-D0tvRTLQ.mjs +1 -0
- package/dist/packem_shared/buildEngine-Jlzf2Jzn.mjs +1 -0
- package/dist/packem_shared/createNotify-jNlehALj.mjs +1 -0
- package/dist/packem_shared/d1SubscriptionStore-67jpK0Vx.mjs +1 -0
- package/dist/packem_shared/defineNotify-DLEy53HJ.mjs +1 -0
- package/dist/packem_shared/enqueuePushBroadcast-tf1LqgzA.mjs +1 -0
- package/dist/packem_shared/fcmId-CFZ8IquF.mjs +1 -0
- package/dist/packem_shared/memorySubscriptionStore-FKZR4-fB.mjs +1 -0
- package/dist/web.mjs +1 -44
- package/package.json +2 -2
- 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/README.md
CHANGED
|
@@ -98,6 +98,48 @@ for (const message of batch.messages) await runPushBroadcastJob(ctx.push, messag
|
|
|
98
98
|
|
|
99
99
|
`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
100
|
|
|
101
|
+
## Security
|
|
102
|
+
|
|
103
|
+
`ctx.push.register(...)` and the browser `subscribeToPush` helper both accept
|
|
104
|
+
client-supplied data, so the facade enforces two boundaries:
|
|
105
|
+
|
|
106
|
+
- **Endpoint validation (anti-SSRF).** Every later `send`/`broadcast` POSTs to a
|
|
107
|
+
subscription's stored Web Push `endpoint`, so a hostile `endpoint` would turn the
|
|
108
|
+
worker into an SSRF / amplification primitive. `register()` validates the endpoint
|
|
109
|
+
**at storage time** (the durable boundary): it must be an absolute `https:` URL
|
|
110
|
+
with a non-private / non-loopback / non-link-local / non-CGNAT host. To hard-pin
|
|
111
|
+
the boundary to the push services you actually use, set `allowedPushOrigins` on
|
|
112
|
+
`defineNotify` — when present, an endpoint's origin must match one of the listed
|
|
113
|
+
origins **exactly** (no wildcards), which also closes DNS rebinding:
|
|
114
|
+
|
|
115
|
+
```ts
|
|
116
|
+
export default defineNotify({
|
|
117
|
+
webPush: (env) => webPushFromEnv(env),
|
|
118
|
+
allowedPushOrigins: ["https://fcm.googleapis.com", "https://updates.push.services.mozilla.com"],
|
|
119
|
+
store: (env) => d1SubscriptionStore(env.DB),
|
|
120
|
+
});
|
|
121
|
+
```
|
|
122
|
+
|
|
123
|
+
- **No secrets on the app facade.** `ctx.push.list()`
|
|
124
|
+
returns the registered devices with the delivery **secrets stripped** — the Web
|
|
125
|
+
Push `keys` (`auth`/`p256dh`) and the FCM `token`, which together with the
|
|
126
|
+
endpoint are enough to deliver arbitrary push to a device. The raw rows are
|
|
127
|
+
reachable only through the internal `SubscriptionStore` (which handlers never
|
|
128
|
+
hold); the broadcast path uses the store directly.
|
|
129
|
+
|
|
130
|
+
## Delivery observability
|
|
131
|
+
|
|
132
|
+
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:
|
|
133
|
+
|
|
134
|
+
- **`notify.send`** `{ channel, provider, status }` — attempted sends. `status` is `accepted` (the provider took it), `failed`, or `gone` (endpoint unregistered — 404/410 / FCM `UNREGISTERED` — and pruned). A single send counts 1; a **broadcast aggregates** into one count per `(provider, status)` bucket (value = the bucket's count), not one per recipient — each `ctx.metrics.count` is a durable write.
|
|
135
|
+
- **`notify.skipped`** `{ channel, reason }` — a send that reached nobody: `no-subscriptions-matched` (empty broadcast) or `channel-not-configured`.
|
|
136
|
+
|
|
137
|
+
A **failed** send also emits one `ctx.log.warn` line carrying the error and, for push, the subscription/user ids — trace-correlated to the enclosing action and durably archived. Successes and prunes stay off the log; failure logs stay per-recipient even in a broadcast (they have no durable write).
|
|
138
|
+
|
|
139
|
+
`accepted` means the provider **accepted** the message, not that it was delivered or opened: Web Push and FCM give no delivery/open receipts, so the status stops at the send attempt. See [Observability → Delivery metrics](/docs/concepts/observability#delivery-metrics-notify).
|
|
140
|
+
|
|
101
141
|
## Status
|
|
102
142
|
|
|
103
|
-
|
|
143
|
+
Shipped: Web Push + FCM channels, chat / in-app / webhook senders, device-subscription storage (memory + D1), queue-backed fan-out, the codegen ctx-splice that auto-wires `ctx.notify` / `ctx.push` from `lunora/notify.ts` (via `createNotify`, mirroring `defineFlags` → `ctx.flags`), the `notify_send_outside_action` advisor lint, the Studio **Notifications** page (registered-device inspector), and [delivery observability](#delivery-observability).
|
|
144
|
+
|
|
145
|
+
Deferred: a filterable per-delivery **activity feed** and per-device history (a Novu-style drill-down). Web Push / FCM give no delivery/open receipts, so it would report only the send-attempt outcome; it needs a field-level predicate on the durable log reader (or a dedicated store) and is not planned until asked for.
|
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
|
+
* `CreateNotifyOptions`'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,61 @@ 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
|
+
}
|
|
190
|
+
/**
|
|
191
|
+
* The compact, stable delivery-status vocabulary emitted on notify observability
|
|
192
|
+
* signals — the `status` dimension on the `notify.send` metric and the failure
|
|
193
|
+
* log line. Modeled on Novu's execution status, but honest to edge push:
|
|
194
|
+
*
|
|
195
|
+
* - `accepted` — the provider took the message (a `Receipt.successful` send).
|
|
196
|
+
* - `failed` — a provider error; the log line carries the `error` text.
|
|
197
|
+
* - `gone` — the endpoint is unregistered (404/410, FCM `UNREGISTERED`) and pruned; push-only.
|
|
198
|
+
*
|
|
199
|
+
* Web Push and FCM give no delivery/open receipts, so the vocabulary stops at the
|
|
200
|
+
* send attempt: a `delivered`/`opened` status would be a lie for these channels.
|
|
201
|
+
* The one place a later `seen`/`read` is real is the in-app inbox, where the
|
|
202
|
+
* client posts a read receipt back — out of scope here.
|
|
203
|
+
*/
|
|
204
|
+
type NotifyDeliveryStatus = "accepted" | "failed" | "gone";
|
|
205
|
+
/**
|
|
206
|
+
* Why a send fanned out to nobody — the "sent 0 because…" signal (mirrors Novu's
|
|
207
|
+
* pre-send `DetailEnum` reasons). Emitted as the `reason` dimension on a
|
|
208
|
+
* `notify.skipped` metric so a no-op is visible in the Studio metric/trend view
|
|
209
|
+
* instead of silent.
|
|
210
|
+
*
|
|
211
|
+
* - `no-subscriptions-matched` — the store held no device for the broadcast filter.
|
|
212
|
+
* - `channel-not-configured` — the target channel was never wired in `defineNotify`.
|
|
213
|
+
*/
|
|
214
|
+
type NotifySkipReason = "channel-not-configured" | "no-subscriptions-matched";
|
|
215
|
+
/**
|
|
216
|
+
* The minimal structural slice of `ctx.log` the notify facade emits through — just
|
|
217
|
+
* the `warn` severity it uses for a failed delivery. Structural (rather than a
|
|
218
|
+
* dependency on `@lunora/server`'s `LunoraLogger`) so codegen passes the real
|
|
219
|
+
* `ctx.log` and a test passes a spy — the D1-store `D1Like` pattern, applied to
|
|
220
|
+
* observability.
|
|
221
|
+
*/
|
|
222
|
+
interface NotifyLogger {
|
|
223
|
+
warn: (message: string, fields?: Record<string, unknown>) => void;
|
|
224
|
+
}
|
|
225
|
+
/**
|
|
226
|
+
* The minimal structural slice of `ctx.metrics` the notify facade emits through —
|
|
227
|
+
* the `count` instrument backing the `notify.send` / `notify.skipped` series.
|
|
228
|
+
* Structural for the same reason as {@link NotifyLogger}.
|
|
229
|
+
*/
|
|
230
|
+
interface NotifyMetrics {
|
|
231
|
+
count: (name: string, value?: number, attributes?: Record<string, unknown>) => void;
|
|
232
|
+
}
|
|
122
233
|
/**
|
|
123
234
|
* The push sub-facade — spliced onto ctx as `ctx.push` (and reachable as
|
|
124
235
|
* `ctx.notify.push`). Owns the device-subscription lifecycle plus targeted and
|
|
@@ -130,10 +241,36 @@ interface LunoraPush {
|
|
|
130
241
|
* Reuses the engine's retry/circuit-breaker middleware; prunes subscriptions
|
|
131
242
|
* the push service reports as gone (HTTP 404/410, FCM `UNREGISTERED`). The `to`
|
|
132
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 `CreateNotifyOptions`'s
|
|
248
|
+
* `broadcastPageSize`. This call still processes the WHOLE matched
|
|
249
|
+
* audience in one request/queue message; use {@link LunoraPush.broadcastPage}
|
|
250
|
+
* directly (as `runPushBroadcastJob` does) to bound a single queue message
|
|
251
|
+
* to one page.
|
|
133
252
|
*/
|
|
134
253
|
broadcast: (payload: PushContent, filter?: SubscriptionFilter) => Promise<BroadcastResult>;
|
|
135
|
-
/**
|
|
136
|
-
|
|
254
|
+
/**
|
|
255
|
+
* Fan-out a push to ONE bounded page of stored subscriptions matching
|
|
256
|
+
* `filter` (page size: `CreateNotifyOptions`'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 `runPushBroadcastJob` 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[]>;
|
|
137
274
|
/** Register (upsert) a device subscription and return the stored record. */
|
|
138
275
|
register: (input: RegisterInput) => Promise<StoredSubscription>;
|
|
139
276
|
/** Send a push to a single stored subscription (by id or record); `to` is derived from it. */
|
|
@@ -170,6 +307,22 @@ type WebPushConfigFactory = (env: NotifyEnv) => WebPushConfig | undefined;
|
|
|
170
307
|
type FcmConfigFactory = (env: NotifyEnv) => FcmConfig | undefined;
|
|
171
308
|
/** Options accepted by `defineNotify`. */
|
|
172
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[];
|
|
173
326
|
/**
|
|
174
327
|
* Optional chat provider factory (Slack/Discord/Teams/Telegram). Wire with a
|
|
175
328
|
* provider from `@visulima/notification/providers/*`. Edge-safe (fetch-based).
|
|
@@ -260,6 +413,16 @@ declare const defineNotify: (config: NotifyConfig) => NotifyDefinition;
|
|
|
260
413
|
declare const isNotifyDefinition: (value: unknown) => value is NotifyDefinition;
|
|
261
414
|
/** Options for {@link createNotify}. */
|
|
262
415
|
interface CreateNotifyOptions {
|
|
416
|
+
/**
|
|
417
|
+
* Page size for `push.broadcast`'s internal keyset pagination over the
|
|
418
|
+
* subscription store (default {@link DEFAULT_BROADCAST_PAGE_SIZE}, 250).
|
|
419
|
+
* Each page is fetched, delivered, and counted independently before the
|
|
420
|
+
* next page's store round trip, so a huge audience is never materialized
|
|
421
|
+
* wholesale in the isolate. Also the per-message bound `push.broadcastPage`
|
|
422
|
+
* (and so `runPushBroadcastJob`) uses. A test/tuning seam — most apps never
|
|
423
|
+
* need to set this.
|
|
424
|
+
*/
|
|
425
|
+
broadcastPageSize?: number;
|
|
263
426
|
/** Max concurrent sends during a `broadcast` (default 10). */
|
|
264
427
|
concurrency?: number;
|
|
265
428
|
/**
|
|
@@ -268,6 +431,22 @@ interface CreateNotifyOptions {
|
|
|
268
431
|
* config resolution entirely.
|
|
269
432
|
*/
|
|
270
433
|
engine?: Notification;
|
|
434
|
+
/**
|
|
435
|
+
* The request's `ctx.log` (structural {@link NotifyLogger}). Codegen threads
|
|
436
|
+
* `ctx.log` in; when present the facade emits one `warn` line per FAILED
|
|
437
|
+
* delivery — trace-correlated to the enclosing action and durably archived by
|
|
438
|
+
* the log sink. Successes and prunes stay off the log to keep the archive
|
|
439
|
+
* clean; they are counted on `metrics` instead. Absent ⇒ no log emits.
|
|
440
|
+
*/
|
|
441
|
+
log?: NotifyLogger;
|
|
442
|
+
/**
|
|
443
|
+
* The request's `ctx.metrics` (structural {@link NotifyMetrics}). Codegen
|
|
444
|
+
* threads `ctx.metrics` in; when present the facade counts every send on the
|
|
445
|
+
* `notify.send` series (dimensions `channel` / `provider` / `status`) and every
|
|
446
|
+
* no-op on `notify.skipped` (`channel` / `reason`) — feeding the durable metric
|
|
447
|
+
* history + trend charts. Absent ⇒ no metric emits.
|
|
448
|
+
*/
|
|
449
|
+
metrics?: NotifyMetrics;
|
|
271
450
|
/** Suppress the in-memory-store dev warning (tests set this). */
|
|
272
451
|
silent?: boolean;
|
|
273
452
|
}
|
|
@@ -318,9 +497,11 @@ declare const buildEngine: (resolved: ResolvedProviders) => Notification;
|
|
|
318
497
|
* A broadcast job body — the JSON-serialisable payload enqueued for off-request
|
|
319
498
|
* fan-out. Shaped to travel through a `@lunora/queue` producer/consumer without
|
|
320
499
|
* `@lunora/notify` depending on `@lunora/queue` (the seam stays structural).
|
|
500
|
+
* `filter.after`, when set, resumes a broadcast partway through (see
|
|
501
|
+
* {@link runPushBroadcastJob}'s continuation semantics).
|
|
321
502
|
*/
|
|
322
503
|
interface PushBroadcastJob {
|
|
323
|
-
/** Subscription filter (which devices/users to target). */
|
|
504
|
+
/** Subscription filter (which devices/users to target; `filter.after` resumes a paged broadcast). */
|
|
324
505
|
filter?: SubscriptionFilter;
|
|
325
506
|
/** The push payload to deliver (the `to` target is derived per subscription). */
|
|
326
507
|
payload: PushContent;
|
|
@@ -334,7 +515,8 @@ interface QueueProducerLike {
|
|
|
334
515
|
/**
|
|
335
516
|
* Enqueue a fan-out broadcast for background delivery through a `@lunora/queue`
|
|
336
517
|
* queue instead of blocking the request. Pair with {@link runPushBroadcastJob} in
|
|
337
|
-
* the queue consumer
|
|
518
|
+
* the queue consumer — see its doc comment for how a large audience continues
|
|
519
|
+
* across MULTIPLE messages (one bounded page per message), not one.
|
|
338
520
|
*
|
|
339
521
|
* ```ts
|
|
340
522
|
* // in a mutation/action:
|
|
@@ -342,17 +524,59 @@ interface QueueProducerLike {
|
|
|
342
524
|
*
|
|
343
525
|
* // in lunora/queues.ts consumer:
|
|
344
526
|
* export const push = defineQueue({ async handler(batch, ctx) {
|
|
345
|
-
* for (const message of batch.messages)
|
|
527
|
+
* for (const message of batch.messages) {
|
|
528
|
+
* const { nextCursor } = await runPushBroadcastJob(ctx.push, message.body);
|
|
529
|
+
*
|
|
530
|
+
* if (nextCursor !== undefined) {
|
|
531
|
+
* // More pages remain — enqueue the continuation. Each message still
|
|
532
|
+
* // does only ONE bounded page of work.
|
|
533
|
+
* await enqueuePushBroadcast(ctx.queues.push, {
|
|
534
|
+
* payload: message.body.payload,
|
|
535
|
+
* filter: { ...message.body.filter, after: nextCursor },
|
|
536
|
+
* });
|
|
537
|
+
* }
|
|
538
|
+
* }
|
|
346
539
|
* }});
|
|
347
540
|
* ```
|
|
348
541
|
*/
|
|
349
542
|
declare const enqueuePushBroadcast: (queue: QueueProducerLike, job: Omit<PushBroadcastJob, "type">) => Promise<void>;
|
|
350
543
|
/**
|
|
351
|
-
* Run an enqueued broadcast job on the consumer side,
|
|
352
|
-
*
|
|
353
|
-
* gone
|
|
544
|
+
* Run ONE bounded page of an enqueued broadcast job on the consumer side,
|
|
545
|
+
* delivering through the push facade's {@link LunoraPush.broadcastPage} (which
|
|
546
|
+
* reuses the engine's retry + circuit-breaker middleware and prunes gone
|
|
547
|
+
* subscriptions).
|
|
548
|
+
*
|
|
549
|
+
* RETRY / CONTINUATION SEMANTICS (rewritten for plan 222 / NOTIFY-01 — a
|
|
550
|
+
* broadcast job used to process the WHOLE audience in one message, which could
|
|
551
|
+
* exceed Worker CPU/wall limits for a large audience and made a retry re-run
|
|
552
|
+
* everything):
|
|
553
|
+
*
|
|
554
|
+
* - A job now processes exactly ONE bounded page (see `CreateNotifyOptions`'s
|
|
555
|
+
* page-size option, default 250, or `job.filter.limit` when smaller),
|
|
556
|
+
* keyset-paginated on the subscription `id` (see `SubscriptionFilter.after`)
|
|
557
|
+
* — so per-message work is bounded regardless of total audience size.
|
|
558
|
+
* - Retry is still gated on `result.failed` — the count of TRANSIENT delivery
|
|
559
|
+
* errors (a provider 5xx / network fault worth another attempt). When at
|
|
560
|
+
* least one recipient in THIS PAGE `failed`, the job is RE-THROWN so the
|
|
561
|
+
* queue does NOT ack it and its normal retry/backoff (and, on exhaustion,
|
|
562
|
+
* dead-letter) applies — to just this page, not the whole broadcast.
|
|
563
|
+
* - A page with zero `failed` resolves and is acked — this includes the
|
|
564
|
+
* all-`pruned` case (every device on the page had unsubscribed:
|
|
565
|
+
* `sent:0`, `failed:0`, `pruned:N`), which is a SUCCESSFUL prune, not a
|
|
566
|
+
* failure, so throwing on it would spuriously retry and pressure the DLQ;
|
|
567
|
+
* and the empty-page case (zero `total`), which has nothing to retry.
|
|
568
|
+
* - The returned `nextCursor` is set when more pages remain. `@lunora/notify`
|
|
569
|
+
* does NOT enqueue the continuation itself — it has no `@lunora/queue`
|
|
570
|
+
* dependency (the seam stays structural) and no reference to the producer
|
|
571
|
+
* that enqueued this message — so the CALLER (the `lunora/queues.ts`
|
|
572
|
+
* consumer) is responsible for re-enqueueing with `filter.after: nextCursor`
|
|
573
|
+
* when present. See the consumer example on {@link enqueuePushBroadcast}.
|
|
574
|
+
* - A retry of a page redelivers only that page's already-delivered recipients
|
|
575
|
+
* on a transient partial failure (a page is not individually idempotent) —
|
|
576
|
+
* the accepted cost of getting the transiently failed ones redelivered, now
|
|
577
|
+
* scoped to one page instead of the whole broadcast.
|
|
354
578
|
*/
|
|
355
|
-
declare const runPushBroadcastJob: (push: LunoraPush, job: PushBroadcastJob) => Promise<
|
|
579
|
+
declare const runPushBroadcastJob: (push: LunoraPush, job: PushBroadcastJob) => Promise<BroadcastPageResult>;
|
|
356
580
|
/**
|
|
357
581
|
* The minimal structural slice of Cloudflare's `D1Database` this store uses. A
|
|
358
582
|
* structural type (rather than importing `@cloudflare/workers-types`) keeps the
|
|
@@ -379,6 +603,15 @@ interface D1StoreOptions {
|
|
|
379
603
|
* backing table is created lazily on first use (`CREATE TABLE IF NOT EXISTS`), so
|
|
380
604
|
* no migration step is required for the subscription table itself.
|
|
381
605
|
*
|
|
606
|
+
* ID SCHEME / LAZY MIGRATION: `id` (the `PRIMARY KEY`, upserted via `ON
|
|
607
|
+
* CONFLICT(id) DO UPDATE`) is a version-prefixed digest of the endpoint/token —
|
|
608
|
+
* currently `wp2_`/`fcm2_` (64-bit FNV-1a; see `normalize.ts`). No table migration
|
|
609
|
+
* runs when the id scheme is revised: a returning device re-registers under its new
|
|
610
|
+
* id and upserts a fresh row, while its old-prefix row (`wp_`/`fcm_`) ages out via
|
|
611
|
+
* the normal gone-pruning on the next failed send. So a table can transiently hold
|
|
612
|
+
* both an old- and new-prefix row for one device — expected, self-healing, and the
|
|
613
|
+
* reason a prefix must NEVER be reused for a different scheme.
|
|
614
|
+
*
|
|
382
615
|
* ```ts
|
|
383
616
|
* export default defineNotify({
|
|
384
617
|
* webPush: (env) => webPushFromEnv(env),
|
|
@@ -394,16 +627,42 @@ declare const d1SubscriptionStore: (database: D1Like, options?: D1StoreOptions)
|
|
|
394
627
|
* (or another backing store) for production so subscriptions survive restarts.
|
|
395
628
|
*/
|
|
396
629
|
declare const memorySubscriptionStore: () => SubscriptionStore;
|
|
397
|
-
/**
|
|
630
|
+
/**
|
|
631
|
+
* Stable store id for a web-push endpoint.
|
|
632
|
+
*
|
|
633
|
+
* The `wp2_` prefix is a version tag (see also {@link fcmId}'s `fcm2_`): it marks
|
|
634
|
+
* the 64-bit-id revision so the pre-existing 32-bit `wp_` rows stay readable and a
|
|
635
|
+
* returning device simply re-registers under the new id, its stale `wp_` row aging
|
|
636
|
+
* out via normal gone-pruning. A future third revision must mint `wp3_` and repeat
|
|
637
|
+
* the lazy migration — NEVER reuse a prefix.
|
|
638
|
+
*/
|
|
398
639
|
declare const webPushId: (endpoint: string) => string;
|
|
399
|
-
/** Stable store id for an FCM device token. */
|
|
640
|
+
/** Stable store id for an FCM device token. See {@link webPushId} for the `_2` version-prefix contract. */
|
|
400
641
|
declare const fcmId: (token: string) => string;
|
|
642
|
+
/** Options threaded into {@link normalizeRegisterInput} from the notify definition. */
|
|
643
|
+
interface NormalizeOptions {
|
|
644
|
+
/**
|
|
645
|
+
* Exact origins (`https://host[:port]`) a web-push endpoint may register from.
|
|
646
|
+
* When set (non-empty), the endpoint's origin must be one of these — the
|
|
647
|
+
* strongest anti-SSRF posture, and the ONLY way to close DNS rebinding for a
|
|
648
|
+
* facade that accepts client-controlled endpoints.
|
|
649
|
+
*
|
|
650
|
+
* When unset, the default posture applies: `https:` scheme + a host the
|
|
651
|
+
* {@link assertPushEndpoint} STRING classifier does not flag as
|
|
652
|
+
* private/loopback. That classifier does NOT resolve DNS, so a public hostname
|
|
653
|
+
* resolving to a private/internal IP (e.g. `https://127.0.0.1.nip.io/…`) is NOT
|
|
654
|
+
* blocked by it — set this allowlist to close that gap.
|
|
655
|
+
*/
|
|
656
|
+
allowedPushOrigins?: string[];
|
|
657
|
+
}
|
|
401
658
|
/**
|
|
402
659
|
* Normalise a `register(...)` input into a {@link StoredSubscription}. Validates
|
|
403
660
|
* the shape (a web-push subscription needs `endpoint` + `keys.{p256dh,auth}`; an
|
|
404
|
-
* FCM entry needs a non-empty `token`)
|
|
661
|
+
* FCM entry needs a non-empty `token`), enforces the anti-SSRF endpoint boundary
|
|
662
|
+
* (see {@link assertPushEndpoint}), validates `metadata` (see
|
|
663
|
+
* {@link validateMetadata}), and stamps `createdAt`/`lastSeenAt`.
|
|
405
664
|
*/
|
|
406
|
-
declare const normalizeRegisterInput: (input: RegisterInput, now?: number) => StoredSubscription;
|
|
665
|
+
declare const normalizeRegisterInput: (input: RegisterInput, now?: number, options?: NormalizeOptions) => StoredSubscription;
|
|
407
666
|
/**
|
|
408
667
|
* The provider `to` target for a stored subscription: the W3C Push subscription
|
|
409
668
|
* (JSON-stringified) for web-push, or the raw device token for FCM. Matches the
|
|
@@ -422,4 +681,4 @@ declare const targetOf: (subscription: StoredSubscription) => string;
|
|
|
422
681
|
* (a cert/session expiry) can never permanently drop a valid subscription.
|
|
423
682
|
*/
|
|
424
683
|
declare const isGoneError: (message: string | undefined) => boolean;
|
|
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 };
|
|
684
|
+
export { type BroadcastOutcome, type BroadcastResult, type CreateNotifyOptions, type D1Like, type D1PreparedLike, type D1StoreOptions, FCM_ENV_KEYS, type FcmConfigFactory, type LunoraNotify, type LunoraPush, type NotifyConfig, type NotifyDefinition, type NotifyDeliveryStatus, type NotifyEnv, type NotifyLogger, type NotifyMetrics, type NotifySkipReason, type PushBroadcastJob, type PushSubscriptionDevice, type PushSubscriptionsResult, type QueueProducerLike, type RegisterInput, type ResolvedProviders, type RoutingPushOptions, type StoredSubscription, type SubscriptionFilter, type SubscriptionKind, type SubscriptionStatus, type SubscriptionStore, WEB_PUSH_ENV_KEYS, type WebPushConfigFactory, buildEngine, createNotify, d1SubscriptionStore, defineNotify, enqueuePushBroadcast, fcmFromEnv, fcmId, isGoneError, isNotifyDefinition, memorySubscriptionStore, normalizeRegisterInput, routingPushProvider, runPushBroadcastJob, targetOf, webPushFromEnv, webPushId };
|