# Run your own relay

> Build, configure and run your own Postern push relay with your own Apple and Google credentials, and point your Hub at it.

Source: https://docs.posternmail.app/relay/run-your-own/

This page sets up `postern-relay`, the program that forwards your Hub's notifications to
Apple and Google. Read [How push works](https://docs.posternmail.app/relay/) first if you have not. With the Postern
app from the App Store or TestFlight you don't need one: use the official relay,
`https://relay.posternmail.app`. Run your own for an app you build yourself, or for
Android.

What you need:

- A machine that can make outgoing HTTPS connections to `api.push.apple.com` (or
  `api.sandbox.push.apple.com`) and `fcm.googleapis.com`, and that your Hub can reach. It can
  be the Hub's own machine.
- Go 1.27 or newer, or Docker, to build the relay from source.
- An HTTPS address for it, for example `https://relay.example.com`, through a reverse proxy.
- Apple and/or Google credentials that match **the app build on your phones**. This is the
  part that decides whether anything arrives, so read the next section before you start.

## Apple and Google credentials

A device token belongs to one app. Apple and Google only deliver a push to it when the push
is signed with credentials of that app's owner:

- **iOS:** the push must be signed with an APNs key of the Apple developer team that owns the
  app's **bundle ID**, and must name that bundle ID as its topic (`APNS_TOPIC`). A key of
  another team is rejected.
- **Android:** the push must be sent with a service account of the **Firebase project** the
  app was built with (its `google-services.json`).

So your relay can only reach apps that you build yourself, with a bundle ID in your own Apple
developer team and a Firebase project of your own. It cannot reach an app built and signed by
someone else: the App Store and TestFlight builds of Postern are reachable only through the
official relay, which holds the project's own APNs key.

The Postern app's identifiers are in `apps/mobile/app.json`: `ios.bundleIdentifier` and
`android.package` are both `app.postern`. That bundle ID belongs to the project's Apple team,
so for a self-built iOS app you change `ios.bundleIdentifier` to one in your team (for
example `com.example.postern`) and use that same value as `APNS_TOPIC`. How to build the apps
is described on [iOS app](https://docs.posternmail.app/apps/ios/) and [Android app](https://docs.posternmail.app/apps/android/).

You can configure only one platform. Pushes for the other one fail with
`platform_not_configured`.

### APNs key (iOS)

1. In the Apple Developer portal, open **Certificates, Identifiers & Profiles → Keys** and
   create a key with **Apple Push Notifications service (APNs)** enabled.
2. Download the `.p8` file. Apple lets you download it only once: keep a copy somewhere safe.
3. Note the **Key ID** (10 characters, shown with the key) and your **Team ID** (10
   characters, shown in your membership details).
4. Decide on the APNs environment. Builds installed from Xcode with a development profile get
   tokens for the **sandbox** servers (`APNS_SANDBOX=true`). TestFlight and App Store builds
   use **production** (the default). One relay talks to one environment.

The key must be a P-256 key in PEM format, which is what Apple's `.p8` files are. The relay
signs a provider token with it (ES256) and renews it every 40 minutes.

### Firebase service account (Android)

1. In the [Firebase console](https://console.firebase.google.com/), use the project that your
   Android build's `google-services.json` comes from. The app and the relay must use the
   same project.
2. Open **Project settings → Service accounts** and choose **Generate new private key**. This
   downloads a JSON file.
3. Make sure the **Firebase Cloud Messaging API (V1)** is enabled for the project.

The relay reads `client_email`, `private_key`, `private_key_id`, `project_id` and
`token_uri` from that file. The file's `type` must be `service_account`.

> [!WARNING]
> The `.p8` key and the service-account JSON let anyone send notifications to your app's
> users. Keep them readable only by the relay, never commit them, and back them up apart from
> the relay's data.

## Build the relay

Both ways build from the repository's `relay/` folder, which is its own Go module. There are
no release archives or images yet (the planned image name is
`ghcr.io/theoriuhd/postern-relay`).

Get the source if you do not have it yet:

```sh
git clone https://github.com/TheOriUHD/postern.git ~/postern
```

### With Go

```sh
cd ~/postern/relay
GOWORK=off CGO_ENABLED=0 go build -trimpath -ldflags "-s -w -X main.version=$(git describe --tags --always)" -o postern-relay ./cmd/relay
sudo install -m 0755 postern-relay /usr/local/bin/postern-relay
```

The result is one static binary. `postern-relay version` prints the version you set with
`-X main.version` (without it, `dev`).

### With Docker

Run this from the repository root, not from `relay/`:

```sh
cd ~/postern
docker build -f relay/Dockerfile -t postern-relay:local --build-arg VERSION=$(git describe --tags --always) .
```

The image runs as user 10001, keeps its data in `/data` (a volume), listens on port 8090,
and has a health check that calls `/healthz`. Its default command is `serve`.

## Configuration

The relay reads only environment variables. Values are trimmed; an empty value counts as
not set. Invalid values stop it at start with an error naming the variable.

| Variable | Default | Meaning |
|---|---|---|
| `RELAY_LISTEN` | `:8090` | Address and port to listen on. Use `127.0.0.1:8090` when a reverse proxy runs on the same machine. |
| `RELAY_DATA_DIR` | `./relay-data` (image: `/data`) | Folder for `relay.db`, the SQLite file with the Hub registrations. Created with mode 0700, the database file is set to 0600. |
| `RELAY_REGISTRATION` | `open` | `open`: any Hub that can reach the relay may register. `closed`: no new registrations (HTTP 403 "Registration is closed on this relay"). |
| `RELAY_MAX_PUSH_PER_MINUTE` | `120` | Push messages per Hub per minute. Each message in a batch counts. Must be a positive integer. |
| `RELAY_MAX_REGISTER_PER_HOUR` | `10` | Registrations per client IP per hour. Must be a positive integer. |
| `RELAY_TRUST_PROXY` | `false` | `true`: take the client IP for the registration limit from the right-most `X-Forwarded-For` entry. Only behind your own reverse proxy. Accepts `1/true/yes/on` and `0/false/no/off`. |
| `RELAY_CLIENT_IP_HEADER` | empty | With `RELAY_TRUST_PROXY=true`: a header your proxy sets to the client IP, which then wins over `X-Forwarded-For`. Behind Cloudflare (a proxied DNS record or `cloudflared`): `CF-Connecting-IP`. |
| `RELAY_LOG_LEVEL` | `info` | `debug`, `info`, `warn` (or `warning`), `error`. |
| `RELAY_LOG_FORMAT` | `json` | `json` or `text`. Logs go to standard error. |
| `APNS_KEY_FILE` | | Path to the APNs `.p8` key. Setting it turns on iOS. |
| `APNS_KEY_ID` | | Key ID of that key. Required with `APNS_KEY_FILE`. |
| `APNS_TEAM_ID` | | Your Apple developer Team ID. Required with `APNS_KEY_FILE`. |
| `APNS_TOPIC` | | The iOS app's bundle ID. Required with `APNS_KEY_FILE`. |
| `APNS_SANDBOX` | `false` | `true` sends to `api.sandbox.push.apple.com` instead of `api.push.apple.com`. |
| `FCM_CREDENTIALS_FILE` | | Path to the Firebase service-account JSON. Setting it turns on Android. |
| `FCM_PROJECT_ID` | `project_id` from the credentials file | Firebase project ID, if you need to override it. |

Start-up errors you may see:

| Message | Fix |
|---|---|
| `APNS_KEY_FILE is set but APNS_KEY_ID, APNS_TEAM_ID missing` (or similar) | Set all four APNs variables together. |
| `APNS_KEY_ID/APNS_TEAM_ID/APNS_TOPIC are set but APNS_KEY_FILE is not` | Set the key file, or remove the other APNs variables. |
| `FCM_PROJECT_ID is set but FCM_CREDENTIALS_FILE is not` | Set the credentials file, or remove `FCM_PROJECT_ID`. |
| `apns: read key file: ...`, `apns: key file is not PEM`, `apns: key must be P-256` | The path is wrong, not readable by the relay's user, or not an APNs `.p8` key. |
| `fcm: credentials type is "...", want service_account`, `fcm: credentials need client_email and private_key` | Use a service-account key from **Project settings → Service accounts**, not `google-services.json`. |
| `fcm: project id missing (set FCM_PROJECT_ID)` | The JSON has no `project_id`: set `FCM_PROJECT_ID`. |
| `RELAY_REGISTRATION must be open or closed, got "..."` | Use `open` or `closed`. |

With neither APNs nor FCM configured the relay still starts, but logs the warning "neither
APNs nor FCM is configured: every push will fail with platform_not_configured".

## Run it

Pick one of the two examples below. Both are examples, not files shipped in the repository:
adjust paths, names and the bundle ID to your setup.

### With systemd (example)

Create a user, a configuration folder and the environment file:

```sh
sudo useradd --system --home-dir /var/lib/postern-relay --shell /usr/sbin/nologin postern-relay
sudo install -d -m 0750 -o root -g postern-relay /etc/postern-relay
```

Copy your `.p8` key and service-account JSON into `/etc/postern-relay/`, then make them
readable only by the relay:

```sh
sudo chown root:postern-relay /etc/postern-relay/AuthKey_ABC123DEFG.p8 /etc/postern-relay/firebase-service-account.json
sudo chmod 0640 /etc/postern-relay/AuthKey_ABC123DEFG.p8 /etc/postern-relay/firebase-service-account.json
```

Write `/etc/postern-relay/relay.env` (mode 0640, owner `root:postern-relay`):

```ini
RELAY_LISTEN=127.0.0.1:8090
RELAY_DATA_DIR=/var/lib/postern-relay
RELAY_REGISTRATION=open
RELAY_TRUST_PROXY=true
APNS_KEY_FILE=/etc/postern-relay/AuthKey_ABC123DEFG.p8
APNS_KEY_ID=ABC123DEFG
APNS_TEAM_ID=TEAM123456
APNS_TOPIC=com.example.postern
FCM_CREDENTIALS_FILE=/etc/postern-relay/firebase-service-account.json
```

Write `/etc/systemd/system/postern-relay.service`:

```ini
[Unit]
Description=Postern push relay
Wants=network-online.target
After=network-online.target

[Service]
Type=simple
User=postern-relay
Group=postern-relay
EnvironmentFile=/etc/postern-relay/relay.env
ExecStart=/usr/local/bin/postern-relay serve
Restart=on-failure
RestartSec=5s
StateDirectory=postern-relay
StateDirectoryMode=0700
UMask=0077
NoNewPrivileges=yes
CapabilityBoundingSet=
ProtectSystem=strict
ProtectHome=yes
PrivateTmp=yes
PrivateDevices=yes
ProtectKernelTunables=yes
ProtectKernelModules=yes
ProtectControlGroups=yes
RestrictAddressFamilies=AF_UNIX AF_INET AF_INET6
RestrictNamespaces=yes
LockPersonality=yes
MemoryDenyWriteExecute=yes
SystemCallArchitectures=native
SystemCallFilter=@system-service

[Install]
WantedBy=multi-user.target
```

Check the credentials, then start it:

```sh
sudo -u postern-relay sh -c 'set -a; . /etc/postern-relay/relay.env; exec postern-relay check'
sudo systemctl daemon-reload
sudo systemctl enable --now postern-relay
```

> **Check:** `postern-relay check` prints `configuration: ok`, then a line for APNs
> (`apns: key loaded, host https://api.push.apple.com, topic com.example.postern`) and FCM
> (`fcm: access token obtained for project ...`), and finally
> `store: /var/lib/postern-relay/relay.db, 0 hubs registered`.
> `sudo systemctl status postern-relay` shows `active (running)`.

> **If it did not work:** `postern-relay check` stops at the first problem and prints it
> after `error:`. For FCM it really asks Google for an access token, so a wrong key or a
> blocked outgoing connection shows up here. See the start-up errors in
> [Configuration](https://docs.posternmail.app/relay/run-your-own/#configuration), and `sudo journalctl -u postern-relay -e` for the service.

### With Docker Compose (example)

Make a folder with the credentials and a `compose.yaml`:

```sh
mkdir -p ~/postern-relay/secrets
```

Copy the `.p8` key and the service-account JSON into `~/postern-relay/secrets/`. The
container runs as user 10001, so give that user read access:

```sh
sudo chown 10001:10001 ~/postern-relay/secrets/*
sudo chmod 0400 ~/postern-relay/secrets/*
```

`~/postern-relay/compose.yaml`:

```yaml
services:
  relay:
    image: postern-relay:local
    restart: unless-stopped
    ports:
      - "127.0.0.1:8090:8090"
    environment:
      RELAY_REGISTRATION: open
      RELAY_TRUST_PROXY: "true"
      APNS_KEY_FILE: /secrets/AuthKey_ABC123DEFG.p8
      APNS_KEY_ID: ABC123DEFG
      APNS_TEAM_ID: TEAM123456
      APNS_TOPIC: com.example.postern
      FCM_CREDENTIALS_FILE: /secrets/firebase-service-account.json
    volumes:
      - relay-data:/data
      - ./secrets:/secrets:ro
    read_only: true
    tmpfs:
      - /tmp
    security_opt:
      - no-new-privileges:true
    cap_drop:
      - ALL

volumes:
  relay-data:
```

Check the credentials, then start it:

```sh
cd ~/postern-relay
docker compose run --rm relay check
docker compose up -d
```

> **Check:** `docker compose run --rm relay check` prints `configuration: ok` and a line
> each for APNs and FCM. `docker compose ps` shows the relay as `healthy` after about half a
> minute.

> **If it did not work:** A `permission denied` on a file in `/secrets` means user 10001
> cannot read it: repeat the `chown`/`chmod` above. Other errors are listed under
> [Configuration](https://docs.posternmail.app/relay/run-your-own/#configuration). Logs: `docker compose logs -f relay`.

## Put it behind HTTPS

The relay speaks plain HTTP. The Hub sends its secret in every push request, so put the
relay behind a reverse proxy with TLS and keep `RELAY_LISTEN` (or the published port) on
`127.0.0.1`.

Caddy (gets a certificate automatically; ports 80 and 443 must reach the machine):

```text
relay.example.com {
	reverse_proxy 127.0.0.1:8090
}
```

nginx (with a certificate you already have):

```nginx
server {
    listen 443 ssl;
    server_name relay.example.com;
    ssl_certificate     /etc/ssl/relay.example.com/fullchain.pem;
    ssl_certificate_key /etc/ssl/relay.example.com/privkey.pem;

    location / {
        proxy_pass http://127.0.0.1:8090;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $host;
    }
}
```

Behind a proxy, set `RELAY_TRUST_PROXY=true` so the registration limit counts real client
addresses instead of the proxy's. The relay then uses the right-most `X-Forwarded-For`
entry, which is the one your proxy adds. Behind Cloudflare, also set
`RELAY_CLIENT_IP_HEADER=CF-Connecting-IP`: a Cloudflare Tunnel does not add the caller to
`X-Forwarded-For` the way a reverse proxy does. Leave both off when nothing sits in front of
the relay, or anyone could pick their own address.

If the Hub and the relay run on the same machine or in the same private network, the Hub
can also use a plain `http://` address such as `http://127.0.0.1:8090`. Use HTTPS for any
connection that leaves the machine or network.

## Connect your Hub

Set `POSTERN_RELAY_URL` on the Hub to the relay's address, as described in
[Set the relay URL on your Hub](https://docs.posternmail.app/relay/#set-the-relay-url-on-your-hub).

How the Hub authenticates:

1. On its first push, the Hub calls `POST /v1/register` with its name (from **Settings →
   Admin → Your Hub**) and version. The relay answers with a random Hub ID (`hub_...`) and a
   random 32-byte secret.
2. The relay stores only a SHA-256 hash of the secret. The Hub stores the secret encrypted
   with its master key, together with the Hub ID and the relay URL.
3. Every push request carries `Authorization: Bearer <secret>` and the Hub ID. A wrong or
   unknown secret gets HTTP 401.
4. If the relay rejects the secret (for example because you deleted the Hub on the relay, or
   lost `relay.db`), the Hub registers again once by itself. That only works while
   registration is open.

Once all your Hubs have registered, close registration so nobody else can use your relay:

```ini
RELAY_REGISTRATION=closed
```

Restart the relay after the change. Registered Hubs keep working.

> [!NOTE]
> With registration closed, a Hub that has to register again (new relay URL, deleted
> registration, lost `relay.db`) cannot. Open registration for a moment, send yourself a
> test mail so the Hub registers, then close it again.

## Check that it works

The health endpoint needs no authentication:

```sh
curl -s https://relay.example.com/healthz
```

```text
{"apns":true,"fcm":true,"ok":true,"version":"dev"}
```

`apns` and `fcm` say which platforms are configured. If the database cannot be reached, the
endpoint answers HTTP 503 with `{"ok":false}`.

Then test the whole path:

1. On the Hub, **Settings → Admin → Status → Phone notifications** says **Working**.
2. On the phone, open Postern, **Settings → Notifications**, and turn on **Notifications**.
3. Put the app in the background and send yourself a message from another account.
4. List the registered Hubs on the relay: **PUSHES** goes up and **LAST PUSH** is set
   (counters are written to the database once a minute).

With the systemd example:

```sh
sudo -u postern-relay sh -c 'set -a; . /etc/postern-relay/relay.env; exec postern-relay hubs list'
```

With the Docker example:

```sh
cd ~/postern-relay && docker compose exec relay postern-relay hubs list
```

```text
ID                              NAME     VERSION  CREATED               LAST PUSH             PUSHES  STATUS
hub_k3x7q2m4w5n6p7r8s9t2v3w4x5  Postern  0.1.0    2026-12-01T10:00:00Z  2026-12-05T08:12:44Z  37      active
```

## Operating the relay

| Command | What it does |
|---|---|
| `postern-relay` or `postern-relay serve` | Runs the relay. |
| `postern-relay check` | Validates the configuration, loads the APNs key, fetches an FCM access token and opens the database, then exits. |
| `postern-relay hubs list` | Lists registered Hubs: ID, name, version, created, last push, push count, status. |
| `postern-relay hubs disable ID` | Rejects pushes from that Hub (HTTP 403 "This hub is disabled on the relay"). |
| `postern-relay hubs enable ID` | Accepts its pushes again. |
| `postern-relay hubs delete ID` | Forgets the Hub. It registers again on its next push if registration is open. |
| `postern-relay version` | Prints the version. |
| `postern-relay help` | Prints the usage. |

The `hubs` and `check` commands read the same environment variables as the server, in
particular `RELAY_DATA_DIR`. They can run while the relay is running.

### Backups

Back up `relay.db` in `RELAY_DATA_DIR` (with Docker, the `relay-data` volume). It holds only
the Hub registrations. If you lose it, every Hub has to register again, which happens
automatically while registration is open. Back up the `.p8` key and the service-account JSON
separately: Apple will not let you download the key again.

### Logs

Logs go to standard error: `sudo journalctl -u postern-relay -f` with systemd,
`docker compose logs -f relay` with Docker. At the default `info` level you see one line
when the relay starts, one per registration (`hub registered`, with Hub ID and version) and
one per push request (`push`, with Hub ID, number of messages, how many were delivered,
unregistered or failed, and the time taken). Request lines (method, path, status) are
logged at `debug`, or at `warn` for server errors. The relay never logs payloads, secrets,
full device tokens or client IP addresses. See [What the relay sees](https://docs.posternmail.app/relay/what-it-sees/#logs).

### Limits

| Limit | Value |
|---|---|
| Messages per push request | 100 |
| Payload size per message | 4 KB (after shortening title and body) |
| Title | 256 characters, longer ones are shortened |
| Body | 1024 characters, longer ones are shortened |
| Collapse key | 64 bytes |
| Thread ID | 128 bytes |
| Push rate per Hub | `RELAY_MAX_PUSH_PER_MINUTE` (default 120), refilled continuously |
| Registrations per IP | `RELAY_MAX_REGISTER_PER_HOUR` (default 10) |

When a Hub is over its push rate, the extra messages get the error `rate_limited`. When it
has nothing left at all, the whole request gets HTTP 429 with a `Retry-After` header.

## Troubleshooting

The relay answers each message with `ok`, or an `error` and whether the token is dead
(`unregistered`). The Hub deletes registrations reported as dead and logs other errors at
debug level (`relay push rejected`). Set `RELAY_LOG_LEVEL=debug` on the relay to see each
failure with an 8-character fingerprint of the token, the provider's HTTP status and reason.

| Error | Meaning | What to do |
|---|---|---|
| `platform_not_configured` | No APNs (iOS) or FCM (Android) credentials on this relay. | Add the missing credentials. |
| `BadDeviceToken` (iOS) | The token is malformed or belongs to the other APNs environment. The Hub deletes it. | If it happens for every device, `APNS_SANDBOX` does not match your build: development builds need `true`, TestFlight and App Store builds `false`. |
| `DeviceTokenNotForTopic` (iOS) | `APNS_TOPIC` is not the bundle ID of the app on the phone. | Set `APNS_TOPIC` to your build's `ios.bundleIdentifier`. |
| `InvalidProviderToken` (iOS) | Apple does not accept the key, Key ID or Team ID. | Check all three; the key must belong to the team that owns the bundle ID. |
| `Unregistered`, `ExpiredToken` (iOS), `UNREGISTERED` (Android) | The app was removed or the token changed. The Hub deletes it. | Nothing; the app registers a new token the next time it starts. |
| `provider_auth_failed` | Google rejected the relay's service account, or Apple refused the request. | Check the service-account JSON and that the FCM API (V1) is enabled; run `postern-relay check`. |
| `SENDER_ID_MISMATCH` (Android) | The app was built with another Firebase project. | Use the service account of the project in the app's `google-services.json`. |
| `rate_limited` | Over the per-Hub limit, or Apple/Google throttled the request. | Raise `RELAY_MAX_PUSH_PER_MINUTE` if one Hub has many devices. |
| `provider_unavailable` | Apple or Google could not be reached or answered with a server error (retried once). | Check the relay's outgoing network. |
| `invalid_message`, `invalid_token`, `payload_too_large` | The Hub sent something the relay refuses. | Make sure Hub and relay come from the same version of the repository. |

HTTP-level answers to the Hub:

| Status | Meaning |
|---|---|
| 401 "Missing bearer secret", "Unknown hub or wrong secret" | The Hub registers again by itself, if registration is open. |
| 403 "This hub is disabled on the relay" | Someone ran `postern-relay hubs disable`. |
| 403 "Registration is closed on this relay" | `RELAY_REGISTRATION=closed` and the Hub tried to register. |
| 429 "Too many registrations, try again later" | More than `RELAY_MAX_REGISTER_PER_HOUR` registrations from one IP. Behind a proxy without `RELAY_TRUST_PROXY=true`, all clients share the proxy's address. |
| 429 "Push rate limit exceeded" | See [Limits](https://docs.posternmail.app/relay/run-your-own/#limits). |
