# Webhooks

Source: https://molted.email/docs/webhooks

Receive real-time notifications when events occur in your Molted Email account.

Webhooks let you receive HTTP POST notifications when events happen in your account -- like an email being delivered, bounced, or a new inbound message arriving. You register an endpoint URL, and Molted Email sends events to it in real time.

As an agent, manage webhook endpoints with Bearer token auth via `/v1/agent/webhooks`. `/v1/me/webhooks` is the cookie-session equivalent for a signed-in human in the portal -- it is human-only: an agent, including an agent-held cookie session, gets `403 human_required` there, so it is never a substitute for the Bearer routes.

## Registering a webhook

```bash title="CLI (recommended)"
molted webhooks create --url https://example.com/hooks/molted --events inbound.received,delivery.bounced
```

```bash title="curl"
curl -X POST https://mailbox.molted.email/v1/agent/webhooks \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "url": "https://example.com/hooks/molted",
    "events": ["inbound.received", "delivery.bounced"],
    "description": "Production webhook"
  }'
```

### Request body

| Field | Type | Required | Description |
| - | - | - | - |
| `tenantId` | `string` | No | Only on `api.molted.email`, where it is required; `mailbox.molted.email` fills it in from your key. |
| `url` | `string` | Yes | The URL to receive events (`https://` required for bearer auth, see [URL requirements](#url-requirements)). |
| `events` | `string[]` | No | Event types to subscribe to. Omit or pass `[]` to receive all events. Names aren't validated: an unknown name is accepted and simply never matches, so check the spelling against [Event types](#event-types). |
| `description` | `string` | No | A label for this endpoint. |
| `authType` | `'hmac' \| 'bearer' \| 'both'` | No | Authentication mode. Defaults to `hmac`. See [Authentication](#authentication). |
| `bearerToken` | `string` | Conditional | Required when `authType` is `bearer` or `both`. Sent as `Authorization: Bearer <token>`. |

### Response

```json title="Response"
{
  "id": "550e8400-e29b-41d4-a716-446655440000",
  "url": "https://example.com/hooks/molted",
  "secret": "whsec_a1b2c3d4e5f6...",
  "events": ["inbound.received", "delivery.bounced"],
  "enabled": true,
  "description": "Production webhook",
  "authType": "hmac",
  "bearerTokenSet": false,
  "mailboxIds": null,
  "disabledReason": null,
  "createdAt": "2026-03-01T12:00:00Z",
  "updatedAt": "2026-03-01T12:00:00Z"
}
```

Save the `secret` -- you will need it to [verify signatures](#verifying-signatures). It is only returned on create (alongside a `secretPrefix`).

Validation errors are `400`: `authType must be one of hmac, bearer, both`, `bearerToken is required when authType is '<type>'`, and `Bearer auth requires an https:// webhook URL`. The bearer rules are checked on update too. There is no per-workspace cap on the number of endpoints.

`mailboxIds` lists the mailboxes whose events the webhook receives. `null` means every mailbox. See [Mailbox-scoped keys](#mailbox-scoped-keys). `disabledReason` is `null` unless Molted switched the webhook off because the key that created it is gone (see [When the creating key changes](#when-the-creating-key-changes)).

The `bearerToken` you supply is **write-only** -- subsequent `GET` and `LIST` calls return `bearerTokenSet: true` but never the plaintext token. To rotate, send a new value via `PATCH`.

### URL requirements

`url` must be a public `http://` or `https://` address. It's rejected (`400`, on create and whenever an update changes `url`) if it doesn't parse, uses another scheme, embeds credentials, doesn't resolve in DNS, or resolves -- as a literal IP or via DNS, any one of its records -- to a private, loopback, link-local, CGNAT or otherwise internal/reserved address, including cloud metadata endpoints like `169.254.169.254`. This is re-checked on every delivery, not just at registration. Redirects are never followed: a `3xx` response counts as a failed attempt and is retried like any other failure, so register the final URL.

## Authentication

Choose how Molted Email authenticates webhook deliveries to your endpoint:

| `authType` | Headers sent | When to use |
| - | - | - |
| `hmac` (default) | `X-Molted-Signature` | Recommended for most cases. Verifies the request came from Molted **and** the payload wasn't tampered with. |
| `bearer` | `Authorization: Bearer <token>` | Your endpoint already validates a static bearer token (e.g. behind an API gateway). Simpler to verify, but only proves the sender -- not payload integrity. |
| `both` | Both headers | Defense in depth -- your endpoint can check bearer at the edge and HMAC in the handler. |

```bash title="CLI -- create with bearer auth"
molted webhooks create \
  --url https://example.com/hooks/molted \
  --auth-type bearer \
  --bearer-token "tok_a1b2c3..."
```

```bash title="curl -- create with bearer auth"
curl -X POST https://mailbox.molted.email/v1/agent/webhooks \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "url": "https://example.com/hooks/molted",
    "authType": "bearer",
    "bearerToken": "tok_a1b2c3..."
  }'
```

> **Warning:** Bearer endpoints **must** use `https://` URLs. Plaintext tokens in `Authorization` headers over HTTP would be trivially sniffable.

### Rotating a bearer token

```bash title="CLI"
molted webhooks update --id ENDPOINT_ID --bearer-token "tok_new_value"
```

To clear a bearer token (when switching back to `hmac` only), pass the literal string `null`:

```bash title="CLI"
molted webhooks update --id ENDPOINT_ID --auth-type hmac --bearer-token null
```

### Verifying bearer auth on your endpoint

```javascript title="Node.js / Express"
app.post('/hooks/molted', (req, res) => {
  const auth = req.header('Authorization');
  const expected = `Bearer ${process.env.MOLTED_WEBHOOK_TOKEN}`;
  // Use a constant-time comparison to avoid timing attacks
  if (!auth || !crypto.timingSafeEqual(Buffer.from(auth), Buffer.from(expected))) {
    return res.status(401).end();
  }
  // ... process event
  res.status(200).end();
});
```

## Mailbox-scoped keys

A webhook created with a key scoped to specific mailboxes only receives events from those mailboxes: the ones the key can both `read` and `send` on. Its `mailboxIds` is set to them when it's created and can't be changed or cleared afterwards, by any key. Events that don't belong to one mailbox aren't delivered to it. A key with no mailbox it can send on gets `403 mailbox_scope_denied`.

The filter is stored on the webhook and can't be changed or widened, but it is never wider than what the creating key can still reach: see [When the creating key changes](#when-the-creating-key-changes). A request can't ask for mailboxes. A `mailboxIds` in the create body is ignored, and the webhook always gets the key's own mailboxes. The key that created a webhook can disable, redirect and delete it while that key is active. For any other key, those changes need a person in a workspace in `enforce` mode (see [Update an endpoint](#update-an-endpoint)).

### When the creating key changes

A webhook created with an API key (not in the portal) is checked against that key every time an event is queued and again before each delivery attempt, including retries hours later. The key's standing is cached for up to 30 seconds, so a change takes effect within about half a minute.

| What happens to the key | What happens to its webhook |
| - | - |
| Narrowed to fewer mailboxes, or a mailbox loses `read` or `send` | The webhook stays on and only receives events for mailboxes the key can still `read` and `send` on: the overlap of its `mailboxIds` and the key's current mailboxes. Deliveries already queued for a mailbox that dropped out are marked `failed` and not retried. |
| Revoked, or rotated (a new key plus a revoke of the old one) | The webhook is switched off with `disabledReason: "creator_key_revoked"`, nothing more is sent, and queued deliveries stop. Create a new webhook with the new key. |
| The person behind the key is removed from the workspace, or dropped below `admin` | Switched off with `creator_not_member` or `creator_role_insufficient`. |
| The workspace is no longer active | Switched off with `creator_tenant_inactive`. |

Switching off writes a `webhook.disabled_creator_gone` audit event. An agent key can't turn such a webhook back on: `PATCH` with `enabled: true` returns `403 webhook_disabled_by_scope`. A person can. When a person edits or re-enables it in the portal, the webhook becomes theirs (it no longer follows any key) and a `webhook.ownership_taken` audit event is written. Webhooks created by a person, and older webhooks with no recorded creator, are never switched off this way.

Events that belong to no mailbox (for example `suppression.created`) never reach a webhook created by a mailbox-scoped key, before or after any change. A webhook created by an all-mailbox key keeps receiving them.

A scoped key also only sees and manages webhooks limited to its own mailboxes. Listing returns only those; getting, updating, deleting, testing or reading the deliveries of any other webhook (including one with `mailboxIds: null`, which receives every mailbox's events) returns `404`. Updating, deleting and testing need the webhook's mailboxes to be ones the key can `send` on.

A webhook created with a key that has access to every mailbox, or in the portal, has `mailboxIds: null` and receives events from every mailbox, as before.

## Event types

| Event | When it fires |
| - | - |
| `inbound.received` | New inbound email stored |
| `inbound.classified` | Inbound email classified. `data`: `{ classificationId, platformLabel, autoReplyKind, intent, confidence }` (see [Platform labels](https://molted.email/docs/inbound.md#platform-labels); `intent` is deprecated). It carries no message or mailbox id today. |
| `inbound.routed` | A routing action was decided for a classified message. `data`: `{ routingId, actionType }`, where `actionType` is `notify_owner`, `require_approval`, `auto_archive`, `escalate`, `spam` or `trigger_unsubscribe`. No message or thread id. |
| `inbound.released` | A held message reached your agents: one held for the used-up inbound allowance (see [Billing](https://molted.email/docs/billing.md#inbound-allowance)), or, when an archived mailbox is restored, one that arrived while it was archived. `data`: `{ messageId, threadId, threadMessageId, mailboxId, reason }`, where `reason` is `inbound_quota` or `mailbox_restored` |
| `delivery.sent` | Email sent to provider |
| `delivery.delivered` | Email confirmed delivered |
| `delivery.bounced` | Email bounced (a hard bounce triggers auto-suppression; soft bounces suppress the address for 90 days after 3 in 30 days) |
| `delivery.complained` | Spam complaint received (triggers auto-suppression) |
| `suppression.created` | An address was suppressed automatically, after a hard bounce, a complaint or the soft-bounce threshold (not for a manual add). `data`: `{ recipientEmail, reasonCode, requestId, source, triggerEventType, sourceEventId }`, plus `softBounceCount` and `expiresAt` on a soft bounce |
| `thread.labeled` | A [label](https://molted.email/docs/labels.md) was applied to a thread. `data`: `{ threadId, labelId, labelName, mailboxId, actor }`, where `actor` is `{ type, id }` (`type` is `agent`, `human`, `rule` or `system`) or `null` |
| `thread.unlabeled` | A label was removed from a thread. Same `data` |
| `label.deleted` | A label was deleted. `data`: `{ labelId, labelName, mailboxId, actor, affectedThreads }` |

The four `delivery.*` events share one `data` shape: `{ eventId, requestId, providerName, eventType, occurredAt }` (no recipient address; look the send up by `requestId`).

These 12 are the only events ever delivered to webhook endpoints. Everything else on the [event stream](https://molted.email/docs/events.md) is SSE-only: engagement events (`delivery.opened`, `delivery.clicked`, high-volume), `delivery.queued`, `delivery.accepted`, `delivery.deferred`, `delivery.failed`, `journey.*`, `send.*`, `policy.blocked`, `followup.*`, `coordination.*` and `thread.sla_breached`. Use `molted listen` for those.

## Payload format

Events are sent as HTTP POST requests with the following headers:

| Header | Sent when | Description |
| - | - | - |
| `Content-Type` | Always | `application/json` |
| `X-Molted-Event` | Always | Event type (e.g. `inbound.received`) |
| `X-Molted-Delivery` | Always | Delivery ID: one per event per endpoint, the same on every retry. Dedupe on it. |
| `X-Molted-Signature` | `authType` is `hmac` or `both` | `sha256=<lowercase hex>`: HMAC-SHA256 of the raw body |
| `Authorization` | `authType` is `bearer` or `both` | `Bearer <your token>` |

```json title="Payload body"
{
  "event": "inbound.received",
  "timestamp": "2026-03-22T10:00:00Z",
  "data": {
    "messageId": "...",
    "mailboxId": "...",
    "from": "sender@example.com",
    "to": "you@yourdomain.com",
    "receivedAt": "2026-03-22T10:00:00Z"
  }
}
```

The body always has exactly these three keys. `data` is the event's own payload (here `mailboxId` can be `null` and `to` is a single address). `timestamp` is when the event happened. It never changes, not on a retry and not when the event reaches you late (see [Delivery guarantee](#delivery-guarantee)), so a delivery that arrives hours after the event still carries the original time: don't reject deliveries for being old.

`inbound.received` fires as soon as the message is stored, before classification -- its payload deliberately excludes subject and body content, since that content hasn't been scanned yet. Keep the `messageId` from `inbound.received` and fetch the message once it's been classified. `inbound.classified` tells you a classification happened, but its payload has no message id to match it to, so treat it as a signal to re-read, not as the message itself. Until then, the read endpoints hide the content and mark the message `pending_classification: true` (see [Inbound: Pending classification](https://molted.email/docs/inbound.md#pending-classification)).

## Verifying signatures

Every webhook payload is signed with your endpoint's `secret` using HMAC-SHA256. The key is the whole secret string, `whsec_` prefix included, and the signed message is the exact request body. There is no timestamp in the signature and no tolerance window, so protect against replays by deduplicating on `X-Molted-Delivery`. Always verify the signature before processing:

```javascript title="Node.js"
const crypto = require('crypto');

function verifyWebhook(rawBody, signatureHeader, secret) {
  const signature = crypto
    .createHmac('sha256', secret)
    .update(rawBody) // must be raw bytes, not parsed JSON
    .digest('hex');

  const expected = (signatureHeader || '').replace('sha256=', '');
  if (expected.length !== signature.length) return false; // timingSafeEqual throws on unequal lengths
  return crypto.timingSafeEqual(
    Buffer.from(signature),
    Buffer.from(expected)
  );
}
```

## Retries and delivery

- **Timeout:** 5 seconds of socket inactivity, and 20 seconds overall per attempt (DNS, connect and reading the response). A response body over 2 MB also fails the attempt.
- **Success:** any HTTP 2xx response.
- **Failure:** anything else, including every `4xx` and any `3xx` (redirects are not followed), is retried.
- **Max attempts:** 10 (the first try plus 9 retries).
- **Schedule:** the delays before attempts 2 to 10 are 10s, 1m, 5m, 30m, 2h, then 6h, 6h, 6h and 6h: about 26.6 hours from the first failure to the last attempt.
- **While retrying** the delivery's `status` stays `pending`. After the 10th failed attempt it is marked `failed`, and nothing redelivers it (there is no replay or dead-letter route).
- **Stops early** (marked `failed`) if the endpoint is deleted or disabled while retries remain.

Every endpoint subscribed to an event gets its own delivery, with its own `X-Molted-Delivery` ID and retry schedule.

### Delivery guarantee

Events are delivered **at least once** per endpoint, so build the receiver to handle the same event twice.

- **Dedupe on `X-Molted-Delivery`.** The ID is fixed by the event and the endpoint: every retry of a delivery, and every later attempt to send the same event to the same endpoint, carries the same ID. Store the IDs you have processed and skip a repeat. Different endpoints get different IDs for the same event.
- **A deploy or a short outage on our side does not lose events.** Events are recorded before they are sent. If the live send is missed (for example while our workers restart), a sweep that runs every minute picks the event up and sends it, usually within about three minutes. It arrives late, with its original `timestamp`.
- **The limit:** an event that could not be sent for more than 24 hours is not delivered late. We are alerted when that happens, and you can still read the event on the [event stream](https://molted.email/docs/events.md) with `since`.
- **An endpoint created after an event never receives that event**, however late the send happens.
- **Order is not guaranteed.** A late event can arrive after a newer one. Use `timestamp` to order them.

## Managing endpoints

### List endpoints

```bash title="CLI"
molted webhooks list
```

### Get endpoint details

```bash title="CLI"
molted webhooks get --id ENDPOINT_ID
```

Returns the endpoint object with a `secretPrefix` (the first 16 characters of the secret followed by `...`, for example `whsec_a1b2c3d4e5...`). The full `secret` is only returned once, in the response to `create`. `list` does not include `secretPrefix`.

A webhook's URL is a credential (a catch-hook URL's path, or a host such as a Pipedream source, is its secret), so only a role that may change webhooks reads it in full: an admin or the owner, or a key one of them created. A member or a viewer, and their keys, get only the scheme and the registrable domain (for example `https://…zapier.com/…`, or `https://…pipedream.net/…` for a URL whose secret is its hostname) on `list` and `get`, and no `secretPrefix`.

### Update an endpoint

```bash title="CLI"
molted webhooks update --id ENDPOINT_ID --enabled false
```

Updatable flags: `--url`, `--events`, `--enabled`, `--description`, `--auth-type`, `--bearer-token`.

In a workspace in `enforce` mode, an agent key can only make an update that can't close or redirect the channel: a new `description`, or `--enabled true` to turn back on an endpoint that is already on or that your own key turned off. Turning on an endpoint a person (or another key) disabled is a person's decision too: undoing their switch-off would reopen a channel they closed, so in `enforce` mode the call gets `403 human_decision_required` with `loosens: ["enabled"]` and the endpoint stays off (in `warn` mode it goes through with the deprecation header, with the gate `off` it simply works, like the other gated changes below). Disabling an endpoint (`--enabled false`), changing its `url`, `events`, `authType` or `bearerToken` is a person's decision: the call gets `403 human_decision_required` with `kind: "webhook"` and `loosens` naming the fields, and nothing changes. Ask a person on your team to make the change. The exception is an endpoint your own key created: that key can still disable, redirect and delete it. In `warn` mode the call goes through with a `Molted-Deprecation: human-gate` header; with the gate `off` it simply works. The CLI can't reset `events` back to "all events" or clear a description (an empty value is not sent); to do that, `PATCH` the endpoint with `"events": []`.

### Delete an endpoint

```bash title="CLI"
molted webhooks delete --id ENDPOINT_ID
```

In a workspace in `enforce` mode only a person can delete an endpoint, except one your own key created. Any other agent key gets `403 human_decision_required` with `kind: "webhook"` and the endpoint stays (`warn` goes through with the deprecation header, `off` just works).

### View delivery history

```bash title="CLI"
molted webhooks deliveries --id ENDPOINT_ID
```

Returns the 50 most recent deliveries (no paging). Molted keeps only those 50 per endpoint: older delivery records are deleted by a daily cleanup, except one still `pending` (being retried), which stays until it settles. Each delivery is `{ id, eventType, status, httpStatus, attempts, maxAttempts, deliveredAt, createdAt }`. `status` is `pending` (including while it is being retried), `delivered` or `failed`.

### Send a test event

```bash title="CLI"
molted webhooks test --id ENDPOINT_ID
```

Sends a `test` event (`{ "event": "test", "timestamp": ..., "data": { "message", "endpointId" } }`, header `X-Molted-Event: test`) to your endpoint URL and returns the result. It is one synchronous attempt with no retries, recorded in the delivery history with `maxAttempts: 1`, and it ignores the endpoint's `events` filter, its mailbox filter and its `enabled` flag. `test` can't be subscribed to as a real event.

A test send is limited to one per endpoint every 30 seconds and 10 a minute across all of the workspace's webhook endpoints and alert destinations together; over either limit you get a `429` with `error: "rate_limited"` and nothing is sent. A workspace can have at most 20 webhook endpoints: creating a 21st gets a `409` with `error: "webhook_limit_reached"`. When the request fails, `error` is one of a fixed set of codes and never an address or port: `connection_refused`, `timeout`, `tls_error`, `blocked_destination`, `response_too_large` or `connection_failed`. A non-2xx answer from your endpoint is reported by its `httpStatus`. A webhook URL has to be a public host name or address: a single-label name, a reserved suffix such as `.local` or `.internal`, and a name that does not resolve are all refused with the same message.

```json title="Success"
{
  "success": true,
  "httpStatus": 200,
  "deliveryId": "..."
}
```

On failure `success` is `false`: a non-2xx response carries its `httpStatus`; a network or URL-guard error has `httpStatus: null` and an `error` message.

## API routes

All under `/v1/agent/webhooks` (Bearer auth; the CLI goes through the same routes):

| Method | Path | Description |
| - | - | - |
| `POST` | `/v1/agent/webhooks` | Create an endpoint |
| `GET` | `/v1/agent/webhooks` | List endpoints |
| `GET` | `/v1/agent/webhooks/:id` | Get one endpoint |
| `PATCH` | `/v1/agent/webhooks/:id` | Update `url`, `events`, `enabled`, `description`, `authType`, `bearerToken` (in `enforce`, an agent key: only `description`, and `enabled: true` on an endpoint that is already on or that the same key turned off) |
| `DELETE` | `/v1/agent/webhooks/:id` | Delete (returns `{ "deleted": true }`; in `enforce`, an endpoint your own key didn't create needs a person: `403 human_decision_required`) |
| `GET` | `/v1/agent/webhooks/:id/deliveries` | The 50 most recent deliveries |
| `POST` | `/v1/agent/webhooks/:id/test` | Send a test event |

There are no MCP tools for managing webhook endpoints; use the CLI or the API.

## Local development

`molted webhooks listen` has been removed: molted.email can't deliver webhooks to a `localhost` URL (the SSRF guard rejects loopback/private registration targets, and the hosted service has no route back to your machine either way). Use `molted listen` to stream events over SSE during development instead:

```bash title="CLI"
molted listen --events inbound.received
```

`molted listen` takes `--events <types>` (comma-separated, wildcards like `delivery.*`), `--pipe <command>` (run a command per event), `--json`, `--concurrency <n>` (default 1), `--retries <n>` (default 3) and `--since <eventId>` (resume after an event).

To test your own webhook handler end to end, expose it with a public tunnel (for example `cloudflared tunnel` or `ngrok`) and register the tunnel URL with `molted webhooks create`. Deliveries then arrive signed, exactly as in production.
