# Build from source and development

> Build the Hub, the Docker image, the desktop and mobile apps and the push relay from source, run everything locally, run the tests, and follow the project's conventions.

Source: https://docs.posternmail.app/development/

This page explains how to build every part of Postern from the source code and how to run it
on your own computer while you work on it. Postern is in beta and **no releases are published
yet**: there are no release archives, `.deb` or `.rpm` packages, container images or signed
desktop installers. Building from source is the way to get Postern today. To install a Hub you
built, follow the [setup guide](https://docs.posternmail.app/setup/).

Before you change code, read the developer contract,
[docs/dev/CONTRACT.md](https://github.com/TheOriUHD/postern/blob/main/docs/dev/CONTRACT.md). It defines who owns which part, the API conventions
and the security rules.

## Prerequisites

| Tool | Version | Needed for |
|---|---|---|
| Git | any recent | the source code, version numbers in builds |
| Go | 1.27 or newer (`hub/go.mod`, `relay/go.mod`) | the Hub, the relay, the test mail server, the mobile engine |
| Node.js | 24 or newer (`engines` in `package.json`) | the web, desktop and mobile apps |
| pnpm | 11 (`packageManager`: `pnpm@11.22.0`) | installing and running the JavaScript packages |
| Docker | any recent | only for the Docker image |
| Xcode | current | only for the iOS app and the iOS engine |
| Android SDK, NDK r26 or newer, JDK 17 | | only for the Android app and the Android engine |

`corepack enable` makes Node use the pnpm version the repository asks for. Then install the
JavaScript dependencies from the repository root:

```sh
git clone https://github.com/TheOriUHD/postern.git
cd postern
corepack enable
pnpm install
```

Go downloads its modules on the first build.

## Repository layout

```text
postern/
├─ hub/                     Go module postern/hub: the Hub
│  ├─ cmd/hub/              the postern-hub program (serve and every CLI command)
│  ├─ cmd/devmail/          local test mail server (IMAP, SMTP, seeded accounts)
│  ├─ engine/               the in-app mail engine for iOS and Android (built with gomobile)
│  └─ internal/
│     ├─ app/               wiring: builds and starts every part
│     ├─ config/            environment variables and flags
│     ├─ envx/              POSTERN_* names with the MC_* fallback
│     ├─ api/ httpx/        HTTP server, routing, errors, rate limits
│     ├─ edge/              access gateway headers (Cloudflare Access)
│     ├─ deps/ core/        shared interfaces between the parts
│     ├─ lifecycle/         start and stop order
│     ├─ store/             SQLite and migrations
│     ├─ vault/             encryption at rest and the key file
│     ├─ changelog/         per-user change feed for app sync
│     ├─ platform/          users, sign-in, devices, pairing, settings, admin, push, CLI, doctor
│     ├─ clientmode/        the device engine (direct mode) behind the desktop and mobile apps
│     ├─ mail/              sync, threads, search, commands; compose/ and automation/ (rules)
│     ├─ provider/          the interface every mail provider implements
│     ├─ providers/         IMAP and SMTP, Gmail API, Microsoft Graph, JMAP, autodiscovery
│     ├─ ids/ version/      ID helpers, version information
│     └─ webui/             the embedded web app (dist/ is filled by scripts/build-hub.sh)
├─ relay/                   Go module postern/relay: the push relay
├─ packages/
│  ├─ protocol/             @postern/protocol: the API contract in TypeScript
│  └─ core/                 @postern/core: API client, sync, stores, outbox for every app
├─ apps/
│  ├─ web/                  @postern/web: the React web app (built into the Hub)
│  ├─ desktop/              @postern/desktop: the Electron app
│  ├─ mobile/               @postern/mobile: the Expo app for iOS and Android
│  └─ site/                 @postern/site: the website and these docs
├─ tests/e2e/               end-to-end tests against a real Hub and devmail
├─ deploy/                  Docker, Compose, systemd, Caddy, nginx, Traefik, cloudflared, Tailscale, install.sh
├─ scripts/build-hub.sh     builds the Hub binary
└─ docs/                    user docs; docs/dev/ holds the developer contract and design notes
```

`go.work` ties the `hub` and `relay` modules together. The pnpm workspace covers `apps/*` and
`packages/*` and uses a hoisted `node_modules`, because React Native resolves packages most
reliably that way. `tests/e2e` is not part of the workspace.

### Root scripts

| Command | What it runs |
|---|---|
| `pnpm dev:web` | `pnpm --filter @postern/web dev` |
| `pnpm build:web` | `pnpm --filter @postern/web build` |
| `pnpm build:hub` | `./scripts/build-hub.sh` |
| `pnpm typecheck` | `typecheck` in every package that has it |
| `pnpm test` | `test` in every package that has it |
| `pnpm lint` | `lint` in every package that has it |
| `pnpm test:core-e2e` | the core end-to-end test (`tests/e2e/core.e2e.test.ts`) |

## Run it locally

You need three terminals: a test mail server, the Hub and the web app with hot reload. Run all
commands from the repository root.

1. Start the test mail server. It keeps everything in memory and needs no Docker.

   ```sh
   cd hub && go run ./cmd/devmail
   ```

2. Start the Hub in development mode, with its data in `./data` at the repository root.

   ```sh
   cd hub && POSTERN_DEV=1 go run ./cmd/hub --data-dir ../data
   ```

3. Start the web app.

   ```sh
   pnpm --filter @postern/web dev
   ```

Open `http://localhost:5173`, run the setup wizard and create your admin account. If the wizard
asks for a setup code, it is in the Hub's log; see [Command line](https://docs.posternmail.app/reference/cli/#setup-code).

Then add a devmail account as an IMAP mailbox:

| Field | Value |
|---|---|
| Email | `you@work.test`, `you@personal.test` or `you@side.test` |
| Password | `devpass` |
| IMAP server | `localhost`, port `1143`, security **None** |
| SMTP server | `localhost`, port `1025`, security **None** |

Mail you send between the three accounts arrives in the others. The data in `./data` is ignored
by git; stop the Hub and delete the folder to start over.

### What the pieces do

| Piece | Listens on | Notes |
|---|---|---|
| devmail | IMAP `127.0.0.1:1143`, SMTP `127.0.0.1:1025`, control API `127.0.0.1:1080` | Plain text, no TLS. Never expose it. |
| Hub | `:8080` (all interfaces, the default of `POSTERN_LISTEN`) | Serves the API and a placeholder page or the embedded web build. |
| Vite dev server | `localhost:5173` | Hot reload. Forwards `/api` to the Hub and keeps the `Host` header, so the Hub's same-origin check passes. |

The Vite server sends `/api` to `POSTERN_HUB_URL` (the older `MC_HUB_URL` also works), default
`http://127.0.0.1:8080`. Set it when your Hub runs elsewhere:

```sh
POSTERN_HUB_URL=http://192.168.1.20:8080 pnpm --filter @postern/web dev
```

`POSTERN_DEV=1` turns on debug logs and relaxes checks that get in the way locally, for example
private addresses for the image proxy and autodiscovery. Never set it on a real Hub. See
[Development settings](https://docs.posternmail.app/configuration/#development-settings).

### devmail options

| Flag | Default | What it does |
|---|---|---|
| `--imap ADDR` | `127.0.0.1:1143` | IMAP listen address |
| `--smtp ADDR` | `127.0.0.1:1025` | SMTP listen address |
| `--http ADDR` | `127.0.0.1:1080` | HTTP control API; `-` turns it off |
| `--seed` | `true` | Fill the accounts with sample mail; `--seed=false` starts empty |
| `--per-account N` | about 150 | Messages per seeded account (for example 25000 for performance work) |
| `--days N` | 60 | Spread the seeded mail over this many days |
| `--trickle DURATION` | off | Deliver a new message to a random account at this interval, for example `45s` |
| `-v` | off | Log deliveries and protocol errors |

### Web app without a Hub

The web app has a demo mode with sample data and no Hub:

```sh
pnpm --filter @postern/web demo
```

You can also add `?demo=1` (signed in), `?demo=login` or `?demo=setup` to the URL of the dev
server. `?demo=0` turns it off again.

## Build the Hub

`scripts/build-hub.sh` builds the web app, copies it into the Hub and builds a static
`postern-hub` binary.

```sh
scripts/build-hub.sh
```

```text
build-hub: building web app (pnpm --filter @postern/web build)
build-hub: embedded web app → hub/internal/webui/dist
build-hub: go build linux/amd64 → /home/you/postern/hub/bin/postern-hub
/home/you/postern/hub/bin/postern-hub
build-hub: done (version 4391ff7-dirty)
```

The script prints the path of each binary on standard output and its progress on standard
error.

| Option | Default | What it does |
|---|---|---|
| `--target LIST`, `--targets LIST` | this computer's system | Cross-compile for one or more `os/arch` pairs, separated by commas, for example `linux/amd64,linux/arm64` |
| `--out DIR` | `hub/bin` | Output folder. A relative path is taken from the repository root. |
| `--name NAME` | `postern-hub` | Base name of the binary |
| `--skip-web` | off | Do not build or copy the web app; use what is already in `hub/internal/webui/dist` |
| `--web-only` | off | Only build the web app and copy it into the Hub; build no binary |
| `--version V` | `git describe --tags --always --dirty` without a leading `v`, or `0.0.0-dev` outside git | Version string shown by `postern-hub version` |
| `-h`, `--help` | | Show the usage |

Every option also works as `--option=value`. The environment variables `COMMIT` and `DATE`
override the commit hash and build date recorded in the binary.

Output names:

| Build | Output |
|---|---|
| No `--target` | `hub/bin/postern-hub` (`.exe` on Windows) |
| Several targets | `hub/bin/postern-hub-<os>-<arch>`, for example `hub/bin/postern-hub-linux-arm64` |
| One target with `--name` or `--out` | `DIR/NAME`, for example `--target darwin/arm64 --out apps/desktop/resources/hub --name hub` gives `apps/desktop/resources/hub/hub` |

The binary is built with `CGO_ENABLED=0`, `-trimpath` and `-ldflags "-s -w"`, so it has no
system dependencies and you can copy it to any machine with the same system and architecture.
The Hub's supported server platform is Linux on amd64 and arm64. Builds for macOS and Windows
exist for the desktop app's built-in Hub.

Examples:

```sh
scripts/build-hub.sh --target linux/amd64,linux/arm64
scripts/build-hub.sh --skip-web --target linux/arm64 --out dist --name postern-hub
scripts/build-hub.sh --web-only
```

Errors:

| Message | Meaning |
|---|---|
| `build-hub: error: pnpm is required to build the web app (or pass --skip-web)` | Install pnpm (`corepack enable`), or skip the web app. |
| `build-hub: error: go is required` | Install Go 1.27 or newer. |
| `build-hub: error: --skip-web and --web-only cannot be combined` | Use one of them. |
| `build-hub: error: invalid target 'X' (expected os/arch, e.g. linux/amd64)` | Write targets as `os/arch`. |
| `build-hub: error: unknown argument: X (see --help)` | Check the spelling. |
| `build-hub: warning: apps/web/dist/index.html not found after build; keeping the embedded placeholder` | The web build produced nothing. The binary serves a "not built" page instead of the web app. |

> [!NOTE]
> Only `hub/internal/webui/dist/.keep` is tracked in git. A Hub built with `go build` alone, or
> with `--skip-web` on a fresh clone, compiles fine but shows a placeholder page instead of the
> web app. The API works either way.

To install the binary on a server, follow the [setup guide](https://docs.posternmail.app/setup/).

## Docker image

The Dockerfile at `deploy/docker/Dockerfile` builds the web app and the Hub in separate stages
and needs the whole repository as its build context. Run it from the repository root:

```sh
docker build -f deploy/docker/Dockerfile -t ghcr.io/theoriuhd/postern-hub:local .
```

The tag `ghcr.io/theoriuhd/postern-hub:local` is the one the setup guide's `.env` expects
(`POSTERN_VERSION=local`). The image is not published anywhere; the name only matches the
Compose file.

| Build argument | Default | What it does |
|---|---|---|
| `VERSION` | `0.0.0-docker` | Version string in the binary |
| `COMMIT` | empty | Commit hash in the binary |
| `DATE` | empty | Build date in the binary |
| `NODE_VERSION` | `22` | Node image for the web stage |
| `GO_VERSION` | `1.27` | Go image for the Hub stage |
| `ALPINE_VERSION` | `3.22` | Base of the final image |

```sh
docker build -f deploy/docker/Dockerfile \
  --build-arg VERSION="$(git describe --tags --always --dirty)" \
  --build-arg COMMIT="$(git rev-parse HEAD)" \
  -t ghcr.io/theoriuhd/postern-hub:local .
```

The final image:

| Property | Value |
|---|---|
| Base | Alpine (so the health check can use `wget`) |
| User | `10001:10001` |
| Program | `postern-hub`, started as `postern-hub serve` |
| Environment | `POSTERN_DATA_DIR=/data`, `POSTERN_KEY_FILE=/key/hub.key`, `POSTERN_LISTEN=:8080` |
| Volumes | `/data`, `/key` |
| Port | `8080` |
| Health check | `GET http://127.0.0.1:8080/api/v1/info` every 30 seconds |

Run it with the Compose file as the [setup guide](https://docs.posternmail.app/setup/) describes. Paths and volumes are
listed in [Ports and paths](https://docs.posternmail.app/reference/ports-and-paths/).

## Desktop app

The desktop app lives in `apps/desktop` (Electron). Run it in development mode:

```sh
pnpm --filter @postern/desktop dev
```

`dev` bundles the app with esbuild in watch mode and restarts Electron when the main process or
the preload script changes. Reload the window for changes to the connect and offline pages.
Connect it to `http://localhost:8080` (your Hub with the embedded web build) or to
`http://localhost:5173` for hot reload of the web app.

In development the **View** menu has **Toggle Developer Tools**. In a packaged build, start the
app with `POSTERN_DEVTOOLS=1` to get the same item.

| Script | What it does |
|---|---|
| `dev` | Development mode, see above |
| `build` | Bundle main, preload and the local pages into `dist/` |
| `start` | `build`, then start Electron |
| `typecheck` | `tsc --noEmit` |
| `test` | Unit tests (`node --test "test/*.test.mjs"`) |
| `smoke` | Start with a throwaway profile, check the connect screen, start a fake Hub, connect, check the desktop bridge and the link policy, then exit. Prints `SMOKE OK` on success. |
| `screenshot` | Like `smoke`, and saves `release/connect.png` |
| `e2e:direct` | End-to-end test of direct mode |
| `bundle-hub` | Build the Hub for the app's built-in Hub, see below |
| `dist` | Build installers into `release/` with electron-builder |
| `icons` | Regenerate the app, tray and badge icons from the SVG sources |

### Bundle the Hub into the desktop app

The desktop app can run a Hub on the same computer. `dist` does not build that Hub; run
`bundle-hub` first:

```sh
scripts/build-hub.sh --web-only
pnpm --filter @postern/desktop bundle-hub
```

| Option | What it does |
|---|---|
| none | Build for this system and every architecture the app ships: macOS arm64 and amd64, Windows amd64, or Linux amd64 and arm64 |
| `--target os/arch` | Build for the given targets (repeat it or separate with commas) |
| `--with-web` | Build the web app first, instead of using what `hub/internal/webui/dist` holds |

The binaries go to `apps/desktop/resources/hub/<mac|win|linux>-<x64|arm64>/hub` (`hub.exe` on
Windows), where electron-builder picks the one for each package.

### Build installers

```sh
pnpm --filter @postern/desktop dist
pnpm --filter @postern/desktop dist -- --dir
```

The second command builds an unpacked app only, which is faster for testing. Other arguments
after `--` go to electron-builder, for example `--mac` or `--publish never`. Installers are
unsigned unless `CSC_LINK`, `WIN_CSC_LINK` or `CSC_NAME` is set; the app only updates itself in
signed builds.

Code layout: `src/main` (windows, navigation policy, IPC, tray, menu, built-in Hub, updater),
`src/preload` (the bridge for Hub pages and a small API for the local pages), `src/renderer`
(connect, offline and **Desktop App Options** pages), `packaging/` (icons and entitlements for
electron-builder).

## Mobile app

The mobile app lives in `apps/mobile` (Expo, iOS and Android). It includes a Go mail engine
for direct mode, built with gomobile. Build the engine once, and again when Go code under
`hub/` changes:

```sh
go install golang.org/x/mobile/cmd/gomobile@latest golang.org/x/mobile/cmd/gobind@latest
gomobile init
apps/mobile/scripts/build-engine.sh
```

| Argument | Builds | Output (ignored by git) |
|---|---|---|
| `ios` (default) | the iOS framework, for devices and the simulator | `apps/mobile/modules/mail-engine/ios/Engine.xcframework` |
| `android` | the Android library | `apps/mobile/modules/mail-engine/android/libs/engine.aar` |
| `all` | both | both |

iOS needs Xcode. Android needs `ANDROID_HOME` (SDK with platform 24 or newer),
`ANDROID_NDK_HOME` (NDK r26 or newer) and a JDK 17. The script never changes `hub/go.mod`; it
binds from a throwaway module.

| Variable | Default | What it does |
|---|---|---|
| `BIND_DIR` | `apps/mobile/build/engine-bind` | Folder for the throwaway module |
| `IOS_MIN` | `15.1` | Minimum iOS version |
| `ANDROID_API` | `24` | Minimum Android API level |
| `ENGINE_TAGS` | empty | Extra Go build tags |

Without the engine the app still builds; the in-app engine is then unavailable and the build
log says `MailEngine: ios/Engine.xcframework not found`. Expo Go cannot load the engine either.

Run the app:

```sh
pnpm --filter @postern/mobile ios
pnpm --filter @postern/mobile android
pnpm --filter @postern/mobile start
```

`ios` and `android` build a development app and start it in the simulator or emulator. `start`
only starts the Expo server. Other scripts: `typecheck`, `lint`, `doctor` (`expo-doctor`) and
`generate:assets`.

The app has to reach your Hub from the simulator or phone. Use your computer's LAN address, for
example `http://192.168.1.20:8080`. The Hub's default `POSTERN_LISTEN` of `:8080` already
listens on every interface. With `POSTERN_DEV=1` the Hub also accepts `exp://` redirect
addresses for browser sign-in.

## Push relay

The push relay is a separate Go module in `relay/`.

```sh
cd relay && go run ./cmd/relay
```

It listens on `:8090` (`RELAY_LISTEN`) and keeps its data in `./relay-data`
(`RELAY_DATA_DIR`). Without Apple (APNs) or Google (FCM) credentials it still accepts
registrations, logs `neither APNs nor FCM is configured: every push will fail with
platform_not_configured`, and answers each push with `platform_not_configured`. Point a local
Hub at it:

```sh
cd hub && POSTERN_DEV=1 POSTERN_RELAY_URL=http://localhost:8090 go run ./cmd/hub --data-dir ../data
```

Its commands are `serve` (the default), `check`, `hubs list`, `hubs disable ID`,
`hubs enable ID`, `hubs delete ID` and `version`. Build its image from the repository root:

```sh
docker build -f relay/Dockerfile -t postern-relay .
```

All relay settings are on [Run your own relay](https://docs.posternmail.app/relay/run-your-own/).

## Tests and checks

### Go

Run these in `hub/` or `relay/`. While other areas are mid-change, test only the packages you
changed.

```sh
cd hub && go build ./... && go vet ./... && go test ./...
cd hub && go test ./internal/mail/...
cd relay && go vet ./... && go test ./...
go run golang.org/x/vuln/cmd/govulncheck@latest ./...
```

### TypeScript

```sh
pnpm typecheck
pnpm test
pnpm lint
```

`pnpm test` runs Vitest in `@postern/web` and `@postern/core` and `node --test` in
`@postern/desktop`.

### End-to-end tests

The end-to-end tests in `tests/e2e` build and run a real Hub and devmail and use the public
API. They need Go and Node 23 or newer (Node runs the TypeScript files directly).

```sh
cd tests/e2e && npm test
cd tests/e2e && npm run test:hub
pnpm test:core-e2e
```

| Script | Tests |
|---|---|
| `test` | all of `hub`, `direct` and `offline` |
| `test:hub` | the Hub |
| `test:direct` | direct mode with a device engine |
| `test:offline` | offline changes and their sync |

### CI

`.github/workflows/ci.yml` runs on pushes to `main`, on pull requests and on demand:

| Job | What it does |
|---|---|
| Go (hub, relay) | `go vet`, `go test -race -count=1` and `govulncheck`, with `GOWORK=off` |
| Go tests on arm64 (hub) | `go test -count=1` on an arm64 runner |
| Build hub | `scripts/build-hub.sh --skip-web` for linux/amd64, linux/arm64, darwin/arm64, darwin/amd64 and windows/amd64 |
| TypeScript | `pnpm install --frozen-lockfile`, `pnpm typecheck`, `pnpm test`, `pnpm build:web` on Node 24 |
| Desktop | typecheck, test and build on Linux, macOS and Windows, plus `smoke` on macOS |
| Shell scripts | `shellcheck` and `bash -n` |

### Releases

`.github/workflows/release.yml` runs GoReleaser (`.goreleaser.yaml`) when a `v*` tag is pushed.
It is set up to produce Hub archives named `postern-hub_<version>_<os>_<arch>`, relay archives,
`.deb` and `.rpm` packages, multi-architecture images for `ghcr.io/theoriuhd/postern-hub` and
`ghcr.io/theoriuhd/postern-relay`, checksums, SBOMs and cosign signatures. No release has been
made yet, so none of these exist.

## Conventions

The full rules are in [CONTRACT.md](https://github.com/TheOriUHD/postern/blob/main/docs/dev/CONTRACT.md). The short version:

- **The protocol comes first.** `packages/protocol/src/index.ts` is the source of truth for the
  API. Change it first, then the Hub and the apps.
- **JSON** uses camelCase. Arrays are never `null`; send `[]`.
- **Go modules.** Never run `go mod tidy` on a shared module. Add a dependency with
  `go get module@version`.
- **Migrations** use your area's number range and are never edited once committed: core
  `0xxx`, platform `1xxx`, mail core `2000` to `2499`, compose `2500` to `2999`, device engine
  `3000` to `3999`.
- **Secrets.** Never log passwords, tokens, keys or message content.
- **Other users' data.** A request for something that belongs to another user gets `not_found`,
  never `forbidden`.
- **Names.** The product was called MailClient before. Environment variables still accept their
  old `MC_*` names as a fallback, and the old `mailclient://` scheme still works; new code uses
  `POSTERN_*` and `postern://`. The `X-MC-Client` header and the `mc_session` cookie keep their
  names.
