Verify Webhook HMAC Signatures Safely

Sign and verify webhook payloads with HMAC-SHA256, timestamp tolerance and constant-time comparison to block replay attacks.

TypescriptSecurity Boundaries

Code

typescriptsnippet
58 lines
import { createHmac, timingSafeEqual } from "node:crypto";

export interface SignatureOptions {
  readonly secret: string;
  readonly toleranceSeconds?: number;
  readonly now?: number;
}

export function signWebhook(payload: string, timestamp: number, secret: string): string {
  if (typeof secret !== "string" || secret.length < 16) {
    throw new RangeError("secret must contain at least 16 characters");
  }
  if (!Number.isInteger(timestamp)) throw new TypeError("timestamp must be an integer");
  const signature = createHmac("sha256", secret).update(`${timestamp}.${payload}`).digest("hex");
  return `t=${timestamp},v1=${signature}`;
}

export function verifyWebhook(payload: string, header: string, options: SignatureOptions): boolean {
  if (typeof header !== "string") throw new TypeError("header must be a string");
  const { secret, toleranceSeconds = 300, now = Date.now() } = options;
  if (typeof secret !== "string" || secret.length < 16) {
    throw new RangeError("secret must contain at least 16 characters");
  }
  const parts = new Map<string, string>();
  for (const part of header.split(",")) {
    const equals = part.indexOf("=");
    if (equals === -1) continue;
    parts.set(part.slice(0, equals).trim(), part.slice(equals + 1).trim());
  }
  const timestampText = parts.get("t");
  const provided = parts.get("v1");
  if (timestampText === undefined || provided === undefined) return false;
  const timestamp = Number(timestampText);
  if (!Number.isInteger(timestamp)) return false;
  if (Math.abs(now / 1000 - timestamp) > toleranceSeconds) return false;
  const expected = createHmac("sha256", secret).update(`${timestamp}.${payload}`).digest("hex");
  const left = fromHex(expected);
  const right = fromHex(provided);
  if (left.length === 0 || left.length !== right.length) return false;
  return timingSafeEqual(left, right);
}

function fromHex(value: string): Uint8Array {
  if (value.length % 2 !== 0 || !/^[0-9a-f]*$/i.test(value)) return new Uint8Array(0);
  const bytes = new Uint8Array(value.length / 2);
  for (let index = 0; index < bytes.length; index += 1) {
    bytes[index] = Number.parseInt(value.slice(index * 2, index * 2 + 2), 16);
  }
  return bytes;
}

const secret = "0123456789abcdef0123456789abcdef";
const payload = JSON.stringify({ event: "invoice.paid", id: "evt_42" });
const header = signWebhook(payload, 1760000000, secret);
console.log(header);
console.log(verifyWebhook(payload, header, { secret, now: 1760000100 * 1000 }));
console.log(verifyWebhook(`${payload} `, header, { secret, now: 1760000100 * 1000 }));
console.log(verifyWebhook(payload, header, { secret, toleranceSeconds: 10, now: 1760000100 * 1000 }));

Output

Captured from a sandboxed run of this snippet in the build pipeline.

t=1760000000,v1=fe5505726c1a1fa7c77d1dbc783115f4b348f5e92c5e361fcfede2e8e2294c28
true
false
false

What the snippet contains

signWebhook builds the t=...,v1=... header via createHmac("sha256", secret).update(${timestamp}.${payload}), and verifyWebhook re-derives the digest, checks the timestamp tolerance, and compares the two hex pairs through fromHex plus timingSafeEqual.

The structure is a loop within a loop: for (const part of header.split(",")) outside, for (let index = 0; index < bytes.length; index += 1) inside. The only import source is node:crypto, a Node.js built-in, exposing createHmac, timingSafeEqual. RangeError and TypeError is the guard’s signal — thrown at the branch, before any partial work happens.

The result is a fresh construction, so callers can keep their originals.

Watch out for

  • node:crypto is a Node.js built-in module — it ships with the runtime, so there is nothing to install.
  • createHmac and timingSafeEqual come from node:crypto, a Node.js built-in — this is server-side code that runs in Node, not a browser API.
  • The guard typeof secret !== "string" || secret.length < 16 short-circuits the flow with an early throw when its condition holds.

Putting it to use

Entry signature: export function signWebhook(payload: string, timestamp: number, secret: string)

signWebhook is the public entry point; everything else in the file exists to support it.

Core lines

if (!Number.isInteger(timestamp)) throw new TypeError("timestamp must be an integer");
if (value.length % 2 !== 0 || !/^[0-9a-f]*$/i.test(value)) return new Uint8Array(0);
if (typeof header !== "string") throw new TypeError("header must be a string");

Interactive Tools for This Topic

FAQ

Does `signWebhook` modify its input?
No. Nothing passed in is written to, which makes the call safe on shared data.
How does the code behave when input is bad?
It throws `RangeError` and `TypeError` before any real work runs, via the guard `typeof secret !== "string" || secret.length < 16` — handle it at the call site or let it propagate deliberately.
Is the imported module an npm package?
No — `node:crypto` is built into Node.js. The `node:` prefix marks core modules, so there is nothing to add to a project.