# Verify and consume webhooks

Wildmail sends HTTP `POST` requests with `Content-Type: application/json`. Verify the signature against the original request bytes before parsing JSON. Parsing and reserializing can change whitespace, escaping, or field order.

## Signing contract

Webhook requests use these headers:

| Header               | Value                                                            |
| -------------------- | ---------------------------------------------------------------- |
| `wildmail-timestamp`  | Unix seconds for this HTTP attempt.                              |
| `wildmail-event-id`   | Stable logical event ID shared by retries and replay.            |
| `wildmail-attempt-id` | Unique ID for this HTTP attempt.                                 |
| `wildmail-key-id`     | Signing-key version ID for the endpoint.                         |
| `wildmail-signature`  | `v1=` followed by a 64-character hexadecimal HMAC-SHA256 digest. |

Compute the digest using the endpoint signing secret as the key and this exact input:

```text
<timestamp>.<event_id>.<raw UTF-8 JSON body>
```

Compare digests in constant time and reject timestamps outside a short tolerance, such as five minutes. Keep receiver clocks synchronized. Automatic retries receive new timestamps, attempt IDs, and signatures. They keep the event ID and pinned endpoint and shaping revision. Retries preserve the request body.

```mermaid
flowchart TD
    A[Receive request] --> B[Capture exact raw bytes]
    B --> C[Check timestamp and HMAC]
    C -->|Invalid| X[Reject request]
    C -->|Valid| D[Parse JSON]
    D --> E[Deduplicate event_id and commit]
    E -->|Duplicate already applied| OK[Return 2xx without repeating effects]
    E -->|Commit succeeds| OK2[Return 2xx]
    E -->|Temporary commit failure| R[Return failure so retained mail can retry]
```

Verify before parsing, then persist the event ID with your business change. A duplicate event should be acknowledged without repeating its side effect. Return success only after a durable commit or enqueue.

## Standard and shaped payloads

The standard event uses the `wildmail.v1` schema and nests the parsed email under `message`. Receiver-added headers remain available, including delivery and authentication headers. `envelope.recipients` contains the Wildmail addresses matched for this endpoint. Original `to`, `cc`, and `bcc` fields are message content supplied by the sender and can differ from that envelope.

```json
{
  "schema_version": "wildmail.v1",
  "event_type": "email.received",
  "event_id": "evt_example",
  "received_at": "2026-11-02T12:00:00.000Z",
  "envelope": {
    "sender": "vendor@example.com",
    "recipients": ["orders@example.net"]
  },
  "message": {
    "message_id": "<purchase@example.com>",
    "thread_id": "507f1f77bcf86cd799439011",
    "date": "2026-11-02T11:59:59.000Z",
    "from": { "name": "Vendor", "address": "vendor@example.com" },
    "reply_to": [],
    "to": [{ "name": "Orders", "address": "orders@example.net" }],
    "cc": [],
    "bcc": [],
    "subject": "Purchase order",
    "headers": [
      { "name": "Delivered-To", "value": "orders@example.net" },
      { "name": "Authentication-Results", "value": "mx.example.net; dkim=pass" }
    ],
    "text": "Please see the attached order.",
    "html": ["<p>Please see the attached order.</p>"],
    "content_type": { "value": "multipart/mixed", "params": {} },
    "attachments": [],
    "authentication": { "dkim": { "result": "pass" } },
    "is_spam": false,
    "spam": { "engine": "rspamd", "status": "scanned", "score": 0.1, "action": "no action", "required_score": 6.0, "symbols": [] }
  }
}
```

`message.subject` and some address fields can be null or empty. Message headers, HTML, MIME types, filenames, and attachment bytes are untrusted input. Authentication results are signals for your application, not proof that attachments are safe.

`message.thread_id` is the conversation ID, identical to `threadId` in the message and thread APIs. It is `null` when thread metadata is unavailable. Thread matching uses message references and normalized subjects, so unrelated messages sharing a subject stay separate and changing the subject can create a new thread. Select `/message/thread_id` in payload shaping to include or rename it. Older events can omit the field. Automatic retries and replay reproduce the original body exactly, including omission of `thread_id` and any earlier schema name.

When scan data is available, `message.is_spam` is a quick boolean verdict and is true only when Rspamd completed a scan and marked the message as spam. False means there is no positive spam verdict; it does not prove the message is clean. Check `message.spam.status` to distinguish a completed scan (`scanned`) from a skipped scan (`skipped`) or scanner error (`error`). `message.spam` is null when scan details are unavailable. When present, it contains `engine`, `status`, numeric or null `score`, string or null `action`, numeric or null `required_score`, and `symbols` entries with `name` and numeric `score`. These fields are selectable in payload shaping. Older events may omit both `is_spam` and `spam`. Receivers should handle missing scan data.

If you configure **Payload shaping**, Wildmail sends the selected fields and structure instead of the standard JSON body. A mapping can omit or rename `event_id`, message content, or attachment fields. The `wildmail-event-id` signature header remains the stable deduplication identity.

## Attachments and retention

With positive retention, attachment descriptors include an ID, filename, content type, disposition, content ID, byte count, SHA-256 digest, and a Wildmail download URL. Download with an account API key that has `messages:read`:

```json
{
  "id": "att_example",
  "filename": "purchase-order.pdf",
  "content_type": "application/pdf",
  "disposition": "attachment",
  "content_id": null,
  "byte_count": 12000,
  "sha256": "<64-character hexadecimal digest>",
  "download_url": "https://wildmail.app/api/messages/<message-id>/attachments/att_example"
}
```

Use the `download_url` with `Authorization: Bearer <key>`. The URL is not a bearer credential by itself. Wildmail checks current account retention before and after opening a download. Verify the returned byte count and SHA-256 digest. Treat sender filenames as untrusted input and do not use them directly as filesystem paths.

With 0-day retention, each attachment has `content_base64` containing the base64 encoding of its bytes and has no download URL. Decode the value before using the bytes. `byte_count` and `sha256` describe the decoded content. Wildmail permits at most one delivery attempt and does not retry or replay the event. A message that has not reached an attempt has a 24-hour safety deadline.

Changing retention applies to existing and future messages. Reducing retention can make existing content unavailable immediately. Extending it can keep eligible existing content available longer. Delivery retry, replay, message detail, raw downloads, and attachment downloads all follow the current policy.

## Test events

The dashboard test action sends a synthetic event with `event_type: "email.test"` and a synthetic message. It does not count toward inbound message usage. It checks signing and endpoint connectivity, but does not contain customer email or attachments. Handle `email.test` separately from `email.received`.

## Runnable TypeScript receiver

Save this as `receiver.ts`, set `WILDMAIL_WEBHOOK_SECRET` to the endpoint secret, and run it with Node.js 24. The example listens on loopback for local receiver development. To receive Wildmail deliveries, expose the receiver through a public HTTPS endpoint and configure that URL in your account.

This sample caps its own request body at 32 MiB. Set the receiver's limit to fit your workload and infrastructure.

```ts
import { createHmac, timingSafeEqual } from "node:crypto";
import { createServer, type IncomingMessage } from "node:http";

const secret = process.env.WILDMAIL_WEBHOOK_SECRET;
if (!secret) throw new Error("Set WILDMAIL_WEBHOOK_SECRET");
const signingSecret: string = secret;
const maxBodyBytes = 32 * 1_048_576;

function header(req: IncomingMessage, name: string): string {
  const value = req.headers[name];
  return typeof value === "string" ? value : "";
}

function verify(req: IncomingMessage, raw: Buffer): string | null {
  const timestamp = header(req, "wildmail-timestamp");
  const eventId = header(req, "wildmail-event-id");
  const signature = header(req, "wildmail-signature");
  if (!/^\d+$/.test(timestamp) || !eventId) return null;
  if (!Number.isSafeInteger(Number(timestamp))) return null;
  if (Math.abs(Date.now() / 1000 - Number(timestamp)) > 300) return null;
  if (!/^v1=[a-f0-9]{64}$/.test(signature)) return null;

  const expected = createHmac("sha256", signingSecret)
    .update(`${timestamp}.${eventId}.`)
    .update(raw)
    .digest();
  const received = Buffer.from(signature.slice(3), "hex");
  return timingSafeEqual(expected, received) ? eventId : null;
}

// Demonstration only. Persist event IDs with business changes in production.
const seen = new Set<string>();

createServer(async (req, res) => {
  if (req.method !== "POST" || req.url !== "/webhook") {
    res.writeHead(404).end();
    return;
  }

  try {
    const chunks: Buffer[] = [];
    let bytes = 0;
    for await (const chunk of req) {
      const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
      bytes += buffer.length;
      if (bytes > maxBodyBytes) {
        res.writeHead(413).end();
        return;
      }
      chunks.push(buffer);
    }

    const raw = Buffer.concat(chunks);
    const eventId = verify(req, raw);
    if (!eventId) {
      res.writeHead(401).end();
      return;
    }

    const event = JSON.parse(raw.toString("utf8"));
    if (!event || typeof event !== "object" || Array.isArray(event)) {
      res.writeHead(400).end();
      return;
    }
    if (!seen.has(eventId)) {
      console.log({ eventId, type: event.event_type });
      seen.add(eventId);
    }
    res.writeHead(204).end();
  } catch (error) {
    res.writeHead(error instanceof SyntaxError ? 400 : 500).end();
  }
}).listen(8787, "127.0.0.1", () => console.log("Receiver on port 8787"));
```

For production, replace the in-memory set with durable deduplication. In one transaction, insert `event_id` with a unique constraint and apply your application changes. If the ID already exists, acknowledge it without repeating effects. Another option is to commit the unique event ID and a durable work item together, then process it asynchronously.

Respond with 2xx only after committing durable state. Return a retryable status if a temporary database or queue failure prevents that commit. Positive-retention events can retry while content remains available. Zero-day events cannot retry. A network failure can leave your receiver unsure whether the event was committed, so always make repeated event IDs safe.
