119 lines
5.7 KiB
TypeScript
119 lines
5.7 KiB
TypeScript
// Mock Web Push service (PEP-55) for tests: plays the browser + push service (FCM) side.
|
|
// `subscribe()` returns what PushSubscription.toJSON() gives in a browser; POSTs to the
|
|
// endpoint are checked like a real push service does (VAPID JWT signed by `k`, aud,
|
|
// exp, aes128gcm) and decrypted with the subscription's private key (RFC 8291).
|
|
import { createDecipheriv, createECDH, createPublicKey, hkdfSync, randomBytes, randomUUID, verify } from "node:crypto";
|
|
import { createServer, type Server } from "node:http";
|
|
import type { AddressInfo } from "node:net";
|
|
|
|
export interface MockPushMessage {
|
|
subscription: string;
|
|
payload: Record<string, unknown>;
|
|
urgency: string | null;
|
|
ttl: string | null;
|
|
}
|
|
|
|
interface MockSub {
|
|
ecdh: ReturnType<typeof createECDH>;
|
|
auth: Buffer;
|
|
/** Answer with this status instead of 201 (e.g. 410 = unsubscribed). */
|
|
status?: number;
|
|
}
|
|
|
|
export class MockPushService {
|
|
readonly messages: MockPushMessage[] = [];
|
|
readonly rejected: Array<{ subscription: string; reason: string }> = [];
|
|
private subs = new Map<string, MockSub>();
|
|
private server: Server | null = null;
|
|
url = "";
|
|
|
|
async start(): Promise<this> {
|
|
this.server = createServer((req, res) => {
|
|
const chunks: Buffer[] = [];
|
|
req.on("data", (c) => chunks.push(c));
|
|
req.on("end", () => {
|
|
const id = /^\/push\/([\w-]+)$/.exec(req.url ?? "")?.[1] ?? "";
|
|
const sub = this.subs.get(id);
|
|
const fail = (status: number, reason: string) => {
|
|
this.rejected.push({ subscription: id, reason });
|
|
res.writeHead(status).end(reason);
|
|
};
|
|
if (req.method !== "POST" || !sub) return fail(404, "no such subscription");
|
|
if (sub.status) return fail(sub.status, "mock status");
|
|
try {
|
|
this.checkVapid(String(req.headers.authorization ?? ""));
|
|
if (req.headers["content-encoding"] !== "aes128gcm") throw new Error("Content-Encoding must be aes128gcm");
|
|
if (!req.headers.ttl) throw new Error("TTL header required");
|
|
const payload = JSON.parse(this.decrypt(sub, Buffer.concat(chunks)).toString("utf8"));
|
|
this.messages.push({ subscription: id, payload, urgency: (req.headers.urgency as string) ?? null, ttl: (req.headers.ttl as string) ?? null });
|
|
res.writeHead(201).end();
|
|
} catch (e) {
|
|
fail(400, (e as Error).message);
|
|
}
|
|
});
|
|
});
|
|
await new Promise<void>((r) => this.server!.listen(0, "127.0.0.1", r));
|
|
this.url = `http://127.0.0.1:${(this.server.address() as AddressInfo).port}`;
|
|
return this;
|
|
}
|
|
|
|
async stop() {
|
|
await new Promise<void>((r) => this.server?.close(() => r()) ?? r());
|
|
}
|
|
|
|
/** A new browser subscription: { endpoint, keys: { p256dh, auth } }. */
|
|
subscribe(): { id: string; endpoint: string; keys: { p256dh: string; auth: string } } {
|
|
const id = randomUUID();
|
|
const ecdh = createECDH("prime256v1");
|
|
ecdh.generateKeys();
|
|
const auth = randomBytes(16);
|
|
this.subs.set(id, { ecdh, auth });
|
|
return { id, endpoint: `${this.url}/push/${id}`, keys: { p256dh: ecdh.getPublicKey().toString("base64url"), auth: auth.toString("base64url") } };
|
|
}
|
|
|
|
/** From now on the push service answers `status` for this subscription (410 = gone). */
|
|
setStatus(id: string, status: number | undefined) {
|
|
const s = this.subs.get(id);
|
|
if (s) s.status = status;
|
|
}
|
|
|
|
for(id: string) {
|
|
return this.messages.filter((m) => m.subscription === id);
|
|
}
|
|
|
|
private checkVapid(authorization: string) {
|
|
const m = /^vapid t=([\w-]+\.[\w-]+\.[\w-]+), k=([\w-]+)$/.exec(authorization);
|
|
if (!m) throw new Error("Authorization must be 'vapid t=…, k=…'");
|
|
const [h, c, s] = m[1]!.split(".") as [string, string, string];
|
|
const raw = Buffer.from(m[2]!, "base64url");
|
|
if (raw.length !== 65 || raw[0] !== 4) throw new Error("k must be an uncompressed P-256 point");
|
|
const key = createPublicKey({ key: { kty: "EC", crv: "P-256", x: raw.subarray(1, 33).toString("base64url"), y: raw.subarray(33).toString("base64url") }, format: "jwk" });
|
|
if (!verify("sha256", Buffer.from(`${h}.${c}`), { key, dsaEncoding: "ieee-p1363" }, Buffer.from(s, "base64url"))) throw new Error("bad VAPID signature");
|
|
const header = JSON.parse(Buffer.from(h, "base64url").toString());
|
|
const claims = JSON.parse(Buffer.from(c, "base64url").toString());
|
|
if (header.alg !== "ES256") throw new Error("alg must be ES256");
|
|
if (claims.aud !== this.url) throw new Error(`aud ${claims.aud} != ${this.url}`);
|
|
if (!(claims.exp > Date.now() / 1000) || claims.exp > Date.now() / 1000 + 24 * 3600) throw new Error("bad exp");
|
|
if (!/^(https?:|mailto:)/.test(String(claims.sub))) throw new Error("sub must be a URL or mailto:");
|
|
}
|
|
|
|
private decrypt(sub: MockSub, body: Buffer): Buffer {
|
|
const salt = body.subarray(0, 16);
|
|
const idlen = body[20]!;
|
|
const asPublic = body.subarray(21, 21 + idlen);
|
|
const ct = body.subarray(21 + idlen);
|
|
const uaPublic = sub.ecdh.getPublicKey();
|
|
const shared = sub.ecdh.computeSecret(asPublic);
|
|
const ikm = Buffer.from(hkdfSync("sha256", shared, sub.auth, Buffer.concat([Buffer.from("WebPush: info\0"), uaPublic, asPublic]), 32));
|
|
const cek = Buffer.from(hkdfSync("sha256", ikm, salt, Buffer.from("Content-Encoding: aes128gcm\0"), 16));
|
|
const nonce = Buffer.from(hkdfSync("sha256", ikm, salt, Buffer.from("Content-Encoding: nonce\0"), 12));
|
|
const d = createDecipheriv("aes-128-gcm", cek, nonce);
|
|
d.setAuthTag(ct.subarray(ct.length - 16));
|
|
const plain = Buffer.concat([d.update(ct.subarray(0, ct.length - 16)), d.final()]);
|
|
let end = plain.length - 1;
|
|
while (end >= 0 && plain[end] === 0) end--;
|
|
if (plain[end] !== 2) throw new Error("bad padding delimiter");
|
|
return plain.subarray(0, end);
|
|
}
|
|
}
|