Aller au contenu
Tous les articles

Cet article est en anglais.

4 min de lecture

Verifying signed webhooks correctly: HMAC, timestamps and replays

A webhook endpoint is a public URL that changes things in your system. How HMAC signatures work, the five mistakes that make verification useless, and receivers in Node.js and Python that get it right.

Par l'équipe TaskToHuman

  • callbacks
  • sécurité
  • webhooks

A webhook receiver is a public URL that makes your system do something: mark an order paid, release a refund, continue a deployment. Anyone on the internet can send a request to it. The only thing that separates a real event from a forged one is the signature, so it is worth getting the verification exactly right.

This article explains how HMAC webhook signatures work and the common mistakes, using the scheme TaskToHuman callbacks use as the example. Most providers use the same idea with different header names.

How the signature works

Sender and receiver share a secret. For every request, the sender computes an HMAC-SHA256 over the exact bytes of the body, together with a timestamp, using that secret as the key, and sends the result in a header:

TTH-Signature: t=1763205641,v1=5257a869e7ecebeda32affa62cdca3fa51cad7e77a0e56ff536d0ce8e108d8bd

Here t is the time of signing in Unix seconds, and v1 is the hex-encoded HMAC-SHA256 of the string t + "." + body. The receiver repeats the computation with its copy of the secret and compares. Someone without the secret cannot produce a matching value, and changing a single byte of the body or the timestamp changes the result completely.

Including the timestamp in the signed data is what makes replay protection possible, as we'll see below.

Mistake 1: verifying a re-serialized body

The most common bug. The framework parses the JSON body, and the code then calls JSON.stringify(req.body) to get "the body" for verification. The result is almost never byte-for-byte what was sent: key order, whitespace, number formatting and Unicode escaping can all differ. Verification fails at random, and someone "fixes" it by turning verification off.

Always verify against the raw bytes you received, before any parsing. In Express that means express.raw() on the webhook route; in Flask, request.get_data().

Mistake 2: comparing with ==

A normal string comparison stops at the first different character, so it takes slightly longer the more leading characters match. Over many requests, that timing difference can leak the expected signature. Use a constant-time comparison: crypto.timingSafeEqual in Node.js, hmac.compare_digest in Python.

Note that Node's timingSafeEqual throws if the two buffers differ in length, so check the length first and treat a mismatch as a failure.

Mistake 3: ignoring the timestamp

A valid signature proves the request was produced by someone with the secret. It does not prove it was produced now. An attacker who captures one genuine request (from a log, a proxy or a misconfigured debug tool) can send it again tomorrow, and the signature still matches.

Reject requests whose timestamp is too far from your clock. Five minutes is a common tolerance: long enough for clock drift and slow networks, short enough to make a captured request useless soon. Because the timestamp is inside the signed data, an attacker can't simply update it.

Mistake 4: not handling duplicates

Even with a timestamp check, the same event can legitimately arrive twice. Senders retry when your endpoint times out, even if your code did process the first attempt. Each retry is signed again with a new timestamp, so it passes verification.

Make processing idempotent. Most providers send a stable event identifier with each delivery; with TaskToHuman it is the TTH-Event-Id header, the same on every retry. Record the identifiers you have handled and skip the ones you have already seen, ideally in the same database transaction as the change the event causes.

Mistake 5: one secret, forever

Secrets leak: into a log, a screenshot, an old laptop. You need to be able to rotate them without dropping events. A good scheme lets the old and new secret overlap for a while and sends one signature per active secret. TaskToHuman keeps the previous secret signing for 24 hours after a rotation, so the header carries two v1 values. Your receiver should accept the request if any of them matches.

A receiver in Node.js

JavaScript
import crypto from "node:crypto";import express from "express";const app = express();const SECRET = process.env.TTH_SIGNING_SECRET;const TOLERANCE_SECONDS = 300;app.post("/hooks/tasktohuman", express.raw({ type: "application/json" }), async (req, res) => {  if (!verify(req.body, req.get("TTH-Signature") ?? "", SECRET)) return res.sendStatus(400);  const eventId = req.get("TTH-Event-Id");  if (await alreadyHandled(eventId)) return res.sendStatus(200);  const task = JSON.parse(req.body.toString("utf8"));  await handleDecision(task, eventId); // marks eventId as handled in the same transaction  res.sendStatus(204);});function verify(rawBody, header, secret) {  const pairs = header.split(",").map((part) => part.trim().split("="));  const t = pairs.find(([key]) => key === "t")?.[1];  const signatures = pairs.filter(([key]) => key === "v1").map(([, value]) => value);  if (!/^\d+$/.test(t ?? "") || signatures.length === 0) return false;  if (Math.abs(Date.now() / 1000 - Number(t)) > TOLERANCE_SECONDS) return false;  const expected = crypto.createHmac("sha256", secret).update(`${t}.`).update(rawBody).digest("hex");  return signatures.some(    (v) => v.length === expected.length && crypto.timingSafeEqual(Buffer.from(v), Buffer.from(expected)),  );}

A receiver in Python

Python
import hashlibimport hmacimport jsonimport osimport timefrom flask import Flask, abort, requestapp = Flask(__name__)SECRET = os.environ["TTH_SIGNING_SECRET"]TOLERANCE_SECONDS = 300@app.post("/hooks/tasktohuman")def callback():    raw = request.get_data()    if not verify(raw, request.headers.get("TTH-Signature", ""), SECRET):        abort(400)    event_id = request.headers.get("TTH-Event-Id")    if already_handled(event_id):        return "", 200    task = json.loads(raw)    handle_decision(task, event_id)  # marks event_id as handled in the same transaction    return "", 204def verify(raw_body: bytes, header: str, secret: str) -> bool:    pairs = [part.strip().split("=", 1) for part in header.split(",") if "=" in part]    t = next((value for key, value in pairs if key == "t"), "")    signatures = [value for key, value in pairs if key == "v1"]    if not t.isdigit() or not signatures:        return False    if abs(time.time() - int(t)) > TOLERANCE_SECONDS:        return False    expected = hmac.new(secret.encode(), t.encode() + b"." + raw_body, hashlib.sha256).hexdigest()    return any(hmac.compare_digest(v, expected) for v in signatures)

A few more habits

  • Answer quickly. Verify, record the event, and return a 2xx within a few seconds. Do slow work in a background job. A receiver that takes too long gets retries, and retries mean more duplicates.
  • Return an error for bad signatures, and log them. A burst of failures means a misconfigured secret or someone probing your endpoint. Don't log the secret or the full signature.
  • Keep the secret out of code. Load it from your secret store or environment, and rotate it when people leave or a log is exposed.
  • Use HTTPS only. The signature protects integrity, not confidentiality. TLS keeps the body private on the way.

The full callback format, header list and retry schedule for TaskToHuman are in the developer docs. In TypeScript and Python, the official SDKs do this check for you: verifyCallback in @tasktohuman/sdk and verify_callback in tasktohuman.

Placez un humain là où ça compte.

Commencez avec un type de tâche et une personne pour y répondre.

Vos humains répondent depuis un lien, sans compte.