Verifying webhooks correctly: signature, replay, duplicates
Published · 2 min read
A webhook endpoint is a public URL that triggers business logic, such as marking an invoice paid. If you skip any of the three checks below, someone can fake or replay events. HMAC signatures are the standard answer, but a signature alone only proves who sent it, not when or how often.
npm install @sandsoftwaresolutions/webhooks
sign(payload, secret) returns sha256=<hex> using Web Crypto, and verify(payload, signature, secret) returns a boolean using a constant-time comparison. The package works in Node 18+, workers and browsers. Everything else (timestamps, duplicates) is protocol you add, and this article shows how.
The receiver and a test that attacks it
import { createServer } from "node:http";
import { sign, verify } from "@sandsoftwaresolutions/webhooks";
const SECRET = "a-long-random-secret-from-your-env";
const TOLERANCE_S = 300;
const seen = new Set(); // use a database or Redis with an expiry in real life
const receiver = createServer(async (req, res) => {
const chunks = []; for await (const c of req) chunks.push(c);
const raw = Buffer.concat(chunks).toString("utf8");
const ts = req.headers["x-timestamp"], id = req.headers["x-event-id"];
// We sign "timestamp.body", so the timestamp cannot be swapped.
if (!(await verify(`${ts}.${raw}`, req.headers["x-signature"], SECRET))) { res.statusCode = 401; return res.end("bad signature"); }
if (Math.abs(Date.now() / 1000 - Number(ts)) > TOLERANCE_S) { res.statusCode = 400; return res.end("too old"); }
if (seen.has(id)) { res.statusCode = 200; return res.end("duplicate, ignored"); }
seen.add(id);
res.end("processed " + JSON.parse(raw).event);
}).listen(0);
await new Promise((r) => receiver.once("listening", r));
const url = `http://127.0.0.1:${receiver.address().port}`;
async function send(body, { ts = Math.floor(Date.now() / 1000), id = "evt_1", secret = SECRET, tamper } = {}) {
const raw = JSON.stringify(body);
const signature = await sign(`${ts}.${raw}`, secret);
const r = await fetch(url, { method: "POST", headers: { "x-timestamp": String(ts), "x-event-id": id, "x-signature": signature }, body: tamper ? raw.replace("10", "1000") : raw });
return `${r.status} ${await r.text()}`;
}
console.log("valid :", await send({ event: "invoice.paid", amount: 10 }));
console.log("replayed :", await send({ event: "invoice.paid", amount: 10 }));
console.log("tampered :", await send({ event: "invoice.paid", amount: 10 }, { id: "evt_2", tamper: true }));
console.log("wrong key :", await send({ event: "invoice.paid", amount: 10 }, { id: "evt_3", secret: "other" }));
console.log("old (1h) :", await send({ event: "invoice.paid", amount: 10 }, { id: "evt_4", ts: Math.floor(Date.now() / 1000) - 3600 }));
receiver.close();
Real output:
valid : 200 processed invoice.paid
replayed : 200 duplicate, ignored
tampered : 401 bad signature
wrong key : 401 bad signature
old (1h) : 400 too old
The three checks, and the mistake behind each
1. Verify the signature over the raw body. The most common bug: the framework parses JSON, you re-serialise it, and the bytes differ from what was signed (key order, whitespace, unicode escapes), so valid events fail, or worse, someone "fixes" it by skipping verification. Read the raw text first, verify, and only then JSON.parse. In the demo, the "tampered" request changes 10 to 1000 and is rejected.
2. Bind a timestamp into what's signed. We sign `${timestamp}.${body}`, not just the body. If the timestamp were a separate unsigned header, an attacker who captured one valid request could replay it forever with a fresh timestamp. Because it is signed, the receiver can reject anything older than a tolerance (5 minutes here). The "old (1h)" request has a valid signature and is still refused. The tolerance also bounds how long you must remember event ids.
3. De-duplicate by event id. Senders retry, and networks duplicate. Processing invoice.paid twice is a real bug. Store seen ids (a database table with a unique constraint, or Redis with an expiry slightly longer than your timestamp tolerance) and return 200 for duplicates: a 4xx would make the sender keep retrying. The demo uses an in-memory Set and says so; that is fine for a demo and wrong for more than one process or a restart.
Smaller details
- Respond quickly. Acknowledge with 2xx first, then do heavy work from a queue. Many senders time out after a few seconds and retry, which creates the duplicates from check 3.
- Use a long random secret from the environment, rotate it by accepting two secrets for a while, and use a separate secret per endpoint or customer.
- Don't log the signature header or the secret. Anyone who can read your logs shouldn't be able to forge events.
- Sending webhooks yourself? Use the same
signover`${timestamp}.${body}`, sendx-timestamp,x-event-id, andx-signature, and document the tolerance. Receivers shouldn't have to guess your protocol. - Third-party webhooks (Stripe, GitHub, …) have their own signature formats. Use that vendor's documented method rather than this one; the three principles above are exactly what they implement.