Verifying webhooks

Check every webhook's signature before you act on it, so nobody can fake or replay an event.

Embed
Preview of the card
<a href="https://trackified.net/docs/verifying-webhooks"><img src="https://trackified.net/docs/_api/public/orgs/e2a7773e-db9e-41cb-bd59-bd248745cac3/spaces/9d63a5d4-feb0-4803-84a5-dc68639362a6/pages/480f39bb-31fc-4eb2-a3eb-e2b145bdd2a9/social-card.svg?v=3e7ae33eec8b" alt="Verifying webhooks" width="600" height="315"></a>

Each request has an x-tracking-signature header with a Unix timestamp and an HMAC-SHA256 digest:

x-tracking-signature: t=1792560000,v1=<hex digest>

digest = HMAC_SHA256(webhook_secret, "<t>.<raw request body>")

Your webhook secret (whsec_…) is shown once, when you create the endpoint. While you're rotating the secret, the header carries one v1 per secret:

x-tracking-signature: t=1792560000,v1=<hex, new secret>,v1=<hex, old secret>

To verify a request:

  1. Read the raw body, before any JSON parsing.

  2. Split the header on , and read t and every v1.

  3. Reject the request if t is more than 5 minutes from now. This stops replays.

  4. Compute the HMAC-SHA256 of <t>.<raw body> with your secret, as hex.

  5. Compare it with each v1 in constant time. The request is valid if any one matches.

Use the raw body

Compute the digest over the body exactly as it arrived. Parsing and re-serialising the JSON changes the bytes, and the signature stops matching.

With a library

Each library verifies the signature, checks the timestamp (5 minutes by default) and parses the event in one call. It fails if anything is wrong.

import { Trackified } from "trackified";

// rawBody: string, Buffer or Uint8Array, exactly as received
const event = await Trackified.webhooks.constructEvent(
  rawBody,
  request.headers["x-tracking-signature"],
  process.env.TRACKIFIED_WEBHOOK_SECRET!,
); // throws SignatureVerificationError

To get a yes or no instead of an exception, use verify with the same arguments: Trackified.webhooks.verify, trackified.verify, trackified.VerifyWebhook, Trackified::WebhookSignature.verify or WebhookSignature::verify. Each also takes a tolerance if you need more or less than 5 minutes.

Why a request was rejected

From version 0.2, a failed verification says why. The exception carries a reason, and verifyDetailed (verify_detailed, VerifyDetailed) returns {valid, reason} without throwing.

Reason

Meaning

missing

No signature header, or no secret configured.

malformed

The header has no t or no v1, t isn't a number, or a signature isn't valid hex.

timestamp

t is more than the tolerance (5 minutes) from your clock. Check the server's clock, or a delayed queue.

mismatch

No signature matches. Usually the wrong secret, or a body that was parsed and re-serialised.

Log the reason, but answer every rejected request with the same 400.

Rotate the secret

Rotate the secret if it leaks, or on a schedule. The old secret keeps working for a window you choose, so no event is lost while you deploy.

  1. Ask for a new secret

    Call POST /v1/webhooks/{id}/rotate-secret with expires_in_hours (default 24, at most 168), or rotateSecret in a library. The response has the new secret, once, and previous_secret_expires_at.

    curl -X POST https://api.trackified.net/v1/webhooks/wh_.../rotate-secret \
      -H "Authorization: Bearer $TRACKIFIED_API_KEY" \
      -H "Content-Type: application/json" \
      -d '{"expires_in_hours": 24}'
  2. Verify with both secrets

    Until previous_secret_expires_at, every delivery is signed with both secrets. Deploy your handler with both, new first. Every library's verify functions take a list of secrets and accept the request if any matches.

    const event = await Trackified.webhooks.constructEvent(rawBody, header, [newSecret, oldSecret]);
  3. Drop the old secret

    Once the window ends, remove the old secret from your config. To end the window early, rotate with expires_in_hours: 0: that drops the old secret at once.

Don't rotate again before you've deployed the new secret. A second rotation drops the original secret at once: the secret from the first rotation becomes the old one, with a fresh window. Because a rotation isn't safe to repeat, the TypeScript library doesn't retry rotateSecret.

Every library page has a full handler for that language's usual web framework.

Without a library

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

// header: the x-tracking-signature value, e.g. "t=1792560000,v1=5f2c…"
// rawBody: the request body exactly as received, before JSON.parse
// secrets: your secret, or [newSecret, oldSecret] while rotating
export function verifyTrackifiedSignature(header, rawBody, secrets) {
  let timestamp;
  const signatures = [];
  for (const part of (header ?? "").split(",")) {
    const [key, value] = part.trim().split("=", 2);
    if (key === "t") timestamp = value;
    else if (key === "v1" && /^[0-9a-f]{64}$/i.test(value ?? "")) signatures.push(Buffer.from(value, "hex"));
  }
  if (!/^\d+$/.test(timestamp ?? "") || signatures.length === 0) return false;

  // Reject events older than five minutes to stop replays.
  if (Math.abs(Date.now() / 1000 - Number(timestamp)) > 5 * 60) return false;

  for (const secret of [secrets].flat()) {
    const expected = createHmac("sha256", secret).update(`${timestamp}.${rawBody}`).digest();
    if (signatures.some((sig) => timingSafeEqual(sig, expected))) return true;
  }
  return false;
}

Test your code

POST /v1/webhooks/{id}/test returns a signed sample event without sending it: a signature header value and the body it signs, as a sample tracking.updated event. During a rotation the signature carries both v1 values, like a real delivery. The body comes back parsed, so serialise it compactly (JSON.stringify(body) in JavaScript, json.dumps(body, separators=(",", ":")) in Python) to get the signed bytes. Then feed both to your verification code within 5 minutes.

The CLI can check a signature too. It exits with status 1 if the signature is invalid:

trackified verify-webhook --secret "$TRACKIFIED_WEBHOOK_SECRET" \
  --header "t=1792560000,v1=5f2c..." --body-file body.json
Updated