# Webhooks

## Subscribe [#subscribe]

`POST /email/webhooks` with an HTTPS `url` and the `event_types` you want. The
answer includes a `signing_secret`, shown only once: store it.

| Event | When |
|---|---|
| `queued` | Accepted and waiting to go out |
| `delivered` | The recipient's server accepted it |
| `deferred` | Delayed; Relevate keeps trying |
| `permanently_failed` | Bounced or refused |
| `complained` | Marked as spam |
| `suppressed` | Not sent: the address is blocked |
| `opened`, `clicked` | Where tracking is allowed |
| `inbound.received` | An email arrived at one of your inboxes |

Every event carries the `email_id` and your `tags`. Clicked links come without
their query string, so tokens in links aren't passed on.

## Verify the signature [#verify-the-signature]

Each request has `X-Relevate-Signature: t=<unix seconds>,v1=<hex>`. `v1` is
HMAC-SHA256 of `"<t>.<raw body>"` with your signing secret. Compare in constant
time, and refuse a `t` more than five minutes off.

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

export function verify(rawBody: string, header: string, secret: string) {
  const parts = Object.fromEntries(header.split(",").map((p) => p.split("=")));
  const age = Math.abs(Date.now() / 1000 - Number(parts.t));
  if (!parts.t || !parts.v1 || age > 300) return false;
  const expected = createHmac("sha256", secret)
    .update(`${parts.t}.${rawBody}`)
    .digest("hex");
  return timingSafeEqual(Buffer.from(expected), Buffer.from(parts.v1));
}
```

## Delivery [#delivery]

- Answer with any `2xx` within 10 seconds. Redirects count as failures.
- Failures are retried with growing gaps, up to six hours apart, 12 times.
- `X-Relevate-Event-Id` is the same on every retry: use it to skip duplicates.
- `GET /email/webhooks/{id}/deliveries` shows recent attempts; replay one with
  `POST /email/webhooks/{id}/deliveries/{delivery_id}/replay`.
