> ## Documentation Index
> Fetch the complete documentation index at: https://docs.trustware.io/llms.txt
> Use this file to discover all available pages before exploring further.

# Verify webhook signatures

> Check that a webhook delivery came from Trustware using Standard Webhooks v1 HMAC signatures, with Node and Python examples and a test vector.

Anyone who learns your webhook URL can POST to it. Verify every delivery before you act on it, and reject any request that fails.

Trustware signs every delivery to the [Standard Webhooks](https://www.standardwebhooks.com) v1.0.0 specification, with the symmetric `v1` (HMAC-SHA256) scheme. The simplest correct approach is the official Standard Webhooks library for your language. It checks the signature for you, in constant time, and rejects a `webhook-timestamp` more than 5 minutes away from your clock.

## Your signing secret

Your secret looks like `whsec_` followed by base64. The Client Dashboard shows it once, when you register your webhook URL or rotate the secret. Store it the way you store other server secrets, such as in an environment variable or a secrets manager, and never ship it to a browser.

If you lose it, rotate it from the dashboard. Trustware can't show an existing secret again. See [rotate the secret](https://docs.trustware.io/webhooks/dashboard-setup.md#rotate-the-secret).

## Verify with a library

The Standard Webhooks libraries accept the secret exactly as the dashboard shows it, `whsec_` prefix included.

```js Node.js (Express) theme={null}
import express from "express";
import { Webhook } from "standardwebhooks";

const webhook = new Webhook(process.env.TRUSTWARE_WEBHOOK_SECRET);
const app = express();

// Read the body as raw bytes. A parsed and re-serialized body won't verify.
app.post(
  "/trustware/webhooks",
  express.raw({ type: "application/json", limit: "256kb" }),
  (req, res) => {
    let event;
    try {
      event = webhook.verify(req.body.toString("utf8"), req.headers);
    } catch {
      return res.status(400).send("invalid signature");
    }

    // event.type, event.sequence, event.data ...
    // Deduplicate on req.headers["webhook-id"], then record the event.
    res.sendStatus(204);
  },
);
```

```python Python (Flask) theme={null}
import os

from flask import Flask, request
from standardwebhooks import Webhook, WebhookVerificationError

webhook = Webhook(os.environ["TRUSTWARE_WEBHOOK_SECRET"])
app = Flask(__name__)


@app.post("/trustware/webhooks")
def trustware_webhook():
    try:
        # get_data() returns the raw bytes, before any JSON parsing.
        event = webhook.verify(request.get_data(), dict(request.headers))
    except WebhookVerificationError:
        return "invalid signature", 400

    # event["type"], event["sequence"], event["data"] ...
    # Deduplicate on request.headers["webhook-id"], then record the event.
    return "", 204
```

Install the library with `npm install standardwebhooks` or `pip install standardwebhooks`. Libraries for other languages are listed on the [Standard Webhooks site](https://www.standardwebhooks.com).

## Verify without a library

If you can't add a dependency, the scheme is short enough to implement directly:

1. Read the `webhook-id`, `webhook-timestamp` and `webhook-signature` headers. Reject the request if any is missing.
2. Reject the request unless `webhook-timestamp` is whole Unix seconds, digits only, within 5 minutes of your clock, the tolerance the Standard Webhooks libraries use. This stops an old, captured delivery from being replayed.
3. Build the signed content: `webhook-id` + `.` + `webhook-timestamp` exactly as received + `.` + the raw body bytes.
4. Take your secret, remove the `whsec_` prefix, and base64-decode the rest. That's the HMAC key.
5. Compute HMAC-SHA256 of the signed content with that key.
6. `webhook-signature` holds one or more space-separated entries, each `v1,` followed by a base64 signature. Accept the delivery if any `v1` entry matches your HMAC. Compare in constant time, and ignore entries with any other version prefix.

```js Node.js theme={null}
import crypto from "node:crypto";

const TOLERANCE_SECONDS = 5 * 60;

export function verifyTrustwareWebhook(rawBody, headers, secret) {
  const id = headers["webhook-id"];
  const timestamp = headers["webhook-timestamp"];
  const signatureHeader = headers["webhook-signature"];
  if (!id || !timestamp || !signatureHeader) {
    throw new Error("Missing webhook-id, webhook-timestamp or webhook-signature");
  }

  // Digits only. Number() alone would also accept " 1", "1.5", "1e9" and "0x1".
  if (typeof timestamp !== "string" || !/^[0-9]+$/.test(timestamp)) {
    throw new Error(`webhook-timestamp ${timestamp} is not Unix seconds`);
  }
  const seconds = Number(timestamp);
  if (!Number.isSafeInteger(seconds)) {
    throw new Error(`webhook-timestamp ${timestamp} is out of range`);
  }
  const now = Math.floor(Date.now() / 1000);
  if (Math.abs(now - seconds) > TOLERANCE_SECONDS) {
    throw new Error(`webhook-timestamp ${timestamp} is outside the 5 minute tolerance`);
  }

  const key = Buffer.from(secret.replace(/^whsec_/, ""), "base64");
  const expected = crypto
    .createHmac("sha256", key)
    .update(`${id}.${timestamp}.`)
    .update(rawBody) // a Buffer of the exact bytes received
    .digest();

  const verified = signatureHeader.split(" ").some((entry) => {
    const [version, signature] = entry.split(",");
    if (version !== "v1" || !signature) return false;
    const received = Buffer.from(signature, "base64");
    return (
      received.length === expected.length &&
      crypto.timingSafeEqual(received, expected)
    );
  });
  if (!verified) {
    throw new Error("No v1 signature in webhook-signature matched");
  }

  return JSON.parse(rawBody.toString("utf8"));
}
```

## Common mistakes

* **Verifying a parsed body.** Frameworks that parse JSON before your handler runs hand you an object, not the bytes Trustware signed. Re-serializing it changes whitespace or key order, and the signature fails. Configure the route to give you the raw body.
* **Using the secret with its prefix as the key.** The HMAC key is the base64-decoded part after `whsec_`, not the string itself. The libraries handle this for you.
* **Checking only the first signature.** During a secret rotation, `webhook-signature` carries two signatures. Accept the delivery if any one matches.
* **Comparing with `==`.** Use a constant-time comparison, such as `crypto.timingSafeEqual` in Node.js or `hmac.compare_digest` in Python.
* **A drifting server clock.** The timestamp check fails every delivery if your clock is more than 5 minutes off. Keep it synced with NTP.

## Secret rotation

When you rotate your secret, Trustware signs every delivery with both the old and the new secret for 24 hours, so `webhook-signature` holds two `v1` entries. Deploy the new secret to your server within that window. A delivery verifies against either secret, so you don't drop any during the switch.

After 24 hours the old secret is deleted and deliveries carry only the new signature. Rotating again inside the 24 hours ends the previous secret's overlap at once, so a delivery never carries more than two signatures.

## Test vector

Use this to check your own implementation. The body is exactly the bytes shown: 286 bytes, with no trailing newline.

| Input | Value |
| - | - |
| Secret | `whsec_AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8=` (key bytes `0x00` to `0x1f`) |
| `webhook-id` | `5b1f0c2e-8d1a-4c3b-9e7f-2a6d4b8c0e11` |
| `webhook-timestamp` | `1793880000` (2026-11-05T12:00:00Z) |
| Body | `{"type":"route_intent.expired","timestamp":"2026-11-05T12:00:00Z","apiVersion":"v1","sequence":1,"test":true,"data":{"intent_id":"00000000-0000-0000-0000-000000000000","status":"expired","intent_status":"expired","create_date":"2026-11-04T11:00:00Z","expiresAt":"2026-11-04T11:30:00Z"}}` |
| `webhook-signature` | `v1,sbS7GSClJCsZ7SSApW5El8T5YQX8iAw6MbNqsC8I1L4=` |

During a rotation to a second secret, `whsec_ICEiIyQlJicoKSorLC0uLzAxMjM0NTY3ODk6Ozw9Pj8=` (key bytes `0x20` to `0x3f`), the same delivery carries the new secret's signature first:

```
v1,7UkMaBGrsLRtlYA83JdeAm4quCwy4DPbFInDwHGtwac= v1,sbS7GSClJCsZ7SSApW5El8T5YQX8iAw6MbNqsC8I1L4=
```

The test vector's timestamp is in the past, so a verifier that enforces the 5 minute tolerance rejects it. Check the HMAC step on its own, or freeze your test clock at `1793880000`.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.