cursedbelt-server 4.75.0 → 4.77.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.
@@ -10,6 +10,12 @@
10
10
  * 963 photographs. A page is held too: one that reads its table whole and sorts it to hand back its
11
11
  * LIMIT pays for the archive on every page (photos' `albums/assets`, 331,190 rows for one page).
12
12
  *
13
+ * A search keyed by `col IS NULL` alone is held the same way, whatever the column: the plan prints it as
14
+ * `(col=?)`, a keyed search, but the key is every row that has no value yet — usually most of the table.
15
+ * Photos' art-face hides reached `faces` through `faces_entity (entity_id=?)` for `f.entity_id IS NULL`,
16
+ * 16,314 of 23,978 faces per statement, twice per described photograph: 1.78 M rows read by one sync
17
+ * (forge task 5517). The plan cannot tell `= ?` from `IS NULL`, so the check reads the statement too.
18
+ *
13
19
  * ```ts
14
20
  * const statements = await preparedBy(db, () => app.request('/api/heavy'));
15
21
  * expect(await planOffenders(db, statements)).toEqual([]);
@@ -32,6 +38,12 @@ export declare const LOW_CARDINALITY_COLUMNS: readonly string[];
32
38
  export interface PlanCheckOptions {
33
39
  /** Replaces {@link LOW_CARDINALITY_COLUMNS}. */
34
40
  lowCardinality?: readonly string[];
41
+ /**
42
+ * The statement the plan is of. Given, a search keyed by one column alone that the statement tests
43
+ * `IS NULL` (`f.entity_id IS NULL` → `SEARCH f USING INDEX faces_entity (entity_id=?)`) reads every
44
+ * row with no value, and counts as reading its table whole. {@link planOffenders} always passes it.
45
+ */
46
+ sql?: string;
35
47
  }
36
48
  /** The steps of `plan` that run once per outer row: inside a correlated subquery, or an `EXISTS` semi-join. */
37
49
  export declare function perRowSteps(plan: readonly PlanRow[]): PlanRow[];
@@ -10,6 +10,12 @@
10
10
  * 963 photographs. A page is held too: one that reads its table whole and sorts it to hand back its
11
11
  * LIMIT pays for the archive on every page (photos' `albums/assets`, 331,190 rows for one page).
12
12
  *
13
+ * A search keyed by `col IS NULL` alone is held the same way, whatever the column: the plan prints it as
14
+ * `(col=?)`, a keyed search, but the key is every row that has no value yet — usually most of the table.
15
+ * Photos' art-face hides reached `faces` through `faces_entity (entity_id=?)` for `f.entity_id IS NULL`,
16
+ * 16,314 of 23,978 faces per statement, twice per described photograph: 1.78 M rows read by one sync
17
+ * (forge task 5517). The plan cannot tell `= ?` from `IS NULL`, so the check reads the statement too.
18
+ *
13
19
  * ```ts
14
20
  * const statements = await preparedBy(db, () => app.request('/api/heavy'));
15
21
  * expect(await planOffenders(db, statements)).toEqual([]);
@@ -24,13 +30,26 @@
24
30
  export const LOW_CARDINALITY_COLUMNS = ['state', 'status', 'deleted_at', 'owner_id'];
25
31
  const escapeRegExp = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
26
32
  const lowCardinalityRule = (columns) => columns.length === 0 ? null : new RegExp(` USING (?:COVERING )?INDEX \\S+ \\((?:${columns.map(escapeRegExp).join('|')})=\\?\\)`);
27
- /** A step that reads its table whole: a scan with no index, or a search by a low-cardinality column alone. */
28
- function readsWhole(detail, derived, low) {
33
+ /** `SEARCH <alias> [EXISTS ]USING [COVERING ]INDEX <index> (<column>=?)` — a search keyed by one column alone. */
34
+ const ONE_KEY = /^SEARCH (\S+) (?:EXISTS )?USING (?:COVERING )?INDEX \S+ \((\w+)=\?\)$/;
35
+ /**
36
+ * Whether `sql` tests `alias.column IS NULL` (or a bare `column IS NULL`): the search {@link ONE_KEY} names is then
37
+ * keyed by NULL. A unary `+` (`+f.entity_id IS NULL`) is SQLite's way to keep a term off every index, so it is not one.
38
+ */
39
+ function keyedByNull(detail, sql) {
40
+ const m = sql ? ONE_KEY.exec(detail) : null;
41
+ if (!m || !sql)
42
+ return false;
43
+ const [, alias, column] = m;
44
+ return new RegExp(`(?<![\\w.+])(?:${escapeRegExp(alias)}\\.)?${escapeRegExp(column)}\\s+IS\\s+NULL\\b`, 'i').test(sql);
45
+ }
46
+ /** A step that reads its table whole: a scan with no index, or a search by a low-cardinality column (or NULL) alone. */
47
+ function readsWhole(detail, derived, low, sql) {
29
48
  const bareScan = /^SCAN (?!CONSTANT ROW)/.test(detail) &&
30
49
  !detail.includes(' VIRTUAL TABLE ') &&
31
50
  !derived.has(detail.split(' ')[1] ?? '') &&
32
51
  !/ USING (?:COVERING )?INDEX /.test(detail);
33
- return bareScan || (low?.test(detail) ?? false);
52
+ return bareScan || (low?.test(detail) ?? false) || keyedByNull(detail, sql);
34
53
  }
35
54
  /** What a subquery made (`MATERIALIZE hit`, `CO-ROUTINE (subquery-1)`): its rows were counted where they were made. */
36
55
  const derivedOf = (plan) => new Set(plan.flatMap((r) => /^(?:MATERIALIZE|CO-ROUTINE) (\S+)/.exec(r.detail)?.[1] ?? []));
@@ -57,7 +76,7 @@ export function perRowSteps(plan) {
57
76
  export function perRowReads(plan, opts = {}) {
58
77
  const derived = derivedOf(plan);
59
78
  const low = lowCardinalityRule(opts.lowCardinality ?? LOW_CARDINALITY_COLUMNS);
60
- return (opts.perEvent ? plan : perRowSteps(plan)).filter((r) => readsWhole(r.detail, derived, low)).map((r) => r.detail);
79
+ return (opts.perEvent ? plan : perRowSteps(plan)).filter((r) => readsWhole(r.detail, derived, low, opts.sql)).map((r) => r.detail);
61
80
  }
62
81
  /**
63
82
  * The outer steps of a paged read that reads its table whole and then sorts every row it kept (`USE
@@ -70,7 +89,7 @@ export function wholeTablePages(plan, opts = {}) {
70
89
  return [];
71
90
  const derived = derivedOf(plan);
72
91
  const low = lowCardinalityRule(opts.lowCardinality ?? LOW_CARDINALITY_COLUMNS);
73
- return outer.filter((r) => readsWhole(r.detail, derived, low)).map((r) => r.detail);
92
+ return outer.filter((r) => readsWhole(r.detail, derived, low, opts.sql)).map((r) => r.detail);
74
93
  }
75
94
  /**
76
95
  * Every distinct statement `run` prepares on `db`, in first-prepared order. `db.prepare` is restored
@@ -117,10 +136,10 @@ export async function planOffenders(db, statements, opts = {}) {
117
136
  continue;
118
137
  const plan = await planOf(db, sql);
119
138
  const where = sql.replace(/\s+/g, ' ').trim().slice(0, 160);
120
- for (const step of perRowReads(plan, { ...opts, perEvent: write }))
139
+ for (const step of perRowReads(plan, { ...opts, perEvent: write, sql }))
121
140
  offenders.push(`${step} ← ${where}`);
122
141
  if (!write && /\bLIMIT\b/i.test(sql))
123
- for (const step of wholeTablePages(plan, opts))
142
+ for (const step of wholeTablePages(plan, { ...opts, sql }))
124
143
  offenders.push(`page: ${step} ← ${where}`);
125
144
  }
126
145
  return offenders;
@@ -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
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "cursedbelt-server",
3
- "version": "4.75.0",
3
+ "version": "4.77.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.",
@@ -307,6 +307,12 @@
307
307
  "source": "./src/server/notifications/d1.ts",
308
308
  "import": "./dist/server/notifications/d1.js"
309
309
  },
310
+ "./web-push": {
311
+ "types": "./dist/server/push/webPush.d.ts",
312
+ "bun": "./src/server/push/webPush.ts",
313
+ "source": "./src/server/push/webPush.ts",
314
+ "import": "./dist/server/push/webPush.js"
315
+ },
310
316
  "./resume": {
311
317
  "types": "./dist/server/resume/index.d.ts",
312
318
  "bun": "./src/server/resume/index.ts",
@@ -447,7 +453,7 @@
447
453
  "@node-rs/argon2": "^2.0.2",
448
454
  "@types/bun": "^1.3.14",
449
455
  "@types/node": "^24",
450
- "cursedbelt": "^6.9.1",
456
+ "cursedbelt": "^6.15.0",
451
457
  "hono": "4.12.28",
452
458
  "kysely": "^0.28.17",
453
459
  "kysely-bun-sqlite": "^0.4.0",
@@ -55,6 +55,45 @@ describe('perRowReads', () => {
55
55
  });
56
56
  });
57
57
 
58
+ describe('a search keyed by NULL (forge task 5517)', () => {
59
+ const byEntity = 'SEARCH f USING INDEX faces_entity (entity_id=?)';
60
+ const outer: PlanRow[] = [{ id: 4, parent: 0, detail: byEntity }];
61
+
62
+ test("the statement's `IS NULL` makes a one-column key read the table whole; `= ?` on the same plan does not", () => {
63
+ const hide = "UPDATE faces SET dismissed_at = ? WHERE id IN (SELECT f.id FROM faces f WHERE f.asset_id IN (SELECT value FROM json_each(?)) AND f.entity_id IS NULL)";
64
+ expect(perRowReads(outer, { perEvent: true, sql: hide })).toEqual([byEntity]);
65
+ expect(perRowReads(outer, { perEvent: true, sql: 'UPDATE faces SET dismissed_at = ? WHERE id IN (SELECT f.id FROM faces f WHERE f.entity_id = ?)' })).toEqual([]);
66
+ // Without the statement the plan alone cannot tell, so it stays a keyed search.
67
+ expect(perRowReads(outer, { perEvent: true })).toEqual([]);
68
+ });
69
+
70
+ test('another alias, a compound key, IS NOT NULL and a unary + are not a NULL key', () => {
71
+ expect(perRowReads(outer, { perEvent: true, sql: 'SELECT 1 FROM faces f JOIN faces g ON g.entity_id IS NULL WHERE f.entity_id = ?' })).toEqual([]);
72
+ expect(perRowReads(outer, { perEvent: true, sql: 'SELECT 1 FROM faces f WHERE f.entity_id IS NOT NULL' })).toEqual([]);
73
+ expect(perRowReads(outer, { perEvent: true, sql: 'SELECT 1 FROM faces f WHERE +f.entity_id IS NULL' })).toEqual([]);
74
+ expect(perRowReads([{ id: 4, parent: 0, detail: 'SEARCH f USING INDEX faces_entity (entity_id=? AND kind=?)' }], { perEvent: true, sql: 'SELECT 1 FROM faces f WHERE f.entity_id IS NULL AND f.kind = ?' })).toEqual([]);
75
+ // A bare column, the table read under its own name.
76
+ expect(perRowReads([{ id: 4, parent: 0, detail: 'SEARCH faces USING INDEX faces_entity (entity_id=?)' }], { perEvent: true, sql: 'UPDATE faces SET x = 1 WHERE entity_id IS NULL' })).toEqual([
77
+ 'SEARCH faces USING INDEX faces_entity (entity_id=?)',
78
+ ]);
79
+ });
80
+
81
+ test('planOffenders reads the statement itself: a write reaching its rows by NULL is named, by the asked-for key passes', async () => {
82
+ const db = createLocalD1(new Database(':memory:'));
83
+ await db.batch([
84
+ db.prepare('CREATE TABLE faces (id TEXT PRIMARY KEY, asset_id TEXT, entity_id TEXT)'),
85
+ db.prepare('CREATE INDEX faces_asset ON faces (asset_id)'),
86
+ db.prepare('CREATE INDEX faces_entity ON faces (entity_id)'),
87
+ ]);
88
+ const where = 'f.asset_id IN (SELECT value FROM json_each(?)) AND f.entity_id IS NULL';
89
+ const byNull = `UPDATE faces SET entity_id = 'x' WHERE id IN (SELECT f.id FROM faces f WHERE ${where})`;
90
+ expect((await planOf(db, byNull)).some((r) => r.detail === 'SEARCH f USING INDEX faces_entity (entity_id=?)')).toBe(true);
91
+ expect(await planOffenders(db, [byNull], { writes: true })).toEqual([`SEARCH f USING INDEX faces_entity (entity_id=?) ← ${byNull}`]);
92
+ const byAsset = `UPDATE faces SET entity_id = 'x' WHERE id IN (SELECT f.id FROM faces f INDEXED BY faces_asset WHERE ${where})`;
93
+ expect(await planOffenders(db, [byAsset], { writes: true })).toEqual([]);
94
+ });
95
+ });
96
+
58
97
  describe('wholeTablePages', () => {
59
98
  const sorted = (outer: string): PlanRow[] => [
60
99
  { id: 7, parent: 0, detail: outer },
@@ -10,6 +10,12 @@
10
10
  * 963 photographs. A page is held too: one that reads its table whole and sorts it to hand back its
11
11
  * LIMIT pays for the archive on every page (photos' `albums/assets`, 331,190 rows for one page).
12
12
  *
13
+ * A search keyed by `col IS NULL` alone is held the same way, whatever the column: the plan prints it as
14
+ * `(col=?)`, a keyed search, but the key is every row that has no value yet — usually most of the table.
15
+ * Photos' art-face hides reached `faces` through `faces_entity (entity_id=?)` for `f.entity_id IS NULL`,
16
+ * 16,314 of 23,978 faces per statement, twice per described photograph: 1.78 M rows read by one sync
17
+ * (forge task 5517). The plan cannot tell `= ?` from `IS NULL`, so the check reads the statement too.
18
+ *
13
19
  * ```ts
14
20
  * const statements = await preparedBy(db, () => app.request('/api/heavy'));
15
21
  * expect(await planOffenders(db, statements)).toEqual([]);
@@ -36,20 +42,40 @@ export const LOW_CARDINALITY_COLUMNS: readonly string[] = ['state', 'status', 'd
36
42
  export interface PlanCheckOptions {
37
43
  /** Replaces {@link LOW_CARDINALITY_COLUMNS}. */
38
44
  lowCardinality?: readonly string[];
45
+ /**
46
+ * The statement the plan is of. Given, a search keyed by one column alone that the statement tests
47
+ * `IS NULL` (`f.entity_id IS NULL` → `SEARCH f USING INDEX faces_entity (entity_id=?)`) reads every
48
+ * row with no value, and counts as reading its table whole. {@link planOffenders} always passes it.
49
+ */
50
+ sql?: string;
39
51
  }
40
52
 
41
53
  const escapeRegExp = (s: string) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
42
54
  const lowCardinalityRule = (columns: readonly string[]): RegExp | null =>
43
55
  columns.length === 0 ? null : new RegExp(` USING (?:COVERING )?INDEX \\S+ \\((?:${columns.map(escapeRegExp).join('|')})=\\?\\)`);
44
56
 
45
- /** A step that reads its table whole: a scan with no index, or a search by a low-cardinality column alone. */
46
- function readsWhole(detail: string, derived: ReadonlySet<string>, low: RegExp | null): boolean {
57
+ /** `SEARCH <alias> [EXISTS ]USING [COVERING ]INDEX <index> (<column>=?)` — a search keyed by one column alone. */
58
+ const ONE_KEY = /^SEARCH (\S+) (?:EXISTS )?USING (?:COVERING )?INDEX \S+ \((\w+)=\?\)$/;
59
+
60
+ /**
61
+ * Whether `sql` tests `alias.column IS NULL` (or a bare `column IS NULL`): the search {@link ONE_KEY} names is then
62
+ * keyed by NULL. A unary `+` (`+f.entity_id IS NULL`) is SQLite's way to keep a term off every index, so it is not one.
63
+ */
64
+ function keyedByNull(detail: string, sql: string | undefined): boolean {
65
+ const m = sql ? ONE_KEY.exec(detail) : null;
66
+ if (!m || !sql) return false;
67
+ const [, alias, column] = m as unknown as [string, string, string];
68
+ return new RegExp(`(?<![\\w.+])(?:${escapeRegExp(alias)}\\.)?${escapeRegExp(column)}\\s+IS\\s+NULL\\b`, 'i').test(sql);
69
+ }
70
+
71
+ /** A step that reads its table whole: a scan with no index, or a search by a low-cardinality column (or NULL) alone. */
72
+ function readsWhole(detail: string, derived: ReadonlySet<string>, low: RegExp | null, sql?: string): boolean {
47
73
  const bareScan =
48
74
  /^SCAN (?!CONSTANT ROW)/.test(detail) &&
49
75
  !detail.includes(' VIRTUAL TABLE ') &&
50
76
  !derived.has(detail.split(' ')[1] ?? '') &&
51
77
  !/ USING (?:COVERING )?INDEX /.test(detail);
52
- return bareScan || (low?.test(detail) ?? false);
78
+ return bareScan || (low?.test(detail) ?? false) || keyedByNull(detail, sql);
53
79
  }
54
80
 
55
81
  /** What a subquery made (`MATERIALIZE hit`, `CO-ROUTINE (subquery-1)`): its rows were counted where they were made. */
@@ -78,7 +104,7 @@ export function perRowSteps(plan: readonly PlanRow[]): PlanRow[] {
78
104
  export function perRowReads(plan: readonly PlanRow[], opts: PlanCheckOptions & { perEvent?: boolean } = {}): string[] {
79
105
  const derived = derivedOf(plan);
80
106
  const low = lowCardinalityRule(opts.lowCardinality ?? LOW_CARDINALITY_COLUMNS);
81
- return (opts.perEvent ? plan : perRowSteps(plan)).filter((r) => readsWhole(r.detail, derived, low)).map((r) => r.detail);
107
+ return (opts.perEvent ? plan : perRowSteps(plan)).filter((r) => readsWhole(r.detail, derived, low, opts.sql)).map((r) => r.detail);
82
108
  }
83
109
 
84
110
  /**
@@ -91,7 +117,7 @@ export function wholeTablePages(plan: readonly PlanRow[], opts: PlanCheckOptions
91
117
  if (!outer.some((r) => r.detail === 'USE TEMP B-TREE FOR ORDER BY')) return [];
92
118
  const derived = derivedOf(plan);
93
119
  const low = lowCardinalityRule(opts.lowCardinality ?? LOW_CARDINALITY_COLUMNS);
94
- return outer.filter((r) => readsWhole(r.detail, derived, low)).map((r) => r.detail);
120
+ return outer.filter((r) => readsWhole(r.detail, derived, low, opts.sql)).map((r) => r.detail);
95
121
  }
96
122
 
97
123
  /**
@@ -141,8 +167,8 @@ export async function planOffenders(
141
167
  if (write ? !opts.writes : !/^\s*(?:SELECT|WITH)\b/i.test(sql)) continue;
142
168
  const plan = await planOf(db, sql);
143
169
  const where = sql.replace(/\s+/g, ' ').trim().slice(0, 160);
144
- for (const step of perRowReads(plan, { ...opts, perEvent: write })) offenders.push(`${step} ← ${where}`);
145
- if (!write && /\bLIMIT\b/i.test(sql)) for (const step of wholeTablePages(plan, opts)) offenders.push(`page: ${step} ← ${where}`);
170
+ for (const step of perRowReads(plan, { ...opts, perEvent: write, sql })) offenders.push(`${step} ← ${where}`);
171
+ if (!write && /\bLIMIT\b/i.test(sql)) for (const step of wholeTablePages(plan, { ...opts, sql })) offenders.push(`page: ${step} ← ${where}`);
146
172
  }
147
173
  return offenders;
148
174
  }
@@ -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
+ }