Track 06 · Lesson 8 of 8APIs and servers
Securing webhooks
Lesson 8 of 8· 8 min
A webhook endpoint is a public URL that moves money or data when it’s called. Anyone who finds it can send it fake events. Three checks separate real events from forged, tampered, replayed and duplicated ones.
Real or fake?
Real HMAC signatures, computed in your browser
// Node: verify before trusting anything in the body
const [t, sig] = parse(req.headers["webhook-signature"])
const expected = createHmac("sha256", SECRET).update(`${t}.${rawBody}`).digest("hex")
if (!timingSafeEqual(Buffer.from(sig), Buffer.from(expected))) return res.status(400).end()
if (Date.now() / 1000 - Number(t) > 300) return res.status(400).end() // replay
if (await seen(event.id)) return res.status(200).end() // duplicate
await queue.add(event) // do the slow work later
res.status(200).end() // answer fast, or the provider retries1. Verify the signature#
The provider and you share a secret. For each event, it computes an HMAC of the timestamp and the exact raw body, and sends it in a header. You compute the same HMAC and compare. A forger without the secret can’t produce a valid one, and changing a single character of the body changes the result completely.
Compare with a constant-time function (timingSafeEqual in Node) and use the raw body: parsing and re-serialising JSON changes spacing and breaks the signature.
2. Check the timestamp#
A valid signature only proves the provider sent this event once. An attacker who captured a real request can send it again tomorrow. Because the timestamp is part of what’s signed, rejecting anything older than a few minutes stops replays.
3. Process each event once#
Retries are normal, so the same event will arrive more than once. Record each event id you’ve processed and answer 200 without doing anything when it comes again.
Check yourself