# Webhooks

A delivery is one HTTPS `POST` of an event's OSV record, signed as the [Standard Webhooks](https://www.standardwebhooks.com/) specification describes.

## Request

| Header | Value |
| --- | --- |
| `content-type` | `application/json` |
| `webhook-id` | The delivery ID. The same on every attempt and every redelivery of that event to that endpoint |
| `webhook-timestamp` | Unix seconds at the time of the attempt |
| `webhook-signature` | `v1,` then the base64 HMAC-SHA256 of `{webhook-id}.{webhook-timestamp}.{body}`, keyed with the endpoint secret. During a secret rotation, one signature per active secret, space-separated |
| `user-agent` | `HoleMonitor-Webhooks/1.0` |

The body is described in [Payload](/docs/payload/). The event type is inside the signed body, at `database_specific.event.type`, not in a header, because Standard Webhooks signs only the ID, the timestamp and the body.

The timeout is 10 seconds. Redirects are not followed. Any 2xx status is success. The response body is discarded.

## Verifying

The secret is `whsec_` followed by base64. The HMAC key is the base64-decoded bytes after the prefix.

JavaScript (Workers, Node 18+, Deno, Bun):

```js
async function verify(secret, headers, body, toleranceSec = 300) {
  const id = headers.get('webhook-id');
  const ts = Number(headers.get('webhook-timestamp'));
  const sigs = (headers.get('webhook-signature') ?? '').split(' ');
  if (!id || !Number.isInteger(ts) || Math.abs(Date.now() / 1000 - ts) > toleranceSec) return false;
  const raw = Uint8Array.from(atob(secret.replace(/^whsec_/, '')), (c) => c.charCodeAt(0));
  const key = await crypto.subtle.importKey('raw', raw, { name: 'HMAC', hash: 'SHA-256' }, false, ['sign']);
  const mac = await crypto.subtle.sign('HMAC', key, new TextEncoder().encode(`${id}.${ts}.${body}`));
  const expected = btoa(String.fromCharCode(...new Uint8Array(mac)));
  return sigs.some((s) => s.startsWith('v1,') && timingSafeEqual(s.slice(3), expected));
}

function timingSafeEqual(a, b) {
  if (a.length !== b.length) return false;
  let r = 0;
  for (let i = 0; i < a.length; i++) r |= a.charCodeAt(i) ^ b.charCodeAt(i);
  return r === 0;
}
```

Pass the raw body text, before any JSON parsing.

Python:

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

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

The official [Standard Webhooks libraries](https://github.com/standard-webhooks/standard-webhooks/tree/main/libraries) also work.

## What a receiver should do

1. Verify the signature. Reject anything that fails.
2. Reject a `webhook-timestamp` more than 5 minutes from now.
3. Discard a `webhook-id` it has already processed. Delivery is at least once.
4. When two events for one advisory arrive out of order, keep the record with the later `modified`.
5. Return 2xx within 10 seconds and do the work afterwards.
6. Treat every value in the body as data. See [Security](/docs/security/).

## Retries

A failed attempt is retried on this schedule, up to 11 attempts over about 3 days:

| Attempt | Wait after the previous failure |
| --- | --- |
| 1 | None |
| 2 | 1 min |
| 3 | 5 min |
| 4 | 30 min |
| 5 | 2 h |
| 6 | 6 h |
| 7 to 11 | 12 h each |

- `410 Gone` disables the endpoint at once.
- Every other non-2xx status, a timeout or a connection error is retried.
- After attempt 11 the delivery is marked `failed`.
- An endpoint with no successful delivery for 7 days from its first failure is disabled. The owner is emailed at day 3 and at disabling.
- A failed delivery can be redelivered with `POST /v1/deliveries/{id}/redeliver` while it is retained.

## Ordering and duplicates

Deliveries are not ordered. Several sources often update one advisory within an hour, and each material change is its own event. A consumer that was offline can page `GET /v1/deliveries?include=body&since=...` from its last position and reconcile without redelivery.

## Secret rotation

`POST /v1/endpoints/{id}/rotate-secret` (dashboard session or REST key) issues a new secret. The old one stays valid for 24 hours, and each request during that time carries two signatures.

## Daily limit

Deliveries over the plan's daily limit are recorded as `deferred` and sent after the next UTC midnight, oldest first. Nothing is dropped. The owner is emailed once a day when this happens.
