# Receiving Herald webhooks

Herald's `webhook` notifier POSTs `herald.event/v1` events. The envelope and both event types
are described in [`schemas/herald-event-v1.json`](schemas/herald-event-v1.json) (JSON Schema,
draft 2020-12); configuration is in
[Channels: Webhook for agents](channels.md#webhook-for-agents).

## Headers

| Header | When | Value |
|---|---|---|
| `Content-Type` | always | `application/json` |
| `X-Herald-Event` | always | `briefing.published` or `run.failed` |
| `X-Herald-Event-Id` | always | the envelope `id`, also for `markdown`, `text` and `template` bodies |
| `X-Herald-Signature` | `auth.type: "hmac"` | `t=<unix seconds>,v1=<hex HMAC-SHA256 of "<t>." + raw body>` |
| `webhook-id` | `auth.type: "standard-webhooks"` | the envelope `id` (the same on every retry) |
| `webhook-timestamp` | `auth.type: "standard-webhooks"` | unix seconds of this attempt |
| `webhook-signature` | `auth.type: "standard-webhooks"` | `v1,<base64 HMAC-SHA256 of "<webhook-id>.<webhook-timestamp>." + raw body>`, keyed with the base64-decoded part of the `whsec_` secret |
| `Authorization` | `auth.type: "bearer"` | `Bearer <token>` |

## Body size

With `max_body_bytes` set on the notifier, a body over the cap is not sent as is. Herald sends
the `markdown` format instead (`{id, type, title, markdown}`): the briefing's header and as many
whole `## ` sections as fit, then a note ("7 of 12 sections") and a link to the full briefing
when `site.base_url` is set. If not even that fits, nothing is sent and the run report says so.

## Receiver checklist

1. Verify the signature (or token) over the **raw** body bytes, before parsing JSON.
2. Reject timestamps older than 5 minutes, so a captured request cannot be replayed later.
3. Drop events whose `id` you have already processed. Herald retries on 5xx, 429 and network
   errors, and the `id` stays the same for the same day, type and language.
4. Answer 2xx quickly. Answer 4xx only for requests that will never succeed: Herald does not
   retry them.
5. Ignore fields you do not know; new optional fields may appear within `v1`.

## Verifying the signature

Python:

```python
import hashlib
import hmac
import time


def verify(secret: str, header: str, body: bytes, tolerance_s: int = 300) -> bool:
    try:
        parts = dict(p.strip().split("=", 1) for p in header.split(","))
        ts, sig = int(parts["t"]), parts["v1"]
    except (ValueError, KeyError):
        return False
    if abs(time.time() - ts) > tolerance_s:
        return False
    expected = hmac.new(secret.encode(), f"{ts}.".encode() + body, hashlib.sha256).hexdigest()
    return hmac.compare_digest(expected, sig)
```

Node (18+):

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

function verify(secret, header, rawBody, toleranceS = 300) {
  const parts = Object.fromEntries(
    (header || "").split(",").map((p) => p.trim().split(/=(.*)/s).slice(0, 2))
  );
  const ts = Number(parts.t);
  if (!Number.isInteger(ts) || !parts.v1) return false;
  if (Math.abs(Date.now() / 1000 - ts) > toleranceS) return false;
  const expected = crypto
    .createHmac("sha256", secret)
    .update(`${ts}.`)
    .update(rawBody) // a Buffer with the exact bytes received
    .digest("hex");
  const a = Buffer.from(expected);
  const b = Buffer.from(parts.v1);
  return a.length === b.length && crypto.timingSafeEqual(a, b);
}
```

With Express, read the raw body with `express.raw({ type: "application/json" })` and pass
`req.body` (a Buffer) to `verify`.

## Verifying a Standard Webhooks signature

`auth.type: "standard-webhooks"` follows the
[Standard Webhooks spec](https://github.com/standard-webhooks/standard-webhooks/blob/main/spec/standard-webhooks.md),
so any of its [official libraries](https://github.com/standard-webhooks/standard-webhooks/tree/main/libraries)
(or a platform that accepts it, such as OpenBot and Hermes) verifies Herald's events. By hand, in
Python:

```python
import base64
import hashlib
import hmac
import time


def verify(secret: str, headers, body: bytes, tolerance_s: int = 300) -> bool:
    key = base64.b64decode(secret.removeprefix("whsec_"))
    msg_id = headers.get("webhook-id", "")
    ts = headers.get("webhook-timestamp", "")
    if not msg_id or not ts.isdigit() or abs(time.time() - int(ts)) > tolerance_s:
        return False
    mac = hmac.new(key, f"{msg_id}.{ts}.".encode() + body, hashlib.sha256).digest()
    expected = "v1," + base64.b64encode(mac).decode()
    return any(
        hmac.compare_digest(expected, s) for s in headers.get("webhook-signature", "").split()
    )
```

Generate a secret with `echo "whsec_$(openssl rand -base64 32)"`.

## Trying it locally

`herald dev sink` is a small receiver that does all of the above: it checks the HMAC signature
(`--secret`), the Standard Webhooks signature (`--standard-webhooks-secret`, timing-safe, ±5
minutes) or the bearer token (`--token`), validates envelopes against the schema, prints one
line per event and saves each event as `<id>.json` in `--out` (a repeated `id` overwrites the
same file).

```bash
uv run herald dev sink --port 8787 --secret "$HERALD_WEBHOOK_SECRET" --out herald-sink
```
