# Webhooks

Register an endpoint once, verify it, and receive signed events from monitors and batches.

Webhook endpoints are registered once per team and referred to by id from [monitors](https://millionshort.com/docs/monitor/parameters) and [batches](https://millionshort.com/docs/extract/batch). Events can always be pulled instead; a webhook is a convenience, not a requirement.

## Endpoints

| Endpoint | What it does |
|---|---|
| `POST /v1/webhooks` | Register a URL. Returns the endpoint with `status: "pending"` and its `secret`, shown once |
| `POST /v1/webhooks/{id}/verify` | Sends a `webhook.test` event carrying a random `challenge`. The endpoint becomes `active` when its 2xx answer contains `HMAC-SHA256(secret, challenge)` in hex. Repeating the challenge is not enough: the endpoint must hold the secret |
| `GET /v1/webhooks`, `GET /v1/webhooks/{id}` | List, or read one. Free |
| `POST /v1/webhooks/{id}/test` | Sends a `webhook.test` event to an active endpoint |
| `POST /v1/webhooks/{id}/rotate` | Issues a new secret, shown once. For 24 hours deliveries carry both signatures |
| `GET /v1/webhooks/{id}/deliveries` | The delivery log |
| `DELETE /v1/webhooks/{id}` | Remove it. Its monitors keep running and their events are pulled |

## Register and verify

```bash
curl https://api.millionshort.com/v1/webhooks \
  -H "Authorization: Bearer $MILLIONSHORT_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{ "url": "https://hooks.example.com/millionshort", "description": "production" }'
```

```python
import os

import requests

r = requests.post(
    "https://api.millionshort.com/v1/webhooks",
    headers={"Authorization": "Bearer " + os.environ["MILLIONSHORT_API_KEY"]},
    json={
        "url": "https://hooks.example.com/millionshort",
        "description": "production"
    },
    timeout=30,
)
r.raise_for_status()
print(r.json()["data"])
```

```ts
const res = await fetch('https://api.millionshort.com/v1/webhooks', {
  method: 'POST',
  headers: {
    Authorization: `Bearer ${process.env.MILLIONSHORT_API_KEY}`,
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    "url": "https://hooks.example.com/millionshort",
    "description": "production"
  }),
});
if (!res.ok) throw new Error(`POST /v1/webhooks failed: ${res.status}`);
const { data } = (await res.json()) as { data: unknown };
console.log(data);
```

```bash
curl -X POST https://api.millionshort.com/v1/webhooks/$WEBHOOK_ID/verify \
  -H "Authorization: Bearer $MILLIONSHORT_API_KEY"
```

```python
import os

import requests

r = requests.post(
    f"https://api.millionshort.com/v1/webhooks/{os.environ['WEBHOOK_ID']}/verify",
    headers={"Authorization": "Bearer " + os.environ["MILLIONSHORT_API_KEY"]},
    timeout=30,
)
r.raise_for_status()
print(r.json()["data"])
```

```ts
const res = await fetch(`https://api.millionshort.com/v1/webhooks/${process.env.WEBHOOK_ID}/verify`, {
  method: 'POST',
  headers: { Authorization: `Bearer ${process.env.MILLIONSHORT_API_KEY}` },
});
if (!res.ok) throw new Error(`POST /v1/webhooks/…/verify failed: ${res.status}`);
const { data } = (await res.json()) as { data: unknown };
console.log(data);
```

Only an `active` endpoint receives events. An endpoint still `pending` 24 hours after registration is deleted.

| Field | Type | Notes |
|---|---|---|
| `id` | string | |
| `url` | string | |
| `description` | string or null | |
| `status` | `pending`, `active` or `disabled` | |
| `secret` | string | Starts with `whsec_`. Only in the answers to register and rotate |
| `created_at` | date and time | |
| `last_success_at` | date and time, or null | |
| `consecutive_failures` | integer | |

## What your endpoint receives

A `POST` with a JSON body, the event, and three headers:

```text
MS-Event-Id: evt_01J...
MS-Timestamp: 1763460000
MS-Signature: t=1763460000,v1=<hex>
```

The signature is `HMAC-SHA256(secret, "<event id>.<t>.<raw body>")`, in hex. The key is the whole secret string, `whsec_` included, as UTF-8 bytes. `t` is the same number as `MS-Timestamp`. Every delivery is signed, the verification challenge included. During a rotation there are two `v1=` values, and either may match.

## Check the signature

```python
import hashlib
import hmac
import time


def verify(secret, event_id, timestamp, signature_header, raw_body, tolerance=300):
    """True when the delivery is ours and recent. raw_body is bytes, exactly as received."""
    if abs(time.time() - int(timestamp)) > tolerance:
        return False
    signed = event_id.encode() + b"." + str(timestamp).encode() + b"." + raw_body
    expected = hmac.new(secret.encode(), signed, hashlib.sha256).hexdigest()
    sent = [part[3:] for part in signature_header.split(",") if part.startswith("v1=")]
    return any(hmac.compare_digest(expected, candidate) for candidate in sent)
```

```ts
import { createHmac, timingSafeEqual } from 'node:crypto';

/** True when the delivery is ours and recent. rawBody is the bytes exactly as received. */
export function verify(
  secret: string,
  eventId: string,
  timestamp: string,
  signatureHeader: string,
  rawBody: Uint8Array,
  tolerance = 300,
): boolean {
  if (Math.abs(Date.now() / 1000 - Number(timestamp)) > tolerance) return false;
  const expected = createHmac('sha256', secret)
    .update(`${eventId}.${timestamp}.`)
    .update(rawBody)
    .digest();
  return signatureHeader
    .split(',')
    .filter((part) => part.startsWith('v1='))
    .map((part) => Buffer.from(part.slice(3), 'hex'))
    .some((sent) => sent.length === expected.length && timingSafeEqual(sent, expected));
}
```

Your endpoint should:

1. Reject a delivery whose timestamp is more than 300 seconds from now.
2. Compare signatures in constant time, as above.
3. Remember `MS-Event-Id` for 24 hours and drop repeats. A retry keeps the event id and carries a fresh timestamp and signature.
4. Answer with a 2xx status quickly, and do the work afterwards.

## Delivery rules

- `https` only. The URL must be a public address. It is checked at registration and again on every delivery.
- A redirect counts as a failure. The answer's body is ignored, except when verifying. The timeout is 10 seconds. A payload is at most 256 KB.
- **Retries:** six attempts: one at once, then a retry about 1 minute, 10 minutes, 1 hour, 6 hours and 24 hours after each failure, on anything that is not a 2xx.
- **Auto-disable:** after 20 failures in a row, or 3 days of failed attempts with no success, the endpoint becomes `disabled`. Its monitors are paused with a `monitor.paused` event, and their events stay available to pull for 30 days.

## The delivery log

`GET /v1/webhooks/{id}/deliveries` returns the latest attempts, newest first:

| Field | Type | Notes |
|---|---|---|
| `event_id` | string | |
| `event_type` | string | |
| `attempt` | integer | |
| `status_code` | integer or null | What your endpoint answered |
| `duration_ms` | integer | |
| `ok` | boolean | |
| `at` | date and time | |

The log never holds the body of a delivery.

## Limits

- 10 endpoints per team, and 20 registrations a day.
- `/verify` and `/test`: 5 an hour per endpoint, and 20 an hour per team.

## Event types

`monitor.changed`, `monitor.failed`, `monitor.paused`, `extract_batch.completed` and `webhook.test`. The [Monitors](https://millionshort.com/docs/monitor/parameters#events) page describes what each carries.

An [Agent](https://millionshort.com/docs/agent) run started with a `webhook_id` delivers `agent.completed` when it ends, with the run's `id`, `status`, `stop_reason` and `credits_used`. See [the webhook event](https://millionshort.com/docs/agent/parameters#the-webhook-event).
