diff --git a/package.json b/package.json index b81ecf853..d7b49d5ba 100644 --- a/package.json +++ b/package.json @@ -99,7 +99,7 @@ "tailwind-merge": "^3.7.0", "tesseract.js": "^7.0.0", "undici": "^8.12.4", - "web-push": "^3.6.7", + "web-push": "^4.0.0", "yaml": "^2.9.1", "zod": "^4.6.7", "zod-openapi": "^6.0.2", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 2e95172c9..2e7c06a7d 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -182,8 +182,8 @@ importers: specifier: ^8.12.4 version: 8.12.4 web-push: - specifier: ^3.6.7 - version: 3.6.7(supports-color@7.2.0) + specifier: ^4.0.0 + version: 4.0.0(supports-color@7.2.0) yaml: specifier: ^2.9.1 version: 2.9.1 @@ -3439,9 +3439,9 @@ packages: engines: {node: '>=0.4.0'} hasBin: true - agent-base@7.1.4: - resolution: {integrity: sha512-MnA+YT8fwfJPgBx3m60MNqakm30XOkyIoH1y6huTQvC0PwZG7ki8NacLBcrPbNoo8vEZy7Jpuk7+jMO+CUovTQ==} - engines: {node: '>= 14'} + agent-base@9.0.0: + resolution: {integrity: sha512-TQf59BsZnytt8GdJKLPfUZ54g/iaUL2OWDSFCCvMOhsHduDQxO8xC4PNeyIkVcA5KwL2phPSv0douC0fgWzmnA==} + engines: {node: '>= 20'} ajv-formats@2.1.1: resolution: {integrity: sha512-Wx0Kx52hxE7C18hkMEggYlEifqWZtYaRgouJor+WMdPnQyEK13vgEWyVNup7SoeeoLMsr4kf5h6dOW11I15MUA==} @@ -4776,13 +4776,13 @@ packages: resolution: {integrity: sha512-4FbRdAX+bSdmo4AUFuS0WNiPz8NgFt+r8ThgNWmlrjQjt1Q7ZR9+zTlce2859x4KSXrwIsaeTqDoKQmtP8pLmQ==} engines: {node: '>= 0.8'} - http_ece@1.2.0: - resolution: {integrity: sha512-JrF8SSLVmcvc5NducxgyOrKXe3EsyHMgBFgSaIUGmArKe+rwr0uphRkRXvwiom3I+fpIfoItveHrfudL8/rxuA==} + http_ece@1.2.1: + resolution: {integrity: sha512-+tzLoMYgXvicu60sVFoswTiu6BiQ6EX3DORRJQ3W2dNpNWCyZ3tcmRFZZ3jgVyw8ziWUCeUARKCkYDY6JgFx+w==} engines: {node: '>=16'} - https-proxy-agent@7.0.6: - resolution: {integrity: sha512-vK9P5/iUfdl95AI+JVyUuIcVtd4ofvtrOr3HNtM2yxC9bnMbEdp3x01OhQNnjb8IJYi38VlTE3mBXwcfvywuSw==} - engines: {node: '>= 14'} + https-proxy-agent@9.1.0: + resolution: {integrity: sha512-ag87y7cJJ9/3+GxFr8Oy4O5faDsGRGnBGsJj/YjOSsSx/5eadKLYTMPlzuR6obgoCDDm0abAAZitXXQkMOPSpA==} + engines: {node: '>= 20'} human-signals@2.1.0: resolution: {integrity: sha512-B4FFZ6q/T2jhhksgkbEW3HBvWIfDW85snkQgawt07S7J5QXTk6BkNV+0yAeZrM5QpMAdYlocGoljn0sJ/WQkFw==} @@ -6029,6 +6029,15 @@ packages: resolution: {integrity: sha512-5nnx0yGyVUcY6t9RnWcARWtwT9F1D8O9rt08htPvnd49W1IgZtmLkhu9WfMzQj1cFxjHIO6connUNVW5k7AVyQ==} engines: {node: '>= 0.10'} + proxy-agent-negotiate@1.1.0: + resolution: {integrity: sha512-N8IBcM3UgCVzz2L2Lqv8DVntDnnC8/hiV4nEDUPkqq72TPUgYWjQc+bdZlBPZK9LzPAvOY//gAt0S0DApoOXWQ==} + engines: {node: '>= 20'} + peerDependencies: + kerberos: ^2.0.0 + peerDependenciesMeta: + kerberos: + optional: true + pump@3.0.4: resolution: {integrity: sha512-VS7sjc6KR7e1ukRFhQSY5LM2uBWAUPiOPa/A3mkKmiMwSmRFUITt0xuj+/lesgnCv+dPIEYlkzrcyXgquIHMcA==} @@ -7023,8 +7032,8 @@ packages: weapon-regex@2.0.6: resolution: {integrity: sha512-iJC2vqYp+bh3r4X6zjuP0h65XqXjgUX3nJgmhj0PQMrdhAbUwCfN76CSTEEQqV3G7468kjOJ69PmytTG8l/8Gg==} - web-push@3.6.7: - resolution: {integrity: sha512-OpiIUe8cuGjrj3mMBFWY+e4MMIkW3SVT+7vEIjvD9kejGUypv8GPDf84JdPWskK8zMRIJ6xYGm+Kxr8YkPyA0A==} + web-push@4.0.0: + resolution: {integrity: sha512-iKzGK/q3k+kjoPK+fkbs8ymYvEqu5RJNAypEskW+UAYsC44upqb0f+T8QSYW4naowl9bzjlHRe8CI0NFCBzZeQ==} engines: {node: '>= 16'} hasBin: true @@ -10562,7 +10571,7 @@ snapshots: acorn@8.19.0: {} - agent-base@7.1.4: {} + agent-base@9.0.0: {} ajv-formats@2.1.1(ajv@8.20.0): optionalDependencies: @@ -12075,13 +12084,15 @@ snapshots: statuses: 2.0.2 toidentifier: 1.0.1 - http_ece@1.2.0: {} + http_ece@1.2.1: {} - https-proxy-agent@7.0.6(supports-color@7.2.0): + https-proxy-agent@9.1.0(supports-color@7.2.0): dependencies: - agent-base: 7.1.4 + agent-base: 9.0.0 debug: 4.4.3(supports-color@7.2.0) + proxy-agent-negotiate: 1.1.0 transitivePeerDependencies: + - kerberos - supports-color human-signals@2.1.0: {} @@ -13222,6 +13233,8 @@ snapshots: forwarded: 0.2.0 ipaddr.js: 1.9.1 + proxy-agent-negotiate@1.1.0: {} + pump@3.0.4: dependencies: end-of-stream: 1.4.5 @@ -14416,14 +14429,14 @@ snapshots: weapon-regex@2.0.6: {} - web-push@3.6.7(supports-color@7.2.0): + web-push@4.0.0(supports-color@7.2.0): dependencies: asn1.js: 5.4.1 - http_ece: 1.2.0 - https-proxy-agent: 7.0.6(supports-color@7.2.0) + http_ece: 1.2.1 + https-proxy-agent: 9.1.0(supports-color@7.2.0) jws: 4.0.1 - minimist: 1.2.8 transitivePeerDependencies: + - kerberos - supports-color webidl-conversions@3.0.1: {} diff --git a/src/lib/notifications/senders/__tests__/web-push-library-contract.test.ts b/src/lib/notifications/senders/__tests__/web-push-library-contract.test.ts new file mode 100644 index 000000000..4c84ab0b6 --- /dev/null +++ b/src/lib/notifications/senders/__tests__/web-push-library-contract.test.ts @@ -0,0 +1,230 @@ +/** + * Wire contract between HealthLog and `web-push`, exercised against the real + * library rather than a mock. + * + * Every sender test mocks `web-push`, so a major bump of it would pass them + * all while changing what a push service receives. The sender only borrows + * three functions from the library (`generateVAPIDKeys`, `setVapidDetails`, + * `generateRequestDetails`) and dials the result itself through `safeFetch`, + * so this file pins what those three must keep doing: + * + * 1. They are reachable on the namespace a dynamic `import("web-push")` + * returns, which is how the sender and the VAPID route load the library. + * 2. A VAPID key pair stored before an upgrade is still accepted, and a fresh + * one has the same shape. + * 3. The request a subscription gets: method, the RFC 8030 headers (TTL, + * Urgency, aes128gcm encoding), a VAPID `Authorization` whose JWT verifies + * against the public key and names the endpoint's origin, and a body the + * subscriber's keys decrypt back to the exact payload (RFC 8291). + */ +import { + createECDH, + createHash, + createDecipheriv, + createHmac, + createPublicKey, + randomBytes, + verify, +} from "node:crypto"; +import { describe, expect, it } from "vitest"; + +const ENDPOINT = "https://push.example.test/send/abc123?x=1"; +const SUBJECT = "mailto:operator@example.test"; + +/** A P-256 key pair from a fixed seed, so its encoded form is stable. */ +function fixedVapidKeys() { + const ecdh = createECDH("prime256v1"); + ecdh.setPrivateKey(createHash("sha256").update("healthlog-vapid").digest()); + return { + publicKey: ecdh.getPublicKey().toString("base64url"), + privateKey: ecdh.getPrivateKey().toString("base64url"), + }; +} + +/** A browser-side subscription: its own P-256 key pair plus an auth secret. */ +function subscriber() { + const ecdh = createECDH("prime256v1"); + ecdh.generateKeys(); + const auth = randomBytes(16); + return { + ecdh, + auth, + subscription: { + endpoint: ENDPOINT, + keys: { + p256dh: ecdh.getPublicKey().toString("base64url"), + auth: auth.toString("base64url"), + }, + }, + }; +} + +function hmac(key: Buffer, data: Buffer): Buffer { + return createHmac("sha256", key).update(data).digest(); +} + +/** RFC 8291 / RFC 8188 decryption of a single-record aes128gcm body. */ +function decryptAes128gcm( + body: Buffer, + ecdh: ReturnType, + auth: Buffer, +) { + const salt = body.subarray(0, 16); + const recordSize = body.readUInt32BE(16); + const idLength = body[20]!; + const serverPublic = body.subarray(21, 21 + idLength); + const record = body.subarray(21 + idLength); + expect(record.length).toBeLessThanOrEqual(recordSize); + + const shared = ecdh.computeSecret(serverPublic); + const keyInfo = Buffer.concat([ + Buffer.from("WebPush: info\0"), + ecdh.getPublicKey(), + serverPublic, + ]); + const ikm = hmac( + hmac(auth, shared), + Buffer.concat([keyInfo, Buffer.from([1])]), + ); + const prk = hmac(salt, ikm); + const cek = hmac( + prk, + Buffer.from("Content-Encoding: aes128gcm\0\x01"), + ).subarray(0, 16); + const nonce = hmac( + prk, + Buffer.from("Content-Encoding: nonce\0\x01"), + ).subarray(0, 12); + + const decipher = createDecipheriv("aes-128-gcm", cek, nonce); + decipher.setAuthTag(record.subarray(record.length - 16)); + const padded = Buffer.concat([ + decipher.update(record.subarray(0, record.length - 16)), + decipher.final(), + ]); + // The last record ends in the 0x02 delimiter followed by zero padding. + let end = padded.length - 1; + while (end >= 0 && padded[end] === 0) end -= 1; + expect(padded[end]).toBe(2); + return padded.subarray(0, end).toString("utf8"); +} + +function verifyVapidJwt(jwt: string, publicKeyB64: string) { + const [header, claims, signature] = jwt.split("."); + const point = Buffer.from(publicKeyB64, "base64url"); + const key = createPublicKey({ + key: { + kty: "EC", + crv: "P-256", + x: point.subarray(1, 33).toString("base64url"), + y: point.subarray(33, 65).toString("base64url"), + }, + format: "jwk", + }); + const valid = verify( + "sha256", + Buffer.from(`${header}.${claims}`), + { key, dsaEncoding: "ieee-p1363" }, + Buffer.from(signature!, "base64url"), + ); + return { + valid, + header: JSON.parse(Buffer.from(header!, "base64url").toString()), + claims: JSON.parse(Buffer.from(claims!, "base64url").toString()), + }; +} + +type RequestDetails = { + endpoint: string; + method: string; + headers: Record; + body: Buffer | null; +}; + +describe("web-push library contract", () => { + it("exposes the three functions on the dynamically imported namespace", async () => { + const webpush = await import("web-push"); + expect(typeof webpush.generateVAPIDKeys).toBe("function"); + expect(typeof webpush.setVapidDetails).toBe("function"); + expect(typeof webpush.generateRequestDetails).toBe("function"); + }); + + it("accepts a stored VAPID pair and mints new ones of the same shape", async () => { + const webpush = await import("web-push"); + const stored = fixedVapidKeys(); + expect(() => + webpush.setVapidDetails(SUBJECT, stored.publicKey, stored.privateKey), + ).not.toThrow(); + + const fresh = webpush.generateVAPIDKeys(); + expect(Buffer.from(fresh.publicKey, "base64url")).toHaveLength(65); + expect(Buffer.from(fresh.privateKey, "base64url")).toHaveLength(32); + expect(fresh.publicKey).toMatch(/^[A-Za-z0-9_-]+$/); + expect(fresh.privateKey).toMatch(/^[A-Za-z0-9_-]+$/); + }); + + it("builds a signed, encrypted request the subscriber can open", async () => { + const webpush = await import("web-push"); + const vapid = fixedVapidKeys(); + webpush.setVapidDetails(SUBJECT, vapid.publicKey, vapid.privateKey); + const { ecdh, auth, subscription } = subscriber(); + const payload = JSON.stringify({ + title: "Reminder", + body: "Täglich 08:00", + }); + + const details = webpush.generateRequestDetails( + subscription, + payload, + ) as unknown as RequestDetails; + + expect(details.endpoint).toBe(ENDPOINT); + expect(details.method).toBe("POST"); + expect(Object.keys(details.headers).sort()).toEqual([ + "Authorization", + "Content-Encoding", + "Content-Length", + "Content-Type", + "TTL", + "Urgency", + ]); + // The sender passes no TTL, so the library default is what a push + // service is told to hold an undelivered reminder for: four weeks. + expect(String(details.headers.TTL)).toBe("2419200"); + expect(details.headers.Urgency).toBe("normal"); + expect(details.headers["Content-Encoding"]).toBe("aes128gcm"); + expect(details.headers["Content-Type"]).toBe("application/octet-stream"); + expect(Buffer.isBuffer(details.body)).toBe(true); + expect(Number(details.headers["Content-Length"])).toBe( + details.body!.length, + ); + + const auth_ = String(details.headers.Authorization); + const match = /^vapid t=([^,]+), k=(.+)$/.exec(auth_); + expect(match).not.toBeNull(); + expect(match![2]).toBe(vapid.publicKey); + const jwt = verifyVapidJwt(match![1]!, vapid.publicKey); + expect(jwt.valid).toBe(true); + expect(jwt.header).toEqual({ typ: "JWT", alg: "ES256" }); + expect(jwt.claims.aud).toBe("https://push.example.test"); + expect(jwt.claims.sub).toBe(SUBJECT); + const now = Math.floor(Date.now() / 1000); + expect(jwt.claims.exp).toBeGreaterThan(now); + expect(jwt.claims.exp).toBeLessThanOrEqual(now + 24 * 60 * 60); + + expect(decryptAes128gcm(details.body!, ecdh, auth)).toBe(payload); + }); + + it("carries the Urgency the sender asks for on an urgent event", async () => { + const webpush = await import("web-push"); + const vapid = fixedVapidKeys(); + webpush.setVapidDetails(SUBJECT, vapid.publicKey, vapid.privateKey); + const { subscription } = subscriber(); + + const details = webpush.generateRequestDetails(subscription, "{}", { + urgency: "high", + }) as unknown as RequestDetails; + + expect(details.headers.Urgency).toBe("high"); + }); +});