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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -17,21 +17,25 @@ import { defineNotify, webPushFromEnv, fcmFromEnv, d1SubscriptionStore } from "@
17
17
 
18
18
  export default defineNotify({
19
19
  webPush: (env) => webPushFromEnv(env), // reads VAPID_PUBLIC_KEY / VAPID_PRIVATE_KEY / VAPID_SUBJECT
20
- fcm: (env) => fcmFromEnv(env), // reads FCM_PROJECT_ID / FCM_ACCESS_TOKEN (prefer a getAccessToken in prod)
20
+ fcm: (env) => fcmFromEnv(env), // reads FCM_SERVICE_ACCOUNT (+ optional FCM_PROJECT_ID)
21
21
  store: (env) => d1SubscriptionStore(env.DB),
22
22
  });
23
23
  ```
24
24
 
25
- `.dev.vars` (scaffolded by `lunora dev` from `@lunora/config`'s package-secrets registry):
25
+ `.dev.vars` (scaffolded by `lunora dev` from `@lunora/config`'s package-secrets registry — only for the channels `defineNotify` configures):
26
26
 
27
27
  ```
28
28
  VAPID_PUBLIC_KEY=<your-vapid-public-key>
29
29
  VAPID_PRIVATE_KEY=<your-vapid-private-key>
30
30
  VAPID_SUBJECT=mailto:you@example.com
31
- FCM_PROJECT_ID=<your-firebase-project-id>
32
- FCM_ACCESS_TOKEN=<your-fcm-access-token>
31
+ FCM_SERVICE_ACCOUNT=<base64-of-your-service-account-key-json>
33
32
  ```
34
33
 
34
+ `.dev.vars` cannot hold the JSON's quotes, so store the key file base64-encoded:
35
+ `lunora env set FCM_SERVICE_ACCOUNT "$(base64 < key.json | tr -d '\n')"`. In production
36
+ the raw JSON works too: `wrangler secret put FCM_SERVICE_ACCOUNT < key.json`.
37
+ `FCM_PROJECT_ID` is optional and overrides the key file's `project_id`.
38
+
35
39
  Generate a VAPID keypair once: `npx web-push generate-vapid-keys`.
36
40
 
37
41
  ## Register a device (browser)
@@ -39,40 +43,105 @@ Generate a VAPID keypair once: `npx web-push generate-vapid-keys`.
39
43
  ```ts
40
44
  import { subscribeToPush } from "@lunora/notify/web";
41
45
 
42
- const subscription = await subscribeToPush({ serviceWorkerUrl: "/sw.js", vapidPublicKey });
43
- await client.mutation("registerDevice", { subscription });
46
+ const { replacedEndpoint, subscription } = await subscribeToPush({ serviceWorkerUrl: "/sw.js", vapidPublicKey });
47
+ await client.mutation("registerDevice", { replacedEndpoint, subscription });
44
48
  ```
45
49
 
50
+ Without `serviceWorkerUrl`, `subscribeToPush` uses the page's existing
51
+ registration: await your own `navigator.serviceWorker.register()` first, or the
52
+ call rejects with "no service worker is registered" instead of waiting for it.
53
+
54
+ `replacedEndpoint` is set only after a **VAPID key rotation**: the stale browser
55
+ subscription is dropped and a new one minted, and the new one has a new endpoint
56
+ — hence a new store id — so it never upserts over the old row. Every send to that
57
+ row now answers `403 VapidPkHashMismatch`, which is (correctly) not a "gone"
58
+ signal, so nothing prunes it either. Forward it and unregister it:
59
+
46
60
  ```ts
47
61
  // lunora/registerDevice.ts (a mutation — storage write is fine here)
48
- export const registerDevice = mutation({
49
- args: { subscription: v.any() },
50
- handler: async (ctx, { subscription }) => {
62
+ import { webPushId } from "@lunora/notify";
63
+
64
+ export const registerDevice = mutation
65
+ .input({ replacedEndpoint: v.optional(v.string()), subscription: v.any() })
66
+ .mutation(async ({ ctx, args: { replacedEndpoint, subscription } }) => {
67
+ if (replacedEndpoint !== undefined) {
68
+ await ctx.push.unregister(webPushId(replacedEndpoint), { userId: ctx.auth?.userId });
69
+ }
70
+
51
71
  await ctx.push.register({ subscription, userId: ctx.auth?.userId });
52
- },
72
+ });
73
+ ```
74
+
75
+ `unregister`'s owner argument is **required**, and the row is removed only when
76
+ it carries that same owner. A subscription id is derived from the endpoint, so
77
+ `replacedEndpoint` is a caller-controlled key and nothing about it proves the
78
+ browser that sent it ever held the subscription it names — without the scope,
79
+ anyone who could guess or observe another user's endpoint could silence that
80
+ device. A row owned by someone else is left alone silently, so the call cannot be
81
+ used to probe which endpoints exist. Register with the same `userId` you
82
+ unregister with; devices registered anonymously (`userId` absent) all share the
83
+ one anonymous scope and get no separation from this check.
84
+
85
+ `register` is scoped the same way, because an unguarded upsert closes only half
86
+ of that: re-registering a victim's endpoint under your own `userId` (with keys of
87
+ your choosing) takes their device dark just as effectively, and hands you
88
+ `unregister` over it. An endpoint already registered to another user is
89
+ **refused** (`FORBIDDEN`) rather than re-owned — unowned rows stay claimable (the
90
+ device signed in), and a device that legitimately changes hands unregisters as
91
+ its current owner first.
92
+
93
+ **Unregister on sign-out, or the next account on that browser cannot register.**
94
+ `subscribeToPush` REUSES the browser's existing subscription while the VAPID key
95
+ is unchanged, so the endpoint — and the store id derived from it — is the same
96
+ for every account that signs in on that browser. Without the sign-out call, user
97
+ B's `register` hits user A's row and throws `FORBIDDEN`; since `register` is
98
+ usually fire-and-forget on sign-in, that surfaces as a failed mutation and B
99
+ silently never receives a push. Release the row where you clear the session:
100
+
101
+ ```ts
102
+ // lunora/registerDevice.ts — the same file as above
103
+ export const unregisterDevice = mutation.input({ endpoint: v.string() }).mutation(async ({ args: { endpoint }, ctx }) => {
104
+ await ctx.push.unregister(webPushId(endpoint), { userId: ctx.auth?.userId });
53
105
  });
54
106
  ```
55
107
 
108
+ ```ts
109
+ // wherever you sign out. `subscription.endpoint` is on the object subscribeToPush returned.
110
+ await client.mutation("unregisterDevice", { endpoint: subscription.endpoint });
111
+ await auth.signOut();
112
+ ```
113
+
114
+ Keep the browser subscription itself (don't call `unsubscribeFromPush`) unless
115
+ the user is turning notifications off: dropping it re-prompts for permission on
116
+ the next sign-in. Note that only the owner can release a row — B cannot
117
+ `unregister` A's — so a sign-out that never runs (the tab was closed, the session
118
+ expired) leaves the next account refused until A signs in again on that browser
119
+ or the row is removed server-side. On a browser several people sign in on, treat
120
+ the sign-out unregister as required, not as cleanup.
121
+
56
122
  ## Send (from an action)
57
123
 
58
124
  Notification sends are external I/O, so they belong in **actions** (the `notify_send_outside_action` advisor lint enforces this):
59
125
 
60
126
  ```ts
61
- export const announce = action({
62
- args: { title: v.string(), body: v.string() },
63
- handler: async (ctx, { title, body }) => {
64
- const result = await ctx.push.broadcast({ title, body });
65
- // result: { total, sent, pruned, failed, outcomes }
66
- },
127
+ export const announce = action.input({ title: v.string(), body: v.string() }).action(async ({ ctx, args: { title, body } }) => {
128
+ const result = await ctx.push.broadcast({ title, body });
129
+ // result: { total, sent, pruned, failed, outcomes }
67
130
  });
68
131
  ```
69
132
 
70
- `broadcast` reuses the engine's retry + circuit-breaker middleware and prunes subscriptions the push service reports as gone (HTTP 404/410, FCM `UNREGISTERED`). A single targeted send:
133
+ `broadcast` reuses the engine's retry + circuit-breaker middleware and prunes subscriptions the push service reports as gone (Web Push HTTP 404/410; FCM's `NOT_FOUND` answer for a dead token, plus the `UNREGISTERED`/`NotRegistered` codes a legacy transport sends). A single targeted send:
71
134
 
72
135
  ```ts
73
136
  await ctx.push.send(subscriptionId, { title: "Hi", body: "…" });
74
137
  ```
75
138
 
139
+ `send` and `broadcast` take per-message delivery hints, overriding the channel's `urgency` / `ttl`. Web Push sends them as the `Urgency` / `TTL` headers; FCM maps them to `android.priority` / `android.ttl`:
140
+
141
+ ```ts
142
+ await ctx.push.broadcast({ title: "Approval needed", body: "…", urgency: "high", ttl: 3600 }, { userId });
143
+ ```
144
+
76
145
  Multi-channel through `ctx.notify.send`:
77
146
 
78
147
  ```ts
@@ -90,8 +159,36 @@ Move a large broadcast off the request path with `@lunora/queue`:
90
159
  // producer (mutation/action)
91
160
  await enqueuePushBroadcast(ctx.queues.push, { payload: { title: "New drop", body: "…" } });
92
161
 
93
- // consumer (lunora/queues.ts)
94
- for (const message of batch.messages) await runPushBroadcastJob(ctx.push, message.body);
162
+ // lunora/notify-fanout.ts — an INTERNAL ACTION, because that is where
163
+ // `ctx.push` and `ctx.queues` exist.
164
+ export const deliverPage = internalAction.input({ job: v.any() }).action(async ({ args: { job }, ctx }) => {
165
+ const { failedIds, nextFilter } = await runPushBroadcastPage(ctx.push, job);
166
+
167
+ // One message = ONE bounded page. Discarding `nextFilter` delivers only the
168
+ // first page (default 250 devices) and reports success for the whole audience.
169
+ // Pass it verbatim — it carries the cursor AND the remaining `filter.limit`.
170
+ if (nextFilter !== undefined) {
171
+ await enqueuePushBroadcast(ctx.queues.push, { payload: job.payload, filter: nextFilter });
172
+ }
173
+
174
+ // Redeliver ONLY the recipients that failed — a retry of the whole page would
175
+ // re-POST everyone it already reached.
176
+ if (failedIds.length > 0) {
177
+ await enqueuePushBroadcast(ctx.queues.push, { payload: job.payload, retryIds: failedIds });
178
+ }
179
+ });
180
+
181
+ // lunora/queues.ts — a `QueueRunContext` is exactly `{ env, log, run }`: no
182
+ // `ctx.push`, no `ctx.queues`. The consumer hands each message to the action above.
183
+ // (Note the handler signature: `(context, batch)`, in that order.)
184
+ export const push = defineQueue<PushBroadcastJob>({
185
+ handler: async (context, batch) => {
186
+ for (const message of batch.messages) {
187
+ await message.run(internal.notifyFanout.deliverPage, { job: message.body });
188
+ message.ack();
189
+ }
190
+ },
191
+ });
95
192
  ```
96
193
 
97
194
  ## Subscription storage
@@ -123,15 +220,17 @@ client-supplied data, so the facade enforces two boundaries:
123
220
  - **No secrets on the app facade.** `ctx.push.list()`
124
221
  returns the registered devices with the delivery **secrets stripped** — the Web
125
222
  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.
223
+ endpoint are enough to deliver arbitrary push to a device. Every other facade
224
+ read is projected the same way; the broadcast path uses the store directly. The
225
+ one place a handler does see a raw row is the return of `ctx.push.register(...)`,
226
+ which echoes back the record the caller just supplied — nothing it did not
227
+ already hold, and never another device's.
129
228
 
130
229
  ## Delivery observability
131
230
 
132
231
  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
232
 
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.
233
+ - **`notify.send`** `{ channel, provider, status }` — attempted sends. `status` is `accepted` (the provider took it), `failed`, or `gone` (endpoint unregistered — Web Push 404/410, or FCM's `NOT_FOUND` for a dead token — 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
234
  - **`notify.skipped`** `{ channel, reason }` — a send that reached nobody: `no-subscriptions-matched` (empty broadcast) or `channel-not-configured`.
136
235
 
137
236
  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).