# HTTP API

> An overview of the Hub's HTTP API: base path, authentication, CSRF rules, the WebSocket, errors, rate limits and every endpoint, grouped.

Source: https://docs.posternmail.app/reference/api/

This page is an overview of the HTTP API the Hub serves to Postern's web, desktop and mobile
apps. It helps when you debug a proxy, write a health check or read the logs. The typed contract
is [packages/protocol/src/index.ts](https://github.com/TheOriUHD/postern/blob/main/packages/protocol/src/index.ts): every request and
response shape is defined there, and the Hub mirrors it.

> [!IMPORTANT]
> The API exists for Postern's own apps. It is not documented or promised as a stable public
> API: endpoints and fields can change with any release while Postern is in beta. The only
> fixed points are the major version in the path (`/api/v1`) and `apiVersion` in
> [`/api/v1/info`](https://docs.posternmail.app/reference/api/#hub-info). If you build on it, pin the Hub version you tested with.

## Basics

| | |
|---|---|
| Base path | `/api/v1` on the Hub's address, like `https://mail.example.com/api/v1/info`. |
| Format | JSON in and out, UTF-8, field names in camelCase. Unknown request fields are ignored. Arrays are never `null`. |
| IDs | Opaque strings with a type prefix (`usr_01m93dh1ewdkz3ekf2wkfwgacp`, `thr_...`). Never parse them. |
| Times | RFC 3339 in UTC with milliseconds: `2026-12-05T10:00:00.000Z`. |
| Lists | Wrapped in an object (`{"mailboxes": [...]}`), so fields can be added later. |
| Empty answers | `204 No Content`. |
| Request size | JSON bodies up to 4 MiB (`413 too_large` above). Attachment uploads up to `POSTERN_MAX_UPLOAD_MB`. |
| Caching | Responses carry `Cache-Control: no-store`. Thread lists and counts carry a weak `ETag` and `Cache-Control: private, no-cache`; send `If-None-Match` to get `304 Not Modified` when nothing changed. |
| Compression | Text responses are gzip-compressed when the client accepts it. |

Every response also carries `X-Content-Type-Options: nosniff`, `Referrer-Policy: no-referrer`,
`X-Frame-Options: DENY`, `Cross-Origin-Opener-Policy: same-origin` and a restrictive
`Permissions-Policy`; over HTTPS also `Strict-Transport-Security: max-age=31536000`.

Outside `/api/` the Hub serves the web app (with `index.html` for every app route such as
`/setup`, `/login`, `/app-login`, `/pair`, `/invite/<code>`, `/mail/...`, `/settings/...`) and
`GET /healthz`, which answers `ok` with status 200 for container and load-balancer checks.

## Authentication

Each signed-in device has one session. The Hub stores only a hash of its token.

| Client | How it authenticates | Session lifetime |
|---|---|---|
| Web app in a browser, desktop app showing a Hub | The cookie `mc_session` (HttpOnly, `SameSite=Lax`), set at sign-in. | 30 days, extended while in use |
| iOS and Android apps | `Authorization: Bearer <token>` on every request. | 90 days, extended while in use |
| Desktop app's mail engine (direct mode) | `Authorization: Bearer <token>` (the device token from the browser sign-in). | 30 days, extended while in use |

When both are present, the bearer token wins. Native apps get their token from the sign-in
result (`token` in `AuthResult`): through `POST /api/v1/auth/login` (iOS, Android), through the
browser sign-in with PKCE (`/app-login` in the web app, then `POST /api/v1/auth/app-token`) or
through [pairing](https://docs.posternmail.app/apps/pairing/).

A request without valid credentials to a protected endpoint gets `401 unauthorized`
("Sign in required", or "Your session has expired. Please sign in again." for an expired or
revoked token). A disabled account gets "This account has been disabled." Admin endpoints answer
`403 forbidden` ("Administrator access required") to other users. A resource that belongs to
another user is reported as `404 not_found`, never `403`.

Behind Cloudflare Access, native apps also send the gateway headers
(`CF-Access-Client-Id`, `CF-Access-Client-Secret`) on every request; see
[Configuration](https://docs.posternmail.app/configuration/#access-gateway-cloudflare-access).

## CSRF and same-origin rules

The Hub sends no CORS headers, so browsers cannot call it from another site. On top of that:

- Every request to `/api/` with a method other than `GET`, `HEAD` or `OPTIONS` must carry the
  header `X-MC-Client` (the apps send their kind: `web`, `desktop`, `ios`, `android`). Without
  it: `403 csrf` "Missing X-MC-Client header".
- If such a request has an `Origin` header, it must match the Hub's host (the host of
  `POSTERN_PUBLIC_URL`, or the request's `Host`, or `X-Forwarded-Host` with
  `POSTERN_TRUST_PROXY`). Otherwise: `403 csrf` "Cross-origin request rejected".
- One endpoint accepts a plain HTML form post without the header,
  `POST /api/v1/auth/app-code/redirect`, and only with a same-origin `Origin` (and
  `Sec-Fetch-Site: same-origin` when the browser sends it).
- The WebSocket accepts only same-origin browser connections.

A reverse proxy must therefore pass the `Host` header through unchanged (or set
`X-Forwarded-Host`, with `POSTERN_TRUST_PROXY` on). See [Reverse proxy](https://docs.posternmail.app/reach/reverse-proxy/).

## Errors

Every error has a non-2xx status and this body:

```json
{"error": {"code": "csrf", "message": "Missing X-MC-Client header"}}
```

`message` is meant for people and may be shown in the apps. `details` is present for some codes
(for example `{"setupCode": true}` when the setup code is missing). The codes:

| Code | Typical status | Meaning |
|---|---|---|
| `invalid_request` | 400 | The request is malformed or a value is invalid. |
| `unauthorized` | 401 | Not signed in, or the session expired. |
| `forbidden` | 403 | Not allowed (for example not an administrator, or a wrong setup code). |
| `not_found` | 404 | No such resource for this user. |
| `conflict` | 409 | The state does not allow it (for example "This Hub is already set up"). |
| `gone` | 410 | The sync cursor expired: load a fresh bootstrap. |
| `too_large` | 413 | Body or upload too large. |
| `rate_limited` | 429 | Too many attempts; see `Retry-After`. |
| `totp_required` | 401 | Sign-in needs a TOTP or recovery code. |
| `setup_required` | | The Hub has no administrator yet. |
| `auth_failed` | 422 | A mail provider rejected the credentials. |
| `provider_error` | 422, 502 | A mail provider or identity provider failed or is unreachable. |
| `not_configured` | 404 | A feature is not set up on this Hub (for example single sign-on). |
| `csrf` | 403 | Missing `X-MC-Client` header or cross-origin request. |
| `reauth_required` | 403 | Confirm with the password, or sign in again, first. |
| `not_implemented` | 501 | The endpoint exists in the protocol but this Hub does not provide it. |
| `internal` | 500 | An unexpected error. The Hub logs the cause; the response says only "Internal server error". |

## Rate limits

Rate limits apply to the public sign-in endpoints only, per client IP (see
[Client IP behind a proxy](https://docs.posternmail.app/configuration/#client-ip-behind-a-proxy)) or per account. Each
is a token bucket: a burst, then one more attempt per interval. Over the limit the Hub answers
`429 rate_limited` "Too many attempts. Please wait a moment and try again." with a `Retry-After`
header in seconds. The buckets are kept in memory and reset when the Hub restarts.

| Limit | Applies to | Burst | Then one per |
|---|---|---|---|
| Sign-in per IP | `POST /auth/login`, `POST /auth/passkeys/login/finish` | 20 | 15 s |
| Failed sign-ins per account | Wrong password or TOTP at sign-in, and wrong confirmations of the password | 5 | 1 min |
| Setup and registration per IP | `POST /setup`, `POST /auth/register` | 5 | 1 min |
| Pairing claims per IP | `POST /pairing/claim` | 10 | 30 s |
| Companion devices per user | `POST /devices/current/companions` | 5 | 1 min |
| Other public endpoints per IP | `GET /auth/invites/{code}`, `POST /auth/app-token`, `GET /auth/oidc/start`, `POST /auth/passkeys/login/begin` | 30 | 5 s |
| TOTP setup per user | `POST /account/totp/enable` | 5 | 1 min |

A successful sign-in resets the account's counter.

## Hub info

`GET /api/v1/info` needs no sign-in. The apps call it first to learn about the Hub; health
checks and `postern-hub doctor` use it too. A new Hub with `POSTERN_PUBLIC_URL` set answers:

```json
{
  "name": "Postern",
  "version": "0.1.0",
  "apiVersion": 1,
  "capabilities": ["calendarInvites", "followUp", "imageProxy", "invites", "pairing", "passkeys", "rules", "screener", "search", "sendLater", "sendWithDraft", "snooze", "splits", "templates", "totp", "undoSend", "webPush"],
  "setupRequired": true,
  "setupCodeRequired": true,
  "publicUrl": "https://mail.example.com",
  "auth": {"password": true, "passkeys": true, "oidc": null, "registration": "invite"},
  "webPushPublicKey": "BCh2eWrlhwFeFe633aA6Ic7oiFV936RosJbbr1i8RzkNDdSA2qz_-JXongLGdJRBcQS5AyWUlmNbhHdexDO3e38"
}
```

| Field | Meaning |
|---|---|
| `name` | The Hub's name (admin panel), `Postern` by default. |
| `version` | The Hub's version. |
| `apiVersion` | Major API version, `1`. |
| `capabilities` | Features this Hub offers, sorted. See [Capabilities](https://docs.posternmail.app/reference/capabilities/). |
| `setupRequired` | `true` until the first administrator exists. |
| `setupCodeRequired` | Present (`true`) while setup is needed and the request does not come straight from the Hub's own machine. |
| `publicUrl` | `POSTERN_PUBLIC_URL`, or `null`. |
| `auth.password` | Always `true`. |
| `auth.passkeys` | `true` when the Hub is reached over HTTPS or `localhost` with a domain name (WebAuthn needs both). |
| `auth.oidc` | `{"name": "<button label>"}` with single sign-on, else `null`. |
| `auth.registration` | `invite` (people join with an invite) or `closed`. |
| `webPushPublicKey` | The VAPID key for browser notifications, or `null`. |

A device engine (desktop direct mode) answers the same request locally with the Hub's info plus
`mode: "engine"`, `hubUrl`, `hubOnline` and `pendingChanges`.

## Sync and the WebSocket

The apps keep their data current with three pieces:

1. `GET /api/v1/sync/bootstrap` returns a snapshot of everything except thread lists (user,
   device, settings, mailboxes, folders, identities, spaces, tags, rules, splits, templates,
   drafts, outbox, marks, senders, folder preferences) and a `cursor`.
2. `GET /api/v1/sync/changes?cursor=N&limit=1000` returns the changes since the cursor, oldest
   first, with `hasMore`. A cursor that is too old answers `410 gone`: load a new bootstrap.
3. `GET /api/v1/ws` is a WebSocket that says when to fetch changes.

WebSocket messages are JSON objects with a `type`:

| Direction | Type | Meaning |
|---|---|---|
| client → Hub | `auth` | `{"type":"auth","token":"..."}`, the first message from native apps (browsers use the cookie). Must arrive within 10 seconds. |
| client → Hub | `ping` | Sent every 30 seconds. A connection silent for 2 minutes is closed. |
| Hub → client | `hello` | Once authenticated: the current `cursor`, `serverTime` and `deviceId`. |
| Hub → client | `changes` | The change log advanced to `cursor`: fetch `/sync/changes`. |
| Hub → client | `notification` | A notification to show (new mail, follow-up, snooze, failed send, system). |
| Hub → client | `pairing.request` | A new device asks to be paired; approve or deny it. |
| Hub → client | `session.revoked` | This device was signed out. |
| Hub → client | `pong` | Answer to `ping`. |
| Hub → client | `error` | For example an authentication failure, followed by close code `4401`. |
| engine → client | `engine.status` | Direct mode only: whether the Hub is reachable and how many local changes wait. |

A reverse proxy must pass WebSocket upgrades on `/api/v1/ws`.

## Endpoints

Access: **public** (no sign-in), **user** (any signed-in user), **admin** (administrators). All
paths start with `/api/v1`.

### Hub, setup and sign-in

| Method and path | Access | Purpose |
|---|---|---|
| `GET /info` | public | Hub name, version, capabilities and sign-in options. |
| `POST /setup` | public | Create the first administrator (only while `setupRequired`; needs the setup code from another machine). |
| `POST /auth/login` | public | Sign in with email and password (and TOTP or a recovery code). |
| `POST /auth/logout` | user | Sign out this device. |
| `GET /auth/session` | user | The current user and device. |
| `POST /auth/passkeys/login/begin`, `POST /auth/passkeys/login/finish` | public | Sign in with a passkey. |
| `GET /auth/oidc/start`, `GET /auth/oidc/callback` | public | Single sign-on redirect and return. |
| `POST /auth/app-code` | user | Browser sign-in for an app: issue a one-time ticket (may need the password again). |
| `POST /auth/app-code/redirect` | user | HTML form post that redirects to the app with the code. |
| `POST /auth/app-token` | public | The app exchanges the code and PKCE verifier for a device token. |
| `GET /auth/invites/{code}` | public | Look up an invite. |
| `POST /auth/register` | public | Create an account with an invite. |
| `GET /auth/local` | public | Device engines only: sign the local app in to the engine. |

### Pairing

| Method and path | Access | Purpose |
|---|---|---|
| `POST /pairing` | user | Create a pairing code and QR code (valid 5 minutes). |
| `POST /pairing/claim` | public | The new device claims a code. |
| `GET /pairing/claims/{claimId}` | public | The new device polls for approval (with its poll token). |
| `POST /pairing/claims/{claimId}/approve`, `.../deny` | user | Approve or deny the new device. |

### Account, devices and settings

| Method and path | Access | Purpose |
|---|---|---|
| `PATCH /account` | user | Change name or sign-in email. |
| `DELETE /account` | user | Delete your own account. |
| `POST /account/password` | user | Change the password. |
| `POST /account/totp/setup`, `.../enable`, `.../disable` | user | Set up, turn on or turn off TOTP. |
| `GET /account/passkeys`, `POST /account/passkeys/register/begin`, `.../finish`, `DELETE /account/passkeys/{id}` | user | List, add and remove passkeys. |
| `GET /account/security-events` | user | Your security log. |
| `GET /account/export` | user | Export your account data. |
| `GET /devices` | user | Your signed-in devices. |
| `PATCH /devices/{id}`, `DELETE /devices/{id}` | user | Rename or sign out a device. |
| `POST /devices/current/push`, `DELETE /devices/current/push` | user | Register or remove this device's push channel (Web Push, relay, UnifiedPush). |
| `POST /devices/current/companions` | user (iPhone app sessions only) | Sign in a companion device (`{"client":"watchos","deviceName":"Apple Watch"}`). Answers `201` with an `AuthResult` and token. The companion is listed with `parentId`, never gets mailbox credentials, and is signed out with its phone. Capability `companionDevices`. |
| `GET /settings`, `PATCH /settings` | user | Account and device settings (see [Capabilities](https://docs.posternmail.app/reference/capabilities/#settings-model)). |
| `GET /sync/bootstrap`, `GET /sync/changes` | user | Sync, see above. |
| `GET /ws` | public (authenticates itself) | The WebSocket. |

### Administration

| Method and path | Access | Purpose |
|---|---|---|
| `GET /admin/status` | admin | Version, uptime, disk use, users, TLS, relay, last backup, warnings. |
| `PATCH /admin/settings` | admin | Hub name and registration (`invite` or `closed`). |
| `GET /admin/users`, `PATCH /admin/users/{id}`, `DELETE /admin/users/{id}` | admin | List users, change role or disable, delete. |
| `POST /admin/users/{id}/reset-password` | admin | Issue a temporary password. |
| `GET /admin/invites`, `POST /admin/invites`, `DELETE /admin/invites/{id}` | admin | Manage invites. |
| `GET /admin/providers`, `PUT /admin/providers/google`, `PUT /admin/providers/microsoft` | admin | Google and Microsoft app credentials. |
| `GET /admin/sync-health` | admin | Sync state and errors of every mailbox. |

### Mailboxes

| Method and path | Access | Purpose |
|---|---|---|
| `POST /mailboxes/discover` | user | Find the provider and server settings for an address. |
| `GET /mailboxes`, `POST /mailboxes` | user | List mailboxes; add one (the Hub tests the connection first). |
| `PATCH /mailboxes/{id}`, `DELETE /mailboxes/{id}` | user | Change name, color, notifications, order, pause; remove (nothing is deleted at the provider). |
| `PUT /mailboxes/{id}/credentials` | user | New password or token. |
| `POST /mailboxes/{id}/resync` | user | Full re-sync. |
| `POST /mailboxes/check` | user | Check for new mail now. |
| `POST /mailboxes/oauth/start` | user | Start Google or Microsoft sign-in. |
| `GET /oauth/callback/google`, `GET /oauth/callback/microsoft` | public | Return from the provider's sign-in. |
| `POST /mailboxes/oauth/device/start`, `GET /mailboxes/oauth/device/{flowId}` | user | Microsoft device-code sign-in. |
| `GET /mailboxes/{id}/snapshot` | user | A device engine copies the Hub's message list for its first download. |
| `GET /vault/mailboxes`, `PUT /vault/mailboxes/{id}` | user | Direct mode: mailbox credentials for the user's own devices, and credentials a device added offline. |

### Reading and organizing

| Method and path | Access | Purpose |
|---|---|---|
| `GET /threads` | user | Thread list for a view, folder, tag or search (`q`). |
| `GET /threads/{id}` | user | One conversation with its messages. |
| `GET /threads/lookup` | user | Find a thread by `Message-ID` header. |
| `GET /counts` | user | Unread and total counts. |
| `GET /messages/{id}`, `GET /messages/{id}/body`, `GET /messages/{id}/raw` | user | Message metadata, sanitized body, original source. |
| `GET /message-source` | user | Direct mode: the stored source of a message by `Message-ID`. |
| `GET /attachments/{id}` | public with a signed link, else user | Download an attachment. |
| `GET /proxy/image` | public with a signed link | Load a remote image through the Hub. |
| `GET /search/suggest` | user | Search suggestions. |
| `POST /commands` | user | Mark read, flag, archive, move, tag, snooze, pin, mute, follow up and other actions, in batches. |
| `GET /folders`, `POST /folders`, `PATCH /folders/{id}`, `GET /folder-prefs` | user | Folders and folder preferences. |
| `GET /tags`, `POST /tags`, `PATCH /tags/{id}`, `DELETE /tags/{id}` | user | Tags. |
| `GET /identities`, `POST /identities`, `PATCH /identities/{id}`, `DELETE /identities/{id}` | user | Sender identities and signatures. |
| `GET /spaces`, `POST /spaces`, `PATCH /spaces/{id}`, `DELETE /spaces/{id}` | user | Spaces. |
| `GET /splits`, `POST /splits`, `PATCH /splits/{id}`, `DELETE /splits/{id}` | user | Split inbox tabs. |
| `GET /marks`, `POST /marks`, `GET /senders`, `POST /senders` | user | Per-message state (snooze, pin, mute, follow-up, screener) and per-sender decisions. |
| `GET /contacts`, `GET /contacts/{id}`, `PATCH /contacts/{id}` | user | Contacts. |

### Compose and sending

| Method and path | Access | Purpose |
|---|---|---|
| `POST /uploads`, `GET /uploads/{id}` | user | Upload and fetch attachments for a draft. |
| `POST /compose/prefill` | user | Reply, reply-all and forward contents. |
| `POST /compose/identity` | user | Suggest the sender identity. |
| `GET /drafts`, `POST /drafts`, `PUT /drafts/{id}`, `DELETE /drafts/{id}` | user | Drafts. |
| `POST /drafts/{id}/send` | user | Send (with undo send and send later). |
| `GET /outbox`, `POST /outbox/{id}/cancel`, `POST /outbox/{id}/send-now`, `POST /outbox/adopt` | user | The outbox; `adopt` takes over sends a device queued offline. |
| `GET /templates`, `POST /templates`, `PATCH /templates/{id}`, `DELETE /templates/{id}` | user | Templates. |

### Rules, alerts and AI

| Method and path | Access | Purpose |
|---|---|---|
| `GET /rules`, `POST /rules`, `PATCH /rules/{id}`, `DELETE /rules/{id}` | user | Rules. |
| `POST /rules/test`, `POST /rules/{id}/apply` | user | Test a rule against recent mail; apply it to existing mail. |
| `GET /rules/activity`, `POST /rules/activity/{id}/undo` | user | Rule activity and undo. |
| `GET /rules/settings`, `PUT /rules/settings` | user | Rule time zone, limits and retention. |
| `GET /rules/captured`, `GET /rules/captured/{id}`, `GET /rules/captured/{id}/eml`, `POST /rules/captured/{id}/restore`, `DELETE /rules/captured/{id}` | user | Captured mail. |
| `GET /rules/queue`, `GET /rules/queue/{id}/eml`, `POST /rules/queue/{id}/retry`, `.../recipients`, `.../restore` | user | The sending queue for rule mail. |
| `GET /alerts`, `POST /alerts/{id}/dismiss` | user | Rule alerts. |
| `GET /alerts/channels`, `PUT /alerts/channels`, `POST /alerts/channels/test` | user | Alert channels (ntfy, Discord, Gotify). |
| `GET /ai/config`, `PUT /ai/config`, `POST /ai/summarize`, `POST /ai/draft` | user | AI assist. |

## Device engines

In direct mode (the desktop app with a remote Hub) the app talks to its own mail engine on
`127.0.0.1`, not to the Hub. The engine serves the same `/api/v1` paths: mail routes (threads,
messages, commands, search, counts, rule tests) from its local copy, and everything owned by the
Hub (account, devices, settings, rules, admin) forwarded to the Hub. While the Hub is
unreachable, it applies changes locally and sends them later. Design:
[DIRECT-MODE.md](https://github.com/TheOriUHD/postern/blob/main/docs/dev/DIRECT-MODE.md).

## Versioning and compatibility

- The path carries the major version (`/api/v1`) and `/info` reports `apiVersion: 1`.
  `postern-hub doctor` treats a server with another `apiVersion` as "not a compatible Postern
  Hub".
- Within a major version, fields and endpoints are added. Clients ignore fields they do not
  know, and the Hub ignores unknown request fields.
- Optional features are announced in `capabilities` (for example `sendWithDraft`, which tells
  clients that `POST /drafts/{id}/send` accepts the draft in the same request). Clients check
  the list before using such a feature.
- The developer contract for both sides is [CONTRACT.md](https://github.com/TheOriUHD/postern/blob/main/docs/dev/CONTRACT.md). The list of routes
  with their access level is `ENDPOINTS` at the end of `packages/protocol/src/index.ts`.
