# Receiving webhooks

OpenEmail's webhooks with the TypeScript SDK, end to end: register a hook, verify and parse what it sends, answer it, recover from failures, test it.

The API sends two kinds of webhook, both POSTs signed with the hook's secret
(`x-openemail-signature: sha256=<hex HMAC-SHA256 of the exact body>`):

- **Event batches**: what changed in a mailbox or a domain (mail arriving,
  flags changing, deliveries settling), as identifiers.
- **Message deliveries**: a whole message, for an address whose mail goes to
  a URL.

## Register a hook

A mailbox's and a domain's event webhooks each get their own copy of a batch,
signed with their own secret:

```ts
await openemail.mailboxes.setEventWebhook(mailboxId, { url: 'https://example.com/hooks/openemail', secret })
await openemail.domains.setEventWebhook(domain, { url: 'https://example.com/hooks/openemail', secret })
```

Messages come from a mailbox's message webhook,
[`mailboxes.setMessageWebhook`](/docs/sdks/typescript/mailboxes/set-message-webhook),
and from a route: [`routes.create`](/docs/sdks/typescript/routes/create) with a
`webhookUrl`, as its destination or as a tap beside another one (its secret is
`webhookSecret`).

Give each a secret. It is optional, but without one the API signs nothing, so
there is nothing to check: `verifyWebhookSignature` and the parsers throw a
`TypeError` when given an empty secret.

## Receive the raw body

The signature is over the body's exact bytes: parsed and written again, it is
no longer what was signed. Read the body before anything parses it.

- **A handler given a Fetch `Request`** (Next.js route handlers, Hono,
  Cloudflare Workers, Bun, Deno): `await request.text()`.
- **Express**: give the hook's route `express.raw()`, and pass `req.body`, a
  `Buffer`:

  ```js
  app.post('/hooks/openemail', express.raw({ type: '*/*' }), async (req, res) => {
    const batch = await parseEventWebhook(req.body, req.get('x-openemail-signature'), secret)
    res.sendStatus(204)
  })
  ```

The body is a string, an `ArrayBuffer` or any typed array (a `Buffer`, a
`DataView`); anything else, parsed JSON or a `Blob`, throws a `TypeError`.

## Verify and parse

```ts
import { parseEventWebhook, WebhookSignatureError } from '@openemail/sdk'

async function onEvents(request: Request): Promise<Response> {
  const body = await request.text()
  const signature = request.headers.get('x-openemail-signature')
  try {
    const batch = await parseEventWebhook(body, signature, secret)
    // queue the batch's work here, then answer
    return new Response(null, { status: 204 })
  } catch (error) {
    if (!(error instanceof WebhookSignatureError)) throw error
    return new Response(null, { status: 401 })
  }
}
```

- `parseEventWebhook` checks the signature, then parses the batch
  (`EventWebhookPayload`). It throws a `WebhookSignatureError` when the
  signature is not the body's.
- `parseMessageWebhook` does the same for a message delivery
  (`WebhookDeliveryPayload`).
- `verifyWebhookSignature(body, signature, secret)` only answers whether the
  signature is the body's, compared in constant time.

## Answer, and dedupe

Answer `2xx` within 30 seconds and do the work after. A non-`2xx` answer or a
timeout is a failed attempt, sent again later on a backoff; a redirect is never
followed, and counts as a failed attempt too.

- A batch keeps its `id` across retries, and a mailbox's and a domain's copies
  of one batch share it: dedupe on its `id` and its `scope`.
- A message delivery keeps its `deliveryId`: dedupe on that.

## Refuse a replayed batch

A batch's `sentAt` is its attempt's own time, in epoch seconds, inside the
signed body. A retry carries a fresh one; a request captured and sent again
later carries an old one. Refuse a batch whose `sentAt` is more than a few
minutes from now:

```ts
import type { EventWebhookPayload } from '@openemail/sdk'

function isFresh(batch: EventWebhookPayload): boolean {
  return Math.abs(Date.now() / 1000 - batch.sentAt) <= 300  // five minutes, either way
}
```

## When the answers keep failing

After 24 hours of failed attempts the API disables the hook: its
`disabledReason` is `failing`. Setting the hook again enables it.

```ts
const hook = await openemail.mailboxes.getEventWebhook(mailboxId)
if (hook.disabledReason === 'failing') await openemail.mailboxes.setEventWebhook(mailboxId, { url: hook.url, secret })
```

Events are signals, not a journal. After a disabled hook, or any gap, catch up
with [`messages.getChanges`](/docs/sdks/typescript/messages/get-changes) from
the last batch's state, its `states.Email`:

```ts
const changes = await openemail.messages.getChanges(mailboxId, { since: state })
```

## Send a test

[`mailboxes.testEventWebhook`](/docs/sdks/typescript/mailboxes/test-event-webhook)
and [`domains.testEventWebhook`](/docs/sdks/typescript/domains/test-event-webhook)
send the hook one batch now: a way to check an endpoint before real events
arrive.

## Message deliveries

A message delivery's POST is the delivery itself: answer `2xx` within 30
seconds, or it is sent again with the same `deliveryId`. Its bodies and
attachments are inlined up to fixed ceilings (1 MiB a body, 256 KiB an
attachment, 1 MiB of attachments in all). Anything larger arrives as a signed
link that expires (`url`, `rawUrl`), which needs no credential: fetch it as it
is, or pass its token, the link's last segment, to
[`deliveries.download`](/docs/sdks/typescript/deliveries/download). A route or
a tap set to `webhookFormat: 'reference'` gets the envelope and every header
without the parsed bodies, for a receiver that parses MIME itself.

What each payload holds is in the API reference's [Webhooks](/docs/api/webhooks):
an [event batch](/docs/api/webhooks/event-batch) and a
[message delivery](/docs/api/webhooks/message-delivery).
