Implement webhooks with signature headers
Implement webhooks with a signature header that signs the timestamp and the body together, so receivers can reject tampered and replayed requests.
A signature over the body alone proves who sent it, but not when. An attacker who captures a valid request can replay it later. Signing a timestamp with the body closes that gap.
import { createHmac, timingSafeEqual } from 'node:crypto';
const secret = 'whsec_demo';
function sign(body, timestamp) {
const mac = createHmac('sha256', secret).update(`${timestamp}.${body}`).digest('hex');
return `t=${timestamp},v1=${mac}`;
}
function verify(header, body, now, toleranceSec = 300) {
const parts = Object.fromEntries(header.split(',').map((p) => p.split('=')));
if (Math.abs(now - Number(parts.t)) > toleranceSec) return false;
const expected = createHmac('sha256', secret).update(`${parts.t}.${body}`).digest();
const received = Buffer.from(parts.v1, 'hex');
return received.length === expected.length && timingSafeEqual(received, expected);
}
const body = '{"event":"paid"}';
const header = sign(body, 1_700_000_000);
console.log(verify(header, body, 1_700_000_100));
console.log(verify(header, body, 1_700_001_000));
console.log(verify(header, '{"event":"refund"}', 1_700_000_100));true
false
falseThe first check passes: the signature is valid and the request is 100 seconds old. The second is rejected as too old, even though the signature is correct, and the third fails because the body changed.
The header format, t=...,v1=..., is the one Stripe uses, and the v1 label leaves room for a new scheme later. Send the header as X-Signature or a name of your choosing, and give receivers a way to rotate the secret.