> ## Documentation Index
> Fetch the complete documentation index at: https://docs.burakov.net/llms.txt
> Use this file to discover all available pages before exploring further.

# Configure, operate & API

> Configuration, delivery, backups and the API of a self-hosted Quietletter core.

This page is for whoever runs a **Quietletter core** instance — the open-source server from
[Run your own instance](https://docs.burakov.net/quietletter/self-hosting.md). It covers how to run, configure and upgrade it,
what it sends and when, how to keep it safe, and the API it speaks.

## What your instance is

* **Single-tenant.** One instance serves one owner. There are no accounts, sign-ups, plans or
  limits — every feature is unlocked.
* **The same protocol as the hosted service.** The core is a second, independent implementation
  of the protocol the Quietletter cloud speaks, so the Quietletter app connects to it unchanged.
* **Content-blind.** It stores ciphertext and a passphrase-wrapped content key — never your
  passphrases or plaintext. The only exceptions are items you deliberately mark *readable*, and
  public pages, which are plaintext by nature. Beyond that it stores what delivery needs: titles,
  schedules and state, recipients, action types, message subjects, file names, types and sizes.
* **AGPL-3.0.** Anyone who hosts a modified version for others must share its source. The
  Quietletter apps are licensed separately.

## Running it

With Docker, `docker compose up --build -d` is all it takes (see the
[quick start](https://docs.burakov.net/quietletter/self-hosting.md#quick-start)). It starts PostgreSQL and the server, applies
the database migrations, and serves on `http://localhost:8080`. The firing engine runs inside the
server every `SWEEP_INTERVAL_SECONDS` (60 by default), so no external scheduler is needed.

The server has no TLS of its own. Serve it to the internet through a reverse proxy with HTTPS — the
app refuses plain-HTTP instances outside your local network. The server trusts the proxy's
forwarded headers.

> [!NOTE]
>
> Under Docker Compose the server always uses the bundled database and listens on port 8080
> inside its container. `PORT` in `.env` only chooses the port published on your machine.

### Without Docker

You need **Node.js 24.16 or newer** and your own PostgreSQL database. Put your settings in `.env`
(start from `env/env.prod`; it is read automatically) — at least `DATABASE_URL` and `OWNER_TOKEN`,
which the migration step checks too.

```bash theme={null}
npm install
npm run build
npm run db:migrate:prod   # apply the database migrations
npm start                 # start the server
```

To drive the firing engine from cron instead of the built-in interval, set
`SWEEP_INTERVAL_SECONDS=0` and run one sweep per tick with `node dist/sweep.js`.

### Upgrading

Back up the database first (see [Keeping it running](#keeping-it-running)), then:

* **With Docker** — `git pull`, then `docker compose up --build -d`. Migrations run automatically
  every time the container starts.
* **Without Docker** — `git pull`, `npm install`, `npm run build`, `npm run db:migrate:prod`, then
  restart the server.

## Configuration

`env/env.prod` lists every setting with a short explanation — copy it to `.env` and fill in its
`REPLACE_ME` values. The server refuses to start when a value is invalid or any `REPLACE_ME` value
is left, so an unfilled copy stops it at boot.

| Variable | Default | Meaning |
| - | - | - |
| `DATABASE_URL` | — (required) | PostgreSQL connection string. |
| `OWNER_TOKEN` | — (required, 16+ chars) | The owner's bearer token for the owner API. |
| `PUBLIC_URL` | `http://localhost:8080` | Public base URL (no trailing slash) used in release and public-page links. |
| `DOCS_URL`, `PRIVACY_URL`, `TERMS_URL` | Quietletter's own | Footer links on the public pages. Running an instance for other people? Point the privacy and terms links at your own documents. |
| `SWEEP_INTERVAL_SECONDS` | `60` | How often the built-in sweep runs; `0` turns it off (use cron). |
| `FIRE_RETENTION_DAYS` | `90` | How long encrypted payloads and release links are kept after a switch fires. |
| `OWNER_EMAIL` | — | Where your check-in warning emails go. Empty = warnings are console-only. |
| `SMTP_HOST` | — | SMTP server for outgoing mail. Unset = mail is printed to the console. |
| `SMTP_PORT`, `SMTP_SECURE` | `587`, `false` | SMTP port, and whether to use TLS from the first byte. |
| `SMTP_USER`, `SMTP_PASS` | — | SMTP credentials, if your server needs them. |
| `MAIL_FROM` | `Quietletter <no-reply@quietletter.local>` | Sender of every email. |
| `EMAIL_DEV_MODE` | `false` | `true` prints mail to the console even when SMTP is configured. |
| `HOST`, `PORT` | `0.0.0.0`, `8080` | Where the server listens. |
| `NODE_ENV`, `LOG_LEVEL` | `production`, `info` | Runtime mode and log verbosity. |

> [!WARNING]
>
> Use a long, random `OWNER_TOKEN` (`openssl rand -hex 32`). Anyone who has it can disarm or
> reconfigure your switches.

## Authentication

Every owner call sends the token as a bearer header:

```
Authorization: Bearer <OWNER_TOKEN>
```

All `/v1/switches…` routes require it. The recipient release routes and public pages need no
token — they are protected by their unguessable link instead.

## What your instance sends

* **Email** goes out over SMTP — or to the console when SMTP isn't configured. Your own warning
  emails go to `OWNER_EMAIL`; without it, warnings are only logged.
* Email is also the channel that carries your recipients' release links, so **configure SMTP
  before you rely on the instance** — in console mode a fired switch reaches the log, not your
  recipients.
* **Push and SMS are console-only.** The core ships no push or SMS provider, so those warning
  steps are written to the log, where you can wire up a provider of your own. In the Quietletter
  app, check-in reminders still fire on your device.
* **Language.** Emails are written in the language saved with each switch (English or Russian).
  The recipient release page is in English.

## How a switch fires

Firing is decided on the server, never on a device — your phone may be offline for the whole grace
window. Each sweep:

1. Moves a switch from **active** to **grace** once its check-in deadline passes.
2. Sends the warning steps that are now due.
3. Once the grace window (never less than 48 hours) has elapsed, **fires**: publishes any public
   pages, then emails each recipient a private release link for encrypted items, with any
   readable messages (each under its subject, in action order) included in the email.
4. Records every delivery before sending it, so crashes, overlapping sweeps and catch-up runs
   never send twice. A failed recipient email is retried on later sweeps for up to a day after
   firing.
5. Deletes expired release links, and the payloads of switches that fired more than
   `FIRE_RETENTION_DAYS` ago.

Your latest action always wins: the sweep moves a switch to grace or fires it only if it is still
exactly as the sweep read it, so a check-in, disarm or edit that lands mid-sweep is never
overridden. A fired switch is final — checking it in, disarming it or editing it answers
`409 already_fired`.

## Public pages (self-host only)

Quietletter has five action types: `message`, `file`, `secret`, `private_page` and `public_page`.
The hosted service refuses `public_page` — a truly public page is plaintext by nature and would
make the host a publisher. **Your instance accepts it** through the API (`PUT /v1/switches/:id`);
the app doesn't offer it as an action.

When a switch with a public page fires, its content is published at `/p/<slug>`. The slug comes
from the action's `slug` (or its subject, or the switch title); a taken slug gets a short random
suffix. The page is public and indexable, and — unlike encrypted payloads — it is **not** removed
by the retention purge: a published page is meant to stay up. Deleting the switch deletes its
public page too.

> [!WARNING]
>
> Whatever a public page publishes is your responsibility as the operator of the instance.

## Keeping it running

* **Back up regularly.** A plain database dump captures every switch, recipient, action and
  encrypted payload — a complete, portable backup that is enough to stand up an identical
  instance elsewhere. Because payloads are ciphertext, the dump is safe to keep offsite:

  ```bash theme={null}
  docker compose exec db pg_dump -U quietletter quietletter > quietletter-backup.sql
  ```

* **Keep an export too.** **Settings → Backup & transfer → Export switches** in the app (or
  `GET /v1/switches/export`) saves every live switch to one file that imports into another
  instance or into the hosted service — see [Back up and move your switches](https://docs.burakov.net/quietletter/backup-and-transfer.md).

* **Publish your own shutdown protocol.** If you will ever stop running an instance, give your
  recipients advance notice on more than one channel, a final export, and a pointer to the
  core's repository so they can keep the switches alive themselves. "A service outlives its
  operator" is only partly solvable — open source plus export is the escape hatch, not a
  guarantee.

* **Keep passphrases out-of-band.** The server can never recover a zero-knowledge passphrase.
  Make sure your recipients can get theirs even if you are gone.

## API reference

All JSON routes live under `/v1`. Bodies are camelCase, timestamps ISO-8601, and errors come back
as `{ "code": "...", "message": "..." }`.

Limits: **300 requests per minute** per client, JSON bodies up to **8 MB**, a single payload upload
up to **3 MB**, and an import up to **50 MB**. Cross-origin requests are allowed from any origin
(the owner token is what protects your switches).

### Owner routes (bearer token)

| Method & path | Purpose |
| - | - |
| `GET /v1/switches` | List all switches with their recipients and actions. |
| `GET /v1/switches/export` | Every live switch, payloads included, as one export file (see below). |
| `POST /v1/switches/import` | Recreate the switches of an export file; answers with what was imported and what was skipped. |
| `GET /v1/switches/:id` | One switch. |
| `PUT /v1/switches/:id` | Create or replace a switch by its client-generated UUID, with nested recipients and actions. The server computes the deadline: an edit counts from the last check-in and never moves the deadline into the past (a shorter cadence starts the grace window now); once the grace window is running, it never brings the fire time closer either (a shorter grace moves the deadline later). The state fields are read-only; a fired switch answers `409 already_fired`. |
| `PUT /v1/switches/:id/regional` | Fill in the time zone and language a switch saved by an older app is missing (`{ timezone, locale }`); only missing values are written and the deadline never moves. |
| `DELETE /v1/switches/:id` | Delete a switch and everything under it (idempotent). |
| `POST /v1/switches/:id/checkin` | Proof of life: resets the deadline and re-activates the switch. |
| `POST /v1/switches/:id/disarm` | Turn the switch off; a later check-in (**Re-arm** in the app) turns it back on with a fresh cycle. |
| `PUT /v1/switches/:id/actions/:actionId/payload` | Upload the encrypted (or readable) content of one action. |

A switch's safety settings:

* **`cadence`** — `{ value, unit }` with `unit` = `day`, `week` or `month`.
* **`grace`** — `{ value, unit }` with `unit` = `hour` or `day`; never less than **48 hours**.
* **`warnings`** — escalation steps `{ offsetHours, channels }`, where `offsetHours` counts from the
  missed deadline and must be less than the grace period (the longer of `grace` and 48 hours), so
  every warning goes out before the switch fires; `push` and `email` must both appear across the
  steps.

Left out, they default to the Balanced preset: every 30 days, 14 days of grace, warnings at 0, 72
and 168 hours. The floors are enforced when you save and again when the sweep runs.

A **payload** is either zero-knowledge — `mode: "zk"` with `ciphertext`, `wrappedKey`, `salt`,
`nonce` and `algo` (or a `blobRef` for a large file) — or `mode: "readable"` with
`readableContent`, which is allowed only for a `message` or a `public_page`. A `public_page` must
be readable; `file`, `secret` and `private_page` are always zero-knowledge. `ciphertext` holds up
to 2,000,000 characters — the app keeps files to 1 MB so they always fit.

### Export file

The export is plain JSON that the hosted service produces and accepts in exactly the same shape:

```json theme={null}
{
    "format": "quietletter-export",
    "schemaVersion": 1,
    "exportedAt": "2026-10-09T12:00:00.000Z",
    "source": "self-host",
    "switches": [
        {
            "id": "…", "title": "…", "state": "active",
            "cadence": { "value": 30, "unit": "day" }, "grace": { "value": 14, "unit": "day" },
            "warnings": [{ "offsetHours": 0, "channels": ["push", "email"] }],
            "warningPhone": null, "timezone": "Europe/Kyiv", "locale": "en",
            "lastCheckinAt": "…", "createdAt": "…",
            "recipients": [{ "id": "…", "email": "…", "phone": null, "name": "…" }],
            "actions": [{ "id": "…", "type": "secret", "sortOrder": 0, "config": { "mode": "zk" },
                          "payload": { "mode": "zk", "ciphertext": "…", "wrappedKey": "…", "salt": "…",
                                       "nonce": "…", "algo": "…", "blobRef": null, "size": 42,
                                       "readableContent": null, "schemaVersion": 1 } }]
        }
    ]
}
```

* **Exported:** every switch that hasn't fired, with its recipients, actions and payloads exactly
  as stored — zero-knowledge payloads stay ciphertext. Release links, the delivery log and
  published public pages are history, not setup, and stay behind. `payload` is `null` for an
  action whose content was never uploaded.
* **Time zone + language:** `timezone` is the zone the check-in rhythm follows; `locale` is the
  language of that switch's emails. Both are optional: files without them still import (a missing
  zone is filled in the next time the app opens the list). The hosted service writes and reads
  `timezone` only — it sends emails in the language you use the app in.
* **Imported:** each switch is checked against the same rules as `PUT /v1/switches/:id` (the
  48-hour grace floor, push + email warnings that all fall before the fire time, the
  zero-knowledge rules). Its timer starts at the
  moment of import — nothing can fire early — and a `disarmed` switch stays disarmed.
* **Idempotent:** ids are kept, so a switch that already exists is skipped (`exists`), and an id
  already used by another switch is skipped as a `conflict`. Invalid entries are skipped as
  `invalid` without failing the rest; everything that is imported is written in one transaction.
* **Versioned:** a file with a higher `schemaVersion` than the server knows is refused with
  `unsupported_export_version`; anything else that isn't an export gets `invalid_export_file`.
  Unknown fields are ignored. A payload that points at an external blob (`blobRef`) can't be
  imported. The import body may be up to 50 MB.

The import answers with one result per switch, in file order:

```json theme={null}
{ "imported": 1, "skipped": 1, "results": [
    { "id": "…", "title": "For my family", "status": "imported" },
    { "id": "…", "title": "Old switch", "status": "skipped", "reason": "exists" }
] }
```

The hosted service applies its plan limits to an import and skips switches with a public page
(`self_host_only`); your instance accepts them.

### Public routes (no token)

| Method & path | Purpose |
| - | - |
| `GET /v1/release/:token` | The content-blind bundle a recipient of a **fired** switch decrypts in the browser. 404 for an unknown or expired link, or a switch that hasn't fired. |
| `GET /release/:token` | The ready-made release page the fire emails link to: shows readable content right away and decrypts encrypted items in the browser. |
| `GET /vendor/libsodium-sumo.js`, `GET /vendor/libsodium-wrappers.js` | The libsodium build the release page decrypts with, served by your instance — the page loads nothing from a CDN. |
| `GET /p/:slug` | A published public page. |
| `GET /health`, `GET /v1/health` | Liveness check (the app uses it when you connect an instance). |

### Reference encryption envelope

The server never decrypts anything, but its release page includes an in-browser decryptor for the
envelope `algo = "xchacha20poly1305-argon2id-v1"` (libsodium):

```
KEK        = crypto_pwhash(32, passphrase, salt, INTERACTIVE, INTERACTIVE, ARGON2ID13)
contentKey = crypto_aead_xchacha20poly1305_ietf_decrypt(wrappedKey[24:], wrappedKey[:24], KEK)
plaintext  = crypto_aead_xchacha20poly1305_ietf_decrypt(ciphertext, nonce, contentKey)
```

`salt`, `wrappedKey`, `nonce` and `ciphertext` are all base64. A client that uses a different
envelope can build its own release page on `GET /v1/release/:token` — the server stores and
returns ciphertext unchanged either way.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.