LeepCast
Subscribe
All posts
Security

Verifying Webhook Signatures: HMAC, Timestamps, and Replay Protection

How GitHub, Stripe and the Standard Webhooks spec sign deliveries, why raw bodies and constant-time comparison matter, and a runnable Node. js verifier with replay protection.

LeepCast7 min read
Verifying Webhook Signatures: HMAC, Timestamps, and Replay Protection

A webhook endpoint is an unusual kind of API route. It is public, it accepts POST requests from the internet, and the requests it receives often trigger things that matter: marking an invoice as paid, provisioning an account, kicking off a deployment. Yet the caller is not a logged-in user with a session cookie or a bearer token. It is another company's server, and the only thing standing between your endpoint and a forged request is the signature that server attaches to each delivery.

This explainer covers how webhook signatures actually work, how the major schemes differ, and the handful of implementation details that decide whether verification is real or decorative. It draws on the GitHub and Stripe webhook documentation, the Standard Webhooks specification, and the Node. js crypto reference, and it ends with a small verifier you can run as-is.

Why a webhook endpoint needs its own authentication

Anyone who learns your webhook URL can send it a request. URLs leak through logs, browser history, screenshots, support tickets and misconfigured proxies, so treating the URL itself as a secret is not a defence. Stripe's documentation is blunt about the consequence: without verification, an attacker can send fake events that fulfil orders, grant access or modify records. The fix is to make every delivery prove two things: that it was produced by someone holding a secret shared only with you, and that its contents were not changed in transit.

Webhook providers achieve this with a message authentication code. When you register an endpoint, the provider generates a signing secret and shows it to you once. For every delivery, the provider computes a keyed hash of the request using that secret and sends the result in a header. Your server repeats the computation with its copy of the secret. If the two values match, the request is authentic; if anything differs, it is rejected.

How HMAC signing works

Almost every major provider uses HMAC with SHA-256. HMAC mixes the secret key into the hash in a way that cannot be reproduced without the key, so an attacker who sees thousands of signed payloads still cannot sign a new one. The receiving side follows the same recipe for every scheme, with small variations in the details:

  1. Read the raw request body exactly as it arrived, before any JSON parsing.
  2. Build the signed content the provider describes, which is usually the body alone or the body prefixed with a timestamp and an event ID.
  3. Compute HMAC-SHA256 over that content using the endpoint's signing secret.
  4. Extract the signature or signatures from the header and compare each one to your computed value in constant time.
  5. If the scheme includes a timestamp, reject the request when it falls outside an allowed window.
  6. Only then parse the JSON and hand the event to your business logic.

Three common schemes, side by side

The building blocks are shared, but the header formats differ enough that copying code between providers is a common source of bugs.

  • GitHub sends X-Hub-Signature-256, whose value is the string sha256= followed by a hex-encoded HMAC-SHA256 of the raw body. A legacy X-Hub-Signature header using SHA-1 still exists for compatibility, and GitHub recommends the SHA-256 version. The signature covers only the body, so it carries no timestamp.
  • Stripe sends a Stripe-Signature header containing a timestamp element prefixed with t= and one or more signatures prefixed with a scheme such as v1=. The signed content is the timestamp, a full stop, and the raw body. Stripe tells integrators to ignore every scheme other than v1 to prevent downgrade attacks, and its libraries apply a default tolerance of five minutes.
  • The Standard Webhooks specification, an open format for webhook senders, uses three headers: webhook-id, webhook-timestamp and webhook-signature. The signed content is the ID, the timestamp and the body joined with full stops. Signatures are base64-encoded, prefixed with a version such as v1, and separated by spaces when there is more than one.

The important difference is the timestamp. A body-only signature, like GitHub's, proves authenticity but says nothing about freshness: a captured request stays valid forever. Schemes that sign a timestamp let the receiver reject old deliveries, because changing the timestamp breaks the signature.

Sign the bytes, not the object

The single most common verification failure has nothing to do with cryptography. HMAC operates on bytes, and the provider signed the exact bytes it sent. If your framework parses the JSON and you re-serialise it before verifying, key order, whitespace, number formatting or Unicode escaping can change, and the signature will no longer match even though the data is semantically identical. The Standard Webhooks specification calls this out directly, warning consumers not to parse and re-serialise the body.

In practice this means configuring the webhook route to receive the raw body. Stripe's troubleshooting guide notes that in Express, a global express. json() middleware registered before the webhook route will consume and parse the body first, which breaks verification. Similar care is needed in serverless platforms and API gateways that transform payloads. GitHub adds one more detail: if your language or server lets you specify an encoding, treat the payload as UTF-8, because it can contain Unicode characters.

Comparing signatures without leaking timing

A naive string comparison returns as soon as it finds the first differing character. In principle, an attacker who can measure response times precisely can use that early exit to learn a valid signature one byte at a time. Both GitHub and Stripe instruct integrators to use a constant-time comparison instead, and Node. js provides one in crypto. timingSafeEqual.

That function has a sharp edge worth knowing. According to the Node. js documentation, it throws an error when its two inputs have different byte lengths. A verifier that passes attacker-controlled input straight into it can therefore crash on a malformed header instead of rejecting it cleanly. Check the lengths first, or decode both values to fixed-length buffers. The documentation also notes that the function cannot make the surrounding code timing-safe, so keep the comparison step simple.

Replay protection: timestamps plus event IDs

A valid signature proves that the provider created a request, not that the provider sent it to you just now. An attacker who intercepts one legitimate delivery could resend it later. Signed timestamps narrow that window: Stripe's guidance is to compute the difference between the current time and the signed timestamp and reject anything beyond your tolerance, and it warns that a tolerance of zero disables the recency check entirely rather than making it strict. Because the window is measured against your own clock, keep servers synchronised with NTP.

A timestamp window still allows a replay within those few minutes, and providers legitimately deliver the same event more than once. The second layer is idempotency. Standard Webhooks keeps webhook-id constant across retries precisely so receivers can use it as a deduplication key, and Stripe recommends recording processed event IDs and skipping any you have already handled. Note that Stripe generates a fresh timestamp and signature for every retry, so a retried delivery will pass the freshness check while carrying an event ID you have already seen.

A complete verifier in Node. js

The script below implements the Standard Webhooks v1 scheme using only the built-in node:crypto module. It signs a sample payload the way a sender would, verifies it, and then shows that a tampered body and a late delivery are both rejected. Save it as verify. mjs and run it with node verify. mjs.

javascript
import { createHmac, randomBytes, timingSafeEqual } from "node:crypto";

const TOLERANCE_SECONDS = 5 * 60;

function keyFromSecret(secret) {
  // Standard Webhooks secrets look like "whsec_" + base64(random bytes).
  return Buffer.from(secret.replace(/^whsec_/, ""), "base64");
}

export function sign(secret, id, timestamp, rawBody) {
  const mac = createHmac("sha256", keyFromSecret(secret))
    .update(`${id}.${timestamp}.`)
    .update(rawBody)
    .digest("base64");
  return `v1,${mac}`;
}

export function verify(secret, headers, rawBody, nowSeconds = Math.floor(Date.now() / 1000)) {
  const id = headers["webhook-id"];
  const timestamp = headers["webhook-timestamp"];
  const signatureHeader = headers["webhook-signature"];
  if (!id || !timestamp || !signatureHeader) throw new Error("missing webhook headers");

  const ts = Number(timestamp);
  if (!Number.isInteger(ts) || Math.abs(nowSeconds - ts) > TOLERANCE_SECONDS) {
    throw new Error("timestamp outside tolerance");
  }

  const expected = Buffer.from(sign(secret, id, timestamp, rawBody).slice(3), "base64");
  for (const entry of signatureHeader.split(" ")) {
    const [version, value] = entry.split(",");
    if (version !== "v1" || !value) continue; // ignore unknown schemes
    const received = Buffer.from(value, "base64");
    if (received.length === expected.length && timingSafeEqual(received, expected)) {
      return JSON.parse(rawBody.toString("utf8"));
    }
  }
  throw new Error("no matching signature");
}

// Demo: sign a payload the way a sender would, then verify it.
const secret = "whsec_" + randomBytes(32).toString("base64");
const body = Buffer.from('{"type":"invoice.paid","data":{"id":"inv_123"}}');
const id = "msg_2b7f1c";
const ts = String(Math.floor(Date.now() / 1000));
const headers = {
  "webhook-id": id,
  "webhook-timestamp": ts,
  "webhook-signature": sign(secret, id, ts, body),
};

console.log("valid:", verify(secret, headers, body).type);

try {
  verify(secret, headers, Buffer.from('{"type":"invoice.paid","data":{"id":"inv_999"}}'));
} catch (err) {
  console.log("tampered:", err.message);
}

try {
  verify(secret, headers, body, Number(ts) + 600);
} catch (err) {
  console.log("replayed later:", err.message);
}

Running it prints that the valid event was accepted, followed by the two rejection reasons. A few design choices are deliberate. The timestamp check runs before any HMAC work, so stale requests are cheap to reject. Unknown signature versions are skipped rather than treated as errors, which lets a provider add a new scheme without breaking you. The length check before timingSafeEqual keeps a malformed header from throwing. And the body is parsed only after a signature matches, so unverified input never reaches your JSON parser or your business logic.

Rotating secrets without downtime

Signing secrets should be rotated periodically and immediately if one may have leaked. Doing that safely requires a period in which both the old and new secrets are valid. Stripe handles this by letting you delay the old secret's expiry for up to 24 hours, during which it sends one signature per active secret. Standard Webhooks supports the same pattern by allowing several space-separated signatures in one header. On the receiving side, the loop in the example above already does the right thing: it accepts the request if any v1 signature matches. If you hold two secrets during a rotation, compute an expected value for each and accept a match against either.

Where the sender and receiver do not fully trust each other's security practices, the Standard Webhooks specification also defines an asymmetric option, labelled v1a, that uses ed25519. The provider signs with a private key and receivers verify with a public key, so a leaked verification key cannot be used to forge deliveries.

Production checklist

  • Verify every delivery before acting on it, and return an error status when verification fails.
  • Read the raw body on the webhook route and keep JSON middleware from parsing it first.
  • Use the provider's official library when one exists, and follow its documented scheme exactly when it does not.
  • Compare signatures in constant time and check lengths before calling timingSafeEqual.
  • Reject timestamps outside a small window, never set the tolerance to zero, and keep clocks synced.
  • Deduplicate on the event ID, because retries and duplicate deliveries are normal.
  • Ignore signature schemes you do not recognise instead of falling back to weaker ones.
  • Return a 2xx response quickly and move slow work to a queue, as Stripe recommends, so timeouts do not trigger extra retries.
  • Store signing secrets like any other credential and rotate them with an overlap period.

The short version

Webhook signatures are simple in principle and fragile in practice. The cryptography is a single HMAC call; the failures come from parsing the body too early, comparing strings the fast way, skipping the timestamp, or forgetting that the same event will arrive twice. Treat the raw bytes as sacred, compare in constant time, bound the delivery window, and deduplicate on the event ID, and a public endpoint becomes one that only the provider can drive.

Share

Enjoyed this?

Get the next deep dive in your inbox. No spam — just the stories worth reading.

Subscribe to the newsletter

Comments