# Webhooks

Source: https://docs.simail.ai/webhooks/

> Signed HTTPS deliveries of simail events (Standard Webhooks): setup, verification, retries, automatic disabling, replay and the read-only API.

simail publishes an [event](/event-types/) whenever something happens in an inbox. You can consume the
same events in three ways:

| Channel | Best for | Permission |
|---|---|---|
| [`GET /v0/events`](/events/) (polling with a cursor) | simple agents, no public endpoint needed | `event_read` |
| Webhooks (signed HTTPS POST, this page) | servers | created by a human in the console; `webhook_read` to inspect |
| [WebSocket](/realtime/) `wss://api.simail.ai/v0/ws` | long-running agents | `event_read` |

Payloads are thin (no subject or body) and identical on every channel; see [Event types](/event-types/).

## Setting up an endpoint

A human creates an endpoint in the console (**Webhooks → New**) and must pick the `event_types`
explicitly; there is no "all events" default. Endpoints can be filtered by pod or inbox and can carry
custom headers (stored encrypted). Inbound events that did not [wake your agent](/event-types/#waking-your-agent)
(`message.received`, `message.received.spam`, `message.received.blocked`, `message.held`) are delivered only if the
endpoint has **Include non-waking events** (`include_non_wake`) on. Every other event type (`message.sent`, `send.*`,
`approval.*`, `label.*`, `org.*` and so on) is not affected by this switch. Creating
or changing an endpoint requires re-verification. The signing secret (`whsec_…`) is shown once; a human
can rotate it, and during rotation both the old and new signatures are sent for 24 hours.

Endpoint rules: `https://` on port 443, a public host name (no IP literals, `localhost`, `.local` or
`.internal`, and no simail-owned domains).

## Request

- `POST`, `content-type: application/json`, `user-agent: simail-webhooks/1`.
- Headers `webhook-id` (the `event_id`), `webhook-timestamp` (Unix seconds) and `webhook-signature`
  (`v1,<base64 HMAC-SHA256>`). The same values are also sent as `svix-id`, `svix-timestamp` and
  `svix-signature`, so existing Standard Webhooks and Svix verifiers work unchanged.
- 10-second timeout. Redirects are not followed (a `3xx` counts as a failure). Only a `2xx` is success.

## Verify every delivery

Compute `base64(HMAC-SHA256(secret, "{webhook-id}.{webhook-timestamp}.{raw body}"))` with the bytes
after `whsec_` (base64-decoded) as the key, compare it in constant time to each `v1,` value in
`webhook-signature`, and reject timestamps more than 5 minutes away. During secret rotation, both the
old and new signatures are sent for 24 hours.

```ts
// Verify a simail webhook (Standard Webhooks). Works in Node 20+, Cloudflare Workers, Deno and Bun.
// This file is shown verbatim on docs.simail.ai/webhooks and is exercised by the docs tests.

const TOLERANCE_SECONDS = 300;

function base64ToBytes(b64: string): Uint8Array<ArrayBuffer> {
  const bin = atob(b64);
  const out = new Uint8Array(bin.length);
  for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);
  return out;
}

function bytesToBase64(bytes: Uint8Array): string {
  let bin = "";
  for (const b of bytes) bin += String.fromCharCode(b);
  return btoa(bin);
}

function constantTimeEqual(a: string, b: string): boolean {
  if (a.length !== b.length) return false;
  let diff = 0;
  for (let i = 0; i < a.length; i++) diff |= a.charCodeAt(i) ^ b.charCodeAt(i);
  return diff === 0;
}

/**
 * @param secret  the endpoint secret shown once in the console, e.g. "whsec_…"
 * @param headers the request headers
 * @param body    the raw request body, exactly as received (do not re-serialize JSON)
 * @returns true only for an authentic, fresh delivery
 */
export async function verifySimailWebhook(
  secret: string,
  headers: Headers,
  body: string,
  nowSeconds: number = Math.floor(Date.now() / 1000),
): Promise<boolean> {
  const id = headers.get("webhook-id");
  const timestamp = headers.get("webhook-timestamp");
  const signatures = headers.get("webhook-signature");
  if (!id || !timestamp || !signatures) return false;

  const ts = Number(timestamp);
  if (!Number.isInteger(ts) || Math.abs(nowSeconds - ts) > TOLERANCE_SECONDS) return false;

  const key = await crypto.subtle.importKey(
    "raw",
    base64ToBytes(secret.replace(/^whsec_/, "")),
    { name: "HMAC", hash: "SHA-256" },
    false,
    ["sign"],
  );
  const mac = await crypto.subtle.sign("HMAC", key, new TextEncoder().encode(`${id}.${timestamp}.${body}`));
  const expected = bytesToBase64(new Uint8Array(mac));

  // During secret rotation the header carries two space-separated "v1,<signature>" values.
  return signatures.split(" ").some((part) => {
    const [version, signature] = part.split(",", 2);
    return version === "v1" && signature !== undefined && constantTimeEqual(signature, expected);
  });
}
```

Use `webhook-id` to de-duplicate: retries and replays keep the same id.

## Retries and disabling

- Failed deliveries are retried 9 times: after 5 s, 5 min, 30 min, 2 h, 5 h, 10 h, 12 h, 12 h and
  12 h (about 54 hours). `Retry-After` is respected (up to 12 hours).
- A `410 Gone` response **disables the endpoint immediately**.
- An endpoint that keeps failing for 5 days is disabled automatically. A human re-enables it.
- Each endpoint receives at most 60 requests per minute; extra deliveries are delayed, not dropped.
- Every attempt is logged (status code and timing, never the response body):
  `GET /v0/webhooks/{webhook_id}/deliveries`.

## Replay and test

From the console, a human can replay events for an endpoint (up to 7 days or 1,000 events) or send a
test delivery. Replays keep the original `webhook-id` with a fresh timestamp and signature.

## API

`GET /v0/webhooks`, `GET /v0/webhooks/{webhook_id}`, `GET /v0/webhooks/{webhook_id}/headers` (names
only) and `…/deliveries` need `webhook_read`. Creating, changing and deleting webhooks is
`403 human_required` through the API, so a compromised key cannot add an exfiltration endpoint. See
[Webhooks API](/api/webhooks/).

Polling webhooks (`/v0/webhooks/polling`) are not offered; use [`GET /v0/events`](/events/).
