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
23 changes: 23 additions & 0 deletions src/webhooks/webhooks.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -447,6 +447,29 @@ describe('Webhook signatures', () => {

expect(webhook.id).toEqual('wh_123');
});

it.each([
['null', 'null'],
['array', '[]'],
['number', '42'],
['missing id', JSON.stringify({ event: 'user.created', data: {} })],
['missing event', JSON.stringify({ id: 'wh_1', data: {} })],
[
'non-object data',
JSON.stringify({ id: 'wh_1', event: 'user.created', data: null }),
],
])('rejects invalid verified JSON shape (%s)', async (_label, rawBody) => {
const hash = signRaw(rawBody, timestamp, secret);
const sigHeader = `t=${timestamp}, v1=${hash}`;

await expect(
workos.webhooks.constructEvent({
payload: rawBody,
sigHeader,
secret,
}),
).rejects.toThrow(/Webhook payload must/);
});
});
});
// @oagen-ignore-end
Expand Down
26 changes: 23 additions & 3 deletions src/webhooks/webhooks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -177,10 +177,30 @@ export class Webhooks {
// Parse only after verification succeeds — a malformed body never reaches
// JSON.parse on an unauthenticated request.
private parseVerifiedPayload(payload: WebhookPayload): EventResponse {
if (typeof payload === 'object' && !isBinaryPayload(payload)) {
return payload as unknown as EventResponse;
const parsed: unknown =
typeof payload === 'object' && !isBinaryPayload(payload)
? payload
: JSON.parse(decodePayloadToString(payload));
if (
typeof parsed !== 'object' ||
parsed === null ||
Array.isArray(parsed)
) {
throw new Error('Webhook payload must be a JSON object');
}
return JSON.parse(decodePayloadToString(payload)) as EventResponse;
const record = parsed as Record<string, unknown>;
if (
typeof record.id !== 'string' ||
typeof record.event !== 'string' ||
typeof record.data !== 'object' ||
record.data === null ||
Array.isArray(record.data)
) {
throw new Error(
'Webhook payload must include string id, string event, and object data',
);
}
return parsed as unknown as EventResponse;
}
// @oagen-ignore-end
}