Webhook HMAC Signature Verification

Verify a hex HMAC signature over a webhook body with a timestamp tolerance, using constant-time comparison.

JavascriptSecurity Boundaries

Code

javascriptsnippet
15 lines
import { createHmac, timingSafeEqual } from 'node:crypto';

export function verifyWebhook({ body, signature, timestamp, secret, toleranceMs = 300000, now = Date.now() }) {
  if (typeof body !== 'string' || typeof signature !== 'string' || typeof secret !== 'string') {
    throw new TypeError('body, signature and secret must be strings');
  }
  const ts = Number(timestamp);
  if (!Number.isFinite(ts)) throw new TypeError('timestamp must be numeric');
  if (Math.abs(now - ts) > toleranceMs) return { ok: false, reason: 'timestamp out of tolerance' };
  const expected = createHmac('sha256', secret).update(ts + '.' + body).digest('hex');
  const a = Buffer.from(expected, 'hex');
  const b = Buffer.from(signature, 'hex');
  if (a.length !== b.length) return { ok: false, reason: 'signature length mismatch' };
  return timingSafeEqual(a, b) ? { ok: true } : { ok: false, reason: 'signature mismatch' };
}

How it works

Webhook HMAC Signature Verification is built around the function verifyWebhook.

The import names the platform contact area: createHmac, timingSafeEqual, all from node:crypto. A guard precedes the TypeError: bad state stops the flow there instead of continuing.

The result comes back as an object carrying false.

What to watch for

  • The dependency surface is just node:crypto, and that one is built into Node.js.
  • crypto exist only in browsers — a Node runtime has no shims for them out of the box.
  • The guard typeof body !== 'string' || typeof signature !== 'string' || typeof… short-circuits the flow with an early throw when its condition holds.

Applying it

Entry signature: export function verifyWebhook({ body, signature, timestamp, secret, toleranceMs = 300000, now = Date.now()

Treat verifyWebhook as the API: import it, and ignore the supporting code.

The call returns false.

Statements that matter

if (Math.abs(now - ts) > toleranceMs) return { ok: false, reason: 'timestamp out of tolerance' };
return timingSafeEqual(a, b) ? { ok: true } : { ok: false, reason: 'signature mismatch' };
if (a.length !== b.length) return { ok: false, reason: 'signature length mismatch' };

Interactive Tools for This Topic

FAQ

Does `verifyWebhook` modify its input?
No. The code builds and returns a new value and leaves the arguments untouched, so it is safe to call on shared or frozen data structures.
What does the snippet do with malformed data?
The code throws `TypeError` — the guard `typeof body !== 'string' || typeof signature !== 'string'…` rejects bad states before the main logic runs. Handle it at the call site or let it propagate deliberately.
Does this require external packages?
No — `node:crypto` is a Node.js built-in module; nothing to install.