Verify webhooks

Verify the HMAC-SHA256 signature on a onefold webhook delivery before you trust it, with examples in TypeScript and Python.

Verify the signature of every webhook delivery before you act on it. Anyone who learns your endpoint's URL can send it a request; only onefold can produce a valid signature.

The signature

onefold signs each delivery with the endpoint's signing secret:

signature = HMAC-SHA256(secret, timestamp + "." + body)
PartValue
secretThe endpoint's signing secret: the whole string, including the eitozx_whsec_ prefix
timestampThe X-Webhook-Timestamp header, exactly as sent
bodyThe raw request body, byte for byte
ResultHex-encoded, in the X-Webhook-Signature header

The checks

  1. Read the raw body. Compute the signature over the bytes you received. Do not parse the JSON and serialize it again; the result differs and the signature fails.
  2. Compute and compare. Use a constant-time comparison.
  3. Check the timestamp. Reject a delivery whose timestamp is more than five minutes from your server's clock. onefold does not enforce this for you; it is what stops a captured delivery from being sent again later.
import { createHmac, timingSafeEqual } from "node:crypto";

export function verifyWebhook(
  rawBody: string,
  headers: Headers,
  secret: string,
): boolean {
  const timestamp = headers.get("x-webhook-timestamp") ?? "";
  const signature = headers.get("x-webhook-signature") ?? "";
  if (Math.abs(Date.now() / 1000 - Number(timestamp)) > 300) return false;

  const expected = createHmac("sha256", secret)
    .update(`${timestamp}.${rawBody}`)
    .digest("hex");
  return (
    signature.length === expected.length &&
    timingSafeEqual(Buffer.from(signature), Buffer.from(expected))
  );
}

Getting the raw body

Most frameworks parse JSON before your handler runs. Read the unparsed body instead:

FrameworkRaw body
Next.js route handlerawait request.text()
Expressexpress.raw({ type: "application/json" }) on the webhook route
Djangorequest.body
Flaskrequest.get_data()

Headers on every delivery

HeaderValue
X-Webhook-EventThe event name, for example consent.granted
X-Webhook-TimestampUnix time in seconds when the delivery was signed
X-Webhook-SignatureThe hex signature
X-Webhook-DeliveryThe ID of this delivery
X-Webhook-Event-IdThe ID of the original event

When verification fails

CauseFix
The body was parsed and re-serializedSign the raw bytes
The wrong secretUse this endpoint's signing secret, not the client secret or another endpoint's
The eitozx_whsec_ prefix was removedUse the whole secret
The secret was rotatedUse the new secret

On this page