# Verifying webhook signatures

Risk Register signs every outbound webhook with HMAC-SHA256 over
the **raw request body** plus a unix timestamp. Verifying the
signature on every received webhook is the only way to be sure the
event came from us and wasn't tampered with in transit.

The format is Stripe-style. Despite the header names, it is not the
Standard Webhooks scheme (which signs `<id>.<timestamp>.<body>` and
encodes the result in base64), so Standard Webhooks libraries will
not verify these deliveries. Use the code on this page.

## Headers

Every webhook delivery carries three headers:

| Header              | Value                                                    | Purpose                                                          |
|---------------------|----------------------------------------------------------|------------------------------------------------------------------|
| `Webhook-Id`        | UUID, e.g. `b1c2d3e4-…`                                  | The event's `id`, stable across retries. Not signed: dedupe on the body's `id` (see [Idempotency](#idempotency)) |
| `Webhook-Timestamp` | Unix epoch seconds, e.g. `1748000000`                    | When this delivery attempt was signed. Replay defence: reject a delivery more than 5 minutes old |
| `Webhook-Signature` | `t=<timestamp>,v1=<hex>` (may carry a second `v1=` during rotation) | HMAC-SHA256 over `<timestamp>.<raw_body>` with your secret |

> **During a secret rotation** the header carries **two** `v1=` signatures
> — one for the new secret and one for the previous secret, for a 24-hour
> grace window (see [Rotating your signing secret](#rotating-your-signing-secret)).
> Your verifier **must accept a match on ANY `v1=` value**, not just the
> first or last. The examples below do this. A verifier that parses the
> header into a single `v1` (e.g. `Object.fromEntries`) will reject
> deliveries during a rotation: iterate every `v1=` instead.

Every delivery attempt is signed again when it is sent, with a fresh
`Webhook-Timestamp`. A retry sent two hours after the event carries a
timestamp from the moment of the retry, so it passes the 5-minute
check like a first attempt. The event's own time is `createdAt` in
the body, which never changes.

## What gets signed

The signed payload is **the literal string `<Webhook-Timestamp>.<raw_body>`** —
the timestamp from the header, a literal `.` character, then the
exact bytes of the request body. No JSON canonicalisation, no
whitespace stripping. Use the raw body bytes from your HTTP
framework before any JSON parsing.

## Verification (Node.js)

`rawBody` must be a `Buffer` holding the request body exactly as it
arrived. In Express, mount `express.raw({ type: 'application/json' })`
on the webhook route and pass `req.body`; don't use `express.json()`
there, which parses the body and discards the bytes. `headers` is
Node's request header object, whose keys are lower-case.

```js
import crypto from 'node:crypto';

function verifyWebhook(secret, headers, rawBody) {
  const signatureHeader = headers['webhook-signature'];
  const timestamp = headers['webhook-timestamp'];

  if (!signatureHeader || !timestamp) {
    throw new Error('missing webhook headers');
  }
  if (!Buffer.isBuffer(rawBody)) {
    throw new Error('rawBody must be a Buffer of the raw request bytes');
  }

  // Replay defence: reject a delivery signed more than 5 minutes ago.
  // A timestamp that isn't a whole number is rejected outright: NaN
  // would otherwise slip past the comparison below.
  if (!/^\d+$/.test(timestamp)) {
    throw new Error('malformed webhook timestamp');
  }
  const ageSeconds = Math.floor(Date.now() / 1000) - Number(timestamp);
  if (Math.abs(ageSeconds) > 300) {
    throw new Error('webhook timestamp outside tolerance window');
  }

  // Parse `t=<ts>,v1=<hex>[,v1=<hex>]` and collect EVERY `v1=` value:
  // there are two during a secret rotation (see the note above).
  const pairs = signatureHeader.split(',').map((p) => p.split('='));
  const t = pairs.find(([k]) => k === 't')?.[1];
  const providedSigs = pairs.filter(([k]) => k === 'v1').map(([, v]) => v);
  if (t !== timestamp) {
    throw new Error('signature timestamp mismatch');
  }
  if (providedSigs.length === 0) {
    throw new Error('signature header missing v1 value');
  }

  // Recompute HMAC-SHA256 over `<timestamp>.<raw_body>` with YOUR secret.
  // The body goes in as bytes, in its own update: putting the Buffer in
  // a template string would decode and re-encode it, and stop being the
  // exact bytes that were signed.
  const expectedBuf = crypto
    .createHmac('sha256', secret)
    .update(`${timestamp}.`, 'utf8')
    .update(rawBody)
    .digest();

  // Constant-time compare against each candidate: `===` would leak
  // timing information to an attacker who can probe the endpoint.
  const ok = providedSigs.some((provided) => {
    const a = Buffer.from(provided, 'hex');
    return (
      a.length === expectedBuf.length && crypto.timingSafeEqual(a, expectedBuf)
    );
  });
  if (!ok) {
    throw new Error('invalid signature');
  }
}
```

## Verification (Python)

`headers` must be a case-insensitive mapping, such as `request.headers`
in Flask or Django: a plain `dict` built from the request would miss
`Webhook-Signature` under a differently-cased key. `raw_body` is the
request body as `bytes`, before any JSON parsing.

```python
import hmac
import hashlib
import time

def verify_webhook(secret: str, headers, raw_body: bytes):
    signature_header = headers.get("webhook-signature")
    timestamp = headers.get("webhook-timestamp")
    if not signature_header or not timestamp:
        raise ValueError("missing webhook headers")

    # Replay defence: reject a delivery signed more than 5 minutes ago.
    if not (timestamp.isascii() and timestamp.isdigit()):
        raise ValueError("malformed webhook timestamp")
    age = int(time.time()) - int(timestamp)
    if abs(age) > 300:
        raise ValueError("webhook timestamp outside tolerance window")

    # Collect EVERY `v1=` value: there are two during a secret rotation
    # (see the note above).
    pairs = [p.split("=", 1) for p in signature_header.split(",")]
    t = next((v for k, v in pairs if k == "t"), None)
    provided_sigs = [v for k, v in pairs if k == "v1"]
    # The signature header echoes the same timestamp it signed. A
    # mismatch here means an upstream proxy rewrote one but not
    # the other. Reject before the HMAC compare so a malicious
    # rewrite of `Webhook-Timestamp` alone (without the secret) is
    # caught explicitly rather than as a generic signature failure.
    if t != timestamp:
        raise ValueError("signature timestamp mismatch")
    if not provided_sigs:
        raise ValueError("signature header missing v1 value")

    expected = hmac.new(
        secret.encode("utf-8"),
        f"{timestamp}.".encode("utf-8") + raw_body,
        hashlib.sha256,
    ).hexdigest()

    # Accept a constant-time match against ANY of the candidate signatures.
    if not any(hmac.compare_digest(provided, expected) for provided in provided_sigs):
        raise ValueError("invalid signature")
```

## Idempotency

Dedupe on the event's `id` **from the verified body**. Delivery is
at least once, and every retry of an event carries the same `id`, so
deduping on it means a retried event is not handled twice, as long as
you record the `id` in the same transaction as the work it triggers
(or before you start that work).

Don't dedupe on the `Webhook-Id` header alone. The signature covers
the timestamp and the body, not the headers: someone who captures a
delivery can replay it inside your timestamp window under a different
`Webhook-Id`, and the signature still verifies. They can't change the
body's `id` without breaking it. So verify first, take the id from the
body, and reject a delivery whose `Webhook-Id` differs from it. A
genuine delivery never does: the header carries the body's `id`.

```js
// Mounted with the raw body, so `req.body` is a Buffer:
// app.post('/webhooks/risk-register', express.raw({ type: 'application/json' }), handleWebhook);
async function handleWebhook(req, res) {
  // Verify before trusting anything else in the request.
  let event;
  try {
    verifyWebhook(secret, req.headers, req.body);
    event = JSON.parse(req.body.toString('utf8'));
  } catch {
    return res.sendStatus(400);
  }

  // The header isn't signed; the body's id is. A genuine delivery
  // carries the same value in both.
  if (req.headers['webhook-id'] !== event.id) {
    return res.sendStatus(400);
  }

  // Store the event under its id. `storeIfNew` returns false when the
  // id is already there (a unique key on the id does this in one step).
  // If the store fails, answer 500 so that we retry the delivery.
  let isNew;
  try {
    isNew = await storeIfNew(event.id, event);
  } catch {
    return res.sendStatus(500);
  }

  // Acknowledge straight away: the response timeout is 10 seconds.
  res.sendStatus(200);

  // Do the work after responding (or hand it to a queue). A failure
  // here is yours to retry from the stored event: we won't resend.
  if (isNew) {
    processEvent(event).catch((err) => console.error('webhook processing failed', err));
  }
}
```

## Retries and auto-disable

We try a delivery up to **5 times**, waiting about 5 seconds,
5 minutes, 30 minutes and 2 hours between attempts. After the fifth
failed attempt we abandon the event for that endpoint. Each attempt
is signed again with a fresh `Webhook-Timestamp`; the body and the
`Webhook-Id` stay the same.

If the **last 20 delivery attempts** to your endpoint all failed
(attempts, not events), we **auto-disable** it. The endpoint stays in
your list in the app but stops receiving events; an admin must
explicitly re-enable it. Auto-disable is logged as a
`webhook_endpoint.auto_disabled` audit row visible via the public
audit-log API.

We treat any HTTP 2xx response as a success. Anything else (3xx,
4xx, 5xx, network error, timeout) counts as a failure and consumes
a retry slot.

**Endpoints have a 10-second response timeout.** Acknowledge
quickly: return 200 the moment you've stored the event and its id,
and process the event asynchronously.

## Rotating your signing secret

Rotation has a **24-hour overlap window**. When you rotate the secret,
your previous secret keeps working too: for 24 hours every delivery is
signed with **both** secrets (two `v1=` values in `Webhook-Signature`),
so nothing breaks while you migrate, as long as your verifier accepts a
match on any `v1=` (the examples above do). After 24 hours only the new
secret's signature is emitted.

1. Rotate the secret from the endpoint's page in the app. The new
   secret is shown to you exactly once: copy it immediately.
2. Update your endpoint to verify with the new secret, any time within
   the 24-hour window. Deliveries keep verifying throughout, whether
   your endpoint still holds the old secret or the new one.
3. Send a test event from the endpoint's page and confirm your
   endpoint accepts it.

Notes:

- Only the **most recent** previous secret stays live. If you rotate a
  **second** time before updating your endpoint, the window resets to the
  latest pair and the earliest secret is retired, so update your endpoint
  before rotating again.

## Event types

Some of the event types (the full list, with payloads, is in [Event types](https://riskregister.com/docs/webhook-event-types.md)):

- `risk.created` - fired when a new risk is added.
- `risk.updated` - fired when a risk's fields change through `PATCH`
  or a bulk edit. The verb endpoints (assess, treat) send their own
  events instead.
- `risk.deleted` *(v0.40.0.0+)* - fired when a risk is deleted; the
  payload carries its final state, so you can reconcile your mirror
  without a follow-up GET (which would 404).
- `risk.escalated` - fired (in addition to `risk.updated` or
  `risk.assessed`) when a risk's residual band moves UP (e.g.
  medium → high).
- `risk.de_escalated` *(v0.40.0.0+)* - mirror of `risk.escalated`
  for DOWNWARD transitions. Separate event so subscribers can opt
  into upward-only (often the only direction pager-worthy) without
  filtering payloads in their handler.
- `risk.assessed` *(v0.44.0.0+)* - fired when someone records
  a fresh assessment via `POST /api/v1/risks/{id}/assess`. Captures
  the rationale as a first-class payload field.
- `risk.treated` *(v0.44.0.0+)* - fired when someone records a
  treatment decision via `POST /api/v1/risks/{id}/treat`. Captures
  the rationale as a first-class payload field.
- `control.status_changed` - fired when a control is updated through
  `PATCH`. Despite its name, it is sent for any such update, and the
  payload carries no status field.
- `control.deleted` *(v0.40.0.0+)* - fired when a control is
  deleted; the payload carries its final state.
- `register.created` *(v0.40.0.0+)* - fired on every register
  creation surface (UI, public REST API, clone, AI generation,
  framework instantiation). Clone/template/AI paths additionally
  fire `risk.created` per spawned child risk.
- `register.archived` *(v0.40.0.0+)* - fired on the actual
  transition to `archived` status, whether through the archive
  endpoint or a `PATCH` that sets `status: archived` (UI Edit page
  or public REST API); idempotent on re-archive (no event on a
  no-op). Un-archiving sends no event.
- `review.requested` *(v0.45.0.0+)* - fired when someone opens
  a review request via `POST /api/v1/risks/{id}/request-review`.
- `review.completed` *(v0.45.0.0+)* - fired when a pending review
  is closed via `POST /api/v1/risks/{id}/complete-review`, and when a
  review is recorded in one step with no request first (`previous`
  is then `null`). Always
  advances the risk's `lastReviewedAt` (a record of when it was last
  reviewed). The reminder cron is driven by `reviewDate`, not
  `lastReviewedAt`, so completing does NOT by itself reschedule
  reminders; supply the optional `nextReviewDate` *(v0.49.99.0+)* on
  the request to roll `reviewDate` forward and clear the overdue
  state in the same call. The review's `evidence` carries the links
  given with it *(v0.49.703.0+)*.
- `review.cancelled` *(v0.45.0.0+)* - fired when a pending review
  is cancelled via `POST /api/v1/risks/{id}/cancel-review`. The
  reason given for cancelling is a first-class payload field.
- `review.overdue` - fired by the daily reminder cron when a
  risk's review date has passed (also when 7 days out and on the
  due date itself; the `data.reminderType` field discriminates).
  Each fires at most once per risk, reminder type and review date,
  and only for a risk in an active register *(archived and closed
  registers send none since v0.49.819.0)*.

**Customers MUST tolerate unknown event types**: future event
additions are non-breaking and your handler should silently skip
events it doesn't recognise, not 500 on them.

## Payload shape

Every event has the same envelope:

```json
{
  "id": "5dba8a3c-9b71-4f9b-9b9a-3b8b2a1c4d2e",
  "createdAt": "2026-05-28T12:00:00.000Z",
  "event": "risk.created",
  "data": {
    "risk": { /* RiskDtoV1 from the public REST API */ }
  }
}
```

`id` is the same value as the `Webhook-Id` header. Those four keys
are the whole envelope: there is no organisation id in the body, and
the order of the keys is not fixed. [Event types](https://riskregister.com/docs/webhook-event-types.md#envelope)
describes each key.

`data` shape varies by event type. The table below covers the events
listed above; [Event types](https://riskregister.com/docs/webhook-event-types.md) has every event:

| Event | Payload |
| --- | --- |
| `risk.created` | `{ risk: RiskDtoV1 }` |
| `risk.updated` | `{ risk: RiskDtoV1, previous: RiskDtoV1 }` |
| `risk.deleted` | `{ risk: RiskDtoV1 }` (final state) |
| `risk.escalated` | `{ risk: RiskDtoV1, previous: RiskDtoV1, previousLevel: ScoreBand, currentLevel: ScoreBand }` |
| `risk.de_escalated` | `{ risk: RiskDtoV1, previous: RiskDtoV1, previousLevel: ScoreBand, currentLevel: ScoreBand }` |
| `risk.assessed` | `{ risk: RiskDtoV1, previous: RiskDtoV1, scoresBefore: {...}, scoresAfter: {...}, rationale: string }` |
| `risk.treated` | `{ risk: RiskDtoV1, previous: RiskDtoV1, treatmentBefore: string, treatmentAfter: string, statusBefore: string, statusAfter: string, rationale: string }` |
| `control.status_changed` | `{ control: ControlDtoV1, previous: ControlDtoV1 }` |
| `control.deleted` | `{ control: ControlDtoV1 }` (final state) |
| `register.created` | `{ register: RegisterDtoV1 }` |
| `register.archived` | `{ register: RegisterDtoV1, previous: RegisterDtoV1 }` |
| `review.requested` | `{ review: RiskReviewDtoV1, risk: RiskDtoV1 }` |
| `review.completed` | `{ review: RiskReviewDtoV1, previous: RiskReviewDtoV1 \| null, risk: RiskDtoV1 }` |
| `review.cancelled` | `{ review: RiskReviewDtoV1, previous: RiskReviewDtoV1, risk: RiskDtoV1, reason: string }` |
| `review.overdue` | `{ risk: RiskDtoV1, reminderType: 'review_reminder_7d' \| 'review_reminder_due' \| 'review_reminder_overdue' }` |

`ScoreBand` is `'low' | 'medium' | 'high' | 'critical'`. `scoresBefore`
and `scoresAfter` each hold four numbers: `inherentLikelihood`,
`inherentImpact`, `residualLikelihood` and `residualImpact`.

The DTO shapes are documented in the [public REST API
OpenAPI spec](https://riskregister.com/docs/api/openapi.yaml) — the webhook contract uses the
same DTOs as the corresponding `GET /api/v1/risks/{id}` and `GET
/api/v1/controls/{id}` endpoints, so any client SDK generated from
the OpenAPI spec works for webhook payloads too.
