# Webhooks

With a webhook, RiskPilot POSTs each newly released signal in your package to an HTTPS endpoint you run, a few
seconds after its release. Every delivery is signed with your account's secret and retried with backoff until your
endpoint accepts it.

<Figure name="webhook-sequence" caption="One delivery per signal and account: POST, verify, answer 2xx. Anything else is retried with the same delivery id, six times over about 33 hours." />

## Set it up

Webhooks are part of the packages whose delivery includes them (`desk` and `firm` as standard); on another package
you can save a URL, but nothing is sent to it. You need the live key or a signed-in owner (a named key gets
`403 key_not_allowed`); the portal's **Delivery** page does the same.

1. **Set the URL.** It must be `https://`, on a public host, without a user name or password in it.

   ```bash
   curl -sS -X PATCH "$RISKPILOT_URL/api/v1/customer/delivery" \
     -H "Authorization: Bearer $RISKPILOT_LIVE_KEY" -H "Content-Type: application/json" \
     -d '{ "webhook": "https://hooks.acme.example/riskpilot" }'
   # 200 { "webhook": "https://hooks.acme.example/riskpilot" }
   ```

   An `http://` URL, `localhost`, or an address in a private, loopback or link-local range is refused with 400.
   Names are resolved again at every delivery, and a name that then points at a private address is not called.
   An empty string removes the webhook.

2. **Get the signing secret** (`whsec_…`). The first call creates it; later calls return the same one.

   ```bash
   curl -sS -X POST "$RISKPILOT_URL/api/v1/customer/delivery/secret" -H "Authorization: Bearer $RISKPILOT_LIVE_KEY"
   # 200 { "secret": "whsec_…" }
   ```

   Store it like a password, next to your endpoint.

3. **Send a test** (below) and check your endpoint answers 2xx.

From then on, every signal released while the URL is set is delivered. Signals released before you set it are not
sent afterwards: read those over [REST](/pagination-and-filters#keeping-a-copy-in-sync).

## Events

| `event` | When |
| --- | --- |
| `signal.published` | A signal of a class your package includes is released (live), inside your history window and families. Once per filing. |
| `test` | You (or support) asked for a test delivery. |

A filing an operator holds back is not sent while it is held; it is sent when the hold is lifted. A signal is sent
once: if it is later re-released, no second `signal.published` follows. The sandbox key never causes a delivery.

## The request

```http
POST /riskpilot HTTP/1.1
Host: hooks.acme.example
Content-Type: application/json
User-Agent: RiskPilot-Webhooks/1
RiskPilot-Delivery: 4821
RiskPilot-Signature: t=1762790400,v1=5f3a9c0e…(64 hex characters)

{
  "event": "signal.published",
  "signal": {
    "filingId": "0001437749-26-031545",
    "filedAt": "2026-11-06T21:05:12.000Z",
    "ticker": "ACME",
    "issuerName": "Acme Corp",
    "issuerId": "0000123456",
    "family": "8-K",
    "className": "ACTION",
    "score": 87,
    "label": "PENDING",
    "headline": "Acme agrees to be acquired for $42 per share in cash"
  },
  "deliveryId": "4821",
  "attempt": 1,
  "sentAt": "2026-11-10T16:00:00.412Z"
}
```

| Field | Meaning |
| --- | --- |
| `event` | `signal.published` or `test` |
| `signal` | The signal as it was when the delivery was queued: the same fields as `GET /customer/signals` |
| `deliveryId` | The delivery's id; also in the `RiskPilot-Delivery` header (header names are case-insensitive). The same on every retry |
| `attempt` | 1 for the first try, up to 7 |
| `sentAt` | When this attempt was sent |

The `signal.label` is a snapshot (usually `PENDING`); read the signal again later for its realized label. A test
delivery is `{ "event": "test", "deliveryId": "test_1762790400412", "sentAt": "…" }`.

## Verify the signature

`RiskPilot-Signature` is `t=<unix seconds>,v1=<signature>`, where the signature is the lowercase hex
HMAC-SHA256 of the string `t + "." + body`, keyed with your `whsec_…` secret. To verify:

1. Take the **raw bytes** of the body as received. Do not parse and re-serialise the JSON first: any change of
   spacing or key order breaks the signature.
2. Compute HMAC-SHA256 over `t`, a `.`, and those bytes, with the secret.
3. Compare with `v1` in constant time.
4. Reject a `t` more than 5 minutes from your clock: that stops a captured request being replayed later. Each retry
   carries a fresh `t`.

Answer 400 or 401 when the check fails. That delivery is then retried, which is what you want during a secret
rotation (below).

<CodeTabs>

```js title="Node (Express)"
import crypto from "node:crypto";
import express from "express";

const SECRET = process.env.RISKPILOT_WEBHOOK_SECRET; // whsec_…
const TOLERANCE_SECONDS = 300;

/** True when `header` (riskpilot-signature) signs `rawBody` (a Buffer of the exact bytes received) with `secret`. */
export function verifyRiskPilotSignature(rawBody, header, secret, now = Date.now()) {
  const fields = {};
  for (const part of String(header ?? "").split(",")) {
    const at = part.indexOf("=");
    if (at > 0) fields[part.slice(0, at).trim()] = part.slice(at + 1).trim();
  }
  const t = Number(fields.t);
  if (!Number.isInteger(t) || !/^[0-9a-f]{64}$/.test(fields.v1 ?? "")) return false;
  if (Math.abs(now / 1000 - t) > TOLERANCE_SECONDS) return false;
  const expected = crypto.createHmac("sha256", secret).update(`${t}.`).update(rawBody).digest();
  return crypto.timingSafeEqual(expected, Buffer.from(fields.v1, "hex"));
}

const app = express();

// express.raw keeps the body as a Buffer: verify before parsing.
app.post("/riskpilot", express.raw({ type: "application/json", limit: "1mb" }), async (req, res) => {
  if (!verifyRiskPilotSignature(req.body, req.get("riskpilot-signature"), SECRET)) {
    return res.status(400).send("bad signature");
  }
  const delivery = JSON.parse(req.body.toString("utf8"));
  const isNew = await rememberDelivery(delivery.deliveryId); // e.g. INSERT … ON CONFLICT DO NOTHING
  if (isNew && delivery.event === "signal.published") await queueForProcessing(delivery.signal);
  res.status(204).end(); // answer fast; do the work after
});

app.listen(8080);
```

```python title="Python (Flask)"
import hashlib
import hmac
import json
import os
import time

from flask import Flask, request

SECRET = os.environ["RISKPILOT_WEBHOOK_SECRET"]  # whsec_…
TOLERANCE_SECONDS = 300


def verify_riskpilot_signature(raw_body: bytes, header: str, secret: str, now: float | None = None) -> bool:
    """True when `header` (riskpilot-signature) signs `raw_body` (the exact bytes received) with `secret`."""
    fields = {}
    for part in (header or "").split(","):
        name, sep, value = part.partition("=")
        if sep:
            fields[name.strip()] = value.strip()
    try:
        t = int(fields["t"])
    except (KeyError, ValueError):
        return False
    given = fields.get("v1", "")
    if abs((time.time() if now is None else now) - t) > TOLERANCE_SECONDS:
        return False
    expected = hmac.new(secret.encode(), f"{t}.".encode() + raw_body, hashlib.sha256).hexdigest()
    return hmac.compare_digest(expected, given)


app = Flask(__name__)


@app.post("/riskpilot")
def riskpilot_webhook():
    raw = request.get_data()  # the exact bytes, before any JSON parsing
    if not verify_riskpilot_signature(raw, request.headers.get("RiskPilot-Signature", ""), SECRET):
        return "bad signature", 400
    delivery = json.loads(raw)
    if remember_delivery(delivery["deliveryId"]) and delivery["event"] == "signal.published":
        queue_for_processing(delivery["signal"])
    return "", 204  # answer fast; do the work after
```

</CodeTabs>

Both functions are tested against the API's own signing code. The Python one needs 3.10 or later.

## Answer quickly

- Any **2xx** status means delivered. Anything else (including 3xx: redirects are not followed, and 4xx), no answer
  within **10 seconds**, or no connection counts as a failure.
- Store the delivery and answer; do slow work (database writes to other systems, notifications) afterwards.

## Retries and backoff

A failed delivery is tried again with the **same `deliveryId`**, re-signed with a fresh `t`:

| Attempt | Sent |
| --- | --- |
| 1 | at release (the queue is read every few seconds) |
| 2 | 1 minute after attempt 1 failed |
| 3 | 5 minutes after attempt 2 |
| 4 | 30 minutes after attempt 3 |
| 5 | 2 hours after attempt 4 |
| 6 | 6 hours after attempt 5 |
| 7 | 24 hours after attempt 6 |

After the seventh failure the delivery is **failed** and is not tried again by itself; RiskPilot support can queue
failed deliveries again once your endpoint is fixed (they keep their `deliveryId`). A delivery is also marked failed,
without being sent, when at its turn the account is suspended, the webhook was switched off, or the subscription no
longer allows access.

`GET /api/v1/customer/delivery/log` (and the portal's **Delivery** page) shows the latest 50 deliveries with their
status (`pending`, `delivered`, `failed`), attempts, next attempt, last HTTP status and last error, and the totals.

## Idempotency and order

- **Deduplicate on `deliveryId`.** You may receive the same delivery more than once: when your endpoint processed it
  but the answer was lost or late, or when failed deliveries are queued again. Record each `deliveryId` you accept
  and skip repeats.
- RiskPilot queues at most one `signal.published` per filing for your account, so `signal.filingId` is also a safe
  business key.
- **Order is not guaranteed.** Deliveries are sent several at a time and retries interleave with new ones. Use
  `signal.filedAt` to order, not arrival time.

## Test it

- **Test delivery:** `POST /api/v1/customer/delivery/test` (or **Send test** on the Delivery page) sends a signed
  `test` event to your URL at once and answers with the result, for example `{ "kind": "test", "ok": true, "status": 204,
  "error": null }`. A test is not retried.
- **Locally:** expose your development endpoint through an HTTPS tunnel and set that URL; a plain `http://` or
  private address is refused.
- **Unit tests:** sign a sample body yourself with the functions above (compute `t` and `v1` with your test secret)
  and post it to your handler; also check that a changed body, a wrong secret and an old `t` are rejected.

## Rotate the secret

`POST /api/v1/customer/delivery/rotate-secret` (or **Rotate secret** on the Delivery page) returns a new `whsec_…` and
signs every delivery from then on with it; the old secret stops at once. To switch without losing anything:

1. Make your endpoint accept either of two secrets (try the new one, then the old one).
2. Rotate and deploy the new secret.
3. Deliveries that failed the check in between are retried a minute later and pass.
4. Remove the old secret.

RiskPilot records each rotation in its audit log.
