From 4554d501f663313debe0f9e166a8fa0e94fed5ae Mon Sep 17 00:00:00 2001 From: Jason Olinger <72224982+jolinger-godaddy@users.noreply.github.com> Date: Mon, 23 Nov 2026 17:11:09 -0500 Subject: [PATCH] [COMMEX-2359] Harden platform webhook verification verifyWebhookSubscription now compares in constant time, signs the exact body bytes, accepts a space-separated list of v1 signatures, and gains a strictRawBody option and an optional toleranceSeconds (off by default). The Express and TanStack webhook middleware turn strictRawBody on; Express reads req.rawBody when kept. Setup problems (raw body lost, no secret) are answered with 500 instead of 401. --- .changeset/commex-2359-webhook-verify.md | 11 + AGENTS.md | 2 +- packages/app-connect/README.md | 83 ++- .../app-connect/src/express/index.test.ts | 192 +++++++ packages/app-connect/src/express/index.ts | 99 +++- packages/app-connect/src/index.ts | 6 + packages/app-connect/src/next/index.ts | 2 + .../app-connect/src/tanstack/index.test.ts | 174 ++++++- packages/app-connect/src/tanstack/index.ts | 69 ++- .../src/types/verifiable-request.ts | 9 +- packages/app-connect/src/utils/config.ts | 125 ++++- .../app-connect/src/utils/verification.ts | 93 ---- .../app-connect/src/utils/webhook.test.ts | 491 ++++++++++++++++++ packages/app-connect/src/utils/webhook.ts | 443 ++++++++++++---- 14 files changed, 1521 insertions(+), 278 deletions(-) create mode 100644 .changeset/commex-2359-webhook-verify.md create mode 100644 packages/app-connect/src/express/index.test.ts create mode 100644 packages/app-connect/src/utils/webhook.test.ts diff --git a/.changeset/commex-2359-webhook-verify.md b/.changeset/commex-2359-webhook-verify.md new file mode 100644 index 000000000..9559c2588 --- /dev/null +++ b/.changeset/commex-2359-webhook-verify.md @@ -0,0 +1,11 @@ +--- +'@godaddy/app-connect': minor +--- + +Harden webhook verification. `verifyWebhookSubscription` compares signatures in constant time, signs the exact body bytes (a Buffer, ArrayBuffer or string), and accepts a space-separated list of `v1,` signatures (either case of the tag), passing when any one matches. + +New `strictRawBody` option refuses a body that is not raw bytes or a string, instead of re-serializing a parsed body with `JSON.stringify`. New `toleranceSeconds` option refuses a timestamp too far from now; it is off by default. + +Behaviour change: the Express and TanStack webhook middleware now turn `strictRawBody` on by default. Express apps must keep the raw body, through `express.json({ verify })` saving `req.rawBody`, or `express.raw({ type: 'application/json' })` on the webhook route in place of an app-wide `express.json()`. A string decoded by `express.text()` doesn't count as raw. Without the raw body the middleware answers 500; pass `strictRawBody: false` to keep the old `JSON.stringify` fallback for a parsed body (a body nothing kept, or one TanStack can't read, is still a 500). The TanStack middleware now reads the body as bytes, so a byte-order mark is kept. Direct calls and the Next.js `verifyWebhookSubscription` keep strict mode off unless you pass `strictRawBody: true`. + +When the app's own setup is wrong at request time (raw body lost, no webhook secret), the middleware answers 500 with a generic `WEBHOOK_VERIFICATION_UNAVAILABLE` body and logs the detail under the same correlation id; a missing secret used to be a 401. Direct calls return `WEBHOOK_RAW_BODY_REQUIRED`, `WEBHOOK_SECRET_REQUIRED`, or `INVALID_WEBHOOK_OPTIONS` for a non-string secret or a NaN or negative `toleranceSeconds`. The middleware throws a TypeError when it is created with such options, so a `secret` passed as a Buffer or KeyObject, which used to work from JavaScript, is now refused: pass the secret string. An internal failure during verification is now `WEBHOOK_VERIFICATION_FAILED` (500) instead of `INVALID_WEBHOOK_SIGNATURE` (401). `webhookFailureStatus` and `webhookFailureBody` are exported from the root and `@godaddy/app-connect/next` for handlers that call `verifyWebhookSubscription` directly. diff --git a/AGENTS.md b/AGENTS.md index 21ba97f8f..5c037b49b 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -265,7 +265,7 @@ C. @godaddy/app-connect - Scripts: - dev/build/typecheck/test/test:watch/test:coverage/lint/check - Gotchas: - - There are older webhook verification helpers also present in verification.ts; index exports use utils/webhook.ts—prefer those + - Webhook verification lives in src/utils/webhook.ts. Webhook signatures are over the raw body bytes; the Express and TanStack webhook middleware are strict about that by default (strictRawBody) - Uses WebCrypto (crypto.subtle); ensure Node 20+ (CI uses Node 24) - Ensure body, header case, and query order are preserved correctly when constructing VerifiableRequest diff --git a/packages/app-connect/README.md b/packages/app-connect/README.md index 2f0165279..55373f1da 100644 --- a/packages/app-connect/README.md +++ b/packages/app-connect/README.md @@ -46,8 +46,9 @@ Verify that incoming requests to your application are genuinely from the GoDaddy Verify that incoming webhook subscriptions are genuinely from the GoDaddy platform by validating HMAC signatures. -- HMAC-SHA256 signature verification -- Support for webhook subscription verification header format +- HMAC-SHA256 signature verification over the raw body bytes, compared in constant time +- Support for webhook subscription verification header format, including a space-separated list of `v1,` signatures +- Strict raw-body mode (on by default in the middleware) and an optional timestamp tolerance - Express.js middleware for easy integration - Configurable via environment variables or runtime options @@ -100,8 +101,17 @@ import { createActionMiddleware } from '@godaddy/app-connect/express'; const app = express(); -// Add body parser middleware first -app.use(express.json()); +// Add body parser middleware first. The verify hook keeps the raw body, +// which webhook verification needs: the signature is over the exact bytes. +// Keep it the Buffer: buf.toString() would turn bytes that aren't valid UTF-8 +// into replacement characters and the signature would no longer match. +app.use( + express.json({ + verify: (req, _res, buf) => { + (req as typeof req & { rawBody?: Buffer }).rawBody = buf; + }, + }), +); // Add action verification middleware app.post('/action-webhook', @@ -111,7 +121,10 @@ app.post('/action-webhook', res.send('Verified action request received!'); }); -// For webhook subscriptions (separate endpoint with webhook verification) +// For webhook subscriptions (separate endpoint with webhook verification). +// It checks req.rawBody, or a Buffer req.body (from +// express.raw({ type: 'application/json' }) on this route instead of the +// app-wide express.json()), and answers 500 when neither is there. app.post('/webhook-subscription', createWebhookMiddleware(), // Import this from '@godaddy/app-connect/express' (req, res) => { @@ -191,18 +204,22 @@ function processActionRequest(req) { import { verifyWebhookSubscription, VerifiableRequest } from '@godaddy/app-connect'; function processWebhookSubscription(req) { - // Create a verifiable request object + // Create a verifiable request object. The body must be the raw bytes as + // received (here kept by an express.json() verify hook), not a parsed object. const verifiableRequest: VerifiableRequest = { method: req.method, url: req.url, path: req.path, query: req.query, headers: req.headers, - body: req.body + // Depending on the body-parser version, the verify hook may not run for an + // empty body, so pass an empty Buffer when Content-Length is 0 (the + // middleware does the same) + body: req.headers['content-length'] === '0' ? Buffer.alloc(0) : req.rawBody }; - // Verify the webhook subscription - const result = verifyWebhookSubscription(verifiableRequest); + // Verify the webhook subscription, refusing a parsed body + const result = verifyWebhookSubscription(verifiableRequest, { strictRawBody: true }); if (!result.success) { // Handle verification failure @@ -233,7 +250,12 @@ Returns a `Result` object that indicates success or contains an error. Verifies that a webhook subscription request has a valid HMAC signature. - `request`: A `VerifiableRequest` object containing the webhook request details -- `options`: Optional configuration including the webhook secret +- `options`: Optional configuration + - `secret`: the webhook secret (defaults to `GODADDY_WEBHOOK_SECRET`) + - `strictRawBody`: refuse a body that is not a raw string or Buffer with `WEBHOOK_RAW_BODY_REQUIRED`, instead of re-serializing a parsed body with `JSON.stringify`. Off by default here; on by default in the Express and TanStack middleware + - `toleranceSeconds`: refuse a `webhook-timestamp` more than this many seconds from now with `WEBHOOK_TIMESTAMP_OUT_OF_TOLERANCE`. Off by default + +The signature is `v1,` of `..`, keyed with the secret and compared in constant time. The `webhook-signature` header may list several space-separated signatures; one match is enough. Pass the body exactly as received (for Next.js, `Buffer.from(await request.arrayBuffer())`; `request.text()` drops a byte-order mark), since a re-serialized body can differ from what was signed. Direct calls, including the Next.js export, keep `strictRawBody` off unless you pass it, so pass `strictRawBody: true` once your route hands over raw bytes. Returns a `Result` object that indicates success or contains an error. @@ -261,13 +283,39 @@ For Next.js App Router (13+), use verification functions directly in your route import { verifyAction, verifyWebhookSubscription, VerifiableRequest } from '@godaddy/app-connect/next'; ``` -See the [Next.js App Router Integration](#nextjs-app-router-integration-nextjs-13) example for action verification details. The pattern is similar for webhook verification. +See the [Next.js App Router Integration](#nextjs-app-router-integration-nextjs-13) example for action verification details. For webhooks, pass the raw bytes, not `request.json()`: -### Helper Functions +```typescript +// app/api/webhooks/route.ts +import { + verifyWebhookSubscription, + webhookFailureBody, + webhookFailureStatus, +} from '@godaddy/app-connect/next'; -#### `getWebhookSecret(options?): string` +export async function POST(request: Request) { + const url = new URL(request.url); + const result = verifyWebhookSubscription( + { + method: request.method, + url: request.url, + path: url.pathname, + query: Object.fromEntries(url.searchParams), + headers: Object.fromEntries(request.headers), + body: Buffer.from(await request.arrayBuffer()), + }, + { strictRawBody: true }, + ); -Retrieves the webhook secret for webhook subscription verification, from options or environment. + if (!result.success) { + // 500 with a generic body for the app's own setup problems, 401 otherwise + return Response.json(webhookFailureBody(result.error), { + status: webhookFailureStatus(result.error?.name), + }); + } + return Response.json({ received: true }); +} +``` ### Error Types @@ -285,6 +333,13 @@ The library exports standardized error types that follow GoDaddy's error schema: - `MissingWebhookHeaderError`: When a required webhook header is missing - `InvalidWebhookSignatureError`: When the webhook signature verification fails +- `WebhookRawBodyRequiredError`: When `strictRawBody` is on and the raw body is unavailable (the middleware answers 500) +- `WebhookSecretRequiredError`: When no webhook secret is configured (the middleware answers 500) +- `InvalidWebhookOptionsError`: When an option would refuse every delivery, such as a negative `toleranceSeconds` (the middleware throws when created) +- `WebhookTimestampOutOfToleranceError`: When `toleranceSeconds` is set and the timestamp is outside it +- `WebhookVerificationFailedError`: When verification failed inside the app, such as a body that can't be serialized (the middleware answers 500) + +`webhookFailureStatus(name)` and `webhookFailureBody(error)` give the status and body the middleware answers with, for handlers that call `verifyWebhookSubscription` directly. ## Upcoming Features diff --git a/packages/app-connect/src/express/index.test.ts b/packages/app-connect/src/express/index.test.ts new file mode 100644 index 000000000..8c7d694ed --- /dev/null +++ b/packages/app-connect/src/express/index.test.ts @@ -0,0 +1,192 @@ +import type { NextFunction, Request, Response } from 'express'; +import { describe, expect, it, vi } from 'vitest'; +import { generateHmac } from '../utils/webhook'; +import { createWebhookMiddleware } from './index'; + +const SECRET = 'whsec_local_test_only'; +const BODY = '{"id":"evt_1","type":"commerce.order.created"}'; +const HEADERS = { + 'webhook-id': 'msg_1', + 'webhook-timestamp': '1795400000', + 'webhook-signature': generateHmac(SECRET, 'msg_1', '1795400000', BODY), + 'content-type': 'application/json', + 'content-length': String(Buffer.byteLength(BODY)), +}; + +function request( + fields: { body?: unknown; rawBody?: unknown }, + headers: Record = HEADERS, +): Request { + return { + method: 'POST', + url: '/webhooks', + originalUrl: '/webhooks', + path: '/webhooks', + query: {}, + headers, + ...fields, + } as unknown as Request; +} + +function run( + req: Request, + options: Parameters[0] = { secret: SECRET }, +) { + const sent: { status?: number; body?: { name?: string } } = {}; + const res = { + status(code: number) { + sent.status = code; + return res; + }, + json(body: { name?: string }) { + sent.body = body; + return res; + }, + } as unknown as Response; + const next = vi.fn() as unknown as NextFunction; + createWebhookMiddleware(options)(req, res, next); + return { sent, next }; +} + +describe('createWebhookMiddleware (Express)', () => { + it('verifies req.rawBody kept by a body parser verify hook', () => { + const { sent, next } = run( + request({ body: JSON.parse(BODY), rawBody: Buffer.from(BODY) }), + ); + expect(next).toHaveBeenCalledWith(); + expect(sent.status).toBeUndefined(); + }); + + it('verifies a Buffer body from express.raw() and a string req.rawBody', () => { + for (const fields of [{ body: Buffer.from(BODY) }, { rawBody: BODY }]) { + const { next } = run(request(fields)); + expect(next).toHaveBeenCalledWith(); + } + }); + + it('does not take a decoded string req.body from express.text() as raw', () => { + const { sent, next } = run(request({ body: BODY })); + expect(next).not.toHaveBeenCalled(); + expect(sent.status).toBe(500); + }); + + it('answers a body nothing kept with 500 even when strictRawBody is false', () => { + const { sent, next } = run(request({}), { + secret: SECRET, + strictRawBody: false, + }); + expect(next).not.toHaveBeenCalled(); + expect(sent.status).toBe(500); + }); + + it('answers a parsed or missing body without the raw body with 500, not 401', () => { + const noLength = { ...HEADERS, 'content-length': undefined }; + for (const [fields, headers] of [ + [{ body: JSON.parse(BODY) }, HEADERS], + [{}, HEADERS], + // Without a length header the body is never assumed empty. + [{ body: JSON.parse(BODY) }, noLength], + [{}, noLength], + ] as const) { + const { sent, next } = run(request(fields, headers)); + expect(next).not.toHaveBeenCalled(); + expect(sent.status).toBe(500); + // The sender gets a generic body; the detail is logged. + expect(sent.body?.name).toBe('WEBHOOK_VERIFICATION_UNAVAILABLE'); + } + }); + + it('answers a body that does not match the signature with 401', () => { + const { sent, next } = run( + request({ rawBody: Buffer.from(BODY.replace('evt_1', 'evt_2')) }), + ); + expect(next).not.toHaveBeenCalled(); + expect(sent.status).toBe(401); + expect(sent.body?.name).toBe('INVALID_WEBHOOK_SIGNATURE'); + }); + + it('keeps the JSON.stringify fallback when strictRawBody is false', () => { + const { next } = run(request({ body: JSON.parse(BODY) }), { + secret: SECRET, + strictRawBody: false, + }); + expect(next).toHaveBeenCalledWith(); + }); + + it('verifies a request that says it has no body as an empty body', () => { + const signature = generateHmac(SECRET, 'msg_1', '1795400000', ''); + for (const body of [undefined, {}]) { + const { next } = run( + request( + { body }, + { + ...HEADERS, + 'content-length': '0', + 'webhook-signature': signature, + }, + ), + ); + expect(next).toHaveBeenCalledWith(); + } + }); + + it('answers a missing webhook secret with 500 and a generic body', () => { + vi.stubEnv('GODADDY_WEBHOOK_SECRET', ''); + try { + const { sent, next } = run(request({ rawBody: Buffer.from(BODY) }), {}); + expect(next).not.toHaveBeenCalled(); + expect(sent.status).toBe(500); + expect(sent.body).toEqual({ + name: 'WEBHOOK_VERIFICATION_UNAVAILABLE', + message: 'Webhook verification is not available', + correlationId: expect.any(String), + }); + } finally { + vi.unstubAllEnvs(); + } + }); + + it('throws when created with a toleranceSeconds that would refuse everything', () => { + expect(() => + createWebhookMiddleware({ secret: SECRET, toleranceSeconds: Number.NaN }), + ).toThrow(TypeError); + }); + it('reads the options on every request, so a secret set later is used', () => { + const options: { secret?: string } = {}; + const middleware = createWebhookMiddleware(options); + options.secret = SECRET; + const next = vi.fn() as unknown as NextFunction; + const res = { + status: () => res, + json: () => res, + } as unknown as Response; + middleware( + request({ rawBody: new Uint8Array(Buffer.from(BODY)).buffer }), + res, + next, + ); + expect(next).toHaveBeenCalledWith(); + }); + + it('answers the empty {} Express 4 leaves for an unparsed body with 500, even when strictRawBody is false', () => { + const { sent, next } = run(request({ body: {} }), { + secret: SECRET, + strictRawBody: false, + }); + expect(next).not.toHaveBeenCalled(); + expect(sent.status).toBe(500); + }); + + it('reads a secret behind a getter on the options object', () => { + class Config { + get secret() { + return SECRET; + } + } + const { next } = run( + request({ rawBody: Buffer.from(BODY) }), + new Config() as unknown as { secret: string }, + ); + expect(next).toHaveBeenCalledWith(); + }); +}); diff --git a/packages/app-connect/src/express/index.ts b/packages/app-connect/src/express/index.ts index c119675dc..78aca6aa5 100644 --- a/packages/app-connect/src/express/index.ts +++ b/packages/app-connect/src/express/index.ts @@ -1,8 +1,12 @@ +import { types } from 'node:util'; import type { NextFunction, Request, Response } from 'express'; import type { VerifiableRequest } from '../types/verifiable-request'; -import type { - VerificationOptions, - WebhookVerificationOptions, +import { + type VerificationOptions, + type WebhookVerificationOptions, + checkWebhookOptions, + webhookFailureBody, + webhookFailureStatus, } from '../utils/config'; import { verifyAction } from '../utils/verification'; import { verifyWebhookSubscription } from '../utils/webhook'; @@ -31,24 +35,105 @@ export function createActionMiddleware(options?: VerificationOptions) { }; } +function isBytes(value: unknown): boolean { + return ArrayBuffer.isView(value) || types.isAnyArrayBuffer(value); +} + /** - * Creates a middleware for Express.js that verifies webhook subscription requests + * True when the request said it has no body (`content-length: 0`), so the + * signed body is empty. Without that header the body is never assumed empty: + * HTTP/2 and some proxies send a real body without a length. + */ +function hasNoBody(req: Request): boolean { + return req.headers['content-length'] === '0'; +} + +/** The empty `{}` Express 4's body-parser leaves when it didn't parse a body. */ +function isEmptyPlaceholder(body: unknown): boolean { + return ( + typeof body === 'object' && + body !== null && + Object.getPrototypeOf(body) === Object.prototype && + Object.keys(body).length === 0 + ); +} + +/** + * Picks the raw webhook body: `req.rawBody` (bytes or a string) when a body + * parser's verify hook kept it, otherwise `req.body` when it is bytes (from + * express.raw()), otherwise an empty body when the request says it has none. + * A string `req.body` (express.text()) is not raw: the parser decoded it, which + * can drop a byte-order mark or apply another charset. Anything else is passed + * on as it is, so strict verification can refuse it. + */ +function rawWebhookBody(req: Request): { + body: unknown; + lost: boolean; + decoded?: boolean; +} { + const { rawBody } = req as Request & { rawBody?: unknown }; + if (typeof rawBody === 'string' || isBytes(rawBody)) { + return { body: rawBody, lost: false }; + } + if (isBytes(req.body)) { + return { body: req.body, lost: false }; + } + if (hasNoBody(req)) { + return { body: Buffer.alloc(0), lost: false }; + } + // A body was sent but nothing kept it: no fallback can verify that. Express + // 4's body-parser leaves an empty `{}` when its content type didn't match, + // so that placeholder counts as lost too. + return { + body: req.body, + lost: req.body === undefined || isEmptyPlaceholder(req.body), + decoded: typeof req.body === 'string', + }; +} + +/** + * Creates a middleware for Express.js that verifies webhook subscription requests. + * + * Strict raw-body verification is on by default: the signature is checked + * against `req.rawBody`, or a Buffer `req.body`, never a re-serialized parsed + * body. A request whose raw body is lost, or an app without a webhook secret, + * is answered with 500, because the app's setup is wrong, not the sender's. + * Pass `strictRawBody: false` to keep the old `JSON.stringify` fallback for a + * parsed body; a body nothing kept is still answered with 500. + * + * The options are read on every request, so a secret set on the object later is used. + * + * @throws TypeError when an option would refuse every delivery */ export function createWebhookMiddleware(options?: WebhookVerificationOptions) { + checkWebhookOptions(options); + return (req: Request, res: Response, next: NextFunction) => { + const { body, lost, decoded } = rawWebhookBody(req); + const strictRawBody = lost || (options?.strictRawBody ?? true); + // Each option is read from the caller's object, not copied with a spread, + // so a secret behind a getter or a prototype still counts. + const webhookOptions: WebhookVerificationOptions = { + secret: options?.secret, + toleranceSeconds: options?.toleranceSeconds, + strictRawBody, + }; const verifiableRequest: VerifiableRequest = { method: req.method, url: req.originalUrl || req.url, path: req.path, query: req.query as Record, headers: req.headers as Record, - body: req.body, + // Strict mode never verifies a string the parser decoded. + body: strictRawBody && decoded ? undefined : body, }; - const result = verifyWebhookSubscription(verifiableRequest, options); + const result = verifyWebhookSubscription(verifiableRequest, webhookOptions); if (!result.success) { - return res.status(401).json(result.error); + return res + .status(webhookFailureStatus(result.error?.name)) + .json(webhookFailureBody(result.error)); } next(); diff --git a/packages/app-connect/src/index.ts b/packages/app-connect/src/index.ts index 0094023ef..025b2d3dc 100644 --- a/packages/app-connect/src/index.ts +++ b/packages/app-connect/src/index.ts @@ -22,9 +22,15 @@ export { } from './errors/verification-errors'; // Export webhook verification types and errors export { + InvalidWebhookOptionsError, InvalidWebhookSignatureError, MissingWebhookHeaderError, + WebhookRawBodyRequiredError, + WebhookSecretRequiredError, + WebhookTimestampOutOfToleranceError, + WebhookVerificationFailedError, } from './utils/webhook'; +export { webhookFailureBody, webhookFailureStatus } from './utils/config'; // Export action verification types and options export type { diff --git a/packages/app-connect/src/next/index.ts b/packages/app-connect/src/next/index.ts index 7376395d8..532700b70 100644 --- a/packages/app-connect/src/next/index.ts +++ b/packages/app-connect/src/next/index.ts @@ -8,6 +8,8 @@ import { verifyWebhookSubscription as coreVerifyWebhookSubscription } from '../u // Re-export the VerifiableRequest type for Next.js users export type { VerifiableRequest } from '../types/verifiable-request'; +// The status and body the other adapters answer a failed webhook with +export { webhookFailureBody, webhookFailureStatus } from '../utils/config'; /** * Verifies a signed action request in a Next.js environment diff --git a/packages/app-connect/src/tanstack/index.test.ts b/packages/app-connect/src/tanstack/index.test.ts index 19be216d2..a59f7a7e6 100644 --- a/packages/app-connect/src/tanstack/index.test.ts +++ b/packages/app-connect/src/tanstack/index.test.ts @@ -233,11 +233,11 @@ describe('createWebhookMiddleware', () => { expect(result).toBe('next-result'); }); - it('should read body as text from cloned request (not json)', async () => { + it('should read the body as bytes from the cloned request (not json or text)', async () => { const body = { event: 'order.created' }; const request = createMockRequest(body); const jsonSpy = vi.spyOn(request, 'json'); - const textSpy = vi.spyOn(Request.prototype, 'text'); + const bytesSpy = vi.spyOn(Request.prototype, 'arrayBuffer'); const next = vi.fn().mockResolvedValue('next-result'); mockVerifyWebhookSubscription.mockReturnValue({ success: true }); @@ -245,11 +245,11 @@ describe('createWebhookMiddleware', () => { createWebhookMiddleware(); await capturedServerFn({ next, request }); - // Should read as text (from clone), not call json() on original + // Should read bytes (from clone), not call json() on original expect(jsonSpy).not.toHaveBeenCalled(); - expect(textSpy).toHaveBeenCalledTimes(1); + expect(bytesSpy).toHaveBeenCalledTimes(1); - textSpy.mockRestore(); + bytesSpy.mockRestore(); }); it('should build a correct VerifiableRequest and pass it to verifyWebhookSubscription', async () => { @@ -265,20 +265,20 @@ describe('createWebhookMiddleware', () => { createWebhookMiddleware(options); await capturedServerFn({ next, request }); - // Verify that body is passed as RAW STRING (not parsed object) for signature verification + // Verify that body is passed as RAW BYTES (not parsed object) for signature verification expect(mockVerifyWebhookSubscription).toHaveBeenCalledWith( expect.objectContaining({ method: 'POST', url: 'https://example.com/api/test?foo=bar', path: '/api/test', - body: JSON.stringify(body), // Raw string, not parsed object + body: Buffer.from(JSON.stringify(body)), // Raw bytes, not parsed object headers: expect.objectContaining({ 'content-type': 'application/json', 'webhook-signature': 'sig-value', }), query: { foo: 'bar' }, }), - options, + { ...options, strictRawBody: true }, ); }); @@ -349,12 +349,12 @@ describe('createWebhookMiddleware', () => { createWebhookMiddleware(); await capturedServerFn({ next, request }); - // Verify raw string is passed exactly as-is to verification + // Verify raw bytes are passed exactly as-is to verification expect(mockVerifyWebhookSubscription).toHaveBeenCalledWith( expect.objectContaining({ - body: rawBodyString, // Exact match including whitespace + body: Buffer.from(rawBodyString), // Exact match including whitespace }), - undefined, + { strictRawBody: true }, ); }); @@ -372,12 +372,156 @@ describe('createWebhookMiddleware', () => { createWebhookMiddleware(); await capturedServerFn({ next, request }); - // Verify exact raw string preservation + // Verify exact raw byte preservation expect(mockVerifyWebhookSubscription).toHaveBeenCalledWith( expect.objectContaining({ - body: rawBodyString, + body: Buffer.from(rawBodyString), }), - undefined, + { strictRawBody: true }, + ); + }); + + it('should keep a byte-order mark that text() would drop', async () => { + const bytes = Buffer.concat([ + Buffer.from([0xef, 0xbb, 0xbf]), + Buffer.from('{"event":"order.created"}'), + ]); + const request = new Request('https://example.com/api/test', { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: bytes, + }); + const next = vi.fn().mockResolvedValue('next-result'); + + mockVerifyWebhookSubscription.mockReturnValue({ success: true }); + + createWebhookMiddleware(); + await capturedServerFn({ next, request }); + + expect(mockVerifyWebhookSubscription).toHaveBeenCalledWith( + expect.objectContaining({ body: bytes }), + { strictRawBody: true }, ); }); -}); \ No newline at end of file + + it('should verify a request without a body as an empty body', async () => { + const request = createMockRequest(); + const next = vi.fn().mockResolvedValue('next-result'); + + mockVerifyWebhookSubscription.mockReturnValue({ success: true }); + + createWebhookMiddleware(); + await capturedServerFn({ next, request }); + + expect(mockVerifyWebhookSubscription).toHaveBeenCalledWith( + expect.objectContaining({ body: Buffer.alloc(0) }), + { strictRawBody: true }, + ); + }); + + it('should pass no body when an earlier middleware already read it', async () => { + const request = createMockRequest({ event: 'order.created' }); + await request.json(); + const next = vi.fn().mockResolvedValue('next-result'); + + mockVerifyWebhookSubscription.mockReturnValue({ success: true }); + + createWebhookMiddleware(); + await capturedServerFn({ next, request }); + + expect(mockVerifyWebhookSubscription).toHaveBeenCalledWith( + expect.objectContaining({ body: undefined }), + { strictRawBody: true }, + ); + }); + + it('should pass no body when the body stream is locked', async () => { + const request = createMockRequest({ event: 'order.created' }); + request.body?.getReader(); + const next = vi.fn().mockResolvedValue('next-result'); + + mockVerifyWebhookSubscription.mockReturnValue({ success: true }); + + createWebhookMiddleware(); + await capturedServerFn({ next, request }); + + expect(mockVerifyWebhookSubscription).toHaveBeenCalledWith( + expect.objectContaining({ body: undefined }), + { strictRawBody: true }, + ); + }); + + it('should refuse an unreadable body even when strict mode is off', async () => { + const request = createMockRequest({ event: 'order.created' }); + await request.json(); + const next = vi.fn().mockResolvedValue('next-result'); + + mockVerifyWebhookSubscription.mockReturnValue({ success: true }); + + createWebhookMiddleware({ strictRawBody: false }); + await capturedServerFn({ next, request }); + + expect(mockVerifyWebhookSubscription).toHaveBeenCalledWith( + expect.objectContaining({ body: undefined }), + { strictRawBody: true }, + ); + }); + it('should answer the app setup errors with 500', async () => { + for (const name of [ + 'WEBHOOK_RAW_BODY_REQUIRED', + 'WEBHOOK_SECRET_REQUIRED', + ]) { + mockVerifyWebhookSubscription.mockReturnValue({ + success: false, + error: { name, message: 'setup' }, + }); + createWebhookMiddleware(); + const thrown = await capturedServerFn({ + next: vi.fn(), + request: createMockRequest({ event: 'order.created' }), + }).catch((error: unknown) => error); + expect(thrown).toBeInstanceOf(Response); + expect((thrown as Response).status).toBe(500); + } + }); + + it('should throw when created with a toleranceSeconds that would refuse everything', () => { + expect(() => createWebhookMiddleware({ toleranceSeconds: -1 })).toThrow( + TypeError, + ); + }); + + it('should let the caller turn strict raw-body verification off', async () => { + const request = createMockRequest({ event: 'order.created' }); + const next = vi.fn().mockResolvedValue('next-result'); + + mockVerifyWebhookSubscription.mockReturnValue({ success: true }); + + createWebhookMiddleware({ secret: 's', strictRawBody: false }); + await capturedServerFn({ next, request }); + + expect(mockVerifyWebhookSubscription).toHaveBeenCalledWith( + expect.anything(), + { secret: 's', strictRawBody: false }, + ); + }); + + it('should read a secret behind a getter on the options object', async () => { + const request = createMockRequest({ event: 'order.created' }); + const next = vi.fn().mockResolvedValue('next-result'); + mockVerifyWebhookSubscription.mockReturnValue({ success: true }); + + class Config { + get secret() { + return 's'; + } + } + createWebhookMiddleware(new Config() as unknown as { secret: string }); + await capturedServerFn({ next, request }); + + expect(mockVerifyWebhookSubscription).toHaveBeenCalledWith( + expect.anything(), + expect.objectContaining({ secret: 's' }), + ); + }); +}); diff --git a/packages/app-connect/src/tanstack/index.ts b/packages/app-connect/src/tanstack/index.ts index 3aacd12c4..3210712d6 100644 --- a/packages/app-connect/src/tanstack/index.ts +++ b/packages/app-connect/src/tanstack/index.ts @@ -1,9 +1,13 @@ import { createMiddleware } from '@tanstack/react-start'; import type { VerifiableRequest } from '../types/verifiable-request'; -import type { - VerificationOptions, - WebhookVerificationOptions, +import { + type VerificationOptions, + type WebhookVerificationOptions, + checkWebhookOptions, + webhookFailureBody, + webhookFailureStatus, } from '../utils/config'; +import { logger } from '../utils/logger'; import { verifyAction } from '../utils/verification'; import { verifyWebhookSubscription } from '../utils/webhook'; @@ -54,23 +58,52 @@ export function createActionMiddleware(options?: VerificationOptions) { } /** - * Creates a middleware for TanStack Start that verifies webhook subscription requests + * Creates a middleware for TanStack Start that verifies webhook subscription requests. + * + * The signature is checked against the exact request body bytes. Strict + * raw-body verification is on by default, so a parsed body never reaches the + * check; pass `strictRawBody: false` to turn it off. A body an earlier + * middleware already read, or an app without a webhook secret, is answered + * with 500, because the app's setup is wrong, not the sender's. + * + * @throws TypeError when an option would refuse every delivery */ export function createWebhookMiddleware(options?: WebhookVerificationOptions) { + checkWebhookOptions(options); + const middleware = createMiddleware({ type: 'request' }).server( async ({ next, request }) => { const url = new URL(request.url); - - // Read raw body as text from cloned request - // This preserves the original request stream for downstream handlers - let rawBody: string | undefined; - - if (request.body) { - // Clone the request to read body without consuming original - const clonedRequest = request.clone(); - rawBody = await clonedRequest.text(); + // Read the exact body bytes from a clone, so the original request + // stream stays readable for downstream handlers. Bytes, not text(): + // decoding would drop a byte-order mark and replace invalid sequences. + // A request without a body is verified as an empty body. A body that + // can't be read (an earlier middleware read or locked it, or the client + // went away) is left out and always refused with a logged 500, even with + // strictRawBody off: no fallback can verify a body nobody can read. + let rawBody: Buffer | undefined; + if (!request.body) { + rawBody = Buffer.alloc(0); + } else if (!request.bodyUsed) { + try { + rawBody = Buffer.from(await request.clone().arrayBuffer()); + } catch (err: unknown) { + // Kept in the debug log, so a locked stream can be told apart from + // a client that went away. + logger.debug({ err, path: url.pathname }, 'Webhook body unreadable'); + rawBody = undefined; + } } + // Read on every request, field by field rather than with a spread, so a + // secret set later, or behind a getter or a prototype, is used. + const webhookOptions: WebhookVerificationOptions = { + secret: options?.secret, + toleranceSeconds: options?.toleranceSeconds, + strictRawBody: + rawBody === undefined || (options?.strictRawBody ?? true), + }; + const verifiableRequest: VerifiableRequest = { method: request.method, url: request.url, @@ -78,15 +111,17 @@ export function createWebhookMiddleware(options?: WebhookVerificationOptions) { query: Object.fromEntries(url.searchParams), // biome-ignore lint/suspicious/noExplicitAny: Headers type compatibility issue headers: Object.fromEntries(request.headers as any), - // Pass raw body string directly for signature verification body: rawBody, }; - const result = verifyWebhookSubscription(verifiableRequest, options); + const result = verifyWebhookSubscription( + verifiableRequest, + webhookOptions, + ); if (!result.success) { - throw new Response(JSON.stringify(result.error), { - status: 401, + throw new Response(JSON.stringify(webhookFailureBody(result.error)), { + status: webhookFailureStatus(result.error?.name), headers: { 'Content-Type': 'application/json' }, }); } diff --git a/packages/app-connect/src/types/verifiable-request.ts b/packages/app-connect/src/types/verifiable-request.ts index 1c9d81464..52bdd4388 100644 --- a/packages/app-connect/src/types/verifiable-request.ts +++ b/packages/app-connect/src/types/verifiable-request.ts @@ -20,9 +20,12 @@ export interface VerifiableRequest { /** * The request body, if any. - * - For Express middleware: pre-parsed object from express.json() - * - For TanStack middleware: raw string from request.text() - * - For Next.js: caller-provided (typically pre-parsed with request.json()) + * - For Express action middleware: pre-parsed object from express.json() + * - For Express webhook middleware: req.rawBody when kept, otherwise req.body + * - For TanStack middleware: raw text (actions) or raw bytes (webhooks) + * - For Next.js: caller-provided (for webhooks, pass Buffer.from(await request.arrayBuffer())) + * + * Webhook signatures are over the raw bytes, so pass a Buffer, ArrayBuffer or string. */ body?: unknown; } diff --git a/packages/app-connect/src/utils/config.ts b/packages/app-connect/src/utils/config.ts index b9893ccdb..9f42ed320 100644 --- a/packages/app-connect/src/utils/config.ts +++ b/packages/app-connect/src/utils/config.ts @@ -1,3 +1,4 @@ +import type { GoDaddyError } from '../types/error-schema'; import { base64ToArrayBuffer } from './strings'; /** @@ -26,6 +27,26 @@ export interface WebhookVerificationOptions { * If not provided, it will be read from the GODADDY_WEBHOOK_SECRET environment variable. */ secret?: string; + + /** + * Refuse a body that is not the raw bytes the platform signed (a string, + * Buffer or ArrayBuffer), instead of falling back to `JSON.stringify` of a + * parsed body. A re-serialized body can differ from what was signed (key + * order, spacing, escapes), so the fallback can refuse real deliveries. + * A missing body (undefined) is refused too, since it usually means the raw + * body was lost; pass `Buffer.alloc(0)` for a request that had no body. + * Off by default for direct calls; the Express and TanStack middleware turn it on. + */ + strictRawBody?: boolean; + + /** + * When set, refuse a delivery whose `webhook-timestamp` (Unix seconds) is more + * than this many seconds away from now. Off by default, because the platform's + * retry timing is not documented and a retried delivery refused as too old is lost. + * Use a few minutes at least: 0 only accepts a delivery checked in the same + * second it was signed, which network delay alone usually misses. + */ + toleranceSeconds?: number; } /** @@ -37,32 +58,108 @@ export const VERIFICATION_CONSTANTS = { DEFAULT_MAX_TIMESTAMP_AGE_SECONDS: 300, // 5 minutes }; +/** Error name for a webhook whose raw body is unavailable under strict verification. */ +export const WEBHOOK_RAW_BODY_REQUIRED = 'WEBHOOK_RAW_BODY_REQUIRED'; + +/** Error name for webhook verification without a configured secret. */ +export const WEBHOOK_SECRET_REQUIRED = 'WEBHOOK_SECRET_REQUIRED'; + +/** Error name for webhook options that would refuse every delivery. */ +export const INVALID_WEBHOOK_OPTIONS = 'INVALID_WEBHOOK_OPTIONS'; + +/** Error name for verification that failed inside the app. */ +export const WEBHOOK_VERIFICATION_FAILED = 'WEBHOOK_VERIFICATION_FAILED'; + /** - * Gets the public key for verification + * The HTTP status to answer a failed webhook verification with. The app's own + * problems (no raw body, no secret, bad options, an internal failure) are + * server errors, so the sender keeps retrying while the app is fixed; + * everything else is 401. The adapters use it; call it from your own handler + * when you use verifyWebhookSubscription directly. */ -export function getPublicKeyBuffer(options?: VerificationOptions): ArrayBuffer { - const publicKey = options?.publicKey || process.env.GODADDY_PUBLIC_KEY; +export function webhookFailureStatus(errorName: string | undefined): 401 | 500 { + return errorName === WEBHOOK_RAW_BODY_REQUIRED || + errorName === WEBHOOK_SECRET_REQUIRED || + errorName === INVALID_WEBHOOK_OPTIONS || + errorName === WEBHOOK_VERIFICATION_FAILED + ? 500 + : 401; +} - if (!publicKey) { - throw new Error( - 'Public key is required for verification. Set GODADDY_PUBLIC_KEY environment variable or provide in options.', - ); +/** + * The body an adapter answers a failed webhook verification with. A setup + * problem gets a generic body with only its correlationId, so an unsigned + * caller learns nothing about how the app is configured; the detail is + * logged with the same correlationId. + */ +export function webhookFailureBody( + err: GoDaddyError | undefined, +): GoDaddyError | undefined { + if (!err || webhookFailureStatus(err.name) !== 500) { + return err; } + return { + name: 'WEBHOOK_VERIFICATION_UNAVAILABLE', + message: 'Webhook verification is not available', + correlationId: err.correlationId, + }; +} - return base64ToArrayBuffer(publicKey); +/** + * Describes an option that would quietly refuse every delivery, such as a + * toleranceSeconds that is NaN or negative. Returns undefined when the + * options are usable. + */ +export function webhookOptionsProblem( + options?: WebhookVerificationOptions, +): string | undefined { + const secret: unknown = options?.secret; + // null and '' mean no secret here, as they always did: GODADDY_WEBHOOK_SECRET is used. + if (secret !== undefined && secret !== null && typeof secret !== 'string') { + return 'secret must be a string'; + } + const strict: unknown = options?.strictRawBody; + if (strict !== undefined && strict !== null && typeof strict !== 'boolean') { + return 'strictRawBody must be true or false'; + } + // null means not set, like undefined. + const tolerance = options?.toleranceSeconds; + if ( + tolerance !== undefined && + tolerance !== null && + (typeof tolerance !== 'number' || + !Number.isFinite(tolerance) || + tolerance < 0) + ) { + return 'toleranceSeconds must be a finite number of seconds, zero or more'; + } + return undefined; } /** - * Gets the webhook secret for verification + * Throws a TypeError for options that would quietly refuse every delivery, + * so middleware fails when it is created rather than on each request. */ -export function getWebhookSecret(options?: WebhookVerificationOptions): string { - const secret = options?.secret || process.env.GODADDY_WEBHOOK_SECRET; +export function checkWebhookOptions( + options?: WebhookVerificationOptions, +): void { + const problem = webhookOptionsProblem(options); + if (problem) { + throw new TypeError(problem); + } +} - if (!secret) { +/** + * Gets the public key for verification + */ +export function getPublicKeyBuffer(options?: VerificationOptions): ArrayBuffer { + const publicKey = options?.publicKey || process.env.GODADDY_PUBLIC_KEY; + + if (!publicKey) { throw new Error( - 'Webhook secret is required for verification. Set GODADDY_WEBHOOK_SECRET environment variable or provide in options.', + 'Public key is required for verification. Set GODADDY_PUBLIC_KEY environment variable or provide in options.', ); } - return secret; + return base64ToArrayBuffer(publicKey); } diff --git a/packages/app-connect/src/utils/verification.ts b/packages/app-connect/src/utils/verification.ts index af337d076..eebabd5ba 100644 --- a/packages/app-connect/src/utils/verification.ts +++ b/packages/app-connect/src/utils/verification.ts @@ -1,5 +1,4 @@ import * as crypto from 'node:crypto'; -import { VerificationError } from '../errors/base-error'; import { ExpiredSignatureError, InvalidAlgorithmError, @@ -12,9 +11,7 @@ import type { VerifiableRequest } from '../types/verifiable-request'; import { VERIFICATION_CONSTANTS, type VerificationOptions, - type WebhookVerificationOptions, getPublicKeyBuffer, - getWebhookSecret, } from './config'; import { logger } from './logger'; import { base64ToArrayBuffer, stringToArrayBuffer } from './strings'; @@ -305,50 +302,6 @@ export async function verifyAction( } } -/** - * Error thrown when a required webhook header is missing - */ -export class MissingWebhookHeaderError extends VerificationError { - constructor(headerName: string) { - super({ - name: 'MISSING_WEBHOOK_HEADER', - message: `Missing required header: ${headerName}`, - details: [ - { - issue: 'MISSING_REQUIRED_HEADER', - description: `The ${headerName} header is required for webhook verification`, - field: headerName, - location: 'header', - }, - ], - }); - } -} - -/** - * Error thrown when webhook signature verification fails - */ -export class InvalidWebhookSignatureError extends VerificationError { - constructor() { - super({ - name: 'INVALID_WEBHOOK_SIGNATURE', - message: 'The webhook signature is invalid', - details: [ - { - issue: 'SIGNATURE_VERIFICATION_FAILED', - description: - 'The webhook signature could not be verified with the provided secret', - field: 'x-godaddy-webhook-signature', - location: 'header', - }, - ], - }); - } -} - -/** - * Verifies a webhook subscription request - */ /** * Recursively stringifies a JavaScript value into a canonical JSON string * that exactly matches Go's json.Marshal(json.Unmarshal(data)) behavior. @@ -411,49 +364,3 @@ export function canonicalJsonStringify(value: unknown): string { return `{${keyValuePairs.join(',')}}`; } - -/** - * Verifies a webhook subscription request - */ -export function verifyWebhookSubscription( - req: VerifiableRequest, - options?: WebhookVerificationOptions, -): Result { - try { - // Get required headers - const signatureHeader = req.headers['x-godaddy-webhook-signature']; - - // Check if required headers exist - if (!signatureHeader) { - return error( - new MissingWebhookHeaderError('x-godaddy-webhook-signature').toJSON(), - ); - } - - // Get the webhook secret - const secret = getWebhookSecret(options); - - // Create string to sign (request body) - const stringToSign = - typeof req.body === 'string' ? req.body : JSON.stringify(req.body || ''); - - // Create the signature - const expectedSignature = crypto - .createHmac('sha256', secret) - .update(stringToSign) - .digest('hex'); - - // Compare signatures - const providedSignature = Array.isArray(signatureHeader) - ? signatureHeader[0] - : (signatureHeader as string); - - if (providedSignature !== expectedSignature) { - return error(new InvalidWebhookSignatureError().toJSON()); - } - - return ok(); - } catch (_err) { - return error(new InvalidWebhookSignatureError().toJSON()); - } -} diff --git a/packages/app-connect/src/utils/webhook.test.ts b/packages/app-connect/src/utils/webhook.test.ts new file mode 100644 index 000000000..7fb4b7ca9 --- /dev/null +++ b/packages/app-connect/src/utils/webhook.test.ts @@ -0,0 +1,491 @@ +import { createHmac } from 'node:crypto'; +import { afterEach, describe, expect, it, vi } from 'vitest'; +import type { VerifiableRequest } from '../types/verifiable-request'; +import { webhookFailureBody, webhookFailureStatus } from './config'; +import { generateHmac, verifyWebhookSubscription } from './webhook'; + +// A known vector: produced by, and accepted by, this verifier before the +// hardening, which signs the way the platform does (the secret as the key, a V1 tag). +const VECTOR = { + secret: 'whsec_vector', + id: 'msg_2Lx', + timestamp: '1795400000', + body: '{"id":"evt_1","type":"commerce.order.created"}', + signature: 'V1,rO5C/aUP8RekUJ6KU0UzdrIqZdiIRqWbn9vGoRYNgDE=', +}; + +function delivery( + body: unknown, + headers: Record = {}, +): VerifiableRequest { + return { + method: 'POST', + url: '/webhooks', + path: '/webhooks', + query: {}, + headers: { + 'webhook-id': VECTOR.id, + 'webhook-timestamp': VECTOR.timestamp, + 'webhook-signature': VECTOR.signature, + ...headers, + }, + body, + }; +} + +function digest(secret: string, id: string, timestamp: string, body: string) { + return createHmac('sha256', secret) + .update(`${id}.${timestamp}.${body}`) + .digest('base64'); +} + +const options = { secret: VECTOR.secret }; + +describe('verifyWebhookSubscription', () => { + afterEach(() => { + vi.useRealTimers(); + }); + + it('accepts the known vector as a string and as raw bytes', () => { + expect( + generateHmac(VECTOR.secret, VECTOR.id, VECTOR.timestamp, VECTOR.body), + ).toBe(VECTOR.signature); + expect(verifyWebhookSubscription(delivery(VECTOR.body), options)).toEqual({ + success: true, + value: undefined, + }); + expect( + verifyWebhookSubscription(delivery(Buffer.from(VECTOR.body)), options) + .success, + ).toBe(true); + expect( + verifyWebhookSubscription( + delivery(new TextEncoder().encode(VECTOR.body)), + options, + ).success, + ).toBe(true); + const bytes = new TextEncoder().encode(VECTOR.body); + for (const body of [bytes.buffer, new DataView(bytes.buffer)]) { + expect( + verifyWebhookSubscription(delivery(body), { + ...options, + strictRawBody: true, + }).success, + ).toBe(true); + } + }); + + it('accepts the lowercase v1 tag the same as V1', () => { + const lower = VECTOR.signature.replace('V1,', 'v1,'); + expect( + verifyWebhookSubscription( + delivery(VECTOR.body, { 'webhook-signature': lower }), + options, + ).success, + ).toBe(true); + }); + + it('refuses a tampered body, id or timestamp', () => { + for (const request of [ + delivery(VECTOR.body.replace('evt_1', 'evt_2')), + delivery(VECTOR.body, { 'webhook-id': 'msg_other' }), + delivery(VECTOR.body, { 'webhook-timestamp': '1795400001' }), + ]) { + const result = verifyWebhookSubscription(request, options); + expect(result.success).toBe(false); + expect(result.error?.name).toBe('INVALID_WEBHOOK_SIGNATURE'); + } + }); + + it('refuses the right signature checked with another secret', () => { + const result = verifyWebhookSubscription(delivery(VECTOR.body), { + secret: 'whsec_other', + }); + expect(result.error?.name).toBe('INVALID_WEBHOOK_SIGNATURE'); + }); + + it('refuses the same JSON with its keys reordered', () => { + const reordered = '{"type":"commerce.order.created","id":"evt_1"}'; + expect(JSON.parse(reordered)).toEqual(JSON.parse(VECTOR.body)); + const result = verifyWebhookSubscription(delivery(reordered), options); + expect(result.error?.name).toBe('INVALID_WEBHOOK_SIGNATURE'); + }); + + it('signs the exact bytes, so a byte-order mark or other bytes count', () => { + const withBom = Buffer.concat([ + Buffer.from([0xef, 0xbb, 0xbf]), + Buffer.from(VECTOR.body), + ]); + expect(verifyWebhookSubscription(delivery(withBom), options).success).toBe( + false, + ); + const signature = `v1,${createHmac('sha256', VECTOR.secret) + .update(`${VECTOR.id}.${VECTOR.timestamp}.`) + .update(withBom) + .digest('base64')}`; + expect( + verifyWebhookSubscription( + delivery(withBom, { 'webhook-signature': signature }), + options, + ).success, + ).toBe(true); + }); + + it('accepts a space-separated list when any v1 entry matches', () => { + const other = `v1,${digest('whsec_old', VECTOR.id, VECTOR.timestamp, VECTOR.body)}`; + for (const header of [ + `${other} ${VECTOR.signature}`, + `${VECTOR.signature} ${other}`, + `v2,${digest(VECTOR.secret, VECTOR.id, VECTOR.timestamp, VECTOR.body)} ${VECTOR.signature}`, + ]) { + expect( + verifyWebhookSubscription( + delivery(VECTOR.body, { 'webhook-signature': header }), + options, + ).success, + ).toBe(true); + } + }); + + it('refuses a list with no matching v1 entry, and malformed entries', () => { + const right = digest( + VECTOR.secret, + VECTOR.id, + VECTOR.timestamp, + VECTOR.body, + ); + for (const header of [ + `v1,${digest('whsec_old', VECTOR.id, VECTOR.timestamp, VECTOR.body)} v1,bm90LXNpZ25lZA==`, + `v2,${right}`, + right, + `,${right}`, + `v1,${right.slice(0, -1)}`, + `v1,${right}x`, + 'v1,', + ]) { + const result = verifyWebhookSubscription( + delivery(VECTOR.body, { 'webhook-signature': header }), + options, + ); + expect(result.error?.name).toBe('INVALID_WEBHOOK_SIGNATURE'); + } + }); + + it('joins repeated signature headers into one list', () => { + const other = `v1,${digest('whsec_old', VECTOR.id, VECTOR.timestamp, VECTOR.body)}`; + expect( + verifyWebhookSubscription( + delivery(VECTOR.body, { + 'webhook-signature': [other, VECTOR.signature], + }), + options, + ).success, + ).toBe(true); + }); + + it('reads a list joined with ", " the way Node joins a repeated header', () => { + const other = `v1,${digest('whsec_old', VECTOR.id, VECTOR.timestamp, VECTOR.body)}`; + for (const header of [ + `${VECTOR.signature}, ${other}`, + `${other}, ${VECTOR.signature}`, + ]) { + expect( + verifyWebhookSubscription( + delivery(VECTOR.body, { 'webhook-signature': header }), + options, + ).success, + ).toBe(true); + } + }); + + it('reads a list joined with a bare comma by an intermediary', () => { + const other = `v1,${digest('whsec_old', VECTOR.id, VECTOR.timestamp, VECTOR.body)}`; + for (const header of [ + `${other},${VECTOR.signature}`, + `${VECTOR.signature},${other}`, + ]) { + expect( + verifyWebhookSubscription( + delivery(VECTOR.body, { 'webhook-signature': header }), + options, + ).success, + ).toBe(true); + } + }); + + it('signs with the first value of a webhook-id or webhook-timestamp joined with ", "', () => { + expect( + verifyWebhookSubscription( + delivery(VECTOR.body, { + 'webhook-id': `${VECTOR.id}, msg_other`, + 'webhook-timestamp': `${VECTOR.timestamp}, 1`, + }), + options, + ).success, + ).toBe(true); + }); + + it('reads header values a hand-built request passes as numbers', () => { + expect( + verifyWebhookSubscription( + delivery(VECTOR.body, { + 'webhook-timestamp': Number(VECTOR.timestamp) as unknown as string, + }), + options, + ).success, + ).toBe(true); + const wrongSignature = verifyWebhookSubscription( + delivery(VECTOR.body, { 'webhook-signature': 42 as unknown as string }), + options, + ); + expect(wrongSignature.success).toBe(false); + if (!wrongSignature.success) { + expect(wrongSignature.error.name).toBe('INVALID_WEBHOOK_SIGNATURE'); + } + }); + + it('answers an internal failure as the app problem it is, not a bad signature', () => { + // A parsed body JSON.stringify can't serialize. + const result = verifyWebhookSubscription( + delivery({ amount: BigInt(1) }), + options, + ); + expect(result.success).toBe(false); + if (result.success) return; + expect(result.error.name).toBe('WEBHOOK_VERIFICATION_FAILED'); + expect(webhookFailureStatus(result.error.name)).toBe(500); + expect(webhookFailureBody(result.error)?.name).toBe( + 'WEBHOOK_VERIFICATION_UNAVAILABLE', + ); + }); + + it('logs a setup problem at error level once, then at debug', async () => { + vi.resetModules(); + const fresh = await import('./webhook'); + const freshLogger = (await import('./logger')).logger; + const errorLog = vi + .spyOn(freshLogger, 'error') + .mockImplementation(() => {}); + const debugLog = vi + .spyOn(freshLogger, 'debug') + .mockImplementation(() => {}); + try { + for (let i = 0; i < 3; i += 1) { + fresh.verifyWebhookSubscription(delivery({ parsed: true }), { + ...options, + strictRawBody: true, + }); + } + expect(errorLog).toHaveBeenCalledTimes(1); + expect(debugLog).toHaveBeenCalledTimes(2); + } finally { + errorLog.mockRestore(); + debugLog.mockRestore(); + } + }); + + it('falls back to GODADDY_WEBHOOK_SECRET for a null or empty secret', () => { + vi.stubEnv('GODADDY_WEBHOOK_SECRET', VECTOR.secret); + try { + for (const secret of [null, '']) { + expect( + verifyWebhookSubscription(delivery(VECTOR.body), { + secret: secret as unknown as string, + }).success, + ).toBe(true); + } + } finally { + vi.unstubAllEnvs(); + } + }); + + it('verifies a body in a SharedArrayBuffer', () => { + const bytes = Buffer.from(VECTOR.body); + const shared = new SharedArrayBuffer(bytes.length); + new Uint8Array(shared).set(bytes); + expect( + verifyWebhookSubscription(delivery(shared), { + ...options, + strictRawBody: true, + }).success, + ).toBe(true); + }); + + it('treats a null toleranceSeconds as not set and refuses a non-boolean strictRawBody', () => { + expect( + verifyWebhookSubscription(delivery(VECTOR.body), { + ...options, + toleranceSeconds: null as unknown as number, + }).success, + ).toBe(true); + const result = verifyWebhookSubscription(delivery(VECTOR.body), { + ...options, + strictRawBody: 'false' as unknown as boolean, + }); + expect(result.error?.name).toBe('INVALID_WEBHOOK_OPTIONS'); + }); + it('returns INVALID_WEBHOOK_OPTIONS for a secret that is not a string', () => { + const result = verifyWebhookSubscription(delivery(VECTOR.body), { + secret: 42 as unknown as string, + }); + expect(result.error?.name).toBe('INVALID_WEBHOOK_OPTIONS'); + }); + + it('signs with the first value of a repeated webhook-id or webhook-timestamp', () => { + expect( + verifyWebhookSubscription( + delivery(VECTOR.body, { + 'webhook-id': [VECTOR.id, 'msg_other'], + 'webhook-timestamp': [VECTOR.timestamp, '1'], + }), + options, + ).success, + ).toBe(true); + }); + + it('reports a missing secret as WEBHOOK_SECRET_REQUIRED, not a bad signature', () => { + vi.stubEnv('GODADDY_WEBHOOK_SECRET', ''); + try { + const result = verifyWebhookSubscription(delivery(VECTOR.body)); + expect(result.error?.name).toBe('WEBHOOK_SECRET_REQUIRED'); + expect(result.error?.correlationId).toEqual(expect.any(String)); + } finally { + vi.unstubAllEnvs(); + } + }); + + it('returns INVALID_WEBHOOK_OPTIONS for a toleranceSeconds that would refuse everything', () => { + for (const toleranceSeconds of [Number.NaN, -1, Number.POSITIVE_INFINITY]) { + const result = verifyWebhookSubscription(delivery(VECTOR.body), { + ...options, + toleranceSeconds, + }); + expect(result.success).toBe(false); + expect(result.error?.name).toBe('INVALID_WEBHOOK_OPTIONS'); + } + }); + + it('names a missing header', () => { + for (const header of [ + 'webhook-signature', + 'webhook-id', + 'webhook-timestamp', + ]) { + const result = verifyWebhookSubscription( + delivery(VECTOR.body, { [header]: undefined }), + options, + ); + expect(result.error?.name).toBe('MISSING_WEBHOOK_HEADER'); + expect(result.error?.details?.[0]?.field).toBe(header); + } + }); + + describe('strictRawBody', () => { + it('refuses a parsed body instead of re-serializing it', () => { + const parsed = JSON.parse(VECTOR.body); + // Without strict mode the legacy fallback re-serializes, which matches here. + expect(verifyWebhookSubscription(delivery(parsed), options).success).toBe( + true, + ); + for (const body of [parsed, undefined, null, 42]) { + const result = verifyWebhookSubscription(delivery(body), { + ...options, + strictRawBody: true, + }); + expect(result.error?.name).toBe('WEBHOOK_RAW_BODY_REQUIRED'); + } + }); + + it('verifies raw strings and bytes as usual', () => { + for (const body of [VECTOR.body, Buffer.from(VECTOR.body)]) { + expect( + verifyWebhookSubscription(delivery(body), { + ...options, + strictRawBody: true, + }).success, + ).toBe(true); + } + }); + + it('still names a missing header first', () => { + const result = verifyWebhookSubscription( + delivery({}, { 'webhook-id': undefined }), + { ...options, strictRawBody: true }, + ); + expect(result.error?.name).toBe('MISSING_WEBHOOK_HEADER'); + }); + }); + + describe('toleranceSeconds', () => { + const sentAt = Number(VECTOR.timestamp) * 1000; + + it('does not check the timestamp age by default', () => { + vi.useFakeTimers(); + vi.setSystemTime(sentAt + 365 * 24 * 3600 * 1000); + expect( + verifyWebhookSubscription(delivery(VECTOR.body), options).success, + ).toBe(true); + }); + + it('accepts a timestamp within the tolerance on either side', () => { + vi.useFakeTimers(); + for (const offset of [-300_000, 0, 300_000]) { + vi.setSystemTime(sentAt + offset); + expect( + verifyWebhookSubscription(delivery(VECTOR.body), { + ...options, + toleranceSeconds: 300, + }).success, + ).toBe(true); + } + }); + + it('refuses a timestamp outside the tolerance', () => { + vi.useFakeTimers(); + for (const offset of [-301_000, 301_000]) { + vi.setSystemTime(sentAt + offset); + const result = verifyWebhookSubscription(delivery(VECTOR.body), { + ...options, + toleranceSeconds: 300, + }); + expect(result.error?.name).toBe('WEBHOOK_TIMESTAMP_OUT_OF_TOLERANCE'); + } + }); + + it('refuses a signed timestamp that is not Unix seconds', () => { + vi.useFakeTimers(); + vi.setSystemTime(sentAt); + const timestamp = '2026-11-23T00:00:00Z'; + const signature = `v1,${digest(VECTOR.secret, VECTOR.id, timestamp, VECTOR.body)}`; + const result = verifyWebhookSubscription( + delivery(VECTOR.body, { + 'webhook-timestamp': timestamp, + 'webhook-signature': signature, + }), + { ...options, toleranceSeconds: 300 }, + ); + expect(result.error?.name).toBe('WEBHOOK_TIMESTAMP_OUT_OF_TOLERANCE'); + }); + + it('reports a bad signature before an old timestamp', () => { + vi.useFakeTimers(); + vi.setSystemTime(sentAt + 3600_000); + const result = verifyWebhookSubscription( + delivery(VECTOR.body, { 'webhook-signature': 'v1,bm90LXNpZ25lZA==' }), + { ...options, toleranceSeconds: 300 }, + ); + expect(result.error?.name).toBe('INVALID_WEBHOOK_SIGNATURE'); + }); + }); + + it('reads the secret from GODADDY_WEBHOOK_SECRET', () => { + vi.stubEnv('GODADDY_WEBHOOK_SECRET', VECTOR.secret); + try { + expect(verifyWebhookSubscription(delivery(VECTOR.body)).success).toBe( + true, + ); + } finally { + vi.unstubAllEnvs(); + } + }); +}); diff --git a/packages/app-connect/src/utils/webhook.ts b/packages/app-connect/src/utils/webhook.ts index 6cc6b81c0..7e6bbff1d 100644 --- a/packages/app-connect/src/utils/webhook.ts +++ b/packages/app-connect/src/utils/webhook.ts @@ -1,9 +1,18 @@ import * as crypto from 'node:crypto'; +import { types } from 'node:util'; import { type Result, error, ok } from '../types/result'; import type { VerifiableRequest } from '../types/verifiable-request'; import { VerificationError } from '../errors/base-error'; -import type { WebhookVerificationOptions } from './config'; +import { + INVALID_WEBHOOK_OPTIONS, + WEBHOOK_RAW_BODY_REQUIRED, + WEBHOOK_SECRET_REQUIRED, + WEBHOOK_VERIFICATION_FAILED, + type WebhookVerificationOptions, + webhookFailureStatus, + webhookOptionsProblem, +} from './config'; import { logger } from './logger'; /** @@ -55,23 +64,165 @@ export class MissingWebhookHeaderError extends VerificationError { } } +/** + * Error returned when the webhook timestamp is outside the configured tolerance + */ +export class WebhookTimestampOutOfToleranceError extends VerificationError { + constructor({ + toleranceSeconds, + correlationId, + }: { + toleranceSeconds: number; + correlationId?: string; + }) { + super({ + name: 'WEBHOOK_TIMESTAMP_OUT_OF_TOLERANCE', + message: 'The webhook timestamp is outside the allowed tolerance', + correlationId, + details: [ + { + issue: 'TIMESTAMP_OUT_OF_TOLERANCE', + description: `The webhook-timestamp header must be Unix seconds within ${toleranceSeconds} seconds of now`, + field: 'webhook-timestamp', + location: 'header', + }, + ], + }); + } +} + +/** + * Error returned when strict raw-body verification is on and the request body + * is not the raw bytes the platform signed (a string or a Buffer) + */ +export class WebhookRawBodyRequiredError extends VerificationError { + constructor({ correlationId }: { correlationId?: string } = {}) { + super({ + name: WEBHOOK_RAW_BODY_REQUIRED, + message: + 'The raw webhook request body is required to verify the signature', + correlationId, + details: [ + { + issue: 'RAW_BODY_UNAVAILABLE', + description: + "The body was already parsed or is missing. Pass the raw body as a string or Buffer, for example from express.raw({ type: 'application/json' }), or from express.json() with a verify hook that keeps req.rawBody", + location: 'body', + }, + ], + }); + } +} + +/** + * Error thrown when no webhook secret is configured. It is the app's setup + * problem, not the sender's, so adapters answer it with 500. + */ +export class WebhookSecretRequiredError extends VerificationError { + constructor({ correlationId }: { correlationId?: string } = {}) { + super({ + name: WEBHOOK_SECRET_REQUIRED, + message: + 'Webhook secret is required. Provide it via options or GODADDY_WEBHOOK_SECRET environment variable', + correlationId, + }); + } +} + +/** + * Error returned when webhook options would refuse every delivery, such as a + * toleranceSeconds that is NaN or negative. Adapters answer it with 500. + */ +export class InvalidWebhookOptionsError extends VerificationError { + constructor({ + problem, + correlationId, + }: { + problem: string; + correlationId?: string; + }) { + super({ + name: INVALID_WEBHOOK_OPTIONS, + message: `Invalid webhook verification options: ${problem}`, + correlationId, + }); + } +} + +/** + * Error returned when verification itself failed inside the app, for example a + * body that can't be serialized. It isn't the sender's fault, so adapters + * answer it with 500 and the sender retries. + */ +export class WebhookVerificationFailedError extends VerificationError { + constructor({ correlationId }: { correlationId?: string } = {}) { + super({ + name: WEBHOOK_VERIFICATION_FAILED, + message: 'Webhook verification failed with an internal error', + correlationId, + }); + } +} + /** * Get the webhook secret from options or environment - * @throws Error if no webhook secret is available + * @param correlationId Carried on the error, to match it with the request's logs + * @throws WebhookSecretRequiredError if no webhook secret is available */ -export function getWebhookSecret(options?: WebhookVerificationOptions): string { +export function getWebhookSecret( + options?: WebhookVerificationOptions, + correlationId?: string, +): string { // Try to get the webhook secret from options first const secret = options?.secret || process.env.GODADDY_WEBHOOK_SECRET; if (!secret) { - throw new Error( - 'Webhook secret is required. Provide it via options or GODADDY_WEBHOOK_SECRET environment variable', - ); + throw new WebhookSecretRequiredError({ correlationId }); } return secret; } +/** + * Returns the signed payload bytes. Buffers, byte arrays, ArrayBuffers and + * strings are used as they are. Any other value is the legacy fallback: an object is + * JSON-stringified, which only matches when the sender serialized it the same way. + */ +function payloadBytes(payload: unknown): Buffer { + if (payload === undefined || payload === null) { + return Buffer.alloc(0); + } + if (Buffer.isBuffer(payload)) { + return payload; + } + if (ArrayBuffer.isView(payload)) { + return Buffer.from(payload.buffer, payload.byteOffset, payload.byteLength); + } + if (types.isAnyArrayBuffer(payload)) { + return Buffer.from(payload); + } + if (typeof payload === 'string') { + return Buffer.from(payload, 'utf8'); + } + if (typeof payload === 'object') { + return Buffer.from(JSON.stringify(payload), 'utf8'); + } + return Buffer.from(String(payload), 'utf8'); +} + +function hmacBase64( + secret: string, + webhookId: string, + timestamp: string, + payload: unknown, +): string { + return crypto + .createHmac('sha256', secret) + .update(`${webhookId}.${timestamp}.`, 'utf8') + .update(payloadBytes(payload)) + .digest('base64'); +} + /** * Generates an HMAC signature for webhook verification * @@ -79,7 +230,7 @@ export function getWebhookSecret(options?: WebhookVerificationOptions): string { * @param webhookId The webhook ID from the request header * @param timestamp The timestamp from the request header * @param payload The request body - * @returns The generated HMAC signature + * @returns The generated HMAC signature, `V1,` */ export function generateHmac( secret: string, @@ -87,34 +238,99 @@ export function generateHmac( timestamp: string, payload: Buffer | string | Record | unknown, ): string { - let payloadStr: string; + return `V1,${hmacBase64(secret, webhookId, timestamp, payload)}`; +} - if (payload === undefined || payload === null) { - payloadStr = ''; - } else if (Buffer.isBuffer(payload)) { - payloadStr = payload.toString(); - } else if (typeof payload === 'string') { - payloadStr = payload; - } else if (typeof payload === 'object') { - // Handle objects by JSON stringifying them - payloadStr = JSON.stringify(payload); - } else { - // Convert anything else to string - payloadStr = String(payload); - } - - const toSignStr = `${webhookId}.${timestamp}.${payloadStr}`; - const toSignBytes = Buffer.from(toSignStr); - const hmacDigest = crypto - .createHmac('sha256', secret) - .update(toSignBytes) - .digest(); - return `V1,${hmacDigest.toString('base64')}`; +/** + * Compares two strings in constant time when they have the same length. The + * length check leaks only the length, which is fixed for a base64 HMAC-SHA256. + */ +function constantTimeEqual(given: string, expected: string): boolean { + const givenBytes = Buffer.from(given, 'utf8'); + const expectedBytes = Buffer.from(expected, 'utf8'); + return ( + givenBytes.length === expectedBytes.length && + crypto.timingSafeEqual(givenBytes, expectedBytes) + ); } +/** + * Checks a `webhook-signature` header value against the expected digest. The + * header may hold several space-separated `v1,` entries, for example + * during a secret rotation, and a match on any one of them passes. The version + * tag is read without regard to case, so the platform's `V1,` and the `v1,` + * form both work. Entries with any other version are ignored. A trailing comma + * is dropped from each entry, because Node and the Fetch API join a repeated + * header with ", ", and base64 never ends in a comma. + */ +function signatureMatches(header: string, expectedDigest: string): boolean { + let matched = false; + // Split on whitespace, and on a bare comma that starts another entry: an + // intermediary may join repeated headers with "," alone. Base64 has no comma. + for (const listed of header.split(/\s+|,(?=v\d+,)/i)) { + const entry = listed.endsWith(',') ? listed.slice(0, -1) : listed; + const comma = entry.indexOf(','); + if (comma <= 0 || entry.slice(0, comma).toLowerCase() !== 'v1') { + continue; + } + // Every entry is checked, so the time taken doesn't depend on which one matched. + if (constantTimeEqual(entry.slice(comma + 1), expectedDigest)) { + matched = true; + } + } + return matched; +} + +function isRawBody(body: unknown): boolean { + return ( + typeof body === 'string' || + ArrayBuffer.isView(body) || + types.isAnyArrayBuffer(body) + ); +} + +/** + * A single-valued header: the first value when it was sent more than once, + * whether as an array or joined with commas the way Node and Fetch join a + * repeated header. Platform ids and Unix timestamps never contain a comma. + */ +function firstHeaderValue(value: unknown): string | undefined { + const first: unknown = Array.isArray(value) ? value[0] : value; + // A hand-built request may carry a number; read it as text, as before. + return first === undefined || first === null + ? undefined + : String(first).split(',')[0]?.trim(); +} + +/** The signature header: repeated values are one list. */ +function signatureHeaderValue(value: unknown): string | undefined { + if (Array.isArray(value)) { + return value.length > 0 ? value.map(String).join(' ') : undefined; + } + return value === undefined || value === null ? undefined : String(value); +} + +function timestampWithinTolerance( + timestamp: string, + toleranceSeconds: number, +): boolean { + if (!/^\d+$/.test(timestamp)) { + return false; + } + const nowSeconds = Math.floor(Date.now() / 1000); + return Math.abs(nowSeconds - Number(timestamp)) <= toleranceSeconds; +} + +/** Setup error names already logged at error level in this process. */ +const setupErrorsLogged = new Set(); + /** * Verifies a webhook subscription request using GoDaddy's HMAC signing mechanism * + * The signature is `v1,` over + * `..`, keyed with the webhook secret, + * and is compared in constant time. + * * @param req The request to verify * @param options Options for verification including webhook secret * @returns Result indicating success or failure with appropriate error @@ -124,125 +340,124 @@ export function verifyWebhookSubscription( options?: WebhookVerificationOptions, ): Result { const correlationId = crypto.randomUUID(); + // The body and headers are never logged: the body can hold shopper data. + const logContext = { correlationId, method: req.method, path: req.path }; + + const fail = (err: VerificationError, message: string): Result => { + // The app's own setup problems are logged as errors, with the detail the + // adapters leave out of the response. + if (webhookFailureStatus(err.name) === 500) { + // Once per kind at error level, then debug: unsigned requests to a + // misconfigured route can't flood the error log. + const first = !setupErrorsLogged.has(err.name); + setupErrorsLogged.add(err.name); + logger[first ? 'error' : 'debug']( + { ...logContext, error: err.name, detail: err.message }, + message, + ); + } else { + logger.debug({ ...logContext, error: err.name }, message); + } + return error(err.toJSON()); + }; + + const problem = webhookOptionsProblem(options); + if (problem) { + return fail( + new InvalidWebhookOptionsError({ problem, correlationId }), + 'Webhook verification failed - invalid options', + ); + } // Extract required headers - const signature = req.headers['webhook-signature']; - const webhookId = req.headers['webhook-id']; - const timestamp = req.headers['webhook-timestamp']; + const signature = signatureHeaderValue(req.headers['webhook-signature']); + const webhookId = firstHeaderValue(req.headers['webhook-id']); + const timestamp = firstHeaderValue(req.headers['webhook-timestamp']); // Check all required headers exist if (!signature) { - const err = new MissingWebhookHeaderError({ - headerName: 'webhook-signature', - correlationId, - }); - logger.debug( - { - error: err.name, + return fail( + new MissingWebhookHeaderError({ + headerName: 'webhook-signature', correlationId, - request: req, - }, + }), 'Webhook verification failed - missing signature header', ); - return error(err.toJSON()); } if (!webhookId) { - const err = new MissingWebhookHeaderError({ - headerName: 'webhook-id', - correlationId, - }); - logger.debug( - { - error: err.name, + return fail( + new MissingWebhookHeaderError({ + headerName: 'webhook-id', correlationId, - request: req, - }, + }), 'Webhook verification failed - missing webhook-id header', ); - return error(err.toJSON()); } if (!timestamp) { - const err = new MissingWebhookHeaderError({ - headerName: 'webhook-timestamp', - correlationId, - }); - logger.debug( - { - error: err.name, + return fail( + new MissingWebhookHeaderError({ + headerName: 'webhook-timestamp', correlationId, - request: req, - }, + }), 'Webhook verification failed - missing webhook-timestamp header', ); - return error(err.toJSON()); + } + + if (options?.strictRawBody === true && !isRawBody(req.body)) { + return fail( + new WebhookRawBodyRequiredError({ correlationId }), + 'Webhook verification failed - raw body unavailable', + ); } try { // Get the webhook secret - const secret = getWebhookSecret(options); - - // Convert headers to string if they're arrays - const signatureStr = Array.isArray(signature) - ? signature[0] - : (signature as string); - const webhookIdStr = Array.isArray(webhookId) - ? webhookId[0] - : (webhookId as string); - const timestampStr = Array.isArray(timestamp) - ? timestamp[0] - : (timestamp as string); - - // Generate the expected HMAC signature - const expectedSignature = generateHmac( - secret, - webhookIdStr, - timestampStr, - req.body || '', - ); + const secret = getWebhookSecret(options, correlationId); - // Compare signatures - if (signatureStr !== expectedSignature) { - const err = new InvalidWebhookSignatureError({ correlationId }); - logger.debug( - { - error: err.name, - correlationId, - request: req, - }, + const expectedDigest = hmacBase64(secret, webhookId, timestamp, req.body); + + if (!signatureMatches(signature, expectedDigest)) { + return fail( + new InvalidWebhookSignatureError({ correlationId }), 'Webhook verification failed - invalid signature', ); - return error(err.toJSON()); + } + + // Checked after the signature, so only a signed timestamp is judged. + const toleranceSeconds = options?.toleranceSeconds; + if ( + toleranceSeconds !== undefined && + toleranceSeconds !== null && + !timestampWithinTolerance(timestamp, toleranceSeconds) + ) { + return fail( + new WebhookTimestampOutOfToleranceError({ + toleranceSeconds, + correlationId, + }), + 'Webhook verification failed - timestamp outside tolerance', + ); } return ok(undefined); } catch (err) { if (err instanceof VerificationError) { - logger.debug( - { - error: err.name, - correlationId, - request: req, - }, - 'Webhook verification error', - ); - return error(err.toJSON()); + return fail(err, 'Webhook verification error'); } - // Generic verification failure - const verificationError = new InvalidWebhookSignatureError({ - correlationId, - }); - logger.debug( - { - originalError: err, - error: verificationError.name, - correlationId, - request: req, - }, - 'Webhook verification error - generic failure', + // An internal failure is the app's problem, not a bad signature: 500, so + // the sender retries. Throttled like the other setup errors; the stack is + // in every entry, at error level the first time. + const first = !setupErrorsLogged.has(WEBHOOK_VERIFICATION_FAILED); + setupErrorsLogged.add(WEBHOOK_VERIFICATION_FAILED); + logger[first ? 'error' : 'debug']( + { ...logContext, error: WEBHOOK_VERIFICATION_FAILED, err }, + 'Webhook verification error - internal failure', + ); + return error( + new WebhookVerificationFailedError({ correlationId }).toJSON(), ); - return error(verificationError.toJSON()); } }