cursedbelt-server 4.76.0 → 4.78.0

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.
@@ -0,0 +1,94 @@
1
+ /**
2
+ * Web Push sender on WebCrypto alone — RFC 8291 (aes128gcm message encryption over ECDH P-256)
3
+ * and RFC 8292 (VAPID: an ES256 JWT that tells the push service who is calling). No Node
4
+ * `crypto`, no Buffer: the same code runs in a Cloudflare Worker, Bun and a browser test.
5
+ *
6
+ * Shape: {@link encryptPushMessage} turns a payload into the full aes128gcm body (header +
7
+ * one record); {@link vapidAuthorization} mints the `Authorization: vapid t=…, k=…` header;
8
+ * {@link sendWebPush} does both and POSTs to the subscription endpoint, reporting a typed
9
+ * outcome a caller acts on (`gone` → delete the subscription, `retryAfterMs` → back off).
10
+ * {@link decryptPushMessage} is the receiver side, here so a test proves the roundtrip.
11
+ *
12
+ * Proven against RFC 8291 Appendix A in `webPush.spec.ts` byte for byte.
13
+ */
14
+ /** A browser `PushSubscription.toJSON()`, or the row an app stored from one. */
15
+ export interface PushSubscriptionLike {
16
+ endpoint: string;
17
+ keys: {
18
+ p256dh: string;
19
+ auth: string;
20
+ };
21
+ }
22
+ /** A VAPID key pair, both halves base64url: the public key is the 65-byte uncompressed point
23
+ * a client passes as `applicationServerKey`; the private key is the 32-byte scalar `d`. */
24
+ export interface VapidKeys {
25
+ publicKey: string;
26
+ privateKey: string;
27
+ }
28
+ export type PushUrgency = 'very-low' | 'low' | 'normal' | 'high';
29
+ export interface SendWebPushOptions {
30
+ vapid: {
31
+ keys: VapidKeys;
32
+ subject: string;
33
+ };
34
+ /** Seconds the push service may hold an undelivered message. Default 60. */
35
+ ttl?: number;
36
+ urgency?: PushUrgency;
37
+ /** Replaces an earlier undelivered message with the same topic (≤ 32 URL-safe chars). */
38
+ topic?: string;
39
+ /** Injected for tests; defaults to the global fetch. */
40
+ fetch?: typeof fetch;
41
+ /** Clock for the VAPID claims; defaults to Date.now. */
42
+ now?: () => number;
43
+ }
44
+ export interface WebPushOutcome {
45
+ /** HTTP status the push service answered with (0 when the request itself failed). */
46
+ status: number;
47
+ /** 201 (or 200) — the service accepted the message for delivery. */
48
+ delivered: boolean;
49
+ /** 404 or 410 — the subscription no longer exists; the caller should forget it. */
50
+ gone: boolean;
51
+ /** Present on 429 / 503 with a Retry-After the caller should honor. */
52
+ retryAfterMs?: number;
53
+ /** The response body on a non-success, trimmed, for a log line. */
54
+ detail?: string;
55
+ }
56
+ export interface EncryptPushOptions {
57
+ /** 16 random bytes by default; a test fixes it to reproduce the RFC vector. */
58
+ salt?: Uint8Array;
59
+ /** The application server's ephemeral ECDH P-256 pair; fresh per message by default. */
60
+ senderKeyPair?: CryptoKeyPair;
61
+ /** RFC 8188 record size. Default 4096, the ceiling every push service accepts. */
62
+ recordSize?: number;
63
+ }
64
+ /** An ArrayBuffer-backed view: what WebCrypto's BufferSource accepts without a cast. */
65
+ type Bytes = Uint8Array<ArrayBuffer>;
66
+ export declare function base64urlEncode(bytes: Uint8Array | ArrayBuffer): string;
67
+ export declare function base64urlDecode(text: string): Bytes;
68
+ /** Mint a VAPID pair. Store both halves as secrets; publish only `publicKey`. */
69
+ export declare function generateVapidKeys(): Promise<VapidKeys>;
70
+ /** Import the ECDH pair a test or a receiver holds as raw base64url halves. */
71
+ export declare function importEcdhKeyPair(publicKey: string, privateKey: string): Promise<CryptoKeyPair>;
72
+ /**
73
+ * Encrypt one push payload as an aes128gcm body: header (salt ‖ rs ‖ idlen ‖ sender public
74
+ * key) followed by a single record (plaintext ‖ 0x02 ‖ GCM tag). Throws when the payload
75
+ * cannot fit one record of `recordSize`; push services cap the whole body at 4096 bytes, so
76
+ * a payload over ~3990 bytes is a design problem, not something to split.
77
+ */
78
+ export declare function encryptPushMessage(payload: string | Uint8Array, keys: PushSubscriptionLike['keys'], options?: EncryptPushOptions): Promise<Bytes>;
79
+ /**
80
+ * The receiver side of {@link encryptPushMessage} for a single-record body: what a browser
81
+ * does before handing `event.data` to a service worker. Here for tests and local harnesses.
82
+ */
83
+ export declare function decryptPushMessage(input: Uint8Array, receiver: CryptoKeyPair, auth: Uint8Array): Promise<Bytes>;
84
+ /**
85
+ * `Authorization: vapid t=<JWT>, k=<public key>` for one push resource. `subject` is a
86
+ * `mailto:` or `https:` URL the push service may contact about abuse; the audience is the
87
+ * endpoint's origin, so one header serves every subscription on that push service.
88
+ */
89
+ export declare function vapidAuthorization(endpoint: string, keys: VapidKeys, subject: string, now?: number): Promise<string>;
90
+ /** Encrypt, sign and POST one message. Never throws on a service refusal: read the outcome. */
91
+ export declare function sendWebPush(subscription: PushSubscriptionLike, payload: string | Uint8Array, options: SendWebPushOptions): Promise<WebPushOutcome>;
92
+ /** Decode a VAPID public key for `PushManager.subscribe({ applicationServerKey })`. Client-side helper. */
93
+ export declare function applicationServerKey(publicKey: string): Bytes;
94
+ export {};
@@ -0,0 +1,228 @@
1
+ /**
2
+ * Web Push sender on WebCrypto alone — RFC 8291 (aes128gcm message encryption over ECDH P-256)
3
+ * and RFC 8292 (VAPID: an ES256 JWT that tells the push service who is calling). No Node
4
+ * `crypto`, no Buffer: the same code runs in a Cloudflare Worker, Bun and a browser test.
5
+ *
6
+ * Shape: {@link encryptPushMessage} turns a payload into the full aes128gcm body (header +
7
+ * one record); {@link vapidAuthorization} mints the `Authorization: vapid t=…, k=…` header;
8
+ * {@link sendWebPush} does both and POSTs to the subscription endpoint, reporting a typed
9
+ * outcome a caller acts on (`gone` → delete the subscription, `retryAfterMs` → back off).
10
+ * {@link decryptPushMessage} is the receiver side, here so a test proves the roundtrip.
11
+ *
12
+ * Proven against RFC 8291 Appendix A in `webPush.spec.ts` byte for byte.
13
+ */
14
+ /** Copy any Uint8Array (a Node Buffer slice, a SharedArrayBuffer view) onto its own ArrayBuffer. */
15
+ const own = (view) => new Uint8Array(view);
16
+ const enc = new TextEncoder();
17
+ const P256 = { name: 'ECDH', namedCurve: 'P-256' };
18
+ const ES256 = { name: 'ECDSA', namedCurve: 'P-256' };
19
+ const KEY_INFO_PREFIX = 'WebPush: info\0';
20
+ const CEK_INFO = enc.encode('Content-Encoding: aes128gcm\0');
21
+ const NONCE_INFO = enc.encode('Content-Encoding: nonce\0');
22
+ const SALT_BYTES = 16;
23
+ const TAG_BYTES = 16;
24
+ const PUBLIC_KEY_BYTES = 65;
25
+ const HEADER_BYTES = SALT_BYTES + 4 + 1 + PUBLIC_KEY_BYTES;
26
+ const DEFAULT_RECORD_SIZE = 4096;
27
+ const DEFAULT_TTL_SECONDS = 60;
28
+ /** RFC 8292 §2: `exp` must be within 24h; 12h leaves clock skew room on both sides. */
29
+ const VAPID_LIFETIME_SECONDS = 12 * 60 * 60;
30
+ /* ── base64url, WebCrypto-only ─────────────────────────────────────────────────────────── */
31
+ export function base64urlEncode(bytes) {
32
+ const view = bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes);
33
+ let binary = '';
34
+ for (let i = 0; i < view.length; i += 0x8000) {
35
+ binary += String.fromCharCode(...view.subarray(i, i + 0x8000));
36
+ }
37
+ return btoa(binary).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
38
+ }
39
+ export function base64urlDecode(text) {
40
+ const padded = text.replace(/-/g, '+').replace(/_/g, '/').padEnd(Math.ceil(text.length / 4) * 4, '=');
41
+ const binary = atob(padded);
42
+ const out = new Uint8Array(binary.length);
43
+ for (let i = 0; i < binary.length; i++)
44
+ out[i] = binary.charCodeAt(i);
45
+ return out;
46
+ }
47
+ /* ── keys ──────────────────────────────────────────────────────────────────────────────── */
48
+ /** Mint a VAPID pair. Store both halves as secrets; publish only `publicKey`. */
49
+ export async function generateVapidKeys() {
50
+ const pair = await crypto.subtle.generateKey(ES256, true, ['sign', 'verify']);
51
+ const jwk = await crypto.subtle.exportKey('jwk', pair.privateKey);
52
+ if (!jwk.d || !jwk.x || !jwk.y)
53
+ throw new Error('web-push: ECDSA key export lacked d/x/y');
54
+ return {
55
+ publicKey: base64urlEncode(uncompressedPoint(jwk.x, jwk.y)),
56
+ privateKey: jwk.d,
57
+ };
58
+ }
59
+ function uncompressedPoint(x, y) {
60
+ const out = new Uint8Array(PUBLIC_KEY_BYTES);
61
+ out[0] = 0x04;
62
+ out.set(base64urlDecode(x), 1);
63
+ out.set(base64urlDecode(y), 33);
64
+ return out;
65
+ }
66
+ function splitPoint(publicKey) {
67
+ const bytes = base64urlDecode(publicKey);
68
+ if (bytes.length !== PUBLIC_KEY_BYTES || bytes[0] !== 0x04) {
69
+ throw new Error('web-push: public key must be a 65-byte uncompressed P-256 point');
70
+ }
71
+ return { x: base64urlEncode(bytes.subarray(1, 33)), y: base64urlEncode(bytes.subarray(33)) };
72
+ }
73
+ async function importVapidSigningKey(keys) {
74
+ const { x, y } = splitPoint(keys.publicKey);
75
+ return crypto.subtle.importKey('jwk', { kty: 'EC', crv: 'P-256', x, y, d: keys.privateKey, ext: true }, ES256, false, ['sign']);
76
+ }
77
+ /** Import the ECDH pair a test or a receiver holds as raw base64url halves. */
78
+ export async function importEcdhKeyPair(publicKey, privateKey) {
79
+ const { x, y } = splitPoint(publicKey);
80
+ const priv = await crypto.subtle.importKey('jwk', { kty: 'EC', crv: 'P-256', x, y, d: privateKey, ext: true }, P256, false, ['deriveBits']);
81
+ const pub = await crypto.subtle.importKey('raw', base64urlDecode(publicKey), P256, true, []);
82
+ return { privateKey: priv, publicKey: pub };
83
+ }
84
+ /* ── RFC 8291 + RFC 8188 ───────────────────────────────────────────────────────────────── */
85
+ async function hkdf(salt, ikm, info, bytes) {
86
+ const key = await crypto.subtle.importKey('raw', ikm, { name: 'HKDF' }, false, ['deriveBits']);
87
+ const bits = await crypto.subtle.deriveBits({ name: 'HKDF', hash: 'SHA-256', salt, info }, key, bytes * 8);
88
+ return new Uint8Array(bits);
89
+ }
90
+ function concat(...parts) {
91
+ const out = new Uint8Array(parts.reduce((n, p) => n + p.length, 0));
92
+ let at = 0;
93
+ for (const p of parts) {
94
+ out.set(p, at);
95
+ at += p.length;
96
+ }
97
+ return out;
98
+ }
99
+ /** RFC 8291 §3: the content-encryption key and nonce for one message. */
100
+ async function contentKeys(sharedSecret, authSecret, uaPublic, asPublic, salt) {
101
+ const keyInfo = concat(enc.encode(KEY_INFO_PREFIX), uaPublic, asPublic);
102
+ const ikm = await hkdf(authSecret, sharedSecret, keyInfo, 32);
103
+ const cekBytes = await hkdf(salt, ikm, CEK_INFO, 16);
104
+ const nonce = await hkdf(salt, ikm, NONCE_INFO, 12);
105
+ const cek = await crypto.subtle.importKey('raw', cekBytes, { name: 'AES-GCM' }, false, ['encrypt', 'decrypt']);
106
+ return { cek, nonce };
107
+ }
108
+ /**
109
+ * Encrypt one push payload as an aes128gcm body: header (salt ‖ rs ‖ idlen ‖ sender public
110
+ * key) followed by a single record (plaintext ‖ 0x02 ‖ GCM tag). Throws when the payload
111
+ * cannot fit one record of `recordSize`; push services cap the whole body at 4096 bytes, so
112
+ * a payload over ~3990 bytes is a design problem, not something to split.
113
+ */
114
+ export async function encryptPushMessage(payload, keys, options = {}) {
115
+ const plaintext = typeof payload === 'string' ? enc.encode(payload) : own(payload);
116
+ const recordSize = options.recordSize ?? DEFAULT_RECORD_SIZE;
117
+ if (plaintext.length + 1 + TAG_BYTES > recordSize) {
118
+ throw new Error(`web-push: payload of ${plaintext.length} bytes does not fit one ${recordSize}-byte record`);
119
+ }
120
+ const uaPublic = base64urlDecode(keys.p256dh);
121
+ const authSecret = base64urlDecode(keys.auth);
122
+ if (uaPublic.length !== PUBLIC_KEY_BYTES)
123
+ throw new Error('web-push: p256dh must be a 65-byte uncompressed point');
124
+ if (authSecret.length !== 16)
125
+ throw new Error('web-push: auth secret must be 16 bytes');
126
+ const salt = options.salt ? own(options.salt) : crypto.getRandomValues(new Uint8Array(SALT_BYTES));
127
+ if (salt.length !== SALT_BYTES)
128
+ throw new Error('web-push: salt must be 16 bytes');
129
+ const sender = options.senderKeyPair ?? (await crypto.subtle.generateKey(P256, true, ['deriveBits']));
130
+ const asPublic = new Uint8Array(await crypto.subtle.exportKey('raw', sender.publicKey));
131
+ const uaKey = await crypto.subtle.importKey('raw', uaPublic, P256, false, []);
132
+ const shared = new Uint8Array(await crypto.subtle.deriveBits({ name: 'ECDH', public: uaKey }, sender.privateKey, 256));
133
+ const { cek, nonce } = await contentKeys(shared, authSecret, uaPublic, asPublic, salt);
134
+ const record = concat(plaintext, Uint8Array.of(0x02));
135
+ const ciphertext = new Uint8Array(await crypto.subtle.encrypt({ name: 'AES-GCM', iv: nonce }, cek, record));
136
+ const header = new Uint8Array(HEADER_BYTES);
137
+ header.set(salt, 0);
138
+ new DataView(header.buffer).setUint32(SALT_BYTES, recordSize, false);
139
+ header[SALT_BYTES + 4] = PUBLIC_KEY_BYTES;
140
+ header.set(asPublic, SALT_BYTES + 5);
141
+ return concat(header, ciphertext);
142
+ }
143
+ /**
144
+ * The receiver side of {@link encryptPushMessage} for a single-record body: what a browser
145
+ * does before handing `event.data` to a service worker. Here for tests and local harnesses.
146
+ */
147
+ export async function decryptPushMessage(input, receiver, auth) {
148
+ const body = own(input);
149
+ const authSecret = own(auth);
150
+ if (body.length < HEADER_BYTES + TAG_BYTES + 1)
151
+ throw new Error('web-push: body too short');
152
+ const salt = body.subarray(0, SALT_BYTES);
153
+ const idlen = body[SALT_BYTES + 4];
154
+ if (idlen !== PUBLIC_KEY_BYTES)
155
+ throw new Error(`web-push: unexpected key id length ${idlen}`);
156
+ const asPublic = body.subarray(SALT_BYTES + 5, HEADER_BYTES);
157
+ const uaPublic = new Uint8Array(await crypto.subtle.exportKey('raw', receiver.publicKey));
158
+ const asKey = await crypto.subtle.importKey('raw', asPublic, P256, false, []);
159
+ const shared = new Uint8Array(await crypto.subtle.deriveBits({ name: 'ECDH', public: asKey }, receiver.privateKey, 256));
160
+ const { cek, nonce } = await contentKeys(shared, authSecret, uaPublic, asPublic, salt);
161
+ const record = new Uint8Array(await crypto.subtle.decrypt({ name: 'AES-GCM', iv: nonce }, cek, body.subarray(HEADER_BYTES)));
162
+ let end = record.length - 1;
163
+ while (end >= 0 && record[end] === 0)
164
+ end--;
165
+ if (end < 0 || record[end] !== 0x02)
166
+ throw new Error('web-push: record lacks the final-record delimiter');
167
+ return record.subarray(0, end);
168
+ }
169
+ /* ── RFC 8292 VAPID ────────────────────────────────────────────────────────────────────── */
170
+ /**
171
+ * `Authorization: vapid t=<JWT>, k=<public key>` for one push resource. `subject` is a
172
+ * `mailto:` or `https:` URL the push service may contact about abuse; the audience is the
173
+ * endpoint's origin, so one header serves every subscription on that push service.
174
+ */
175
+ export async function vapidAuthorization(endpoint, keys, subject, now = Date.now()) {
176
+ if (!/^(mailto:|https:)/.test(subject))
177
+ throw new Error('web-push: VAPID subject must be a mailto: or https: URL');
178
+ const header = base64urlEncode(enc.encode(JSON.stringify({ typ: 'JWT', alg: 'ES256' })));
179
+ const claims = base64urlEncode(enc.encode(JSON.stringify({
180
+ aud: new URL(endpoint).origin,
181
+ exp: Math.floor(now / 1000) + VAPID_LIFETIME_SECONDS,
182
+ sub: subject,
183
+ })));
184
+ const signingInput = `${header}.${claims}`;
185
+ const key = await importVapidSigningKey(keys);
186
+ const signature = await crypto.subtle.sign({ name: 'ECDSA', hash: 'SHA-256' }, key, enc.encode(signingInput));
187
+ return `vapid t=${signingInput}.${base64urlEncode(signature)}, k=${keys.publicKey}`;
188
+ }
189
+ /* ── send ──────────────────────────────────────────────────────────────────────────────── */
190
+ /** Encrypt, sign and POST one message. Never throws on a service refusal: read the outcome. */
191
+ export async function sendWebPush(subscription, payload, options) {
192
+ const body = await encryptPushMessage(payload, subscription.keys);
193
+ const authorization = await vapidAuthorization(subscription.endpoint, options.vapid.keys, options.vapid.subject, (options.now ?? Date.now)());
194
+ const headers = {
195
+ Authorization: authorization,
196
+ 'Content-Encoding': 'aes128gcm',
197
+ 'Content-Type': 'application/octet-stream',
198
+ 'Content-Length': String(body.length),
199
+ TTL: String(options.ttl ?? DEFAULT_TTL_SECONDS),
200
+ };
201
+ if (options.urgency)
202
+ headers.Urgency = options.urgency;
203
+ if (options.topic)
204
+ headers.Topic = options.topic;
205
+ const doFetch = options.fetch ?? fetch;
206
+ let response;
207
+ try {
208
+ response = await doFetch(subscription.endpoint, { method: 'POST', headers, body });
209
+ }
210
+ catch (error) {
211
+ return { status: 0, delivered: false, gone: false, detail: error instanceof Error ? error.message : String(error) };
212
+ }
213
+ const delivered = response.status === 201 || response.status === 200;
214
+ const gone = response.status === 404 || response.status === 410;
215
+ const outcome = { status: response.status, delivered, gone };
216
+ const retryAfter = response.headers.get('Retry-After');
217
+ if ((response.status === 429 || response.status === 503) && retryAfter) {
218
+ const seconds = Number(retryAfter);
219
+ outcome.retryAfterMs = Number.isFinite(seconds) ? seconds * 1000 : Math.max(0, Date.parse(retryAfter) - Date.now());
220
+ }
221
+ if (!delivered)
222
+ outcome.detail = (await response.text().catch(() => '')).slice(0, 200);
223
+ return outcome;
224
+ }
225
+ /** Decode a VAPID public key for `PushManager.subscribe({ applicationServerKey })`. Client-side helper. */
226
+ export function applicationServerKey(publicKey) {
227
+ return base64urlDecode(publicKey);
228
+ }
@@ -0,0 +1,11 @@
1
+ export interface RequestScope<S extends object> {
2
+ /** Run `work` with `scope` as the current request's — everything it awaits, and defers, sees it. */
3
+ run<T>(scope: S, work: () => T): T;
4
+ /** The current request's scope; THROWS outside one (a stand-in used at isolate scope is a bug). */
5
+ current(): S;
6
+ /** A stand-in for `scope[key]` that reads the current request's value at every property access. */
7
+ late<K extends keyof S>(key: K): NonNullable<S[K]>;
8
+ /** The same, for a value derived from the scope (`(s) => s.env.AE`). */
9
+ lateOf<T extends object>(read: (scope: S) => T | null | undefined, what: string): T;
10
+ }
11
+ export declare function createRequestScope<S extends object>(name: string): RequestScope<S>;
@@ -0,0 +1,61 @@
1
+ /**
2
+ * `cursedbelt-server/request-scope` — one request's things, for an app built ONCE per isolate.
3
+ *
4
+ * Born in auth (forge task 5632), promoted when photos took the same shape: a Worker that rebuilt
5
+ * its whole Hono graph per request paid a flat 5–40 CPU-ms floor on every call. Worker-safe: it
6
+ * needs `nodejs_compat` for `node:async_hooks`, nothing else.
7
+ *
8
+ * The assembly closes over its database, its session store, its throttle… — objects that belong to
9
+ * ONE request on a Worker (`perInvocation`'s query count, a D1 snapshot, a binding's I/O, which
10
+ * workerd refuses to touch from another request). Building the whole route tier per request cost
11
+ * 16–40 CPU-ms on auth-stage; building it once and handing it these values LATE costs nothing.
12
+ *
13
+ * `late(key)` is a stand-in that reads `key` from the CURRENT request's scope at every use, so the
14
+ * assembly can hold it from the first request on. The scope rides `AsyncLocalStorage`, never a
15
+ * module variable: an isolate serves requests concurrently, and a variable set by request B while
16
+ * request A awaits D1 would hand A B's sessions. Work handed to `waitUntil` keeps its own scope.
17
+ *
18
+ * 🔴 A stand-in is for a LEAF service. One with a `mount` (a notification service) registers routes
19
+ * over the internals of whichever request built it — build that once over a late database instead.
20
+ */
21
+ import { AsyncLocalStorage } from "node:async_hooks";
22
+ export function createRequestScope(name) {
23
+ const storage = new AsyncLocalStorage();
24
+ const current = () => {
25
+ const scope = storage.getStore();
26
+ if (!scope)
27
+ throw new Error(`${name}: a request-scoped value was read outside a request`);
28
+ return scope;
29
+ };
30
+ const lateOf = (read, what) => {
31
+ const target = () => {
32
+ const value = read(current());
33
+ if (value === undefined || value === null)
34
+ throw new Error(`${name}: this request has no ${what}`);
35
+ return value;
36
+ };
37
+ return new Proxy({}, {
38
+ get(_shell, prop) {
39
+ const member = Reflect.get(target(), prop);
40
+ if (typeof member !== "function")
41
+ return member;
42
+ // Resolved again at CALL time: a method taken off the stand-in while the assembly is
43
+ // built (request 1) must still run on whichever request calls it.
44
+ return (...args) => {
45
+ const value = target();
46
+ return Reflect.apply(Reflect.get(value, prop, value), value, args);
47
+ };
48
+ },
49
+ has: (_shell, prop) => Reflect.has(target(), prop),
50
+ ownKeys: () => Reflect.ownKeys(target()),
51
+ getOwnPropertyDescriptor(_shell, prop) {
52
+ const descriptor = Reflect.getOwnPropertyDescriptor(target(), prop);
53
+ // A proxy may not report a property non-configurable that its (empty) shell lacks.
54
+ return descriptor ? { ...descriptor, configurable: true } : undefined;
55
+ },
56
+ set: (_shell, prop, value) => Reflect.set(target(), prop, value),
57
+ });
58
+ };
59
+ const late = (key) => lateOf((scope) => scope[key], String(key));
60
+ return { run: (scope, work) => storage.run(scope, work), current, late, lateOf };
61
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "cursedbelt-server",
3
- "version": "4.76.0",
3
+ "version": "4.78.0",
4
4
  "license": "ISC",
5
5
  "type": "module",
6
6
  "description": "The app-facing Bun/Hono server tier of the cursedbelt split — storage, sharing, activity, guard, sync. React-free; cursedbelt-core below it.",
@@ -60,6 +60,12 @@
60
60
  "source": "./src/server/context.ts",
61
61
  "import": "./dist/server/context.js"
62
62
  },
63
+ "./request-scope": {
64
+ "types": "./dist/server/requestScope.d.ts",
65
+ "bun": "./src/server/requestScope.ts",
66
+ "source": "./src/server/requestScope.ts",
67
+ "import": "./dist/server/requestScope.js"
68
+ },
63
69
  "./ctgr-tunnel": {
64
70
  "types": "./dist/server/ctgrTunnel.d.ts",
65
71
  "bun": "./src/server/ctgrTunnel.ts",
@@ -307,6 +313,12 @@
307
313
  "source": "./src/server/notifications/d1.ts",
308
314
  "import": "./dist/server/notifications/d1.js"
309
315
  },
316
+ "./web-push": {
317
+ "types": "./dist/server/push/webPush.d.ts",
318
+ "bun": "./src/server/push/webPush.ts",
319
+ "source": "./src/server/push/webPush.ts",
320
+ "import": "./dist/server/push/webPush.js"
321
+ },
310
322
  "./resume": {
311
323
  "types": "./dist/server/resume/index.d.ts",
312
324
  "bun": "./src/server/resume/index.ts",
@@ -447,7 +459,7 @@
447
459
  "@node-rs/argon2": "^2.0.2",
448
460
  "@types/bun": "^1.3.14",
449
461
  "@types/node": "^24",
450
- "cursedbelt": "^6.13.1",
462
+ "cursedbelt": "^6.28.0",
451
463
  "hono": "4.12.28",
452
464
  "kysely": "^0.28.17",
453
465
  "kysely-bun-sqlite": "^0.4.0",
@@ -0,0 +1,229 @@
1
+ import { describe, expect, test } from 'bun:test';
2
+ import {
3
+ applicationServerKey,
4
+ base64urlDecode,
5
+ base64urlEncode,
6
+ decryptPushMessage,
7
+ encryptPushMessage,
8
+ generateVapidKeys,
9
+ importEcdhKeyPair,
10
+ sendWebPush,
11
+ vapidAuthorization,
12
+ } from './webPush.js';
13
+
14
+ /** RFC 8291 Appendix A — the published worked example, every intermediate value. */
15
+ const RFC = {
16
+ plaintext: 'When I grow up, I want to be a watermelon',
17
+ asPrivate: 'yfWPiYE-n46HLnH0KqZOF1fJJU3MYrct3AELtAQ-oRw',
18
+ asPublic: 'BP4z9KsN6nGRTbVYI_c7VJSPQTBtkgcy27mlmlMoZIIgDll6e3vCYLocInmYWAmS6TlzAC8wEqKK6PBru3jl7A8',
19
+ uaPrivate: 'q1dXpw3UpT5VOmu_cf_v6ih07Aems3njxI-JWgLcM94',
20
+ uaPublic: 'BCVxsr7N_eNgVRqvHtD0zTZsEc6-VV-JvLexhqUzORcxaOzi6-AYWXvTBHm4bjyPjs7Vd8pZGH6SRpkNtoIAiw4',
21
+ auth: 'BTBZMqHH6r4Tts7J_aSIgg',
22
+ salt: 'DGv6ra1nlYgDCS1FRnbzlw',
23
+ ciphertext: '8pfeW0KbunFT06SuDKoJH9Ql87S1QUrdirN6GcG7sFz1y1sqLgVi1VhjVkHsUoEsbI_0LpXMuGvnzQ',
24
+ };
25
+
26
+ const bytes = (b64: string) => base64urlDecode(b64);
27
+
28
+ describe('base64url', () => {
29
+ test('roundtrips arbitrary bytes without padding', () => {
30
+ const raw = crypto.getRandomValues(new Uint8Array(77));
31
+ const text = base64urlEncode(raw);
32
+ expect(text).not.toMatch(/[+/=]/);
33
+ expect(base64urlDecode(text)).toEqual(raw);
34
+ });
35
+ test('decodes the RFC auth secret to 16 bytes', () => {
36
+ expect(bytes(RFC.auth).length).toBe(16);
37
+ });
38
+ });
39
+
40
+ describe('RFC 8291 aes128gcm', () => {
41
+ test('reproduces Appendix A byte for byte with the fixed salt and sender key', async () => {
42
+ const sender = await importEcdhKeyPair(RFC.asPublic, RFC.asPrivate);
43
+ const body = await encryptPushMessage(RFC.plaintext, { p256dh: RFC.uaPublic, auth: RFC.auth }, {
44
+ salt: bytes(RFC.salt),
45
+ senderKeyPair: sender,
46
+ });
47
+ expect(body.length).toBe(144);
48
+ // header: salt(16) ‖ rs=4096 ‖ idlen=65 ‖ as_public(65)
49
+ expect(base64urlEncode(body.subarray(0, 16))).toBe(RFC.salt);
50
+ expect(new DataView(body.buffer, body.byteOffset).getUint32(16, false)).toBe(4096);
51
+ expect(body[20]).toBe(65);
52
+ expect(base64urlEncode(body.subarray(21, 86))).toBe(RFC.asPublic);
53
+ expect(base64urlEncode(body.subarray(86))).toBe(RFC.ciphertext);
54
+ });
55
+
56
+ test('the receiver decrypts the RFC body back to the plaintext', async () => {
57
+ const receiver = await importEcdhKeyPair(RFC.uaPublic, RFC.uaPrivate);
58
+ const sender = await importEcdhKeyPair(RFC.asPublic, RFC.asPrivate);
59
+ const body = await encryptPushMessage(RFC.plaintext, { p256dh: RFC.uaPublic, auth: RFC.auth }, {
60
+ salt: bytes(RFC.salt),
61
+ senderKeyPair: sender,
62
+ });
63
+ const plain = await decryptPushMessage(body, receiver, bytes(RFC.auth));
64
+ expect(new TextDecoder().decode(plain)).toBe(RFC.plaintext);
65
+ });
66
+
67
+ test('a fresh salt and sender pair per message: two bodies differ, both decrypt', async () => {
68
+ const receiver = await importEcdhKeyPair(RFC.uaPublic, RFC.uaPrivate);
69
+ const keys = { p256dh: RFC.uaPublic, auth: RFC.auth };
70
+ const payload = JSON.stringify({ kind: 'alarm', label: 'Wake ☀️' });
71
+ const a = await encryptPushMessage(payload, keys);
72
+ const b = await encryptPushMessage(payload, keys);
73
+ expect(base64urlEncode(a)).not.toBe(base64urlEncode(b));
74
+ for (const body of [a, b]) {
75
+ expect(new TextDecoder().decode(await decryptPushMessage(body, receiver, bytes(RFC.auth)))).toBe(payload);
76
+ }
77
+ });
78
+
79
+ test('refuses a payload that cannot fit one record', async () => {
80
+ const keys = { p256dh: RFC.uaPublic, auth: RFC.auth };
81
+ await expect(encryptPushMessage('x'.repeat(4096 - 17), keys)).resolves.toBeInstanceOf(Uint8Array);
82
+ await expect(encryptPushMessage('x'.repeat(4096 - 16), keys)).rejects.toThrow(/does not fit/);
83
+ });
84
+
85
+ test('refuses malformed subscription keys by name', async () => {
86
+ await expect(encryptPushMessage('hi', { p256dh: RFC.auth, auth: RFC.auth })).rejects.toThrow(/p256dh/);
87
+ await expect(encryptPushMessage('hi', { p256dh: RFC.uaPublic, auth: RFC.salt.slice(0, 8) })).rejects.toThrow(/auth secret/);
88
+ });
89
+
90
+ test('a tampered body fails authentication', async () => {
91
+ const receiver = await importEcdhKeyPair(RFC.uaPublic, RFC.uaPrivate);
92
+ const body = await encryptPushMessage('hello', { p256dh: RFC.uaPublic, auth: RFC.auth });
93
+ body[body.length - 1] ^= 0x01;
94
+ await expect(decryptPushMessage(body, receiver, bytes(RFC.auth))).rejects.toThrow();
95
+ });
96
+ });
97
+
98
+ async function verifyVapid(header: string, endpoint: string) {
99
+ const match = /^vapid t=([^,]+), k=(\S+)$/.exec(header);
100
+ if (!match) throw new Error(`not a vapid header: ${header}`);
101
+ const [, jwt, k] = match;
102
+ const [h, c, s] = jwt.split('.');
103
+ const publicKey = await crypto.subtle.importKey('raw', bytes(k), { name: 'ECDSA', namedCurve: 'P-256' }, false, ['verify']);
104
+ const ok = await crypto.subtle.verify(
105
+ { name: 'ECDSA', hash: 'SHA-256' },
106
+ publicKey,
107
+ bytes(s),
108
+ new TextEncoder().encode(`${h}.${c}`),
109
+ );
110
+ const decode = (part: string) => JSON.parse(new TextDecoder().decode(bytes(part)));
111
+ return { ok, header: decode(h), claims: decode(c), k, aud: new URL(endpoint).origin };
112
+ }
113
+
114
+ describe('RFC 8292 VAPID', () => {
115
+ test('mints a pair whose public half is a 65-byte uncompressed point', async () => {
116
+ const keys = await generateVapidKeys();
117
+ const pub = bytes(keys.publicKey);
118
+ expect(pub.length).toBe(65);
119
+ expect(pub[0]).toBe(0x04);
120
+ expect(bytes(keys.privateKey).length).toBe(32);
121
+ expect(applicationServerKey(keys.publicKey)).toEqual(pub);
122
+ });
123
+
124
+ test('the authorization header carries an ES256 JWT the public key verifies', async () => {
125
+ const keys = await generateVapidKeys();
126
+ const endpoint = 'https://fcm.googleapis.com/fcm/send/abc:def';
127
+ const now = Date.parse('2026-11-18T18:00:00Z');
128
+ const header = await vapidAuthorization(endpoint, keys, 'mailto:owner@example.com', now);
129
+ const v = await verifyVapid(header, endpoint);
130
+ expect(v.ok).toBe(true);
131
+ expect(v.k).toBe(keys.publicKey);
132
+ expect(v.header).toEqual({ typ: 'JWT', alg: 'ES256' });
133
+ expect(v.claims.aud).toBe('https://fcm.googleapis.com');
134
+ expect(v.claims.sub).toBe('mailto:owner@example.com');
135
+ expect(v.claims.exp).toBe(Math.floor(now / 1000) + 12 * 3600);
136
+ expect(v.claims.exp - Math.floor(now / 1000)).toBeLessThanOrEqual(24 * 3600);
137
+ });
138
+
139
+ test('a different key does not verify the signature', async () => {
140
+ const keys = await generateVapidKeys();
141
+ const other = await generateVapidKeys();
142
+ const endpoint = 'https://updates.push.services.mozilla.com/wpush/v2/x';
143
+ const header = await vapidAuthorization(endpoint, keys, 'https://home.example.com');
144
+ const forged = header.replace(/k=\S+$/, `k=${other.publicKey}`);
145
+ expect((await verifyVapid(forged, endpoint)).ok).toBe(false);
146
+ });
147
+
148
+ test('refuses a subject that is not mailto: or https:', async () => {
149
+ const keys = await generateVapidKeys();
150
+ await expect(vapidAuthorization('https://p.example/x', keys, 'owner@example.com')).rejects.toThrow(/subject/);
151
+ });
152
+ });
153
+
154
+ describe('sendWebPush', () => {
155
+ const subscription = {
156
+ endpoint: 'https://push.example.net/send/sub-1',
157
+ keys: { p256dh: RFC.uaPublic, auth: RFC.auth },
158
+ };
159
+
160
+ function service(status: number, headers: Record<string, string> = {}, body = '') {
161
+ const calls: { url: string; init: RequestInit }[] = [];
162
+ const fetchFn = (async (url: string | URL | Request, init?: RequestInit) => {
163
+ calls.push({ url: String(url), init: init ?? {} });
164
+ return new Response(body, { status, headers });
165
+ }) as typeof fetch;
166
+ return { calls, fetch: fetchFn };
167
+ }
168
+
169
+ test('POSTs an encrypted body with the push headers and reports delivered on 201', async () => {
170
+ const keys = await generateVapidKeys();
171
+ const svc = service(201);
172
+ const outcome = await sendWebPush(subscription, JSON.stringify({ kind: 'alarm', id: 'a1' }), {
173
+ vapid: { keys, subject: 'mailto:owner@example.com' },
174
+ ttl: 300,
175
+ urgency: 'high',
176
+ topic: 'alarm-a1',
177
+ fetch: svc.fetch,
178
+ });
179
+ expect(outcome).toEqual({ status: 201, delivered: true, gone: false });
180
+ expect(svc.calls).toHaveLength(1);
181
+ const { url, init } = svc.calls[0];
182
+ expect(url).toBe(subscription.endpoint);
183
+ expect(init.method).toBe('POST');
184
+ const headers = init.headers as Record<string, string>;
185
+ expect(headers['Content-Encoding']).toBe('aes128gcm');
186
+ expect(headers['Content-Type']).toBe('application/octet-stream');
187
+ expect(headers.TTL).toBe('300');
188
+ expect(headers.Urgency).toBe('high');
189
+ expect(headers.Topic).toBe('alarm-a1');
190
+ expect(headers.Authorization).toMatch(/^vapid t=.+, k=/);
191
+ expect((await verifyVapid(headers.Authorization, subscription.endpoint)).ok).toBe(true);
192
+ const body = init.body as Uint8Array;
193
+ expect(headers['Content-Length']).toBe(String(body.length));
194
+ const receiver = await importEcdhKeyPair(RFC.uaPublic, RFC.uaPrivate);
195
+ const plain = await decryptPushMessage(body, receiver, bytes(RFC.auth));
196
+ expect(JSON.parse(new TextDecoder().decode(plain))).toEqual({ kind: 'alarm', id: 'a1' });
197
+ });
198
+
199
+ test('404 and 410 mean the subscription is gone', async () => {
200
+ const keys = await generateVapidKeys();
201
+ for (const status of [404, 410]) {
202
+ const outcome = await sendWebPush(subscription, 'x', {
203
+ vapid: { keys, subject: 'mailto:o@e.com' },
204
+ fetch: service(status, {}, 'unsubscribed').fetch,
205
+ });
206
+ expect(outcome.gone).toBe(true);
207
+ expect(outcome.delivered).toBe(false);
208
+ expect(outcome.detail).toBe('unsubscribed');
209
+ }
210
+ });
211
+
212
+ test('429 carries Retry-After as milliseconds; other failures carry the body', async () => {
213
+ const keys = await generateVapidKeys();
214
+ const vapid = { keys, subject: 'mailto:o@e.com' };
215
+ const slow = await sendWebPush(subscription, 'x', { vapid, fetch: service(429, { 'Retry-After': '30' }).fetch });
216
+ expect(slow).toMatchObject({ status: 429, delivered: false, gone: false, retryAfterMs: 30_000 });
217
+ const bad = await sendWebPush(subscription, 'x', { vapid, fetch: service(400, {}, 'bad vapid').fetch });
218
+ expect(bad).toMatchObject({ status: 400, delivered: false, gone: false, detail: 'bad vapid' });
219
+ });
220
+
221
+ test('a network failure is an outcome, not a throw', async () => {
222
+ const keys = await generateVapidKeys();
223
+ const failing = (async () => {
224
+ throw new Error('ECONNRESET');
225
+ }) as unknown as typeof fetch;
226
+ const outcome = await sendWebPush(subscription, 'x', { vapid: { keys, subject: 'mailto:o@e.com' }, fetch: failing });
227
+ expect(outcome).toEqual({ status: 0, delivered: false, gone: false, detail: 'ECONNRESET' });
228
+ });
229
+ });
@@ -0,0 +1,335 @@
1
+ /**
2
+ * Web Push sender on WebCrypto alone — RFC 8291 (aes128gcm message encryption over ECDH P-256)
3
+ * and RFC 8292 (VAPID: an ES256 JWT that tells the push service who is calling). No Node
4
+ * `crypto`, no Buffer: the same code runs in a Cloudflare Worker, Bun and a browser test.
5
+ *
6
+ * Shape: {@link encryptPushMessage} turns a payload into the full aes128gcm body (header +
7
+ * one record); {@link vapidAuthorization} mints the `Authorization: vapid t=…, k=…` header;
8
+ * {@link sendWebPush} does both and POSTs to the subscription endpoint, reporting a typed
9
+ * outcome a caller acts on (`gone` → delete the subscription, `retryAfterMs` → back off).
10
+ * {@link decryptPushMessage} is the receiver side, here so a test proves the roundtrip.
11
+ *
12
+ * Proven against RFC 8291 Appendix A in `webPush.spec.ts` byte for byte.
13
+ */
14
+
15
+ /** A browser `PushSubscription.toJSON()`, or the row an app stored from one. */
16
+ export interface PushSubscriptionLike {
17
+ endpoint: string;
18
+ keys: { p256dh: string; auth: string };
19
+ }
20
+
21
+ /** A VAPID key pair, both halves base64url: the public key is the 65-byte uncompressed point
22
+ * a client passes as `applicationServerKey`; the private key is the 32-byte scalar `d`. */
23
+ export interface VapidKeys {
24
+ publicKey: string;
25
+ privateKey: string;
26
+ }
27
+
28
+ export type PushUrgency = 'very-low' | 'low' | 'normal' | 'high';
29
+
30
+ export interface SendWebPushOptions {
31
+ vapid: { keys: VapidKeys; subject: string };
32
+ /** Seconds the push service may hold an undelivered message. Default 60. */
33
+ ttl?: number;
34
+ urgency?: PushUrgency;
35
+ /** Replaces an earlier undelivered message with the same topic (≤ 32 URL-safe chars). */
36
+ topic?: string;
37
+ /** Injected for tests; defaults to the global fetch. */
38
+ fetch?: typeof fetch;
39
+ /** Clock for the VAPID claims; defaults to Date.now. */
40
+ now?: () => number;
41
+ }
42
+
43
+ export interface WebPushOutcome {
44
+ /** HTTP status the push service answered with (0 when the request itself failed). */
45
+ status: number;
46
+ /** 201 (or 200) — the service accepted the message for delivery. */
47
+ delivered: boolean;
48
+ /** 404 or 410 — the subscription no longer exists; the caller should forget it. */
49
+ gone: boolean;
50
+ /** Present on 429 / 503 with a Retry-After the caller should honor. */
51
+ retryAfterMs?: number;
52
+ /** The response body on a non-success, trimmed, for a log line. */
53
+ detail?: string;
54
+ }
55
+
56
+ export interface EncryptPushOptions {
57
+ /** 16 random bytes by default; a test fixes it to reproduce the RFC vector. */
58
+ salt?: Uint8Array;
59
+ /** The application server's ephemeral ECDH P-256 pair; fresh per message by default. */
60
+ senderKeyPair?: CryptoKeyPair;
61
+ /** RFC 8188 record size. Default 4096, the ceiling every push service accepts. */
62
+ recordSize?: number;
63
+ }
64
+
65
+ /** An ArrayBuffer-backed view: what WebCrypto's BufferSource accepts without a cast. */
66
+ type Bytes = Uint8Array<ArrayBuffer>;
67
+ /** Copy any Uint8Array (a Node Buffer slice, a SharedArrayBuffer view) onto its own ArrayBuffer. */
68
+ const own = (view: Uint8Array): Bytes => new Uint8Array(view);
69
+
70
+ const enc = new TextEncoder();
71
+ const P256 = { name: 'ECDH', namedCurve: 'P-256' } as const;
72
+ const ES256 = { name: 'ECDSA', namedCurve: 'P-256' } as const;
73
+ const KEY_INFO_PREFIX = 'WebPush: info\0';
74
+ const CEK_INFO = enc.encode('Content-Encoding: aes128gcm\0');
75
+ const NONCE_INFO = enc.encode('Content-Encoding: nonce\0');
76
+ const SALT_BYTES = 16;
77
+ const TAG_BYTES = 16;
78
+ const PUBLIC_KEY_BYTES = 65;
79
+ const HEADER_BYTES = SALT_BYTES + 4 + 1 + PUBLIC_KEY_BYTES;
80
+ const DEFAULT_RECORD_SIZE = 4096;
81
+ const DEFAULT_TTL_SECONDS = 60;
82
+ /** RFC 8292 §2: `exp` must be within 24h; 12h leaves clock skew room on both sides. */
83
+ const VAPID_LIFETIME_SECONDS = 12 * 60 * 60;
84
+
85
+ /* ── base64url, WebCrypto-only ─────────────────────────────────────────────────────────── */
86
+
87
+ export function base64urlEncode(bytes: Uint8Array | ArrayBuffer): string {
88
+ const view = bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes);
89
+ let binary = '';
90
+ for (let i = 0; i < view.length; i += 0x8000) {
91
+ binary += String.fromCharCode(...view.subarray(i, i + 0x8000));
92
+ }
93
+ return btoa(binary).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
94
+ }
95
+
96
+ export function base64urlDecode(text: string): Bytes {
97
+ const padded = text.replace(/-/g, '+').replace(/_/g, '/').padEnd(Math.ceil(text.length / 4) * 4, '=');
98
+ const binary = atob(padded);
99
+ const out = new Uint8Array(binary.length);
100
+ for (let i = 0; i < binary.length; i++) out[i] = binary.charCodeAt(i);
101
+ return out;
102
+ }
103
+
104
+ /* ── keys ──────────────────────────────────────────────────────────────────────────────── */
105
+
106
+ /** Mint a VAPID pair. Store both halves as secrets; publish only `publicKey`. */
107
+ export async function generateVapidKeys(): Promise<VapidKeys> {
108
+ const pair = await crypto.subtle.generateKey(ES256, true, ['sign', 'verify']);
109
+ const jwk = await crypto.subtle.exportKey('jwk', pair.privateKey);
110
+ if (!jwk.d || !jwk.x || !jwk.y) throw new Error('web-push: ECDSA key export lacked d/x/y');
111
+ return {
112
+ publicKey: base64urlEncode(uncompressedPoint(jwk.x, jwk.y)),
113
+ privateKey: jwk.d,
114
+ };
115
+ }
116
+
117
+ function uncompressedPoint(x: string, y: string): Bytes {
118
+ const out = new Uint8Array(PUBLIC_KEY_BYTES);
119
+ out[0] = 0x04;
120
+ out.set(base64urlDecode(x), 1);
121
+ out.set(base64urlDecode(y), 33);
122
+ return out;
123
+ }
124
+
125
+ function splitPoint(publicKey: string): { x: string; y: string } {
126
+ const bytes = base64urlDecode(publicKey);
127
+ if (bytes.length !== PUBLIC_KEY_BYTES || bytes[0] !== 0x04) {
128
+ throw new Error('web-push: public key must be a 65-byte uncompressed P-256 point');
129
+ }
130
+ return { x: base64urlEncode(bytes.subarray(1, 33)), y: base64urlEncode(bytes.subarray(33)) };
131
+ }
132
+
133
+ async function importVapidSigningKey(keys: VapidKeys): Promise<CryptoKey> {
134
+ const { x, y } = splitPoint(keys.publicKey);
135
+ return crypto.subtle.importKey(
136
+ 'jwk',
137
+ { kty: 'EC', crv: 'P-256', x, y, d: keys.privateKey, ext: true },
138
+ ES256,
139
+ false,
140
+ ['sign'],
141
+ );
142
+ }
143
+
144
+ /** Import the ECDH pair a test or a receiver holds as raw base64url halves. */
145
+ export async function importEcdhKeyPair(publicKey: string, privateKey: string): Promise<CryptoKeyPair> {
146
+ const { x, y } = splitPoint(publicKey);
147
+ const priv = await crypto.subtle.importKey(
148
+ 'jwk',
149
+ { kty: 'EC', crv: 'P-256', x, y, d: privateKey, ext: true },
150
+ P256,
151
+ false,
152
+ ['deriveBits'],
153
+ );
154
+ const pub = await crypto.subtle.importKey('raw', base64urlDecode(publicKey), P256, true, []);
155
+ return { privateKey: priv, publicKey: pub };
156
+ }
157
+
158
+ /* ── RFC 8291 + RFC 8188 ───────────────────────────────────────────────────────────────── */
159
+
160
+ async function hkdf(salt: Bytes, ikm: Bytes, info: Bytes, bytes: number): Promise<Bytes> {
161
+ const key = await crypto.subtle.importKey('raw', ikm, { name: 'HKDF' }, false, ['deriveBits']);
162
+ const bits = await crypto.subtle.deriveBits({ name: 'HKDF', hash: 'SHA-256', salt, info }, key, bytes * 8);
163
+ return new Uint8Array(bits);
164
+ }
165
+
166
+ function concat(...parts: Uint8Array[]): Bytes {
167
+ const out = new Uint8Array(parts.reduce((n, p) => n + p.length, 0));
168
+ let at = 0;
169
+ for (const p of parts) {
170
+ out.set(p, at);
171
+ at += p.length;
172
+ }
173
+ return out;
174
+ }
175
+
176
+ /** RFC 8291 §3: the content-encryption key and nonce for one message. */
177
+ async function contentKeys(
178
+ sharedSecret: Bytes,
179
+ authSecret: Bytes,
180
+ uaPublic: Bytes,
181
+ asPublic: Bytes,
182
+ salt: Bytes,
183
+ ): Promise<{ cek: CryptoKey; nonce: Bytes }> {
184
+ const keyInfo = concat(enc.encode(KEY_INFO_PREFIX), uaPublic, asPublic);
185
+ const ikm = await hkdf(authSecret, sharedSecret, keyInfo, 32);
186
+ const cekBytes = await hkdf(salt, ikm, CEK_INFO, 16);
187
+ const nonce = await hkdf(salt, ikm, NONCE_INFO, 12);
188
+ const cek = await crypto.subtle.importKey('raw', cekBytes, { name: 'AES-GCM' }, false, ['encrypt', 'decrypt']);
189
+ return { cek, nonce };
190
+ }
191
+
192
+ /**
193
+ * Encrypt one push payload as an aes128gcm body: header (salt ‖ rs ‖ idlen ‖ sender public
194
+ * key) followed by a single record (plaintext ‖ 0x02 ‖ GCM tag). Throws when the payload
195
+ * cannot fit one record of `recordSize`; push services cap the whole body at 4096 bytes, so
196
+ * a payload over ~3990 bytes is a design problem, not something to split.
197
+ */
198
+ export async function encryptPushMessage(
199
+ payload: string | Uint8Array,
200
+ keys: PushSubscriptionLike['keys'],
201
+ options: EncryptPushOptions = {},
202
+ ): Promise<Bytes> {
203
+ const plaintext = typeof payload === 'string' ? enc.encode(payload) : own(payload);
204
+ const recordSize = options.recordSize ?? DEFAULT_RECORD_SIZE;
205
+ if (plaintext.length + 1 + TAG_BYTES > recordSize) {
206
+ throw new Error(`web-push: payload of ${plaintext.length} bytes does not fit one ${recordSize}-byte record`);
207
+ }
208
+ const uaPublic = base64urlDecode(keys.p256dh);
209
+ const authSecret = base64urlDecode(keys.auth);
210
+ if (uaPublic.length !== PUBLIC_KEY_BYTES) throw new Error('web-push: p256dh must be a 65-byte uncompressed point');
211
+ if (authSecret.length !== 16) throw new Error('web-push: auth secret must be 16 bytes');
212
+
213
+ const salt = options.salt ? own(options.salt) : crypto.getRandomValues(new Uint8Array(SALT_BYTES));
214
+ if (salt.length !== SALT_BYTES) throw new Error('web-push: salt must be 16 bytes');
215
+ const sender = options.senderKeyPair ?? (await crypto.subtle.generateKey(P256, true, ['deriveBits']));
216
+ const asPublic = new Uint8Array(await crypto.subtle.exportKey('raw', sender.publicKey));
217
+ const uaKey = await crypto.subtle.importKey('raw', uaPublic, P256, false, []);
218
+ const shared = new Uint8Array(await crypto.subtle.deriveBits({ name: 'ECDH', public: uaKey }, sender.privateKey, 256));
219
+
220
+ const { cek, nonce } = await contentKeys(shared, authSecret, uaPublic, asPublic, salt);
221
+ const record = concat(plaintext, Uint8Array.of(0x02));
222
+ const ciphertext = new Uint8Array(await crypto.subtle.encrypt({ name: 'AES-GCM', iv: nonce }, cek, record));
223
+
224
+ const header = new Uint8Array(HEADER_BYTES);
225
+ header.set(salt, 0);
226
+ new DataView(header.buffer).setUint32(SALT_BYTES, recordSize, false);
227
+ header[SALT_BYTES + 4] = PUBLIC_KEY_BYTES;
228
+ header.set(asPublic, SALT_BYTES + 5);
229
+ return concat(header, ciphertext);
230
+ }
231
+
232
+ /**
233
+ * The receiver side of {@link encryptPushMessage} for a single-record body: what a browser
234
+ * does before handing `event.data` to a service worker. Here for tests and local harnesses.
235
+ */
236
+ export async function decryptPushMessage(
237
+ input: Uint8Array,
238
+ receiver: CryptoKeyPair,
239
+ auth: Uint8Array,
240
+ ): Promise<Bytes> {
241
+ const body = own(input);
242
+ const authSecret = own(auth);
243
+ if (body.length < HEADER_BYTES + TAG_BYTES + 1) throw new Error('web-push: body too short');
244
+ const salt = body.subarray(0, SALT_BYTES);
245
+ const idlen = body[SALT_BYTES + 4];
246
+ if (idlen !== PUBLIC_KEY_BYTES) throw new Error(`web-push: unexpected key id length ${idlen}`);
247
+ const asPublic = body.subarray(SALT_BYTES + 5, HEADER_BYTES);
248
+ const uaPublic = new Uint8Array(await crypto.subtle.exportKey('raw', receiver.publicKey));
249
+ const asKey = await crypto.subtle.importKey('raw', asPublic, P256, false, []);
250
+ const shared = new Uint8Array(await crypto.subtle.deriveBits({ name: 'ECDH', public: asKey }, receiver.privateKey, 256));
251
+ const { cek, nonce } = await contentKeys(shared, authSecret, uaPublic, asPublic, salt);
252
+ const record = new Uint8Array(await crypto.subtle.decrypt({ name: 'AES-GCM', iv: nonce }, cek, body.subarray(HEADER_BYTES)));
253
+ let end = record.length - 1;
254
+ while (end >= 0 && record[end] === 0) end--;
255
+ if (end < 0 || record[end] !== 0x02) throw new Error('web-push: record lacks the final-record delimiter');
256
+ return record.subarray(0, end);
257
+ }
258
+
259
+ /* ── RFC 8292 VAPID ────────────────────────────────────────────────────────────────────── */
260
+
261
+ /**
262
+ * `Authorization: vapid t=<JWT>, k=<public key>` for one push resource. `subject` is a
263
+ * `mailto:` or `https:` URL the push service may contact about abuse; the audience is the
264
+ * endpoint's origin, so one header serves every subscription on that push service.
265
+ */
266
+ export async function vapidAuthorization(
267
+ endpoint: string,
268
+ keys: VapidKeys,
269
+ subject: string,
270
+ now: number = Date.now(),
271
+ ): Promise<string> {
272
+ if (!/^(mailto:|https:)/.test(subject)) throw new Error('web-push: VAPID subject must be a mailto: or https: URL');
273
+ const header = base64urlEncode(enc.encode(JSON.stringify({ typ: 'JWT', alg: 'ES256' })));
274
+ const claims = base64urlEncode(
275
+ enc.encode(
276
+ JSON.stringify({
277
+ aud: new URL(endpoint).origin,
278
+ exp: Math.floor(now / 1000) + VAPID_LIFETIME_SECONDS,
279
+ sub: subject,
280
+ }),
281
+ ),
282
+ );
283
+ const signingInput = `${header}.${claims}`;
284
+ const key = await importVapidSigningKey(keys);
285
+ const signature = await crypto.subtle.sign({ name: 'ECDSA', hash: 'SHA-256' }, key, enc.encode(signingInput));
286
+ return `vapid t=${signingInput}.${base64urlEncode(signature)}, k=${keys.publicKey}`;
287
+ }
288
+
289
+ /* ── send ──────────────────────────────────────────────────────────────────────────────── */
290
+
291
+ /** Encrypt, sign and POST one message. Never throws on a service refusal: read the outcome. */
292
+ export async function sendWebPush(
293
+ subscription: PushSubscriptionLike,
294
+ payload: string | Uint8Array,
295
+ options: SendWebPushOptions,
296
+ ): Promise<WebPushOutcome> {
297
+ const body = await encryptPushMessage(payload, subscription.keys);
298
+ const authorization = await vapidAuthorization(
299
+ subscription.endpoint,
300
+ options.vapid.keys,
301
+ options.vapid.subject,
302
+ (options.now ?? Date.now)(),
303
+ );
304
+ const headers: Record<string, string> = {
305
+ Authorization: authorization,
306
+ 'Content-Encoding': 'aes128gcm',
307
+ 'Content-Type': 'application/octet-stream',
308
+ 'Content-Length': String(body.length),
309
+ TTL: String(options.ttl ?? DEFAULT_TTL_SECONDS),
310
+ };
311
+ if (options.urgency) headers.Urgency = options.urgency;
312
+ if (options.topic) headers.Topic = options.topic;
313
+ const doFetch = options.fetch ?? fetch;
314
+ let response: Response;
315
+ try {
316
+ response = await doFetch(subscription.endpoint, { method: 'POST', headers, body });
317
+ } catch (error) {
318
+ return { status: 0, delivered: false, gone: false, detail: error instanceof Error ? error.message : String(error) };
319
+ }
320
+ const delivered = response.status === 201 || response.status === 200;
321
+ const gone = response.status === 404 || response.status === 410;
322
+ const outcome: WebPushOutcome = { status: response.status, delivered, gone };
323
+ const retryAfter = response.headers.get('Retry-After');
324
+ if ((response.status === 429 || response.status === 503) && retryAfter) {
325
+ const seconds = Number(retryAfter);
326
+ outcome.retryAfterMs = Number.isFinite(seconds) ? seconds * 1000 : Math.max(0, Date.parse(retryAfter) - Date.now());
327
+ }
328
+ if (!delivered) outcome.detail = (await response.text().catch(() => '')).slice(0, 200);
329
+ return outcome;
330
+ }
331
+
332
+ /** Decode a VAPID public key for `PushManager.subscribe({ applicationServerKey })`. Client-side helper. */
333
+ export function applicationServerKey(publicKey: string): Bytes {
334
+ return base64urlDecode(publicKey);
335
+ }
@@ -0,0 +1,38 @@
1
+ /** `cursedbelt-server/request-scope` — the request scope a once-per-isolate route tier reads (forge tasks 5632, photos per-request floor). */
2
+ import { describe, expect, it } from "bun:test";
3
+ import { createRequestScope } from "./requestScope";
4
+
5
+ describe("🔴 a request scope never hands one request another's value", () => {
6
+ interface Scope {
7
+ name: string;
8
+ store: { whose(): string; label: string };
9
+ }
10
+ const scope = createRequestScope<Scope>("test");
11
+ const of = (name: string): Scope => ({ name, store: { label: name, whose: () => name } });
12
+
13
+ it("two requests interleaving across awaits each read their own", async () => {
14
+ const store = scope.late("store");
15
+ let releaseA: () => void = () => {};
16
+ const a = scope.run(of("a"), async () => {
17
+ await new Promise<void>((resolve) => {
18
+ releaseA = resolve;
19
+ });
20
+ return [store.whose(), store.label];
21
+ });
22
+ const b = scope.run(of("b"), async () => [store.whose(), store.label]);
23
+ expect(await b).toEqual(["b", "b"]);
24
+ releaseA();
25
+ expect(await a).toEqual(["a", "a"]);
26
+ });
27
+
28
+ it("a method taken off the stand-in in one request runs on the request that CALLS it", () => {
29
+ const store = scope.late("store");
30
+ const whose = scope.run(of("builder"), () => store.whose);
31
+ expect(scope.run(of("caller"), () => whose())).toBe("caller");
32
+ });
33
+
34
+ it("is refused outside any request — a stand-in used at isolate scope is a bug, never a silent undefined", () => {
35
+ const store = scope.late("store");
36
+ expect(() => store.whose()).toThrow(/outside a request/);
37
+ });
38
+ });
@@ -0,0 +1,74 @@
1
+ /**
2
+ * `cursedbelt-server/request-scope` — one request's things, for an app built ONCE per isolate.
3
+ *
4
+ * Born in auth (forge task 5632), promoted when photos took the same shape: a Worker that rebuilt
5
+ * its whole Hono graph per request paid a flat 5–40 CPU-ms floor on every call. Worker-safe: it
6
+ * needs `nodejs_compat` for `node:async_hooks`, nothing else.
7
+ *
8
+ * The assembly closes over its database, its session store, its throttle… — objects that belong to
9
+ * ONE request on a Worker (`perInvocation`'s query count, a D1 snapshot, a binding's I/O, which
10
+ * workerd refuses to touch from another request). Building the whole route tier per request cost
11
+ * 16–40 CPU-ms on auth-stage; building it once and handing it these values LATE costs nothing.
12
+ *
13
+ * `late(key)` is a stand-in that reads `key` from the CURRENT request's scope at every use, so the
14
+ * assembly can hold it from the first request on. The scope rides `AsyncLocalStorage`, never a
15
+ * module variable: an isolate serves requests concurrently, and a variable set by request B while
16
+ * request A awaits D1 would hand A B's sessions. Work handed to `waitUntil` keeps its own scope.
17
+ *
18
+ * 🔴 A stand-in is for a LEAF service. One with a `mount` (a notification service) registers routes
19
+ * over the internals of whichever request built it — build that once over a late database instead.
20
+ */
21
+ import { AsyncLocalStorage } from "node:async_hooks";
22
+
23
+ export interface RequestScope<S extends object> {
24
+ /** Run `work` with `scope` as the current request's — everything it awaits, and defers, sees it. */
25
+ run<T>(scope: S, work: () => T): T;
26
+ /** The current request's scope; THROWS outside one (a stand-in used at isolate scope is a bug). */
27
+ current(): S;
28
+ /** A stand-in for `scope[key]` that reads the current request's value at every property access. */
29
+ late<K extends keyof S>(key: K): NonNullable<S[K]>;
30
+ /** The same, for a value derived from the scope (`(s) => s.env.AE`). */
31
+ lateOf<T extends object>(read: (scope: S) => T | null | undefined, what: string): T;
32
+ }
33
+
34
+ export function createRequestScope<S extends object>(name: string): RequestScope<S> {
35
+ const storage = new AsyncLocalStorage<S>();
36
+ const current = (): S => {
37
+ const scope = storage.getStore();
38
+ if (!scope) throw new Error(`${name}: a request-scoped value was read outside a request`);
39
+ return scope;
40
+ };
41
+ const lateOf = <T extends object>(read: (scope: S) => T | null | undefined, what: string): T => {
42
+ const target = (): object => {
43
+ const value = read(current());
44
+ if (value === undefined || value === null) throw new Error(`${name}: this request has no ${what}`);
45
+ return value;
46
+ };
47
+ return new Proxy(
48
+ {},
49
+ {
50
+ get(_shell, prop) {
51
+ const member = Reflect.get(target(), prop);
52
+ if (typeof member !== "function") return member;
53
+ // Resolved again at CALL time: a method taken off the stand-in while the assembly is
54
+ // built (request 1) must still run on whichever request calls it.
55
+ return (...args: unknown[]) => {
56
+ const value = target();
57
+ return Reflect.apply(Reflect.get(value, prop, value) as (...a: unknown[]) => unknown, value, args);
58
+ };
59
+ },
60
+ has: (_shell, prop) => Reflect.has(target(), prop),
61
+ ownKeys: () => Reflect.ownKeys(target()),
62
+ getOwnPropertyDescriptor(_shell, prop) {
63
+ const descriptor = Reflect.getOwnPropertyDescriptor(target(), prop);
64
+ // A proxy may not report a property non-configurable that its (empty) shell lacks.
65
+ return descriptor ? { ...descriptor, configurable: true } : undefined;
66
+ },
67
+ set: (_shell, prop, value) => Reflect.set(target(), prop, value),
68
+ },
69
+ ) as T;
70
+ };
71
+ const late = <K extends keyof S>(key: K): NonNullable<S[K]> =>
72
+ lateOf((scope) => scope[key] as (NonNullable<S[K]> & object) | undefined, String(key)) as NonNullable<S[K]>;
73
+ return { run: (scope, work) => storage.run(scope, work), current, late, lateOf };
74
+ }