Skip to content
Open
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
11 changes: 11 additions & 0 deletions .changeset/commex-2359-webhook-verify.md
Original file line number Diff line number Diff line change
@@ -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.
2 changes: 1 addition & 1 deletion AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
105 changes: 85 additions & 20 deletions packages/app-connect/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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',
Expand All @@ -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) => {
Expand Down Expand Up @@ -188,30 +201,44 @@ function processActionRequest(req) {
#### Webhook Verification

```typescript
import { verifyWebhookSubscription, VerifiableRequest } from '@godaddy/app-connect';

function processWebhookSubscription(req) {
// Create a verifiable request object
import {
verifyWebhookSubscription,
webhookFailureBody,
webhookFailureStatus,
VerifiableRequest,
} from '@godaddy/app-connect';

// An Express route handler that calls the verifier directly
function processWebhookSubscription(req, res) {
// 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
// Keep the detail in your own logs. The sender gets what the middleware
// would answer: 500 with a generic body for the app's own setup problems,
// 401 otherwise, so an unsigned caller never sees how the app is set up.
console.error('Webhook verification failed:', result.error);
return { error: result.error };
return res
.status(webhookFailureStatus(result.error?.name))
.json(webhookFailureBody(result.error));
}

// Process verified webhook
return { success: true };
return res.json({ received: true });
}
```

Expand All @@ -233,7 +260,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,<base64 HMAC-SHA256>` of `<webhook-id>.<webhook-timestamp>.<raw body>`, 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.

Expand Down Expand Up @@ -261,13 +293,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

Expand All @@ -285,6 +343,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

Expand Down
192 changes: 192 additions & 0 deletions packages/app-connect/src/express/index.test.ts
Original file line number Diff line number Diff line change
@@ -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<string, string | undefined> = HEADERS,
): Request {
return {
method: 'POST',
url: '/webhooks',
originalUrl: '/webhooks',
path: '/webhooks',
query: {},
headers,
...fields,
} as unknown as Request;
}

function run(
req: Request,
options: Parameters<typeof createWebhookMiddleware>[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();
});
});
Loading