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

# Webhooks

> Receive alerts as signed POST requests, verify them, and read the delivery log.

One signed `POST` per alert to each endpoint subscribed to its kind. Manage endpoints on the Webhooks screen of the app or with these routes. Every webhook route needs a key with the `approve` scope (only an organization admin can put it on a key) whose creator is still an organization admin, because a webhook sends the organization's alerts to a URL on the internet. URLs must be public `https` with no credentials in them; at most 10 endpoints per organization.

## Routes

| Method | Path | What it does |
| - | - | - |
| `GET` | `/v1/webhooks` | Your webhook endpoints (never the secret) |
| `POST` | `/v1/webhooks` | Add an endpoint; the signing secret is in this response only |
| `PATCH` | `/v1/webhooks/:id` | Change an endpoint's URL, events or active flag |
| `DELETE` | `/v1/webhooks/:id` | Remove an endpoint |
| `POST` | `/v1/webhooks/:id/test` | Send one signed `insightchain.test` event now |
| `POST` | `/v1/webhooks/:id/rotate_secret` | A new signing secret, in this response only |
| `GET` | `/v1/webhooks/:id/deliveries` | The delivery log of an endpoint |
| `POST` | `/v1/webhooks/:id/deliveries/:delivery_id/redeliver` | Send a finished delivery once more, now |

## Register an endpoint

```bash theme={null}
curl -X POST "https://api.insightchain.ai/v1/webhooks" \
  -H "Authorization: Bearer YOUR_APPROVE_KEY" -H "Content-Type: application/json" \
  -d '{ "url": "https://hooks.example.com/insightchain", "events": ["disruption", "connector"] }'
# → 201 { "webhook": { "id": "…", "url": "…", "events": [ … ], "active": true }, "secret": "whsec_…" }
# The secret is shown here and on rotate_secret only. Store it; no route returns it again.
```

## Events

`events` lists the alert kinds an endpoint subscribes to. Omit `events` to subscribe to every kind. A delivery's `type` is `insightchain.<kind>`.

| Kind | Sent when |
| - | - |
| `disruption` | A disruption event affects your network |
| `connector` | A data connection fails |
| `recommendation` | A recommendation is raised |
| `tariff_brief` | A tariff brief is written for your organization |
| `writeback` | An order written to the ERP was stored there differently from what was sent; `data` lists the fields |
| `system_change` | A breaking change is found in a connected system |
| `recall` | A person in your organization confirmed an official product recall notice against one of your items |

## The request

One `POST` per alert and endpoint, with `Content-Type: application/json`. `created_at` is when the alert was raised, and the body is the same on every retry.

```json theme={null}
{
  "type": "insightchain.disruption",
  "alert_id": "0b6c4f0e-…",
  "title": "Severity-5 flood: …",
  "data": { "event_id": "…", "severity": 5, "countries": ["VN"] },
  "created_at": "2026-11-08T10:41:12.345Z"
}
```

| Header | Value |
| - | - |
| `X-InsightChain-Signature-V2` | `t=<unix seconds>,v1=<hex HMAC-SHA256 of "<t>.<raw body>">`. While a rotated secret overlaps, a second `v1` made with the previous secret follows the first |
| `X-InsightChain-Signature` | `sha256=<hex HMAC-SHA256 of the raw body>`. No timestamp. Deprecated: no longer sent from 2027-06-30 |
| `X-InsightChain-Delivery` | The delivery id: one per alert and endpoint, the same on every retry |

## Verify the signature

Do this before trusting the body.

1. Read the raw request body; do not re-serialise parsed JSON.
2. Split `X-InsightChain-Signature-V2` on `,` into `t` and one or two `v1` values.
3. Compute HMAC-SHA256 of `t + "." + rawBody` with the secret you hold, as lowercase hex, and compare it with each `v1` in constant time. Accept the delivery when any matches.
4. Refuse the request when `t` is more than 300 seconds from your clock (replay protection).
5. Dedupe on `alert_id` or `X-InsightChain-Delivery`: delivery is at least once.

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

function verifyWebhook(secret, rawBody, header, nowSeconds = Math.floor(Date.now() / 1000)) {
  const pairs = String(header ?? "").split(",").map((part) => part.trim().split("="));
  const t = Number(pairs.find(([name]) => name === "t")?.[1]);
  // Older than five minutes, or from the future: refuse it (a replayed request).
  if (!Number.isInteger(t) || Math.abs(nowSeconds - t) > 300) return false;
  const expected = Buffer.from(createHmac("sha256", secret).update(`${t}.${rawBody}`).digest("hex"));
  // While a rotated secret overlaps there are two v1 values: accept the delivery when any matches.
  return pairs
    .filter(([name]) => name === "v1")
    .some(([, value]) => {
      const given = Buffer.from(String(value ?? ""));
      return given.length === expected.length && timingSafeEqual(given, expected);
    });
}
```

```python Python theme={null}
import hashlib
import hmac
import time


def verify_webhook(secret, raw_body, header, now=None):
    # raw_body is the request body as bytes, exactly as received.
    t = None
    signatures = []
    for part in (header or "").split(","):
        name, _, value = part.strip().partition("=")
        if name == "t":
            t = value
        elif name == "v1":
            signatures.append(value)
    # Older than five minutes, or from the future: refuse it (a replayed request).
    if t is None or not t.isascii() or not t.isdigit():
        return False
    if abs((time.time() if now is None else now) - int(t)) > 300:
        return False
    expected = hmac.new(secret.encode(), t.encode() + b"." + raw_body, hashlib.sha256).hexdigest().encode()
    # While a rotated secret overlaps there are two v1 values: accept the delivery when any matches.
    return any(hmac.compare_digest(expected, given.encode()) for given in signatures)
```

The [recipes](/docs/recipes.md#get-told-when-something-changes) show the same check with lines that try it out.

## Answering and retries

Any `2xx` within 5 seconds counts as delivered. Redirects are not followed: register the final URL. No answer, a connection error, `408`, `429` and `5xx` are retried: up to 8 attempts per alert and endpoint, waiting 1 min, 5 min, 30 min, 2 h, 6 h, 12 h, 24 h after each failure. Other `4xx` are not retried.

`POST /v1/webhooks/:id/test` sends one `insightchain.test` event now (10 per organization per hour) and reports the outcome. A test event is sent once and never retried.

## Delivery log and redelivery

`GET /v1/webhooks/:id/deliveries` lists every attempt of the last 30 days, newest first: the event type, what started it (`event`, `scheduled`, `redeliver` or `test`), the outcome, what your endpoint answered and how long it took.

`POST /v1/webhooks/:id/deliveries/:delivery_id/redeliver` sends a finished delivery once more, now; `delivery_id` is the `X-InsightChain-Delivery` header your endpoint received. A delivery that is still being retried answers `409` `delivery_pending`, and an endpoint that is switched off `409` `endpoint_inactive`.

```bash theme={null}
curl "https://api.insightchain.ai/v1/webhooks/WEBHOOK_ID/deliveries?outcome=failed&limit=20" \
  -H "Authorization: Bearer YOUR_APPROVE_KEY"
# → { "object": "list", "data": [ { "delivery_id": "…", "event_type": "insightchain.disruption", "attempt": 8,
#       "trigger": "scheduled", "outcome": "failed", "status": "503", "duration_ms": 412, "attempted_at": "…" } ], … }

curl -X POST "https://api.insightchain.ai/v1/webhooks/WEBHOOK_ID/deliveries/DELIVERY_ID/redeliver" \
  -H "Authorization: Bearer YOUR_APPROVE_KEY"
# → { "delivery": { "id": "…", "status": "delivered", "attempts": 9, … },
#     "attempt": { "attempt": 9, "delivered": true, "outcome": "delivered", "status": "200", "duration_ms": 96 } }
```

## Rotating the secret

`POST /v1/webhooks/:id/rotate_secret` returns a new secret, once. Sent without a body, the old secret stops signing at once. With `overlap_seconds` (up to 604,800, seven days) both secrets sign until the window ends: `X-InsightChain-Signature-V2` carries two `v1` values, the new secret's first and the previous one's second. A receiver that accepts any matching `v1` can switch secrets at any point in the window without refusing a delivery.

## The older signature header

> [!WARNING]
>
> `X-InsightChain-Signature` stops being sent on 2027-06-30 (00:00 UTC). Move your receiver to `X-InsightChain-Signature-V2` before that day.

`X-InsightChain-Signature` (`sha256=<hmac of the body>`) has no timestamp, so it cannot stop a replayed request. Until that day both headers are sent, as today; from then on a delivery carries `X-InsightChain-Signature-V2` only, and a receiver that only checks the older header will refuse every delivery.


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