How-To Guide

Verifying Webhook HMAC Signatures Without Timing Leaks

Authenticate inbound webhooks over raw request bytes using constant-time HMAC-SHA256 comparisons, replay timestamp windows, and zero-downtime secret rotation.

On this page

  1. Why Raw Request Bytes Matter Most
  2. Anatomy of Signed Webhook Headers and Provider Variants
  3. Express and Node.js Timing-Safe Implementation
  4. Web Crypto Verification on Edge Workers
  5. Replay Windows, Idempotency, and Rotation Pitfalls
  6. Testing Verification Behavior Against Adversarial Payloads

Why Raw Request Bytes Matter Most

Inbound webhooks cross an unauthenticated internet boundary where any client can POST arbitrary JSON to your endpoint. Mutual TLS is rarely available in multi-tenant SaaS webhook integrations, so providers like Stripe, GitHub, Slack, and Shopify attach a keyed Hash-based Message Authentication Code (HMAC-SHA256) in an HTTP header. Your server proves authenticity by recomputing the same HMAC using a shared secret and checking that it matches the header.

The number one cause of spurious 401 Unauthorized webhook failures in production is accidental JSON re-serialization. Express express.json(), Fastify, and Next.js route handlers parse incoming payloads into JavaScript objects before your handler runs. If you subsequently hash JSON.stringify(req.body), any difference in spacing, floating-point representation, key order, or escaped Unicode turns a genuine webhook into a cryptographic mismatch. Always read the exact raw Buffer or Uint8Array straight from the socket stream before any JSON parser touches it.

Another frequent source of silent mismatches is framework-level character encoding middleware or reverse proxy body buffering. If a gateway decompresses gzip traffic or rewrites line endings (\r\n to \n) before forwarding the body, the SHA-256 HMAC computed downstream will no longer match the sender’s signature. Preserve the unmodified wire bytes end to end, and if you run Next.js App Router or serverless handlers, call await request.arrayBuffer() rather than await request.json() prior to verification.

Anatomy of Signed Webhook Headers and Provider Variants

Modern webhook protocols go beyond hashing the body alone. Hashing only the body leaves you vulnerable to replay attacks: an attacker who captures one valid invoice.paid request could replay it hours later. Providers prevent this by prepending a Unix timestamp to the signed payload (for example, signed_payload = "${timestamp}.${rawBody}") and sending both values inside a structured header such as t=1700000000,v1=5257a869e7ecebeda32affa62cdca3fa51cad7e77a0e56ff536d0ce8e108d8bd.

Notice that providers vary in how they format both headers and encodings. Stripe separates comma-delimited key-value pairs (t=...,v1=...) and includes multiple v1 values during secret rotation, whereas GitHub signs the raw body directly and sends X-Hub-Signature-256: sha256=<hex>, and Slack combines versioned signing (v0=${timestamp}:${rawBody}) with X-Slack-Request-Timestamp. Meanwhile, Standard Webhooks specifies base64-encoded HMAC-SHA256 digests under webhook-signature alongside webhook-id and webhook-timestamp. You should normalize your verifier cleanly per provider rather than stripping prefixes loosely. You can inspect header formats, compute reference HMACs, and compare timing-safe verification behavior locally using the Interactive Webhook Signature Verifier.

Express and Node.js Timing-Safe Implementation

Below is a production-ready Express route and verification helper using Node.js built-in node:crypto. Notice how express.raw({ type: "application/json" }) is scoped strictly to the webhook path while the rest of the application keeps normal JSON parsing, and how timingSafeEqual guards against unequal buffer lengths (because crypto.timingSafeEqual throws a RangeError if two buffers differ in byte length).

import express, { Request, Response } from "express";
import crypto from "node:crypto";

interface VerifyOptions {
  rawBody: Buffer;
  signatureHeader: string | undefined;
  secrets: string[];
  toleranceSeconds?: number;
}

export function verifyWebhookSignature(opts: VerifyOptions): {
  valid: boolean;
  reason?: string;
} {
  const { rawBody, signatureHeader, secrets, toleranceSeconds = 300 } = opts;
  if (!signatureHeader) {
    return { valid: false, reason: "Missing signature header" };
  }

  const parts = signatureHeader.split(",").map((segment) => segment.trim());
  let timestampStr: string | undefined;
  const candidateHexes: string[] = [];

  for (const part of parts) {
    const eqIndex = part.indexOf("=");
    if (eqIndex <= 0) continue;
    const key = part.slice(0, eqIndex);
    const val = part.slice(eqIndex + 1);
    if (key === "t") timestampStr = val;
    if (key === "v1" && /^[0-9a-f]{64}$/i.test(val)) {
      candidateHexes.push(val.toLowerCase());
    }
  }

  if (!timestampStr || candidateHexes.length === 0) {
    return { valid: false, reason: "Malformed signature header format" };
  }

  const timestamp = Number(timestampStr);
  const nowSeconds = Math.floor(Date.now() / 1000);
  if (!Number.isFinite(timestamp) || Math.abs(nowSeconds - timestamp) > toleranceSeconds) {
    return { valid: false, reason: "Timestamp outside replay tolerance window" };
  }

  const signedPayload = Buffer.concat([
    Buffer.from(`${timestampStr}.`, "utf8"),
    rawBody,
  ]);

  let matched = false;
  for (const secret of secrets) {
    const expected = crypto
      .createHmac("sha256", secret)
      .update(signedPayload)
      .digest();

    for (const candidateHex of candidateHexes) {
      const provided = Buffer.from(candidateHex, "hex");
      if (provided.length === expected.length && crypto.timingSafeEqual(expected, provided)) {
        matched = true;
      }
    }
  }

  return matched
    ? { valid: true }
    : { valid: false, reason: "Signature mismatch across active secrets" };
}

export const webhookRouter = express.Router();

webhookRouter.post(
  "/webhooks/billing",
  express.raw({ type: "application/json", limit: "1mb" }),
  (req: Request, res: Response) => {
    if (!Buffer.isBuffer(req.body)) {
      res.status(400).json({ error: "Expected raw request bytes" });
      return;
    }

    const activeSecrets = [
      process.env.WEBHOOK_SECRET_CURRENT,
      process.env.WEBHOOK_SECRET_PREVIOUS,
    ].filter((s): s is string => Boolean(s));

    const result = verifyWebhookSignature({
      rawBody: req.body,
      signatureHeader: req.header("X-Webhook-Signature"),
      secrets: activeSecrets,
    });

    if (!result.valid) {
      res.status(401).json({ error: result.reason });
      return;
    }

    const event = JSON.parse(req.body.toString("utf8"));
    // Enqueue idempotently by event.id before returning 200
    res.status(200).json({ received: true, id: event.id });
  },
);

Web Crypto Verification on Edge Workers

Cloudflare Workers, Deno, and Vercel Edge runtimes do not guarantee node:crypto compatibility without shims, so you should implement the exact same logic using the standard Web Crypto SubtleCrypto interface. Calling crypto.subtle.verify delegates digest comparison directly to the native runtime implementation in constant time, eliminating manual byte-loop bugs.

export async function verifyEdgeHmac(
  rawBody: Uint8Array,
  headerHex: string,
  secret: string,
): Promise<boolean> {
  const cleanHex = headerHex.replace(/^sha256=/i, "").trim().toLowerCase();
  if (!/^[0-9a-f]{64}$/.test(cleanHex)) {
    return false;
  }

  const sigBytes = new Uint8Array(32);
  for (let i = 0; i < 32; i++) {
    sigBytes[i] = parseInt(cleanHex.slice(i * 2, i * 2 + 2), 16);
  }

  const key = await crypto.subtle.importKey(
    "raw",
    new TextEncoder().encode(secret),
    { name: "HMAC", hash: "SHA-256" },
    false,
    ["verify"],
  );

  return crypto.subtle.verify("HMAC", key, sigBytes, rawBody);
}

Replay Windows, Idempotency, and Rotation Pitfalls

Signature verification alone does not make a webhook endpoint idempotent or replay-proof, and small operational shortcuts create high-impact security gaps:

  • Clock skew versus replay windows: Rejecting timestamps strictly older than 30 seconds drops legitimate traffic if upstream clocks drift slightly or delivery queues stall. A five-minute (300 seconds) bidirectional window absorbs normal clock skew while bounding replay exposure, provided you also deduplicate event.id in Redis or a unique database column.
  • Future timestamps: Checking only now - timestamp > tolerance without Math.abs(...) lets a forged or misconfigured far-future timestamp bypass the window check. Always bound both past and future skew symmetrically.
  • Unbounded raw body buffers: Leaving limit unset or excessively large on express.raw allows unauthenticated attackers to exhaust worker memory before signature validation even runs. Cap payloads explicitly (for instance, 1mb) and reject oversized requests with HTTP 413.
  • Silent single-secret rotation: Replacing WEBHOOK_SECRET in-place while retries are still sitting in the sender’s exponential backoff queue causes hours of dropped events. Always deploy an array containing [current, previous] secrets first, switch the provider over, and delete previous after 24 hours.
  • Slow synchronous processing before 200 OK: Verifying the signature and inserting the event ID into a durable queue should take milliseconds. Running downstream email or billing mutations synchronously invites gateway timeouts and duplicate retries.
  • Short-circuiting across rotation keys: When validating [current, previous], evaluate all active secrets before returning instead of exiting early if one key format looks slightly off, and log only which key index matched (key_0 vs key_1) rather than logging the secret prefix itself.

Testing Verification Behavior Against Adversarial Payloads

Confirm your middleware rejects broken signatures without crashing or leaking internal stack traces. Feed golden test fixtures into the Interactive Webhook Signature Verifier to capture exact expected hex strings, then add unit tests asserting five failure boundaries:

  1. Modifying a single whitespace character inside the raw JSON body flips verification to 401.
  2. Sending an empty string or odd-length hex digest returns 401 cleanly instead of throwing RangeError from timingSafeEqual.
  3. Replaying a legitimately signed payload stamped six minutes in the past fails with a replay tolerance error.
  4. Validating against [newSecret, oldSecret] succeeds for signatures produced with either key.
  5. Returning 401 omits any computed expected signature from error logs or HTTP response payloads so callers cannot use your server as a signing oracle.

FAQ

Why does JSON.stringify(req.body) break webhook signature verification?
Re-serializing parsed JSON alters whitespace, indentation, key ordering, numeric formatting like 1.0 versus 1, and Unicode escape sequences. A single differing byte completely changes the SHA-256 HMAC digest and causes valid webhooks to fail.
Does === string comparison really leak webhook secrets in Node.js?
Standard string equality short-circuits at the first mismatched character. Over many local or low-jitter network measurements, attackers can recover valid signature bytes iteratively, whereas timingSafeEqual runs in fixed time regardless of prefix matches.
How do I rotate a compromised or expiring webhook signing secret without dropping events?
Maintain a short-lived array of active secrets—current plus previous—during the rollover window, check the signed header against each key in constant time, and retire the old key once every in-flight retry has drained.

Related Examples

Interactive Tools for This Topic