---
title: "Verify a webhook signature"
description: "Check the timestamp, recompute the HMAC-SHA256 over the signed payload, and compare in constant time before trusting a delivery."
---

Every delivery carries four headers:

```text
X-TrustIvan-Delivery:  d29b1f2e-…
X-TrustIvan-Event:     verdict.recorded
X-TrustIvan-Timestamp: 1787203643
X-TrustIvan-Signature: v1=9f86d081884c7d65…
```

The mixed case in `X-TrustIvan-…` is how the header is spelled on the wire,
not a typo; HTTP header names are case-insensitive, which is why the Node
example below reads them in lower case. Deliveries also
carry the same four values under the pre-rename names `TrustOwl-Delivery`,
`TrustOwl-Event`, `TrustOwl-Timestamp` and `TrustOwl-Signature`, for one
release only, so a receiver written against those keeps verifying while you
move it to the names above. Do not write new code against the old names.

The signature is `HMAC-SHA256`, keyed with your endpoint's secret
(`whsec_…`), over exactly:

```text
v1:<delivery id>:<timestamp>:<raw body>
```

Verify before parsing. A webhook endpoint is a URL anyone on the internet can
POST to, so an unverified body is attacker-controlled input.

## Python

```python
import hashlib
import hmac
import time

TOLERANCE = 300  # seconds; TRUSTIVAN's own window is five minutes


def verify(secret: str, headers, body: bytes, now: float | None = None) -> bool:
    """Return True if `body` is a genuine TRUSTIVAN delivery."""
    now = time.time() if now is None else now

    # 1. The timestamp, first and on its own.
    try:
        timestamp = int(headers["X-TrustIvan-Timestamp"].strip())
    except (KeyError, ValueError):
        return False
    if abs(now - timestamp) > TOLERANCE:
        return False

    delivery = headers.get("X-TrustIvan-Delivery", "")
    if not delivery:
        return False

    # 2. Recompute over the exact bytes that were signed.
    base = f"v1:{delivery}:{timestamp}:".encode() + body
    expected = "v1=" + hmac.new(
        secret.encode(), base, hashlib.sha256
    ).hexdigest()

    # 3. Constant-time comparison, against every signature offered.
    return any(
        hmac.compare_digest(candidate, expected)
        for candidate in headers.get("X-TrustIvan-Signature", "").split()
    )
```

## Node

```js
const crypto = require("node:crypto")

const TOLERANCE = 300

function verify(secret, headers, body, now = Date.now() / 1000) {
  // 1. The timestamp, first and on its own.
  const timestamp = Number.parseInt(
    (headers["x-trustivan-timestamp"] || "").trim(), 10)
  if (!Number.isFinite(timestamp)) return false
  if (Math.abs(now - timestamp) > TOLERANCE) return false

  const delivery = headers["x-trustivan-delivery"]
  if (!delivery) return false

  // 2. Recompute over the exact bytes that were signed.
  const base = Buffer.concat([
    Buffer.from(`v1:${delivery}:${timestamp}:`),
    body,                       // the RAW body, not a re-serialised object
  ])
  const expected = "v1=" + crypto
    .createHmac("sha256", secret).update(base).digest("hex")

  // 3. Constant-time comparison, against every signature offered.
  const offered = (headers["x-trustivan-signature"] || "").split(/\s+/)
  const want = Buffer.from(expected)
  return offered.some((candidate) => {
    const got = Buffer.from(candidate)
    return got.length === want.length && crypto.timingSafeEqual(got, want)
  })
}
```

## Why each step is there

**The timestamp is checked before the MAC.** A MAC over a fixed body never
expires on its own, so replay protection has to come from bounding age. Five
minutes is enough for ordinary clock drift and short enough that a captured
request stops being useful quickly. The window is checked in **both**
directions: a timestamp from the future is as suspect as one from the past.
The timestamp is only trustworthy because it is itself inside the MAC.

**Every field in the signing base is load-bearing.** Without the version, a
future `v2` signature could be presented as a `v1` one. Without the delivery
ID, a captured signature could be replayed as a *different* delivery inside the
timestamp window. Without the timestamp, it could be edited to refresh a stale
capture. Without the body, the signature would authenticate nothing. Colons
separate them, and none of the first three fields can contain a colon, so no
reshuffling of field boundaries produces the same base string.

**The comparison is constant-time.** A byte-by-byte comparison that returns
early leaks, through response timing, how much of a guessed signature was
correct, which turns forgery from infeasible into a few thousand requests.
Use `hmac.compare_digest`, `crypto.timingSafeEqual`, or your language's
equivalent; never `==`.

**The header may carry several signatures, space-separated.** That is
rotation: `POST /webhooks/{id}/rotate-secret` issues a new secret and keeps the
old one working for a 24-hour overlap, during which deliveries are signed with
both. Accept the delivery if **any** signature verifies. Without the overlap,
rotating would drop every delivery between the rotation and your receiver being
reconfigured, which makes rotation an outage, and an outage is a thing people
avoid doing.

**Use the raw request body.** Verify against the bytes you received, before any
JSON parsing, re-serialisation or framework middleware that might reorder keys
or normalise whitespace. Anything that rewrites the body invalidates the
signature.

**Report one failure.** Do not tell a caller whether the timestamp or the MAC
was wrong; that tells an attacker which half to work on. TRUSTIVAN's own
reference implementation returns a single error for the same reason.

## Deduplicate on the delivery ID

Delivery is **at-least-once**. A delivery can genuinely be sent twice when a
response is lost, and retries continue with exponential backoff from 30 seconds
to a 2-hour cap over roughly a day.

> **Receivers must be idempotent.** Record the `X-TrustIvan-Delivery` value and
> ignore a delivery you have already processed.

The delivery ID appears both in that header and as the envelope's `id` field,
as one value that agrees with itself, so you can deduplicate before or after
parsing.

```python
if store.seen(headers["X-TrustIvan-Delivery"]):
    return 200, ""   # already handled; acknowledge and do nothing
```

## Answer quickly

Return `2xx` as soon as the delivery is verified and durably recorded, and do
the real work afterwards. TRUSTIVAN allows 10 seconds for the whole request and
caps the response it reads at 8 KB. An endpoint that fails 20 times
consecutively is disabled, with the reason recorded so you can see what
happened and switch it back on; re-enabling clears the streak.

## Gotchas

- **Header names are case-insensitive in HTTP.** Node lower-cases them; some
  frameworks do not. Look them up accordingly.
- **The secret is returned exactly once**, by create and by rotate. There is no
  read path, not for an admin, not for support. A secret that can be fetched
  is one that ends up in a screenshot.
- **The payload contract is versioned by date** (`version: "2026-08-20"`).
  Switch on it. Fields may be added within a version, but never removed or
  repurposed.
- **`GET /webhooks/deliveries`** shows recent attempts and what went wrong,
  which is the fastest way to tell a signature bug from a connectivity one.

## See also

- [Webhooks](/integrations/webhooks): the three events, the envelope,
  and the delivery guarantees.
- [Troubleshooting webhooks](/troubleshooting/webhooks): deliveries that
  never arrive, and endpoints that get disabled.
