Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions .changeset/verify-webhook.md
Original file line number Diff line number Diff line change
@@ -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.40.0.
42 changes: 42 additions & 0 deletions packages/core/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
6 changes: 5 additions & 1 deletion packages/core/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand All @@ -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.40.0",
"@types/jsonwebtoken": "^9.0.10",
"jose": "^6.1.3",
"jsonwebtoken": "^9.0.2"
Expand Down
226 changes: 226 additions & 0 deletions packages/core/src/webhook.ts
Original file line number Diff line number Diff line change
@@ -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<string, string | string[] | undefined>;

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<string, string | string[] | undefined>;
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;
}
26 changes: 26 additions & 0 deletions packages/core/tests/fixtures/webhookSigning.js
Original file line number Diff line number Diff line change
@@ -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(" "),
};
}
24 changes: 24 additions & 0 deletions packages/core/tests/types/consumer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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", "");
37 changes: 37 additions & 0 deletions packages/core/tests/webhook.constantTime.test.js
Original file line number Diff line number Diff line change
@@ -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);
});
});
Loading
Loading