From 1ba31479236acf3937261106c2bdc6422e2ffe5a Mon Sep 17 00:00:00 2001 From: Brandon Corbett Date: Sat, 7 Nov 2026 20:49:11 -0500 Subject: [PATCH 1/2] feat(webhook): verify Seamless webhook signatures in core and the Node adapters Adds verifyWebhook on @seamless-auth/core/webhook (Standard Webhooks v1, constant-time comparison, 300 s tolerance both ways, two secrets while rotating, raw bytes only, typed with WebhookEventSchema after the signature verifies) and wraps it in requireWebhook for Express, the seamlessWebhook plugin for Fastify, and createWebhookHandler and verifyWebhookRequest for Next.js. Core and the Next.js adapter move to @seamless-auth/types 0.39.0. Closes #269 --- .changeset/verify-webhook.md | 8 + packages/core/README.md | 42 ++ packages/core/package.json | 6 +- packages/core/src/webhook.ts | 226 ++++++++++ .../core/tests/fixtures/webhookSigning.js | 26 ++ packages/core/tests/types/consumer.ts | 24 ++ .../core/tests/webhook.constantTime.test.js | 37 ++ packages/core/tests/webhook.test.js | 391 ++++++++++++++++++ packages/express/README.md | 42 ++ packages/express/package.json | 6 +- packages/express/src/webhook.ts | 81 ++++ packages/express/tests/types/consumer.ts | 17 + packages/express/tests/webhook.test.js | 116 ++++++ packages/fastify/README.md | 40 ++ packages/fastify/package.json | 6 +- packages/fastify/src/webhook.ts | 95 +++++ packages/fastify/tests/types/consumer.ts | 16 + packages/fastify/tests/webhook.test.js | 115 ++++++ packages/nextjs/README.md | 43 ++ packages/nextjs/package.json | 8 +- packages/nextjs/src/webhook.ts | 73 ++++ packages/nextjs/tests/types/consumer.ts | 20 + packages/nextjs/tests/webhook.test.js | 101 +++++ pnpm-lock.yaml | 14 +- 24 files changed, 1541 insertions(+), 12 deletions(-) create mode 100644 .changeset/verify-webhook.md create mode 100644 packages/core/src/webhook.ts create mode 100644 packages/core/tests/fixtures/webhookSigning.js create mode 100644 packages/core/tests/webhook.constantTime.test.js create mode 100644 packages/core/tests/webhook.test.js create mode 100644 packages/express/src/webhook.ts create mode 100644 packages/express/tests/webhook.test.js create mode 100644 packages/fastify/src/webhook.ts create mode 100644 packages/fastify/tests/webhook.test.js create mode 100644 packages/nextjs/src/webhook.ts create mode 100644 packages/nextjs/tests/webhook.test.js diff --git a/.changeset/verify-webhook.md b/.changeset/verify-webhook.md new file mode 100644 index 0000000..3b90ecf --- /dev/null +++ b/.changeset/verify-webhook.md @@ -0,0 +1,8 @@ +--- +"@seamless-auth/core": minor +"@seamless-auth/express": minor +"@seamless-auth/fastify": minor +"@seamless-auth/nextjs": minor +--- + +Verify Seamless webhooks. `@seamless-auth/core/webhook` adds `verifyWebhook`, which checks a Standard Webhooks `v1` signature against the raw body with a constant-time comparison, a 300 second timestamp tolerance in both directions and up to two secrets while one rotates, then returns the event typed with `WebhookEventSchema`. A refused webhook throws `WebhookVerificationError` with a `reason`. The adapters wrap it on their own `/webhook` subpath: `requireWebhook` middleware for Express, the `seamlessWebhook` plugin for Fastify, and `createWebhookHandler` and `verifyWebhookRequest` for Next.js. Core and the Next.js adapter now depend on `@seamless-auth/types` 0.39.0. diff --git a/packages/core/README.md b/packages/core/README.md index 6bf64f6..1027728 100644 --- a/packages/core/README.md +++ b/packages/core/README.md @@ -295,6 +295,48 @@ adapters wrap it; their READMEs list the rules and responses. `tests/fixtures/ve holds the signed vectors every adapter, including Go, Python and Rust, is tested against, with the script that generates them. +## Verifying webhooks + +`verifyWebhook(rawBody, headers, { secret })` from `@seamless-auth/core/webhook` verifies a +Seamless webhook and returns the event typed with `WebhookEventSchema` from +`@seamless-auth/types`. The Express, Fastify and Next.js adapters wrap it (see their READMEs). +It lives on its own subpath so the main entry stays free of zod. + +```ts +import { verifyWebhook, WebhookVerificationError } from "@seamless-auth/core/webhook"; + +try { + const event = verifyWebhook(rawBody, headers, { + secret: process.env.SEAMLESS_WEBHOOK_SECRET!, + }); + if (event.type === "user.created") await provision(event.data.userId); +} catch (err) { + if (err instanceof WebhookVerificationError) return reply(400, err.reason); + throw err; +} +``` + +It follows Standard Webhooks, the way the auth API signs: + +- `rawBody` is the body exactly as received, a string or bytes. The signature covers + `${webhook-id}.${webhook-timestamp}.${body}`, so parsed and re-serialized JSON does not + verify, and passing a parsed object throws a `TypeError`. +- `headers` is a Fetch `Headers` or a Node headers object. +- `secret` is the endpoint's `whsec_` secret, or an array of two while it rotates. Each `v1` + signature in `webhook-signature` is checked against each secret with a constant-time + comparison; entries of other versions are ignored. +- `webhook-timestamp` must be within 300 seconds of this clock, in either direction. +- The body is parsed only after the signature verifies. + +A refused webhook throws `WebhookVerificationError` with a `reason`: `missing_header`, +`malformed_header` (empty, repeated or badly formed), `timestamp_out_of_tolerance`, +`unsupported_version` (no `v1` signature), `invalid_signature`, or `invalid_payload` (signed, +but not a known event). A secret that is not `whsec_` and base64, or more than two secrets, +throws a `TypeError`. + +Delivery is at least once and unordered: dedupe on `event.id`, which equals `webhook-id` and +stays the same across retries. + ## Scoped Roles Core exports `hasScopedRole` and `roleGrantsAccess` for framework adapters and custom servers that diff --git a/packages/core/package.json b/packages/core/package.json index 2fd41e0..e37cc6c 100644 --- a/packages/core/package.json +++ b/packages/core/package.json @@ -30,6 +30,10 @@ "types": "./dist/index.d.ts", "import": "./dist/index.js" }, + "./webhook": { + "types": "./dist/webhook.d.ts", + "import": "./dist/webhook.js" + }, "./handlers/*": { "types": "./dist/handlers/*.d.ts", "import": "./dist/handlers/*.js" @@ -51,7 +55,7 @@ "test:watch": "pnpm run build && NODE_OPTIONS=--experimental-vm-modules jest --watch" }, "dependencies": { - "@seamless-auth/types": "^0.38.0", + "@seamless-auth/types": "^0.39.0", "@types/jsonwebtoken": "^9.0.10", "jose": "^6.1.3", "jsonwebtoken": "^9.0.2" diff --git a/packages/core/src/webhook.ts b/packages/core/src/webhook.ts new file mode 100644 index 0000000..521527e --- /dev/null +++ b/packages/core/src/webhook.ts @@ -0,0 +1,226 @@ +import { createHmac, timingSafeEqual } from "node:crypto"; + +import { WebhookEventSchema, type WebhookEvent } from "@seamless-auth/types"; +import { + WEBHOOK_ID_HEADER, + WEBHOOK_SECRET_PREFIX, + WEBHOOK_SIGNATURE_HEADER, + WEBHOOK_SIGNATURE_VERSION, + WEBHOOK_TIMESTAMP_HEADER, + WEBHOOK_TIMESTAMP_TOLERANCE_SECONDS, +} from "@seamless-auth/types/webhook/constants"; + +export type { WebhookEvent, WebhookEventType } from "@seamless-auth/types"; +export { + WEBHOOK_ID_HEADER, + WEBHOOK_SIGNATURE_HEADER, + WEBHOOK_TIMESTAMP_HEADER, + WEBHOOK_TIMESTAMP_TOLERANCE_SECONDS, +}; + +/** + * Why a webhook was refused. + * + * - `missing_header`: `webhook-id`, `webhook-timestamp` or `webhook-signature` is absent. + * - `malformed_header`: a header is repeated, empty, or not in the expected form. + * - `timestamp_out_of_tolerance`: `webhook-timestamp` is more than 300 s from this clock, either way. + * - `unsupported_version`: no signature in the header is a `v1` signature. + * - `invalid_signature`: no `v1` signature matches any configured secret. + * - `invalid_payload`: the signature verified but the body is not a known Seamless event. + */ +export type WebhookVerificationReason = + | "missing_header" + | "malformed_header" + | "timestamp_out_of_tolerance" + | "unsupported_version" + | "invalid_signature" + | "invalid_payload"; + +export class WebhookVerificationError extends Error { + readonly reason: WebhookVerificationReason; + + constructor(reason: WebhookVerificationReason, message: string) { + super(message); + this.name = "WebhookVerificationError"; + this.reason = reason; + } +} + +/** Fetch `Headers`, or Node's `IncomingHttpHeaders` and anything shaped like it. */ +export type WebhookHeaders = + | Headers + | Record; + +export interface VerifyWebhookOptions { + /** + * The endpoint's signing secret (`whsec_...`), or two while it rotates: the + * new one and the one it replaces. + */ + secret: string | readonly string[]; +} + +const SIGNATURE_BYTES = 32; + +function secretKeys(secret: string | readonly string[]): Buffer[] { + const secrets = typeof secret === "string" ? [secret] : [...secret]; + if (secrets.length < 1 || secrets.length > 2) { + throw new TypeError( + "verifyWebhook takes one webhook secret, or two while it rotates", + ); + } + return secrets.map((value) => { + const encoded = + typeof value === "string" && value.startsWith(WEBHOOK_SECRET_PREFIX) + ? value.slice(WEBHOOK_SECRET_PREFIX.length) + : ""; + const key = Buffer.from(encoded, "base64"); + if (key.length === 0 || key.toString("base64") !== encoded) { + throw new TypeError( + `A webhook secret is "${WEBHOOK_SECRET_PREFIX}" followed by base64`, + ); + } + return key; + }); +} + +function readHeader(headers: WebhookHeaders, name: string): string { + let value: string | string[] | null | undefined; + if (typeof (headers as Headers).get === "function") { + value = (headers as Headers).get(name); + } else { + const record = headers as Record; + const key = Object.keys(record).find((k) => k.toLowerCase() === name); + value = key === undefined ? undefined : record[key]; + } + + if (value === undefined || value === null) { + throw new WebhookVerificationError( + "missing_header", + `Missing ${name} header`, + ); + } + if (typeof value !== "string" || value.trim() === "") { + throw new WebhookVerificationError( + "malformed_header", + `Malformed ${name} header`, + ); + } + return value.trim(); +} + +function rawBytes(rawBody: unknown): Buffer { + if (typeof rawBody === "string") return Buffer.from(rawBody, "utf8"); + if (rawBody instanceof Uint8Array) return Buffer.from(rawBody); + // A parsed object cannot be verified: re-serializing it changes the bytes. + throw new TypeError( + "verifyWebhook needs the raw request body as a string or bytes, not parsed JSON", + ); +} + +/** + * Verifies a Seamless webhook (Standard Webhooks, `v1` HMAC-SHA256) and returns + * the typed event. + * + * Pass the body exactly as received. The signature covers + * `${webhook-id}.${webhook-timestamp}.${body}`, so a body that was parsed and + * serialized again does not verify. The event is parsed only after the + * signature verifies. + * + * Throws `WebhookVerificationError`, with a `reason`, when the request is + * refused, and `TypeError` when the secret or body is not usable at all. + * Delivery is at least once: dedupe on `event.id`, which equals `webhook-id`. + * + * ### Example + * ```ts + * const event = verifyWebhook(rawBody, request.headers, { + * secret: process.env.SEAMLESS_WEBHOOK_SECRET!, + * }); + * if (event.type === "user.created") provision(event.data.userId); + * ``` + */ +export function verifyWebhook( + rawBody: string | Uint8Array, + headers: WebhookHeaders, + options: VerifyWebhookOptions, +): WebhookEvent { + const keys = secretKeys(options.secret); + const body = rawBytes(rawBody); + + const id = readHeader(headers, WEBHOOK_ID_HEADER); + const timestampHeader = readHeader(headers, WEBHOOK_TIMESTAMP_HEADER); + const signatureHeader = readHeader(headers, WEBHOOK_SIGNATURE_HEADER); + + if (!/^\d{1,15}$/.test(timestampHeader)) { + throw new WebhookVerificationError( + "malformed_header", + `Malformed ${WEBHOOK_TIMESTAMP_HEADER} header`, + ); + } + const timestamp = Number(timestampHeader); + const now = Math.floor(Date.now() / 1000); + if (Math.abs(now - timestamp) > WEBHOOK_TIMESTAMP_TOLERANCE_SECONDS) { + throw new WebhookVerificationError( + "timestamp_out_of_tolerance", + `${WEBHOOK_TIMESTAMP_HEADER} is outside the ${WEBHOOK_TIMESTAMP_TOLERANCE_SECONDS} s tolerance`, + ); + } + + const candidates: Buffer[] = []; + let sawVersion = false; + for (const entry of signatureHeader.split(" ")) { + if (entry === "") continue; + const comma = entry.indexOf(","); + if (comma <= 0 || comma === entry.length - 1) { + throw new WebhookVerificationError( + "malformed_header", + `Malformed ${WEBHOOK_SIGNATURE_HEADER} header`, + ); + } + if (entry.slice(0, comma) !== WEBHOOK_SIGNATURE_VERSION) continue; + sawVersion = true; + const decoded = Buffer.from(entry.slice(comma + 1), "base64"); + if (decoded.length === SIGNATURE_BYTES) { + candidates.push(decoded); + } + } + if (!sawVersion) { + throw new WebhookVerificationError( + "unsupported_version", + `${WEBHOOK_SIGNATURE_HEADER} holds no ${WEBHOOK_SIGNATURE_VERSION} signature`, + ); + } + + const signed = Buffer.concat([Buffer.from(`${id}.${timestampHeader}.`), body]); + let verified = false; + for (const key of keys) { + const expected = createHmac("sha256", key).update(signed).digest(); + for (const candidate of candidates) { + // No early exit, so the time taken does not say which entry matched. + if (timingSafeEqual(expected, candidate)) verified = true; + } + } + if (!verified) { + throw new WebhookVerificationError( + "invalid_signature", + "No webhook signature matches the configured secret", + ); + } + + let json: unknown; + try { + json = JSON.parse(body.toString("utf8")); + } catch { + throw new WebhookVerificationError( + "invalid_payload", + "The webhook body is not JSON", + ); + } + const parsed = WebhookEventSchema.safeParse(json); + if (!parsed.success) { + throw new WebhookVerificationError( + "invalid_payload", + "The webhook body is not a known Seamless event", + ); + } + return parsed.data; +} diff --git a/packages/core/tests/fixtures/webhookSigning.js b/packages/core/tests/fixtures/webhookSigning.js new file mode 100644 index 0000000..b880b2e --- /dev/null +++ b/packages/core/tests/fixtures/webhookSigning.js @@ -0,0 +1,26 @@ +// Signs like the auth API (Standard Webhooks v1), for adapter tests. Written +// against the spec, not imported from the verifier under test. +import { createHmac } from "node:crypto"; + +export const WEBHOOK_SECRET = "whsec_AQIDBAUGBwgJCgsMDQ4PEBESExQVFhcYGRobHB0eHyA="; +export const NEXT_WEBHOOK_SECRET = + "whsec_ZWZnaGlqa2xtbm9wcXJzdHV2d3h5ent8fX5/gIGCg4Q="; + +// Spaces and a non-ASCII name, so anything but the exact bytes fails to verify. +export const WEBHOOK_BODY = + '{ "id": "evt_01", "type": "user.created", "version": 1, "timestamp": "2026-01-01T00:00:00.000Z", "data": { "userId": "user_01", "email": "zoë@example.com", "phone": null } }'; + +export function signedHeaders(body, secrets = [WEBHOOK_SECRET], id = "evt_01") { + const timestamp = Math.floor(Date.now() / 1000); + const signed = Buffer.concat([Buffer.from(`${id}.${timestamp}.`), Buffer.from(body)]); + return { + "webhook-id": id, + "webhook-timestamp": String(timestamp), + "webhook-signature": secrets + .map((secret) => { + const key = Buffer.from(secret.slice("whsec_".length), "base64"); + return `v1,${createHmac("sha256", key).update(signed).digest("base64")}`; + }) + .join(" "), + }; +} diff --git a/packages/core/tests/types/consumer.ts b/packages/core/tests/types/consumer.ts index ee03218..5b4d785 100644 --- a/packages/core/tests/types/consumer.ts +++ b/packages/core/tests/types/consumer.ts @@ -13,3 +13,27 @@ void claims; verifyCookieJwt(42); // @ts-expect-error loginHandler takes an input and options loginHandler(42); + +import { + verifyWebhook, + WebhookVerificationError, + type WebhookEvent, + type WebhookVerificationReason, +} from "@seamless-auth/core/webhook"; + +const event: WebhookEvent = verifyWebhook("{}", new Headers(), { + secret: ["whsec_a", "whsec_b"], +}); +if (event.type === "user.created") { + const userId: string = event.data.userId; + void userId; +} +const reason: WebhookVerificationReason = new WebhookVerificationError( + "invalid_signature", + "", +).reason; +void reason; +// @ts-expect-error a parsed body cannot be verified +verifyWebhook({}, {}, { secret: "whsec_a" }); +// @ts-expect-error the reason is a known string +new WebhookVerificationError("nope", ""); diff --git a/packages/core/tests/webhook.constantTime.test.js b/packages/core/tests/webhook.constantTime.test.js new file mode 100644 index 0000000..9dbcfdc --- /dev/null +++ b/packages/core/tests/webhook.constantTime.test.js @@ -0,0 +1,37 @@ +import { jest } from "@jest/globals"; + +const actual = await import("node:crypto"); +const timingSafeEqual = jest.fn(actual.timingSafeEqual); +jest.unstable_mockModule("node:crypto", () => ({ + ...actual, + default: actual, + timingSafeEqual, +})); + +const { verifyWebhook } = await import("../dist/webhook.js"); + +const SECRET_A = "whsec_AQIDBAUGBwgJCgsMDQ4PEBESExQVFhcYGRobHB0eHyA="; +const SECRET_B = "whsec_ZWZnaGlqa2xtbm9wcXJzdHV2d3h5ent8fX5/gIGCg4Q="; +const BODY = + '{"id":"evt_01","type":"user.created","version":1,"timestamp":"2026-01-01T00:00:00.000Z","data":{"userId":"user_01","email":"ada@example.com","phone":null}}'; +const HEADERS = { + "webhook-id": "evt_01", + "webhook-timestamp": "1767225600", + "webhook-signature": + "v1,2Wdjh1HKOsFxwMrIhCkeI9af2ld08BNRpv8fuepQbhg= v1,s6HpmlDOYZalhTpS1nV7JQMhqmAhCh46dQzUOnTdoZE=", +}; + +beforeEach(() => { + jest.spyOn(Date, "now").mockReturnValue(1767225600 * 1000); + timingSafeEqual.mockClear(); +}); +afterEach(() => jest.restoreAllMocks()); + +describe("verifyWebhook comparison", () => { + it("compares in constant time against every secret and signature", () => { + // The first pair already matches; all four are still compared, so timing + // does not reveal which secret or entry verified. + verifyWebhook(BODY, HEADERS, { secret: [SECRET_A, SECRET_B] }); + expect(timingSafeEqual).toHaveBeenCalledTimes(4); + }); +}); diff --git a/packages/core/tests/webhook.test.js b/packages/core/tests/webhook.test.js new file mode 100644 index 0000000..5bd6142 --- /dev/null +++ b/packages/core/tests/webhook.test.js @@ -0,0 +1,391 @@ +import { createHmac } from "node:crypto"; +import { jest } from "@jest/globals"; + +import { + verifyWebhook, + WebhookVerificationError, + WEBHOOK_TIMESTAMP_TOLERANCE_SECONDS, +} from "../dist/webhook.js"; + +// Known-answer vectors, computed outside Node (Python hmac) and pinned here. +const SECRET_A = "whsec_AQIDBAUGBwgJCgsMDQ4PEBESExQVFhcYGRobHB0eHyA="; +const SECRET_B = "whsec_ZWZnaGlqa2xtbm9wcXJzdHV2d3h5ent8fX5/gIGCg4Q="; +const ID = "evt_01"; +const TIMESTAMP = 1767225600; +const BODY = + '{"id":"evt_01","type":"user.created","version":1,"timestamp":"2026-01-01T00:00:00.000Z","data":{"userId":"user_01","email":"ada@example.com","phone":null}}'; +const SIGNATURE_A = "v1,2Wdjh1HKOsFxwMrIhCkeI9af2ld08BNRpv8fuepQbhg="; +const SIGNATURE_B = "v1,s6HpmlDOYZalhTpS1nV7JQMhqmAhCh46dQzUOnTdoZE="; + +function headers(overrides = {}) { + return { + "webhook-id": ID, + "webhook-timestamp": String(TIMESTAMP), + "webhook-signature": SIGNATURE_A, + ...overrides, + }; +} + +function sign(secret, id, timestamp, body) { + const key = Buffer.from(secret.slice("whsec_".length), "base64"); + const digest = createHmac("sha256", key) + .update(`${id}.${timestamp}.${body}`) + .digest("base64"); + return `v1,${digest}`; +} + +function reasonOf(fn) { + try { + fn(); + } catch (err) { + if (err instanceof WebhookVerificationError) return err.reason; + throw err; + } + return "verified"; +} + +const at = (seconds) => + jest.spyOn(Date, "now").mockReturnValue(seconds * 1000); + +beforeEach(() => at(TIMESTAMP)); +afterEach(() => jest.restoreAllMocks()); + +describe("verifyWebhook", () => { + it("verifies the Standard Webhooks specification vector", () => { + // The spec's own example; its body is not a Seamless event, so verification + // gets past the signature and stops at the payload. + at(1614265330); + const verify = (secret) => + verifyWebhook( + '{"test": 2432232314}', + { + "webhook-id": "msg_p5jXN8AQM9LWM0D4loKWxJek", + "webhook-timestamp": "1614265330", + "webhook-signature": "v1,g0hM9SsE+OTPJTGt/tmIKtSyZlE3uFJELVlNIOLJ1OE=", + }, + { secret }, + ); + expect(reasonOf(() => verify("whsec_MfKQ9r8GKYqrTwjUPD8ILPZIo2LaLaSw"))).toBe( + "invalid_payload", + ); + expect(reasonOf(() => verify(SECRET_B))).toBe("invalid_signature"); + }); + + it("returns the typed event for a known-answer vector", () => { + const event = verifyWebhook(BODY, headers(), { secret: SECRET_A }); + expect(event).toEqual({ + id: "evt_01", + type: "user.created", + version: 1, + timestamp: "2026-01-01T00:00:00.000Z", + data: { userId: "user_01", email: "ada@example.com", phone: null }, + }); + }); + + it("verifies the raw bytes as well as a string", () => { + const event = verifyWebhook(Buffer.from(BODY), headers(), { + secret: SECRET_A, + }); + expect(event.id).toBe("evt_01"); + expect( + verifyWebhook(new Uint8Array(Buffer.from(BODY)), headers(), { + secret: SECRET_A, + }).id, + ).toBe("evt_01"); + }); + + it("refuses re-serialized JSON", () => { + const spaced = BODY.replace('"type":', '"type": '); + const signature = sign(SECRET_A, ID, TIMESTAMP, spaced); + expect( + reasonOf(() => + verifyWebhook(spaced, headers({ "webhook-signature": signature }), { + secret: SECRET_A, + }), + ), + ).toBe("verified"); + expect( + reasonOf(() => + verifyWebhook( + JSON.stringify(JSON.parse(spaced)), + headers({ "webhook-signature": signature }), + { secret: SECRET_A }, + ), + ), + ).toBe("invalid_signature"); + }); + + it("refuses a parsed body outright", () => { + expect(() => + verifyWebhook(JSON.parse(BODY), headers(), { secret: SECRET_A }), + ).toThrow(TypeError); + }); + + it.each([ + ["body", () => [BODY.replace("ada@", "eve@"), headers()]], + ["id", () => [BODY, headers({ "webhook-id": "evt_02" })]], + [ + "timestamp", + () => [BODY, headers({ "webhook-timestamp": String(TIMESTAMP + 1) })], + ], + ])("refuses a tampered %s", (_, input) => { + const [body, hdrs] = input(); + expect(reasonOf(() => verifyWebhook(body, hdrs, { secret: SECRET_A }))).toBe( + "invalid_signature", + ); + }); + + it("refuses the wrong secret", () => { + expect(reasonOf(() => verifyWebhook(BODY, headers(), { secret: SECRET_B }))).toBe( + "invalid_signature", + ); + }); + + it("refuses an equal-length wrong signature", () => { + const bytes = Buffer.from(SIGNATURE_A.slice(3), "base64"); + bytes[31] ^= 0x01; + const forged = `v1,${bytes.toString("base64")}`; + expect(forged.length).toBe(SIGNATURE_A.length); + expect( + reasonOf(() => + verifyWebhook(BODY, headers({ "webhook-signature": forged }), { + secret: SECRET_A, + }), + ), + ).toBe("invalid_signature"); + }); + + it("refuses a truncated signature without throwing anything else", () => { + const truncated = `v1,${Buffer.from(SIGNATURE_A.slice(3), "base64") + .subarray(0, 16) + .toString("base64")}`; + expect( + reasonOf(() => + verifyWebhook(BODY, headers({ "webhook-signature": truncated }), { + secret: SECRET_A, + }), + ), + ).toBe("invalid_signature"); + }); + + describe("timestamp tolerance", () => { + const tolerance = WEBHOOK_TIMESTAMP_TOLERANCE_SECONDS; + + it("is 300 seconds", () => { + expect(tolerance).toBe(300); + }); + + it.each([ + ["old", TIMESTAMP + tolerance + 1], + ["future", TIMESTAMP - tolerance - 1], + ])("refuses an %s timestamp", (_, now) => { + at(now); + expect(reasonOf(() => verifyWebhook(BODY, headers(), { secret: SECRET_A }))).toBe( + "timestamp_out_of_tolerance", + ); + }); + + it.each([TIMESTAMP + tolerance, TIMESTAMP - tolerance])( + "accepts the edge of the window (clock at %i)", + (now) => { + at(now); + expect(reasonOf(() => verifyWebhook(BODY, headers(), { secret: SECRET_A }))).toBe( + "verified", + ); + }, + ); + + it("checks the window before the signature", () => { + at(TIMESTAMP + tolerance + 1); + expect( + reasonOf(() => + verifyWebhook(BODY, headers({ "webhook-signature": SIGNATURE_B }), { + secret: SECRET_A, + }), + ), + ).toBe("timestamp_out_of_tolerance"); + }); + }); + + describe("secret rotation", () => { + const both = { secret: [SECRET_A, SECRET_B] }; + + it.each([ + ["the first secret", SIGNATURE_A], + ["the second secret", SIGNATURE_B], + ["both secrets", `${SIGNATURE_A} ${SIGNATURE_B}`], + ])("accepts a delivery signed with %s", (_, signature) => { + expect( + verifyWebhook(BODY, headers({ "webhook-signature": signature }), both).id, + ).toBe("evt_01"); + }); + + it("accepts the new signature beside one from a secret it no longer holds", () => { + expect( + verifyWebhook( + BODY, + headers({ "webhook-signature": `${SIGNATURE_A} ${SIGNATURE_B}` }), + { secret: SECRET_B }, + ).id, + ).toBe("evt_01"); + }); + + it("refuses a signature from neither secret", () => { + const other = "whsec_" + Buffer.alloc(32, 7).toString("base64"); + expect( + reasonOf(() => + verifyWebhook( + BODY, + headers({ "webhook-signature": sign(other, ID, TIMESTAMP, BODY) }), + both, + ), + ), + ).toBe("invalid_signature"); + }); + + it.each([ + ["no secrets", []], + ["three secrets", [SECRET_A, SECRET_B, SECRET_A]], + ["a secret without the whsec_ prefix", SECRET_A.slice(6)], + ["a secret with another prefix", `Whsec_${SECRET_A.slice(6)}`], + ["a secret that is not base64", "whsec_not base64!"], + ["an empty secret", "whsec_"], + ])("refuses %s as configuration", (_, secret) => { + expect(() => verifyWebhook(BODY, headers(), { secret })).toThrow(TypeError); + }); + }); + + describe("signature versions", () => { + it("ignores unknown versions beside a valid v1 signature", () => { + const signature = `v2,${Buffer.alloc(32).toString("base64")} ${SIGNATURE_A} v1a,abcd`; + expect( + verifyWebhook(BODY, headers({ "webhook-signature": signature }), { + secret: SECRET_A, + }).id, + ).toBe("evt_01"); + }); + + it("refuses a header with no v1 signature", () => { + expect( + reasonOf(() => + verifyWebhook( + BODY, + headers({ "webhook-signature": `v2,${SIGNATURE_A.slice(3)}` }), + { secret: SECRET_A }, + ), + ), + ).toBe("unsupported_version"); + }); + }); + + describe("headers", () => { + it.each(["webhook-id", "webhook-timestamp", "webhook-signature"])( + "refuses a missing %s", + (name) => { + const hdrs = headers(); + delete hdrs[name]; + expect(reasonOf(() => verifyWebhook(BODY, hdrs, { secret: SECRET_A }))).toBe( + "missing_header", + ); + }, + ); + + it.each([ + ["an empty id", { "webhook-id": "" }], + ["a repeated id", { "webhook-id": [ID, ID] }], + ["a fractional timestamp", { "webhook-timestamp": `${TIMESTAMP}.0` }], + ["a negative timestamp", { "webhook-timestamp": `-${TIMESTAMP}` }], + ["a non-numeric timestamp", { "webhook-timestamp": "soon" }], + ["a signature without a version", { "webhook-signature": SIGNATURE_A.slice(3) }], + ["a signature without a value", { "webhook-signature": `v1, ${SIGNATURE_A}` }], + ["a signature entry with no version", { "webhook-signature": `,abc ${SIGNATURE_A}` }], + ])("refuses %s", (_, overrides) => { + expect( + reasonOf(() => verifyWebhook(BODY, headers(overrides), { secret: SECRET_A })), + ).toBe("malformed_header"); + }); + + it("refuses a timestamp in milliseconds", () => { + expect( + reasonOf(() => + verifyWebhook(BODY, headers({ "webhook-timestamp": `${TIMESTAMP}000` }), { + secret: SECRET_A, + }), + ), + ).toBe("timestamp_out_of_tolerance"); + }); + + it("reads fetch Headers", () => { + expect( + verifyWebhook(BODY, new Headers(headers()), { secret: SECRET_A }).id, + ).toBe("evt_01"); + }); + + it("reads header names case-insensitively from a plain object", () => { + expect( + verifyWebhook( + BODY, + { + "Webhook-Id": ID, + "WEBHOOK-TIMESTAMP": String(TIMESTAMP), + "Webhook-Signature": SIGNATURE_A, + }, + { secret: SECRET_A }, + ).id, + ).toBe("evt_01"); + }); + }); + + describe("payload", () => { + function signed(body) { + return headers({ "webhook-signature": sign(SECRET_A, ID, TIMESTAMP, body) }); + } + + it("parses only after the signature verifies", () => { + expect( + reasonOf(() => verifyWebhook("not json", headers(), { secret: SECRET_A })), + ).toBe("invalid_signature"); + }); + + it("refuses a signed body that is not JSON", () => { + expect( + reasonOf(() => + verifyWebhook("not json", signed("not json"), { secret: SECRET_A }), + ), + ).toBe("invalid_payload"); + }); + + it("refuses a signed event of an unknown type", () => { + const body = BODY.replace("user.created", "user.teleported"); + expect( + reasonOf(() => verifyWebhook(body, signed(body), { secret: SECRET_A })), + ).toBe("invalid_payload"); + }); + + it("types the test event", () => { + const body = JSON.stringify({ + id: "evt_test", + type: "webhook.test", + version: 1, + timestamp: "2026-01-01T00:00:00.000Z", + data: { endpointId: "ep_1" }, + }); + expect(verifyWebhook(body, signed(body), { secret: SECRET_A }).type).toBe( + "webhook.test", + ); + }); + }); + + it("gives the reason and a name on the error", () => { + try { + verifyWebhook(BODY, headers(), { secret: SECRET_B }); + } catch (err) { + expect(err).toBeInstanceOf(WebhookVerificationError); + expect(err).toBeInstanceOf(Error); + expect(err.name).toBe("WebhookVerificationError"); + expect(err.reason).toBe("invalid_signature"); + return; + } + throw new Error("expected a WebhookVerificationError"); + }); +}); diff --git a/packages/express/README.md b/packages/express/README.md index 0c771a2..a105807 100644 --- a/packages/express/README.md +++ b/packages/express/README.md @@ -888,6 +888,48 @@ and `authTime`. A client credentials token (`sub` equal to `client_id`) verifies --- +### `requireWebhook(options)` + +Verifies a Seamless webhook and puts the typed event on `req.webhook`. Import it from +`@seamless-auth/express/webhook`. + +```ts +import express from "express"; +import { requireWebhook } from "@seamless-auth/express/webhook"; + +const app = express(); + +// Before express.json(): the signature covers the raw bytes. +app.post( + "/webhooks/seamless", + requireWebhook({ secret: process.env.SEAMLESS_WEBHOOK_SECRET! }), + async (req, res) => { + const event = req.webhook!; + if (event.type === "user.created") await provision(event.data.userId); + res.sendStatus(204); + }, +); + +app.use(express.json()); +``` + +The middleware reads the body itself with `express.raw`, whatever the content type, and verifies +those bytes. A route that `express.json()` has already parsed cannot be verified: the request +fails with a `TypeError` passed to `next`, so mount the webhook route first. While the endpoint's +secret rotates, pass both: `secret: [newSecret, oldSecret]`. `limit` caps the body read +(default `"1mb"`). + +A refused webhook gets `400 { "error": "invalid_webhook", "reason": "..." }`, with the reason +from `WebhookVerificationError`: `missing_header`, `malformed_header`, +`timestamp_out_of_tolerance`, `unsupported_version`, `invalid_signature` or `invalid_payload`. +The core README lists what each one means. + +`verifyWebhook` and `WebhookVerificationError` are re-exported for a route that reads the body +its own way, such as `express.raw({ type: "application/json" })` followed by +`verifyWebhook(req.body, req.headers, { secret })`. + +--- + ### `getSeamlessUser(req, options)` Optional helper that calls the Auth Server to retrieve the **fully hydrated user object**. diff --git a/packages/express/package.json b/packages/express/package.json index f542b31..064bfbb 100644 --- a/packages/express/package.json +++ b/packages/express/package.json @@ -27,6 +27,10 @@ ".": { "types": "./dist/index.d.ts", "import": "./dist/index.js" + }, + "./webhook": { + "types": "./dist/webhook.d.ts", + "import": "./dist/webhook.js" } }, "engines": { @@ -34,7 +38,7 @@ }, "scripts": { "build": "pnpm run build:js && pnpm run build:types", - "build:js": "tsup src/index.ts --format esm --out-dir dist --splitting --external @seamless-auth/core --external @seamless-auth/core/*", + "build:js": "tsup src/index.ts src/webhook.ts --format esm --out-dir dist --splitting --external @seamless-auth/core --external @seamless-auth/core/*", "build:types": "tsc -p tsconfig.build.json", "clean": "rm -rf dist", "dev": "tsc --watch", diff --git a/packages/express/src/webhook.ts b/packages/express/src/webhook.ts new file mode 100644 index 0000000..7f1b12a --- /dev/null +++ b/packages/express/src/webhook.ts @@ -0,0 +1,81 @@ +import express, { + type NextFunction, + type Request, + type RequestHandler, + type Response, +} from "express"; +import { + verifyWebhook, + WebhookVerificationError, + type VerifyWebhookOptions, + type WebhookEvent, +} from "@seamless-auth/core/webhook"; + +export { + verifyWebhook, + WebhookVerificationError, +} from "@seamless-auth/core/webhook"; +export type { + VerifyWebhookOptions, + WebhookEvent, + WebhookEventType, + WebhookHeaders, + WebhookVerificationReason, +} from "@seamless-auth/core/webhook"; + +declare global { + namespace Express { + interface Request { + /** Set by `requireWebhook` once the signature verifies. */ + webhook?: WebhookEvent; + } + } +} + +export interface RequireWebhookOptions extends VerifyWebhookOptions { + /** Largest body read, in the `express.raw` format. Defaults to `"1mb"`. */ + limit?: string | number; +} + +/** + * Verifies a Seamless webhook and puts the typed event on `req.webhook`. + * + * Reads the body itself with `express.raw`, because the signature covers the + * exact bytes. Mount it before any `express.json()` that would see the route: + * a body parsed already cannot be verified, and the request fails with a + * `TypeError` passed to `next`. A refused webhook gets + * `400 { error: "invalid_webhook", reason }`. + * + * ### Example + * ```ts + * app.post( + * "/webhooks/seamless", + * requireWebhook({ secret: process.env.SEAMLESS_WEBHOOK_SECRET! }), + * (req, res) => { + * if (req.webhook!.type === "user.created") provision(req.webhook!.data.userId); + * res.sendStatus(204); + * }, + * ); + * app.use(express.json()); + * ``` + */ +export function requireWebhook(options: RequireWebhookOptions): RequestHandler { + const { limit = "1mb", ...verifyOptions } = options; + const raw = express.raw({ type: () => true, limit }); + const verify = (req: Request, res: Response, next: NextFunction) => { + try { + // express.raw leaves req.body unset when the request has no body. + req.webhook = verifyWebhook(req.body ?? "", req.headers, verifyOptions); + } catch (err) { + if (err instanceof WebhookVerificationError) { + res.status(400).json({ error: "invalid_webhook", reason: err.reason }); + return; + } + next(err); + return; + } + next(); + }; + return (req, res, next) => + raw(req, res, (err?: unknown) => (err ? next(err) : verify(req, res, next))); +} diff --git a/packages/express/tests/types/consumer.ts b/packages/express/tests/types/consumer.ts index 33f58a3..74c9c90 100644 --- a/packages/express/tests/types/consumer.ts +++ b/packages/express/tests/types/consumer.ts @@ -58,3 +58,20 @@ const unsubscribable: EmailMessage = { // @ts-expect-error header values are strings const badHeader: EmailMessage = { ...unsubscribable, headers: { "X-Count": 1 } }; void badHeader; + +import { requireWebhook } from "@seamless-auth/express/webhook"; + +const webhookApp = express(); +webhookApp.post( + "/webhooks/seamless", + requireWebhook({ secret: "whsec_a" }), + (req, res) => { + if (req.webhook?.type === "user.created") { + const userId: string = req.webhook.data.userId; + void userId; + } + res.sendStatus(204); + }, +); +// @ts-expect-error requireWebhook needs a secret +requireWebhook({}); diff --git a/packages/express/tests/webhook.test.js b/packages/express/tests/webhook.test.js new file mode 100644 index 0000000..07e62dc --- /dev/null +++ b/packages/express/tests/webhook.test.js @@ -0,0 +1,116 @@ +import express from "express"; +import request from "supertest"; + +import { + NEXT_WEBHOOK_SECRET, + WEBHOOK_BODY, + WEBHOOK_SECRET, + signedHeaders, +} from "../../core/tests/fixtures/webhookSigning.js"; + +const { requireWebhook, verifyWebhook, WebhookVerificationError } = await import( + "../dist/webhook.js" +); + +function app(options = { secret: WEBHOOK_SECRET }) { + const received = []; + const server = express(); + server.post("/webhooks/seamless", requireWebhook(options), (req, res) => { + received.push(req.webhook); + res.sendStatus(204); + }); + server.use(express.json()); + server.post("/json", (req, res) => res.json(req.body)); + return { server, received }; +} + +function deliver(server, body, headers, contentType = "application/json") { + let call = request(server).post("/webhooks/seamless"); + if (contentType) call = call.set("content-type", contentType); + for (const [name, value] of Object.entries(headers)) call = call.set(name, value); + return call.send(body); +} + +describe("requireWebhook", () => { + it("verifies the raw body and puts the typed event on req.webhook", async () => { + const { server, received } = app(); + const res = await deliver(server, WEBHOOK_BODY, signedHeaders(WEBHOOK_BODY)); + expect(res.status).toBe(204); + expect(received).toEqual([ + expect.objectContaining({ + id: "evt_01", + type: "user.created", + data: { userId: "user_01", email: "zoë@example.com", phone: null }, + }), + ]); + }); + + it("reads the body raw whatever the content type", async () => { + const { server } = app(); + const res = await deliver(server, WEBHOOK_BODY, signedHeaders(WEBHOOK_BODY), "text/plain"); + expect(res.status).toBe(204); + }); + + it("refuses a tampered body with the reason", async () => { + const { server, received } = app(); + const res = await deliver( + server, + WEBHOOK_BODY.replace("user_01", "user_02"), + signedHeaders(WEBHOOK_BODY), + ); + expect(res.status).toBe(400); + expect(res.body).toEqual({ error: "invalid_webhook", reason: "invalid_signature" }); + expect(received).toEqual([]); + }); + + it("refuses a delivery with no signature headers", async () => { + const { server } = app(); + const res = await deliver(server, WEBHOOK_BODY, {}); + expect(res.status).toBe(400); + expect(res.body.reason).toBe("missing_header"); + }); + + it("refuses an empty body", async () => { + const { server } = app(); + const res = await deliver(server, undefined, signedHeaders(WEBHOOK_BODY), null); + expect(res.status).toBe(400); + expect(res.body.reason).toBe("invalid_signature"); + }); + + it("accepts either secret while one rotates", async () => { + const { server } = app({ secret: [NEXT_WEBHOOK_SECRET, WEBHOOK_SECRET] }); + for (const secret of [WEBHOOK_SECRET, NEXT_WEBHOOK_SECRET]) { + const res = await deliver(server, WEBHOOK_BODY, signedHeaders(WEBHOOK_BODY, [secret])); + expect(res.status).toBe(204); + } + }); + + it("fails loudly when express.json() parsed the body first", async () => { + const server = express(); + server.use(express.json()); + server.post("/webhooks/seamless", requireWebhook({ secret: WEBHOOK_SECRET }), (_req, res) => + res.sendStatus(204), + ); + const errors = []; + server.use((err, _req, res, _next) => { + errors.push(err); + res.sendStatus(500); + }); + const res = await deliver(server, WEBHOOK_BODY, signedHeaders(WEBHOOK_BODY)); + expect(res.status).toBe(500); + expect(errors[0]).toBeInstanceOf(TypeError); + }); + + it("leaves JSON parsing in place for the app's other routes", async () => { + const { server } = app(); + const res = await request(server).post("/json").send({ hello: "world" }); + expect(res.body).toEqual({ hello: "world" }); + }); + + it("re-exports the core verifier", () => { + expect(typeof verifyWebhook).toBe("function"); + expect(new WebhookVerificationError("invalid_signature", "x").reason).toBe( + "invalid_signature", + ); + }); +}); diff --git a/packages/fastify/README.md b/packages/fastify/README.md index 2fea199..670d9be 100644 --- a/packages/fastify/README.md +++ b/packages/fastify/README.md @@ -316,6 +316,46 @@ from the upstream unchanged, so the dashboard's own caching still applies. Unknown paths under the prefix are forwarded too, which is what makes deep links into the dashboard work: the upstream answers them with the SPA shell. +## Verifying webhooks + +`seamlessWebhook` from `@seamless-auth/fastify/webhook` serves one webhook route, verifies each +delivery and hands the typed event to `onEvent`. + +```ts +import { seamlessWebhook } from "@seamless-auth/fastify/webhook"; + +await app.register(seamlessWebhook, { + path: "/webhooks/seamless", + secret: process.env.SEAMLESS_WEBHOOK_SECRET!, + async onEvent(event, request, reply) { + if (event.type === "user.created") await provision(event.data.userId); + }, +}); +``` + +The signature covers the raw bytes, so inside its own encapsulated context the plugin replaces +the JSON parser with a content type parser that keeps the body as a buffer: + +```ts +fastify.removeAllContentTypeParsers(); +fastify.addContentTypeParser("*", { parseAs: "buffer" }, (_request, body, done) => + done(null, body), +); +``` + +The rest of the app keeps parsing JSON. Register the plugin directly, not through +`fastify-plugin`, or the raw parser applies to every route. `onEvent` answers by returning a +value or sending on `reply`; otherwise the route answers 204. While the endpoint's secret +rotates, pass both: `secret: [newSecret, oldSecret]`. `bodyLimit` caps the body read. + +A refused webhook gets `400 { "error": "invalid_webhook", "reason": "..." }`, with the reason +from `WebhookVerificationError`: `missing_header`, `malformed_header`, +`timestamp_out_of_tolerance`, `unsupported_version`, `invalid_signature` or `invalid_payload`. +The core README lists what each one means. + +`verifyWebhook` and `WebhookVerificationError` are re-exported for a route that sets up its own +raw body parser. + ## Options | Option | Default | Purpose | diff --git a/packages/fastify/package.json b/packages/fastify/package.json index 9e92be3..e4d8301 100644 --- a/packages/fastify/package.json +++ b/packages/fastify/package.json @@ -27,6 +27,10 @@ ".": { "types": "./dist/index.d.ts", "import": "./dist/index.js" + }, + "./webhook": { + "types": "./dist/webhook.d.ts", + "import": "./dist/webhook.js" } }, "engines": { @@ -34,7 +38,7 @@ }, "scripts": { "build": "pnpm run build:js && pnpm run build:types", - "build:js": "tsup src/index.ts --format esm --out-dir dist --splitting --external @seamless-auth/core --external @seamless-auth/core/*", + "build:js": "tsup src/index.ts src/webhook.ts --format esm --out-dir dist --splitting --external @seamless-auth/core --external @seamless-auth/core/*", "build:types": "tsc -p tsconfig.build.json", "clean": "rm -rf dist", "dev": "tsc --watch", diff --git a/packages/fastify/src/webhook.ts b/packages/fastify/src/webhook.ts new file mode 100644 index 0000000..1a48ed7 --- /dev/null +++ b/packages/fastify/src/webhook.ts @@ -0,0 +1,95 @@ +import type { + FastifyInstance, + FastifyReply, + FastifyRequest, +} from "fastify"; +import { + verifyWebhook, + WebhookVerificationError, + type VerifyWebhookOptions, + type WebhookEvent, +} from "@seamless-auth/core/webhook"; + +export { + verifyWebhook, + WebhookVerificationError, +} from "@seamless-auth/core/webhook"; +export type { + VerifyWebhookOptions, + WebhookEvent, + WebhookEventType, + WebhookHeaders, + WebhookVerificationReason, +} from "@seamless-auth/core/webhook"; + +export interface SeamlessWebhookOptions extends VerifyWebhookOptions { + /** The route the webhook is POSTed to, such as `/webhooks/seamless`. */ + path: string; + /** Largest body read, in bytes. Defaults to Fastify's `bodyLimit`. */ + bodyLimit?: number; + /** + * Handles a verified event. Return a value or send on `reply` to answer; + * otherwise the route answers 204. + */ + onEvent: ( + event: WebhookEvent, + request: FastifyRequest, + reply: FastifyReply, + ) => unknown; +} + +/** + * Fastify plugin serving one webhook route. It replaces the JSON parser with a + * raw buffer parser inside its own encapsulated context, because the signature + * covers the exact bytes, so the rest of the app keeps parsing JSON. A refused + * webhook gets `400 { error: "invalid_webhook", reason }`. + * + * Register it without `fastify-plugin`, or the raw parser leaks to every route. + * + * ### Example + * ```ts + * await app.register(seamlessWebhook, { + * path: "/webhooks/seamless", + * secret: process.env.SEAMLESS_WEBHOOK_SECRET!, + * async onEvent(event) { + * if (event.type === "user.created") await provision(event.data.userId); + * }, + * }); + * ``` + */ +export async function seamlessWebhook( + fastify: FastifyInstance, + options: SeamlessWebhookOptions, +) { + const { path, bodyLimit, onEvent, ...verifyOptions } = options; + + fastify.removeAllContentTypeParsers(); + fastify.addContentTypeParser( + "*", + { parseAs: "buffer", bodyLimit }, + (_request, body, done) => done(null, body), + ); + + fastify.post(path, async (request, reply) => { + let event: WebhookEvent; + try { + event = verifyWebhook( + (request.body as Buffer | undefined) ?? "", + request.headers, + verifyOptions, + ); + } catch (err) { + if (err instanceof WebhookVerificationError) { + return reply + .code(400) + .send({ error: "invalid_webhook", reason: err.reason }); + } + throw err; + } + + const result = await onEvent(event, request, reply); + if (reply.sent) return reply; + if (result !== undefined) return result; + return reply.code(204).send(); + }); +} diff --git a/packages/fastify/tests/types/consumer.ts b/packages/fastify/tests/types/consumer.ts index a733386..0444d88 100644 --- a/packages/fastify/tests/types/consumer.ts +++ b/packages/fastify/tests/types/consumer.ts @@ -54,3 +54,19 @@ requireRole(42); getSeamlessUser(42); // @ts-expect-error the plugin is registered with an options object app.register(seamlessAuth, 42); + +import { seamlessWebhook } from "@seamless-auth/fastify/webhook"; + +const webhookApp = Fastify(); +void webhookApp.register(seamlessWebhook, { + path: "/webhooks/seamless", + secret: ["whsec_a", "whsec_b"], + onEvent(event) { + if (event.type === "user.created") { + const userId: string = event.data.userId; + void userId; + } + }, +}); +// @ts-expect-error the plugin needs a path, a secret and onEvent +void webhookApp.register(seamlessWebhook, { secret: "whsec_a" }); diff --git a/packages/fastify/tests/webhook.test.js b/packages/fastify/tests/webhook.test.js new file mode 100644 index 0000000..726d0fc --- /dev/null +++ b/packages/fastify/tests/webhook.test.js @@ -0,0 +1,115 @@ +import Fastify from "fastify"; + +import { + NEXT_WEBHOOK_SECRET, + WEBHOOK_BODY, + WEBHOOK_SECRET, + signedHeaders, +} from "../../core/tests/fixtures/webhookSigning.js"; + +const { seamlessWebhook, verifyWebhook } = await import("../dist/webhook.js"); + +async function build(options = {}) { + const received = []; + const app = Fastify(); + await app.register(seamlessWebhook, { + path: "/webhooks/seamless", + secret: WEBHOOK_SECRET, + onEvent: (event) => { + received.push(event); + }, + ...options, + }); + app.post("/json", async (request) => request.body); + await app.ready(); + return { app, received }; +} + +function deliver(app, payload, headers, contentType = "application/json") { + return app.inject({ + method: "POST", + url: "/webhooks/seamless", + headers: { ...(contentType ? { "content-type": contentType } : {}), ...headers }, + payload, + }); +} + +describe("seamlessWebhook", () => { + it("verifies the raw body and hands the typed event to onEvent", async () => { + const { app, received } = await build(); + const res = await deliver(app, WEBHOOK_BODY, signedHeaders(WEBHOOK_BODY)); + expect(res.statusCode).toBe(204); + expect(received).toEqual([ + expect.objectContaining({ + id: "evt_01", + type: "user.created", + data: { userId: "user_01", email: "zoë@example.com", phone: null }, + }), + ]); + }); + + it("reads the body raw whatever the content type", async () => { + const { app } = await build(); + const res = await deliver(app, WEBHOOK_BODY, signedHeaders(WEBHOOK_BODY), "text/plain"); + expect(res.statusCode).toBe(204); + }); + + it("sends what onEvent returns", async () => { + const { app } = await build({ onEvent: (event) => ({ seen: event.id }) }); + const res = await deliver(app, WEBHOOK_BODY, signedHeaders(WEBHOOK_BODY)); + expect(res.statusCode).toBe(200); + expect(res.json()).toEqual({ seen: "evt_01" }); + }); + + it("lets onEvent answer on reply", async () => { + const { app } = await build({ + onEvent: (_event, _request, reply) => reply.code(202).send({ queued: true }), + }); + const res = await deliver(app, WEBHOOK_BODY, signedHeaders(WEBHOOK_BODY)); + expect(res.statusCode).toBe(202); + }); + + it("refuses a tampered body with the reason", async () => { + const { app, received } = await build(); + const res = await deliver( + app, + WEBHOOK_BODY.replace("user_01", "user_02"), + signedHeaders(WEBHOOK_BODY), + ); + expect(res.statusCode).toBe(400); + expect(res.json()).toEqual({ error: "invalid_webhook", reason: "invalid_signature" }); + expect(received).toEqual([]); + }); + + it("refuses a delivery with no signature headers", async () => { + const { app } = await build(); + const res = await deliver(app, WEBHOOK_BODY, {}); + expect(res.statusCode).toBe(400); + expect(res.json().reason).toBe("missing_header"); + }); + + it("refuses an empty body", async () => { + const { app } = await build(); + const res = await deliver(app, undefined, signedHeaders(WEBHOOK_BODY), null); + expect(res.statusCode).toBe(400); + expect(res.json().reason).toBe("invalid_signature"); + }); + + it("accepts either secret while one rotates", async () => { + const { app } = await build({ secret: [NEXT_WEBHOOK_SECRET, WEBHOOK_SECRET] }); + for (const secret of [WEBHOOK_SECRET, NEXT_WEBHOOK_SECRET]) { + const res = await deliver(app, WEBHOOK_BODY, signedHeaders(WEBHOOK_BODY, [secret])); + expect(res.statusCode).toBe(204); + } + }); + + it("keeps the raw parser inside its own context", async () => { + const { app } = await build(); + const res = await app.inject({ method: "POST", url: "/json", payload: { hello: "world" } }); + expect(res.json()).toEqual({ hello: "world" }); + }); + + it("re-exports the core verifier", () => { + expect(typeof verifyWebhook).toBe("function"); + }); +}); diff --git a/packages/nextjs/README.md b/packages/nextjs/README.md index 5254e61..9e23117 100644 --- a/packages/nextjs/README.md +++ b/packages/nextjs/README.md @@ -366,6 +366,49 @@ and `authTime`. A client credentials token (`sub` equal to `client_id`) verifies `isClient` set to `true` and the client id in `id`, and fails role and step-up checks. Check `isClient` before treating `id` as a user id, or pass `allowClients: false`. +## Verifying webhooks + +`createWebhookHandler` from `@seamless-auth/nextjs/webhook` is a route handler that verifies a +Seamless webhook and hands the typed event to `onEvent`. + +```ts +// app/api/webhooks/seamless/route.ts +import { createWebhookHandler } from "@seamless-auth/nextjs/webhook"; + +export const POST = createWebhookHandler({ + secret: process.env.SEAMLESS_WEBHOOK_SECRET!, + async onEvent(event) { + if (event.type === "user.created") await provision(event.data.userId); + }, +}); +``` + +`onEvent` answers by returning a `Response`; otherwise the handler answers 204. While the +endpoint's secret rotates, pass both: `secret: [newSecret, oldSecret]`. The handler runs on the +Node.js runtime. + +A refused webhook gets `400 { "error": "invalid_webhook", "reason": "..." }`, with the reason +from `WebhookVerificationError`: `missing_header`, `malformed_header`, +`timestamp_out_of_tolerance`, `unsupported_version`, `invalid_signature` or `invalid_payload`. +The core README lists what each one means. + +To verify inside a handler of your own, read the body yourself and do not call +`request.json()` first: + +```ts +import { verifyWebhookRequest } from "@seamless-auth/nextjs/webhook"; + +export async function POST(request: Request) { + const event = await verifyWebhookRequest(request, { secret }); + // ... +} +``` + +`verifyWebhookRequest` reads `request.arrayBuffer()`, the exact bytes. Passing +`await request.text()` to `verifyWebhook(body, request.headers, { secret })` works for the auth +API's UTF-8 JSON too, but `text()` drops a leading byte order mark, so the raw bytes are the +safer input. + ## Options `createSeamlessAuthHandler` takes the same options as the Express and Fastify diff --git a/packages/nextjs/package.json b/packages/nextjs/package.json index 03b5d99..62cf85e 100644 --- a/packages/nextjs/package.json +++ b/packages/nextjs/package.json @@ -28,6 +28,10 @@ ".": { "types": "./dist/index.d.ts", "import": "./dist/index.js" + }, + "./webhook": { + "types": "./dist/webhook.d.ts", + "import": "./dist/webhook.js" } }, "engines": { @@ -35,7 +39,7 @@ }, "scripts": { "build": "pnpm run build:js && pnpm run build:types", - "build:js": "tsup src/index.ts --format esm --out-dir dist --splitting --external @seamless-auth/core --external @seamless-auth/core/*", + "build:js": "tsup src/index.ts src/webhook.ts --format esm --out-dir dist --splitting --external @seamless-auth/core --external @seamless-auth/core/*", "build:types": "tsc -p tsconfig.build.json", "clean": "rm -rf dist", "dev": "tsc --watch", @@ -53,7 +57,7 @@ }, "dependencies": { "@seamless-auth/core": "workspace:^", - "@seamless-auth/types": "^0.38.0", + "@seamless-auth/types": "^0.39.0", "cookie": "^1.1.1" }, "devDependencies": { diff --git a/packages/nextjs/src/webhook.ts b/packages/nextjs/src/webhook.ts new file mode 100644 index 0000000..0aa89a7 --- /dev/null +++ b/packages/nextjs/src/webhook.ts @@ -0,0 +1,73 @@ +import { + verifyWebhook, + WebhookVerificationError, + type VerifyWebhookOptions, + type WebhookEvent, +} from "@seamless-auth/core/webhook"; + +export { + verifyWebhook, + WebhookVerificationError, +} from "@seamless-auth/core/webhook"; +export type { + VerifyWebhookOptions, + WebhookEvent, + WebhookEventType, + WebhookHeaders, + WebhookVerificationReason, +} from "@seamless-auth/core/webhook"; + +/** + * Reads the request body as raw bytes and verifies it as a Seamless webhook. + * Throws `WebhookVerificationError` when it is refused. The body can be read + * once, so do not call `request.json()` first. + */ +export async function verifyWebhookRequest( + request: Request, + options: VerifyWebhookOptions, +): Promise { + const body = new Uint8Array(await request.arrayBuffer()); + return verifyWebhook(body, request.headers, options); +} + +export interface WebhookHandlerOptions extends VerifyWebhookOptions { + /** Handles a verified event. Return a `Response` to answer; otherwise 204. */ + onEvent: ( + event: WebhookEvent, + request: Request, + ) => Response | void | Promise; +} + +/** + * A route handler for `app/.../route.ts` that verifies a Seamless webhook and + * passes the typed event to `onEvent`. A refused webhook gets + * `400 { error: "invalid_webhook", reason }`. Runs on the Node.js runtime. + * + * ### Example + * ```ts + * export const POST = createWebhookHandler({ + * secret: process.env.SEAMLESS_WEBHOOK_SECRET!, + * async onEvent(event) { + * if (event.type === "user.created") await provision(event.data.userId); + * }, + * }); + * ``` + */ +export function createWebhookHandler(options: WebhookHandlerOptions) { + const { onEvent, ...verifyOptions } = options; + return async (request: Request): Promise => { + let event: WebhookEvent; + try { + event = await verifyWebhookRequest(request, verifyOptions); + } catch (err) { + if (err instanceof WebhookVerificationError) { + return Response.json( + { error: "invalid_webhook", reason: err.reason }, + { status: 400 }, + ); + } + throw err; + } + return (await onEvent(event, request)) ?? new Response(null, { status: 204 }); + }; +} diff --git a/packages/nextjs/tests/types/consumer.ts b/packages/nextjs/tests/types/consumer.ts index 48df533..9a9cd2f 100644 --- a/packages/nextjs/tests/types/consumer.ts +++ b/packages/nextjs/tests/types/consumer.ts @@ -74,3 +74,23 @@ getSeamlessClaims(42); requirePermission("a:read", () => new Response(), { ...options, match: "some" }); // @ts-expect-error requireRole takes the roles first requireRole(() => new Response(), options); + +import { + createWebhookHandler, + verifyWebhookRequest, +} from "@seamless-auth/nextjs/webhook"; + +export const POST: (request: Request) => Promise = createWebhookHandler({ + secret: "whsec_a", + onEvent(event) { + if (event.type === "user.created") { + const userId: string = event.data.userId; + void userId; + } + }, +}); +void verifyWebhookRequest(new Request("https://example.com"), { secret: "whsec_a" }).then( + (event) => event.id, +); +// @ts-expect-error onEvent is required +createWebhookHandler({ secret: "whsec_a" }); diff --git a/packages/nextjs/tests/webhook.test.js b/packages/nextjs/tests/webhook.test.js new file mode 100644 index 0000000..f084e3e --- /dev/null +++ b/packages/nextjs/tests/webhook.test.js @@ -0,0 +1,101 @@ +import { + NEXT_WEBHOOK_SECRET, + WEBHOOK_BODY, + WEBHOOK_SECRET, + signedHeaders, +} from "../../core/tests/fixtures/webhookSigning.js"; + +const { createWebhookHandler, verifyWebhookRequest, WebhookVerificationError } = + await import("../dist/webhook.js"); + +function post(body, headers) { + return new Request("https://app.example.com/api/webhooks/seamless", { + method: "POST", + headers: { "content-type": "application/json", ...headers }, + body, + }); +} + +describe("createWebhookHandler", () => { + it("verifies the raw body and hands the typed event to onEvent", async () => { + const received = []; + const POST = createWebhookHandler({ + secret: WEBHOOK_SECRET, + onEvent: (event) => { + received.push(event); + }, + }); + const res = await POST(post(WEBHOOK_BODY, signedHeaders(WEBHOOK_BODY))); + expect(res.status).toBe(204); + expect(received).toEqual([ + expect.objectContaining({ + id: "evt_01", + type: "user.created", + data: { userId: "user_01", email: "zoë@example.com", phone: null }, + }), + ]); + }); + + it("answers with the Response onEvent returns", async () => { + const POST = createWebhookHandler({ + secret: WEBHOOK_SECRET, + onEvent: (event) => Response.json({ seen: event.id }, { status: 202 }), + }); + const res = await POST(post(WEBHOOK_BODY, signedHeaders(WEBHOOK_BODY))); + expect(res.status).toBe(202); + expect(await res.json()).toEqual({ seen: "evt_01" }); + }); + + it("refuses a tampered body with the reason", async () => { + const onEvent = () => { + throw new Error("must not run"); + }; + const POST = createWebhookHandler({ secret: WEBHOOK_SECRET, onEvent }); + const res = await POST( + post(WEBHOOK_BODY.replace("user_01", "user_02"), signedHeaders(WEBHOOK_BODY)), + ); + expect(res.status).toBe(400); + expect(await res.json()).toEqual({ + error: "invalid_webhook", + reason: "invalid_signature", + }); + }); + + it("refuses a delivery with no signature headers", async () => { + const POST = createWebhookHandler({ secret: WEBHOOK_SECRET, onEvent: () => {} }); + const res = await POST(post(WEBHOOK_BODY, {})); + expect(res.status).toBe(400); + expect((await res.json()).reason).toBe("missing_header"); + }); + + it("accepts either secret while one rotates", async () => { + const POST = createWebhookHandler({ + secret: [NEXT_WEBHOOK_SECRET, WEBHOOK_SECRET], + onEvent: () => {}, + }); + for (const secret of [WEBHOOK_SECRET, NEXT_WEBHOOK_SECRET]) { + const res = await POST(post(WEBHOOK_BODY, signedHeaders(WEBHOOK_BODY, [secret]))); + expect(res.status).toBe(204); + } + }); +}); + +describe("verifyWebhookRequest", () => { + it("returns the typed event", async () => { + const event = await verifyWebhookRequest(post(WEBHOOK_BODY, signedHeaders(WEBHOOK_BODY)), { + secret: WEBHOOK_SECRET, + }); + expect(event.type).toBe("user.created"); + }); + + it("verifies the bytes as sent, which request.text() would alter", async () => { + // text() drops a leading byte order mark, so only the raw bytes carry the + // signature through. The signed body then fails to parse, after verifying. + const body = `${WEBHOOK_BODY}`; + const err = await verifyWebhookRequest(post(body, signedHeaders(body)), { + secret: WEBHOOK_SECRET, + }).catch((e) => e); + expect(err).toBeInstanceOf(WebhookVerificationError); + expect(err.reason).toBe("invalid_payload"); + }); +}); diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index dc2a2fc..4263787 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -39,8 +39,8 @@ importers: packages/core: dependencies: '@seamless-auth/types': - specifier: ^0.38.0 - version: 0.38.0 + specifier: ^0.39.0 + version: 0.39.0 '@types/jsonwebtoken': specifier: ^9.0.10 version: 9.0.10 @@ -159,8 +159,8 @@ importers: specifier: workspace:^ version: link:../core '@seamless-auth/types': - specifier: ^0.38.0 - version: 0.38.0 + specifier: ^0.39.0 + version: 0.39.0 cookie: specifier: ^1.1.1 version: 1.1.1 @@ -1116,8 +1116,8 @@ packages: cpu: [x64] os: [win32] - '@seamless-auth/types@0.38.0': - resolution: {integrity: sha512-qALF5GFQEv+9yucQdn179cpTdEMMH/PjtZWAHatWk1qUEOzb1ElOqoBZgC4/THAk6u4aLgDyuDt/dCD/BzloqA==} + '@seamless-auth/types@0.39.0': + resolution: {integrity: sha512-xoJLkpgkisvVvSh3aBxByC5GfWm6LaIulusf+6A2ghok/l5FP6r2V8lwLEqbXO6dy/g01RNWxfTupjWAp42b0A==} engines: {node: '>=22'} '@sinclair/typebox@0.27.10': @@ -3736,7 +3736,7 @@ snapshots: '@rollup/rollup-win32-x64-msvc@4.60.4': optional: true - '@seamless-auth/types@0.38.0': + '@seamless-auth/types@0.39.0': dependencies: zod: 4.6.5 From 344e64302b9b4867304dbb87c0a1f5b493e273fe Mon Sep 17 00:00:00 2001 From: Brandon Corbett Date: Sat, 7 Nov 2026 22:12:23 -0500 Subject: [PATCH 2/2] chore: move core and nextjs to types 0.40.0 --- .changeset/verify-webhook.md | 2 +- packages/core/package.json | 2 +- packages/nextjs/package.json | 2 +- pnpm-lock.yaml | 14 +++++++------- 4 files changed, 10 insertions(+), 10 deletions(-) diff --git a/.changeset/verify-webhook.md b/.changeset/verify-webhook.md index 3b90ecf..be704e1 100644 --- a/.changeset/verify-webhook.md +++ b/.changeset/verify-webhook.md @@ -5,4 +5,4 @@ "@seamless-auth/nextjs": minor --- -Verify Seamless webhooks. `@seamless-auth/core/webhook` adds `verifyWebhook`, which checks a Standard Webhooks `v1` signature against the raw body with a constant-time comparison, a 300 second timestamp tolerance in both directions and up to two secrets while one rotates, then returns the event typed with `WebhookEventSchema`. A refused webhook throws `WebhookVerificationError` with a `reason`. The adapters wrap it on their own `/webhook` subpath: `requireWebhook` middleware for Express, the `seamlessWebhook` plugin for Fastify, and `createWebhookHandler` and `verifyWebhookRequest` for Next.js. Core and the Next.js adapter now depend on `@seamless-auth/types` 0.39.0. +Verify Seamless webhooks. `@seamless-auth/core/webhook` adds `verifyWebhook`, which checks a Standard Webhooks `v1` signature against the raw body with a constant-time comparison, a 300 second timestamp tolerance in both directions and up to two secrets while one rotates, then returns the event typed with `WebhookEventSchema`. A refused webhook throws `WebhookVerificationError` with a `reason`. The adapters wrap it on their own `/webhook` subpath: `requireWebhook` middleware for Express, the `seamlessWebhook` plugin for Fastify, and `createWebhookHandler` and `verifyWebhookRequest` for Next.js. Core and the Next.js adapter now depend on `@seamless-auth/types` 0.40.0. diff --git a/packages/core/package.json b/packages/core/package.json index e37cc6c..7db33d3 100644 --- a/packages/core/package.json +++ b/packages/core/package.json @@ -55,7 +55,7 @@ "test:watch": "pnpm run build && NODE_OPTIONS=--experimental-vm-modules jest --watch" }, "dependencies": { - "@seamless-auth/types": "^0.39.0", + "@seamless-auth/types": "^0.40.0", "@types/jsonwebtoken": "^9.0.10", "jose": "^6.1.3", "jsonwebtoken": "^9.0.2" diff --git a/packages/nextjs/package.json b/packages/nextjs/package.json index 62cf85e..b2a079f 100644 --- a/packages/nextjs/package.json +++ b/packages/nextjs/package.json @@ -57,7 +57,7 @@ }, "dependencies": { "@seamless-auth/core": "workspace:^", - "@seamless-auth/types": "^0.39.0", + "@seamless-auth/types": "^0.40.0", "cookie": "^1.1.1" }, "devDependencies": { diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 4263787..4c07ab5 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -39,8 +39,8 @@ importers: packages/core: dependencies: '@seamless-auth/types': - specifier: ^0.39.0 - version: 0.39.0 + specifier: ^0.40.0 + version: 0.40.0 '@types/jsonwebtoken': specifier: ^9.0.10 version: 9.0.10 @@ -159,8 +159,8 @@ importers: specifier: workspace:^ version: link:../core '@seamless-auth/types': - specifier: ^0.39.0 - version: 0.39.0 + specifier: ^0.40.0 + version: 0.40.0 cookie: specifier: ^1.1.1 version: 1.1.1 @@ -1116,8 +1116,8 @@ packages: cpu: [x64] os: [win32] - '@seamless-auth/types@0.39.0': - resolution: {integrity: sha512-xoJLkpgkisvVvSh3aBxByC5GfWm6LaIulusf+6A2ghok/l5FP6r2V8lwLEqbXO6dy/g01RNWxfTupjWAp42b0A==} + '@seamless-auth/types@0.40.0': + resolution: {integrity: sha512-NpFVCWE0VSNrBK9M4yBxsloyQgGHXP6B8/QmDPxsFz48/qV6jcDqdUpuV4PAJslG9B9X+4BcnTSQzI+iPSRNsA==} engines: {node: '>=22'} '@sinclair/typebox@0.27.10': @@ -3736,7 +3736,7 @@ snapshots: '@rollup/rollup-win32-x64-msvc@4.60.4': optional: true - '@seamless-auth/types@0.39.0': + '@seamless-auth/types@0.40.0': dependencies: zod: 4.6.5