# Webhooks

A webhook endpoint is a URL on your server that receives events as JSON `POST` requests. Add
endpoints in the dashboard, one per mode, and choose the [event types](https://docs.signapi.dev/webhooks) and topics each
one receives.

## Responding

Answer with any `2xx` status within 15 seconds. Do the work afterwards, for example in a queue:
anything else, including a timeout, counts as a failure.

Failed deliveries are retried with growing waits for up to 48 hours. Every attempt for one event
carries the same `webhook-id`, so use it to ignore duplicates. Events can arrive out of order;
compare `timestamp`, or read the current state from the API before acting. An endpoint that fails
for five days in a row is turned off and the account owner is emailed.

## Checking the signature

Every delivery has three headers:

- `webhook-id`: the delivery's ID, `msg_…`
- `webhook-timestamp`: when it was sent, in Unix seconds
- `webhook-signature`: one or more signatures, `v1,<base64>`, separated by spaces

To check a delivery, take the endpoint's signing secret (`whsec_…`), drop the `whsec_` prefix and
base64-decode the rest to get the key. Compute an HMAC-SHA256 of `{webhook-id}.{webhook-timestamp}.{raw body}`
with that key and base64-encode it. The delivery is genuine if the result equals any of the
signatures after `v1,`. Reject timestamps more than five minutes old.

```js
import { createHmac, timingSafeEqual } from "node:crypto"

export function verify(secret, headers, rawBody) {
  const key = Buffer.from(secret.replace(/^whsec_/, ""), "base64")
  const id = headers["webhook-id"]
  const ts = headers["webhook-timestamp"]
  if (Math.abs(Date.now() / 1000 - Number(ts)) > 300) return false
  const expected = createHmac("sha256", key).update(`${id}.${ts}.${rawBody}`).digest()
  return headers["webhook-signature"].split(" ").some((sig) => {
    const [version, value] = sig.split(",")
    const got = Buffer.from(value ?? "", "base64")
    return version === "v1" && got.length === expected.length && timingSafeEqual(got, expected)
  })
}
```

Use the raw body exactly as received: parsing and re-serializing the JSON changes it. While you
rotate a secret, deliveries carry a signature for the old and the new secret.

## Developing locally

`signapi listen --forward-to http://localhost:3000/webhooks` registers a temporary test-mode
endpoint and forwards each signed delivery to your local handler, without exposing it to the
internet. `signapi trigger envelope.completed` sends a sample event. See [CLI](https://docs.signapi.dev/cli).
