Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

Self-hosted servers: phones pair through MausBot Relay (serve --relay) (#5353)

Milind Soni2e1ff4bc07dd
diff --git a/companion/src/e2e/origin.ts b/companion/src/e2e/origin.ts
index aea254ad41..d27b861e9e 100644
--- a/companion/src/e2e/origin.ts
+++ b/companion/src/e2e/origin.ts
@@ -42,18 +42,67 @@ export interface E2EOrigin {
close(): void;
}
+/** How long a stream may take to send a request's headers, and then its whole body. Node's own headersTimeout and
+ * requestTimeout are checked only by a server that listens, and this one never does. */
+export interface E2EOriginDeadlines {
+ headersMs: number;
+ requestMs: number;
+}
+
+/** Each stream must send complete request headers within `headersMs` of opening or of its last response, and a request's
+ * whole body within `requestMs`; otherwise the stream is destroyed. */
+function enforceDeadlines(server: ReturnType<typeof createServer>, deadlines: E2EOriginDeadlines) {
+ const timers = new WeakMap<object, { arm(): void; clear(): void }>();
+ const onRequest = (req: IncomingMessage, res?: ServerResponse) => {
+ const guard = timers.get(req.socket);
+ if (!guard) return;
+ guard.clear();
+ // Only an unfinished request: a handler that never reads a GET (an event stream, a download) leaves it unconsumed.
+ const body = setTimeout(() => {
+ if (!req.complete) req.socket.destroy();
+ }, deadlines.requestMs);
+ body.unref?.();
+ const done = () => clearTimeout(body);
+ req.once("end", done);
+ req.once("close", done);
+ res?.once("finish", () => guard.arm());
+ };
+ server.on("request", onRequest);
+ server.on("upgrade", (req: IncomingMessage) => {
+ timers.get(req.socket)?.clear();
+ });
+ return (socket: Duplex) => {
+ let timer: ReturnType<typeof setTimeout> | null = null;
+ const clear = () => {
+ if (timer) clearTimeout(timer);
+ timer = null;
+ };
+ const arm = () => {
+ clear();
+ timer = setTimeout(() => socket.destroy(), deadlines.headersMs);
+ timer.unref?.();
+ };
+ socket.once("close", clear);
+ timers.set(socket, { arm, clear });
+ arm();
+ };
+}
+
export function createE2EOrigin(
handle: (req: IncomingMessage, res: ServerResponse) => void,
upgrade: (req: IncomingMessage, socket: Duplex, head: Buffer) => void,
+ deadlines?: E2EOriginDeadlines,
): E2EOrigin {
// Gzipped like the tunnel listener: the relay hop is the person's home upload too.
const server = createServer(gzipTunnelReplies(handle));
server.on("upgrade", upgrade);
+ const guard = deadlines ? enforceDeadlines(server, deadlines) : null;
return {
connect(context) {
const [near, far] = duplexPair();
const serverSide = socketLike(far);
contexts.set(serverSide, context);
+ guard?.(serverSide);
server.emit("connection", serverSide);
return Promise.resolve(near);
},
diff --git a/companion/src/e2e/registry.ts b/companion/src/e2e/registry.ts
index 3d6fdd85d6..8823555156 100644
--- a/companion/src/e2e/registry.ts
+++ b/companion/src/e2e/registry.ts
@@ -2,7 +2,6 @@
// device and the open pairing window, and which device holds which live session over which route.
import type { Duplex } from "node:stream";
-import type { DeviceRegistry } from "../devices.ts";
import { admission, admissionHash, credentialHash, credentialHashFromHex, keyId, psk } from "./credentials.ts";
import { descriptorFor, type E2EDescriptor } from "./descriptor.ts";
import { CLOSE, TRANSPORT_RELAY, type KeyPair, type PskCandidate, type TransportByte } from "./noise.ts";
@@ -23,6 +22,18 @@ export interface RelayIdentity {
nodes: string[];
}
+/** The paired devices and open pairing windows: the sidecar's DeviceRegistry, or a server's sessions. A server keeps only
+ * a pairing credential's SHA-256 (hex), so a window carries that or its token. */
+export interface E2EDevices {
+ records(): readonly { id: string; tokenHash: string; routes?: "any" | "local" }[];
+ pairingWindows(): readonly ({ token: string } | { tokenHash: string })[];
+ confirm(id: string): void;
+ markE2E(id: string): void;
+}
+
+const windowHash = (window: { token: string } | { tokenHash: string }): Buffer | null =>
+ "token" in window ? credentialHash(window.token) : credentialHashFromHex(window.tokenHash);
+
interface Live {
session: E2ESession<Peer>;
context: E2EContext;
@@ -38,7 +49,7 @@ export const PAIRING_SESSION_MS = 150_000;
export const MAX_PENDING_HANDSHAKES = 16;
export class E2ERegistry {
- readonly #devices: DeviceRegistry;
+ readonly #devices: E2EDevices;
readonly #live = new Set<Live>();
#key: KeyPair | null = null;
#relay: RelayIdentity | null = null;
@@ -48,7 +59,7 @@ export class E2ERegistry {
* reaches the phone before the relay closes it. */
readonly #held = new Map<string, number>();
- constructor(devices: DeviceRegistry) {
+ constructor(devices: E2EDevices) {
this.#devices = devices;
}
@@ -85,7 +96,8 @@ export class E2ERegistry {
if (hash) out.push({ id: { kind: "device", id: device.id }, psk: psk(hash, id) });
}
for (const window of this.#devices.pairingWindows()) {
- const hash = credentialHash(window.token);
+ const hash = windowHash(window);
+ if (!hash) continue;
const admHash = this.#relay ? admissionHash(admission(hash, this.#relay.hostId)) : null;
out.push({ id: { kind: "pairing", admHash }, psk: psk(hash, id) });
}
@@ -102,7 +114,10 @@ export class E2ERegistry {
const hash = credentialHashFromHex(device.tokenHash);
if (hash) out.push(admissionHash(admission(hash, hostId)));
}
- for (const window of this.#devices.pairingWindows()) out.push(admissionHash(admission(credentialHash(window.token), hostId)));
+ for (const window of this.#devices.pairingWindows()) {
+ const hash = windowHash(window);
+ if (hash) out.push(admissionHash(admission(hash, hostId)));
+ }
for (const live of this.#live) if (live.pairingAdmission) out.push(live.pairingAdmission);
out.push(...this.#held.keys());
return [...new Set(out)].sort();
diff --git a/compose.yaml b/compose.yaml
index 4e69759ac1..4fa9e9555c 100644
--- a/compose.yaml
+++ b/compose.yaml
@@ -27,6 +27,9 @@ services:
OMB_SERVER_NAME: ${OMB_SERVER_NAME:-mausbot-docker}
OMB_PUBLIC_URL: ${OMB_PUBLIC_URL:-http://localhost:${OMB_HTTP_PORT:-8080}}
OMB_WEBHOOK_PUBLIC_URL: ${OMB_WEBHOOK_PUBLIC_URL:-${OMB_PUBLIC_URL:-http://localhost:${OMB_HTTP_PORT:-8080}}}
+ # "1": phones pair by QR through MausBot Relay (docs/phone-relay-server.md). Sign the
+ # container in once first: docker compose exec omb openmausbot login --relay
+ OMB_PHONE_RELAY: ${OMB_PHONE_RELAY:-}
healthcheck:
test:
- CMD
diff --git a/deploy/.env.example b/deploy/.env.example
index 58d95eb4a5..5ea06092de 100644
--- a/deploy/.env.example
+++ b/deploy/.env.example
@@ -22,3 +22,9 @@ OMB_SIGNIN_SMTP_FROM=
# The server image this install runs. `./update.sh` writes this line: the stable
# version, pinned by digest. Leave it out to follow `latest` (every main push).
# OMB_IMAGE=
+
+# Optional: "1" lets the MausBot phone app pair by QR through MausBot Relay,
+# end-to-end encrypted, from anywhere. Sign the container in once first:
+# docker compose exec omb openmausbot login --relay
+# then: docker compose exec omb openmausbot pair --phone
+OMB_PHONE_RELAY=
diff --git a/deploy/docker-compose.yml b/deploy/docker-compose.yml
index 36e92b99f7..c7112acd27 100644
--- a/deploy/docker-compose.yml
+++ b/deploy/docker-compose.yml
@@ -51,6 +51,9 @@ services:
OMB_SIGNIN_MEMBER_EMAILS:
OMB_SIGNIN_SMTP_URL:
OMB_SIGNIN_SMTP_FROM:
+ # "1": phones pair by QR through MausBot Relay (docs/phone-relay-server.md). Sign the
+ # container in once first: docker compose exec omb openmausbot login --relay
+ OMB_PHONE_RELAY:
healthcheck:
test: ["CMD-SHELL", "curl -sf http://127.0.0.1:8799/api/health | grep -q openmausbot"]
interval: 30s
diff --git a/deploy/install.sh b/deploy/install.sh
index f1b2dd3dd8..19e881a298 100755
--- a/deploy/install.sh
+++ b/deploy/install.sh
@@ -660,6 +660,8 @@ services:
OMB_SIGNIN_MEMBER_EMAILS:
OMB_SIGNIN_SMTP_URL:
OMB_SIGNIN_SMTP_FROM:
+ # "1": phones pair by QR through MausBot Relay. Sign in once: docker compose exec omb openmausbot login --relay
+ OMB_PHONE_RELAY:
healthcheck:
test: ["CMD-SHELL", "curl -sf http://127.0.0.1:8799/api/health | grep -q openmausbot"]
interval: 30s
diff --git a/deploy/update.sh b/deploy/update.sh
index 254e8743ed..be6fb0c786 100755
--- a/deploy/update.sh
+++ b/deploy/update.sh
@@ -353,6 +353,8 @@ services:
OMB_SIGNIN_MEMBER_EMAILS:
OMB_SIGNIN_SMTP_URL:
OMB_SIGNIN_SMTP_FROM:
+ # "1": phones pair by QR through MausBot Relay. Sign in once: docker compose exec omb openmausbot login --relay
+ OMB_PHONE_RELAY:
healthcheck:
test: ["CMD-SHELL", "curl -sf http://127.0.0.1:8799/api/health | grep -q openmausbot"]
interval: 30s
diff --git a/docs/deploy-vps.md b/docs/deploy-vps.md
index c1cb2e902f..2e1ec8f683 100644
--- a/docs/deploy-vps.md
+++ b/docs/deploy-vps.md
@@ -87,6 +87,8 @@ Three ways to make the server reachable are covered. Pick one; the rest of the g
| **B. Your own domain** (Docker + Caddy) | a domain name, ports 80/443 | anyone with a pairing code, over HTTPS | a permanent address you own |
| **C. Your Tailscale network** (`serve --tailscale`) | Tailscale on the server and your devices | only your tailnet | the most private; nothing public at all |
+Only need the phone app? Add `--relay` to path B or C on a machine signed in with `openmausbot login --relay` (never on a machine with a path A address), or use it on its own: the app pairs by QR through MausBot Relay, end-to-end encrypted, with no domain, open port or VPN. See [Phones through MausBot Relay](phone-relay-server.md).
+
Whichever you pick, the login is the same: you **pair** each device once with a short code and it stays signed in. A session lasts 30 days; using it with half that or less left renews it to a full 30, up to 180 days from pairing (`OMB_SESSION_TTL_DAYS` and `OMB_SESSION_MAX_DAYS` change both numbers). There is no password.
## Hetzner launch check (2026-09-07)
diff --git a/docs/phone-relay-server.md b/docs/phone-relay-server.md
new file mode 100644
index 0000000000..a92f0c690a
--- /dev/null
+++ b/docs/phone-relay-server.md
@@ -0,0 +1,277 @@
+# Phones through MausBot Relay on a self-hosted server
+
+`openmausbot serve --relay` lets the MausBot phone app pair with a server on a
+VPS by scanning a QR code, from anywhere: no domain, no open port, no VPN and
+no tunnel address. The server dials out to MausBot Relay, the phone dials the
+relay, and the relay passes sealed bytes it cannot open. It is the same
+end-to-end encrypted connection the desktop app gives phones; the wire spec is
+[`companion/src/e2e/README.md`](../companion/src/e2e/README.md).
+
+It is off unless asked for, and it changes nothing about `--tunnel`, your own
+domain, `--public-url`, `--lan` or `--tailscale`.
+
+**In this release `--relay` is only for a machine that has no tunnel address**,
+signed in with `openmausbot login --relay`. A server says it is one
+(`kind: "server"`) when it registers, asks for its address and asks for a relay
+token, and the hosted control plane never gives a server's tunnel to the relay.
+A control plane that predates that rule gives back the tunnel of any
+installation that took a relay token in the last two days and then refuses it a
+tunnel for good, and a server may be pointed at one. So the server still keeps
+the relay off, and says why, when it serves `--tunnel`, runs on a fleet
+credential (`OMB_INSTALLATION_CREDENTIAL`), or holds a tunnel address from a
+plain `openmausbot login`.
+
+## Use it
+
+```sh
+npx openmausbot login --relay # once: an emailed code signs this machine in; no tunnel address is reserved
+npx openmausbot serve --relay # prints a QR for the phone app once the relay connects
+npx openmausbot pair --phone # a QR for another phone, later
+npx openmausbot devices # every paired device; `devices revoke ID` removes one
+```
+
+`--relay` can join `--domain`, `--public-url`, `--tailscale` or `--lan`: those
+stay the way in for browsers and the desktop app, and the QR also names the
+server's HTTPS address for a phone app that has no encrypted connection yet. It
+cannot join `--tunnel`, and `start --relay` refuses when the saved startup
+choice is a tunnel. As a service: `openmausbot service install --relay`. A
+service prints no pairing QR into its log (the credential would sit in the
+journal); `serve --relay` shows it only at a terminal, and `pair --phone` makes
+one whenever asked.
+
+With Docker, set `OMB_PHONE_RELAY=1` in `.env` (`deploy/docker-compose.yml`,
+the root `compose.yaml` and the compose file the installer writes all pass it to
+the server container), `docker compose up -d`, then:
+
+```sh
+docker compose exec omb openmausbot login --relay
+docker compose exec omb openmausbot pair --phone
+```
+
+A phone code is chat and approvals only (`pair --phone`), as on every other way
+in. Up to 20 phones pair through the relay per server.
+
+## What the phone talks to
+
+Over the relay a phone speaks plain HTTP/1.1, carried in yamux streams inside a
+Noise session. On a desktop each stream lands on the companion sidecar, which
+checks its allowlist and device token and forwards to the harness over
+loopback. The sidecar answers three things itself: `POST /api/pair`,
+`GET /api/companion/endpoints`, and its computer-viewer relay. Everything else
+is the harness's own API.
+
+A self-hosted server is that harness, and the phone app already talks to it
+directly over HTTPS: the server answers `POST /api/pair` in the shape the
+companion apps decode (`token`, `device`, `serverName`), and the phone then
+sends `Authorization: Bearer <session>` on the same API routes. So the server
+needs no sidecar. It runs the same end-to-end responder and relay client (the
+same code, imported from `companion/src/e2e/`) and hands each stream to its own
+request handler. It adds the `e2e` descriptor to the `/api/pair` answer and
+answers `/api/companion/endpoints` itself, as the sidecar does.
+
+The QR is the desktop's: an `openmausbot://pair` link with the one-time pairing
+credential and `e2e={v:1,k,h,r}` (the server's connection key, its relay host
+id and the relay nodes). With a public HTTPS address it has the shape of the
+desktop's default QR: that address as the hosted endpoint, which a phone
+without the encrypted connection uses and one with it never does. With no
+address it names `relay-only.invalid:443`, a name that never resolves
+(RFC 6761), so the relay is the only way in.
+
+### Does today's phone app pair with it unchanged?
+
+Probably, and nothing on the server side waits for a phone change; it is not
+proven end to end, because the phone apps live in another repository. What
+this repository shows:
+
+- The desktop's default QR already leaves the relay as the phone's only
+ encrypted route: it carries a hosted address and `e2e`, and the phone never
+ uses a hosted address for the encrypted connection, so it pairs through the
+ relay with the pairing credential (`companion/src/e2e/README.md`, sections 3
+ and 4; `companion/test/e2e/sidecar.test.ts` does exactly this).
+- The server presents the same responder, key schedule, relay protocol,
+ descriptor and `/api/pair` shape. The tests here pair the reference phone
+ (`companion/src/e2e/phone.ts`) with the real server through a relay.
+- The server already answers the companion apps' own pairing route, so the
+ phone apps pair with servers today through the same `/api/pair` the relay
+ carries.
+
+Not verifiable here: whether the store build starts a relay pairing when the
+QR's direct address cannot be resolved (the relay-only QR), and whether it
+reads a server's answers on routes the sidecar would have filtered. The first
+real check is one phone scanning a relay QR from a server; if the store build
+refuses the relay-only QR, the change it needs is to try the relay when no
+direct route resolves, which is what the spec's route order already says.
+
+Computer viewing and live browser views use WebSocket upgrades. Over the relay
+these answer `501` for now, so a phone shows computer access as unavailable;
+chat, approvals, events and files work.
+
+## Shared code; the desktop is unchanged
+
+Nothing had to move out of `electron/`. The relay client and the whole
+encrypted stack are already plain Node in `companion/src/e2e/`, and the token
+refresher (`electron/relay-token.mjs`) and the control plane client
+(`electron/control-plane-client.mjs`) import nothing from Electron. The server
+already imports both folders (`server/tunnel.ts`, `server/request-auth.ts`).
+
+The one change to shared code: `E2ERegistry` took the sidecar's
+`DeviceRegistry`; it now takes the `E2EDevices` interface that registry
+already satisfies, and a pairing window may carry the credential's SHA-256
+instead of the credential, because a server stores only the digest. The
+desktop computes the same values as before; its end-to-end, relay-client,
+malicious-relay, vector and sidecar tests pass unchanged. The control plane
+client and the account service take an optional `kind` that only the server
+passes, so the desktop's requests are the same bytes as before.
+`relay-token.d.mts` and the additions to the `.d.mts` files are type
+declarations only.
+
+## The control plane
+
+`openmausbot login` registers the server as an installation (its platform, and
+`appVersion` the npm package's version) and keeps its `omb_install_…`
+credential in `tunnel-account.json`, mode 0600. Plain `login` also reserves a
+tunnel address; `login --relay` reserves none (the account service's on-demand
+path, the one the desktop takes when the relay carries its phones), so a
+relay-only server never takes one of the scarce tunnels. The server asks
+`POST /v1/installations/self/relay-token` hourly with the desktop's body plus
+the server's kind, `{appVersion, devices: {e2e, legacy}, kind: "server"}`. A
+control plane older than `kind` answers `400 invalid_request`; the server then
+asks once more without it.
+
+A server qualifies today; no control plane change is needed to get a token:
+
+- The token route takes any installation credential, desktop or server.
+- `relayAdmits` asks only whether the relay is on, the installation is not
+ blocked, and it is inside `RELAY_ROLLOUT_PERCENT` (100 in `wrangler.jsonc`)
+ or named in `RELAY_ALLOW_INSTALLATIONS`.
+- `RELAY_CAPABLE_MIN_VERSION` gates tunnel provisioning (`409 relay_capable`),
+ not tokens. A published server reports a version such as `0.1.152`, which the
+ route accepts; a development build reporting `unknown` is refused (400).
+
+**Servers keep their tunnel.** A server's tunnel serves browsers and the
+desktop app, not only phones. The server sends `kind: "server"` on
+`POST /v1/installations`, `POST .../self/endpoint` and `POST .../self/relay-token`
+(`openmausbot login`, `serve --tunnel`, a fleet container and `serve --relay`
+alike); the desktop app sends nothing new. The hosted control plane stores it,
+never marks a server's tunnel for the relay (`relay_proven`, `legacy_cutoff`)
+and never answers a server `relay_capable` (its README, "Self-hosted servers").
+
+A control plane without that rule gives back the tunnel of any installation
+that took a relay token in the last two days at a relay-capable version, and
+then answers it `409 relay_capable` ("retired") for good; it reads no device
+counts, so nothing else a server sends protects its tunnel. So for this release
+the server also protects itself: it never asks for a relay token while it
+serves a tunnel (`serve --tunnel` marks it; the socket Docker's Caddy uses is
+not one), runs on a fleet credential, or holds a tunnel address (above). The
+`legacy` count it reports (its sessions the relay does not carry) changes
+nothing there.
+
+## Security
+
+**The connection key.** `<data dir>/phone-relay-key.json`, mode 0600, made the
+first time the relay runs and never replaced: every phone pinned its public
+half from the QR. A file that cannot be read turns the relay off with a log
+line rather than making a new key. It is part of the data directory, so a
+backup restores it and a restored server keeps its phones. The list of relay
+phones is `phone-relay-phones.json`, also 0600; it holds session ids only.
+
+**A compromised relay** sees the host id, the SHA-256 of each admission value,
+IP addresses, timing and sizes. It can drop, delay or close sessions and write
+any close code. It cannot read or change a byte (Noise `NKpsk0` with AES-GCM
+and per-direction counters: a dropped, reordered or replayed record ends the
+session), cannot pose as the server (it has no private key), cannot pair a
+phone (it never holds a pairing credential, only a digest of a value derived
+from it), and cannot mint a relay token (the control plane holds the signing
+key). A phone treats only the authenticated GoAway(3) inside the session as
+"removed", so a forged 4001 cannot make it forget the server.
+
+**Pairing proves the owner.** The QR carries a 256-bit, single-use pairing
+credential that only the owner can mint: `openmausbot pair --phone` on the
+machine (the owner, or on a shared server the per-launch owner token `serve`
+holds), or a signed-in admin in the web UI. It is both the handshake's key and
+the credential `/api/pair` redeems, so only someone holding the QR completes a
+handshake at all. Through the relay `/api/pair` takes only a credential: a
+12-character typed code is refused, and the browser's pairing route
+(`/api/auth/pair`) answers 404. A window lasts 10 minutes unless `--ttl` says
+otherwise, and the session that redeems it closes after 150 seconds if it has
+not paired.
+
+**Not a way around the server's sign-in.** A relayed request reaches the
+server's request handler with no peer address, which `request-auth.ts` always
+treats as remote; its `Host`, proxy headers, cookies and every
+`x-openmausbot-*` header are replaced or removed first. So it is never loopback,
+never owner or service trust: it needs a session bearer, the session's scopes
+apply (a chat-only phone stays chat-only), and a Team server's per-person rules
+apply. Inside one encrypted session only the session whose key opened it is
+accepted, as a bearer token or as a stream ticket (another session's ticket is
+refused without being spent); before pairing, only `POST /api/pair` and
+`GET /api/health` are.
+
+**Another account.** The relay identity (`h`) belongs to the installation, so
+signing the machine in to a different account gives it a new one, and phones
+paired before then pair again. Signing in again to the same account keeps it.
+
+**Removal.** `openmausbot devices revoke ID` (or the web UI) ends the session,
+and the phone hears GoAway(3) inside the encryption, then 4001; the relay stops
+admitting it at once. A session that expires is removed the same way.
+
+**Shared and Team servers.** A phone acts as the person whose pairing window it
+redeemed, exactly as over HTTPS: a member's own phone code makes a phone that is
+that member. Service trust is untouched, because no relayed request is local.
+
+**Rate limits.** The relay: 60 new sockets a minute and 256 open per IP; per
+server one control socket, 16 phone sessions and 32 admission values. The
+server: 16 handshakes at once; 20 relay phones; 4 live sessions per phone and 2
+per pairing window (a new one closes the oldest, so one phone cannot hold all
+16); the pairing lockout (5 wrong in 5 minutes locks pairing for 5 minutes),
+counted per paired phone and per pairing window, so a paired phone cannot lock
+pairing for others and whoever holds a window's QR is still locked out on it.
+Each stream must send complete request headers within 30 seconds of opening or
+of its last answer, and a request's whole body within 5 minutes, or it is
+closed. The control plane: 60 relay tokens an hour per installation.
+
+It never runs on a MausBot Cloud, a hosted workspace or the desktop app (whose
+companion already carries phones), whatever the environment says.
+
+## When the relay cannot be reached
+
+The server keeps working on every other way in; the relay only adds one. What
+`serve --relay` and `pair --phone` say:
+
+| Situation | Line |
+|---|---|
+| The machine serves a tunnel, runs on a fleet credential or holds a tunnel address | MausBot Relay stays off here: (why). A relay token would make that tunnel go for good; use the relay on a machine signed in with `openmausbot login --relay`. |
+| Not signed in, or the sign-in expired | MausBot Relay needs this machine signed in to a MausBot account: `openmausbot login --relay` |
+| The control plane says no (rollout, blocked, switched off) | MausBot Relay is not available for this machine right now. The server keeps working here; it asks again every half hour. |
+| The control plane does not answer | The MausBot account service did not answer. The server keeps working here and keeps trying. |
+| The relay does not answer | Can't reach MausBot Relay yet. The server keeps working here and keeps trying; phones pair once it connects. |
+
+The server log says `phone relay: connecting`, `phone relay: connected via
+relay2.openmausbot.com` and `phone relay: relay token …`. It redials at once,
+then backs off to a minute, moves to the next node on a restart or refusal, and
+renews its token hourly; sessions already open survive a token renewal. A phone
+that cannot reach the relay shows "Can't reach MausBot Relay right now. Trying
+again…".
+
+## Not yet
+
+- WebSocket routes through the relay (Local VM and computer viewing, live
+ browser): they need the upgrade path to accept a socket that is not a TCP
+ socket. Medium.
+- The web UI: a relay QR in the server's own Settings → Remote access, and the
+ relay's state there. Medium.
+- `openmausbot setup` and `start` offering the relay, `status` showing it, and
+ saving it with the startup choices. Small.
+- Moving a phone already paired over HTTPS onto the relay without pairing
+ again (trust on first use of `k` from `/api/companion/endpoints`). Small to
+ medium, and needs the phone apps' behaviour confirmed.
+- Dropping the server's own tunnel refusal and allowing `--relay` with
+ `--tunnel`, once no supported control plane predates the server exemption.
+ Small.
+- The same stream deadlines on the desktop's companion: its encrypted streams
+ have the same gap, reachable only by a paired phone. Small.
+- Renewing the installation credential before its 90 days end. `serve
+ --relay` does not run the account service that renews it, so after 90 days
+ the relay reports "needs this machine signed in" until `login --relay` is run
+ again. Small.
+- A check with the store phone apps against a real relay. Small, by hand.
diff --git a/docs/self-hosting.md b/docs/self-hosting.md
index ca8551e687..2d96fc27d4 100644
--- a/docs/self-hosting.md
+++ b/docs/self-hosting.md
@@ -28,6 +28,7 @@ For server feature switches, defaults and configuration-file instructions, see
| Tailscale on the server and your devices | `npx openmausbot serve --tailscale` | `https://<machine>.<tailnet>.ts.net/pair#code=…` |
| Only this network (home or office) | `npx openmausbot serve --lan` | `http://192.168.1.20:8799/pair#code=…` |
| Nothing at all | `npx openmausbot login`, then `npx openmausbot serve --tunnel` | `https://c-….openmausbot.com/pair#code=…` |
+| Only the phone app, from anywhere (a machine with no tunnel address, for now) | `npx openmausbot login --relay`, then `npx openmausbot serve --relay` | a QR for the MausBot app ([MausBot Relay](phone-relay-server.md)) |
`--lan` can be added to any of the others. Plain `http://` is only for a
private network: the desktop app accepts it on LAN addresses, Tailscale
diff --git a/electron/companion-account-service.d.mts b/electron/companion-account-service.d.mts
index 64636d0d0f..0792b952d4 100644
--- a/electron/companion-account-service.d.mts
+++ b/electron/companion-account-service.d.mts
@@ -63,7 +63,8 @@ export declare function createCompanionAccountService(options: {
derive: (current: CredentialDocument) => CredentialDocument,
afterPersist?: (next: CredentialDocument) => Promise<void> | void,
) => Promise<unknown>;
- identity: { name: string; platform: string; appVersion?: string };
+ /** `kind`: a self-hosted server says `server` on registration and when it asks for its address. */
+ identity: { name: string; platform: string; appVersion?: string; kind?: "desktop" | "server" };
newClientInstanceId: () => string;
activatePersistedEndpoint?: () => Promise<{ status: string; ready: boolean }>;
stopManagedEndpoint?: () => Promise<void>;
@@ -82,6 +83,8 @@ export declare function createCompanionAccountService(options: {
/** Hold the address only while something needs it (the desktop app). */
onDemand?: boolean;
managedEndpointNeeded?: () => Promise<boolean | "unused" | null>;
+ /** MausBot Relay: `capable` lets a "no" from managedEndpointNeeded hold even right after sign-in. */
+ relay?: { capable: () => boolean; legacyDevices: () => Promise<number | null> };
releaseGraceMs?: number;
releaseJitterMs?: number;
/** One line per failed setup step: code, HTTP status, request id, retry delay. */
diff --git a/electron/companion-account-service.mjs b/electron/companion-account-service.mjs
index e55b441fa5..aa92bf63d7 100644
--- a/electron/companion-account-service.mjs
+++ b/electron/companion-account-service.mjs
@@ -512,7 +512,7 @@ export function createCompanionAccountService({
clientInstanceId,
name: identity.name,
platform: identity.platform,
- appVersion: identity.appVersion,
+ appVersion: identity.appVersion, ...(identity.kind ? { kind: identity.kind } : {}),
});
// Persist the verified installation before provisioning, or each Retry rotates the credential until rate-limited.
try {
@@ -531,7 +531,7 @@ export function createCompanionAccountService({
};
if (onDemand && (await currentNeed()) === false) return withoutTunnel();
let relayOnly = null;
- const endpoint = await client.ensureEndpoint(installation.credential, { appVersion: identity.appVersion, ...(await relay.legacyDevices().then((count) => (count === null ? {} : { legacyDevices: count }))) })
+ const endpoint = await client.ensureEndpoint(installation.credential, { appVersion: identity.appVersion, ...(identity.kind ? { kind: identity.kind } : {}), ...(await relay.legacyDevices().then((count) => (count === null ? {} : { legacyDevices: count }))) })
.catch((error) => {
if (error?.code !== "relay_capable") throw error;
relayOnly = error.tunnel ?? "none";
diff --git a/electron/control-plane-client.d.mts b/electron/control-plane-client.d.mts
index 5f577971c3..567f3aa576 100644
--- a/electron/control-plane-client.d.mts
+++ b/electron/control-plane-client.d.mts
@@ -9,6 +9,9 @@ export declare class ControlPlaneError extends Error {
constructor(code: string, status?: number, requestId?: string, retryAfterMs?: number);
}
+/** Sent only when given: a self-hosted server says `server`, and the control plane never gives its tunnel to the relay. */
+export type InstallationKind = "desktop" | "server";
+
export declare function normalizeControlPlaneURL(value: unknown): string;
export declare function normalizeAccountEmail(value: unknown): string;
@@ -53,13 +56,20 @@ export interface ControlPlaneClient {
name: string;
platform: string;
appVersion?: string;
+ kind?: InstallationKind;
}): Promise<{ installation: ControlPlaneInstallation; credential: string; credentialExpiresAt: number | null }>;
/** `appVersion`, when printable and at most 64 characters, is sent as the
* release this installation runs. */
ensureEndpoint(
installationCredential: string,
- options?: { appVersion?: string },
+ options?: { appVersion?: string; kind?: InstallationKind },
): Promise<{ endpoint: ControlPlaneEndpoint; connectorToken: string }>;
+ /** MausBot Relay: the control plane's 200 body (checked by relay-token.mjs's validRelayGrant), or a
+ * ControlPlaneError with code `relay_unavailable` (503) outside the rollout. */
+ relayToken(
+ installationCredential: string,
+ options: { appVersion: string; devices: { e2e: number; legacy: number }; kind?: InstallationKind },
+ ): Promise<unknown>;
getEndpoint(installationCredential: string): Promise<{ url: string; status: string } | null>;
deleteEndpoint(installationCredential: string): Promise<void>;
revokeInstallation(accountToken: string, installationId: string): Promise<void>;
diff --git a/electron/control-plane-client.mjs b/electron/control-plane-client.mjs
index 642eb418cd..250f813370 100644
--- a/electron/control-plane-client.mjs
+++ b/electron/control-plane-client.mjs
@@ -62,6 +62,22 @@ const reportableAppVersion = (value) => {
return version;
};
+/** A self-hosted server says so; the control plane then never gives its tunnel to the relay. Sent only when given, since
+ * a control plane older than the field refuses it. */
+const installationKind = (kind) => (kind === "desktop" || kind === "server" ? { kind } : {});
+
+/** `send(extra)` with the kind, and once more without it when the control plane refuses the request as invalid (400
+ * invalid_request): one older than the field refuses it, as it does any field it does not know. */
+async function withKind(kind, send) {
+ const extra = installationKind(kind);
+ try {
+ return await send(extra);
+ } catch (error) {
+ if (!extra.kind || error?.code !== "invalid_request" || error?.status !== 400) throw error;
+ return send({});
+ }
+}
+
const MAX_RETRY_AFTER_MS = 24 * 60 * 60 * 1_000;
/** What `409 relay_capable` may say about the tunnel this computer goes without: old phone apps no longer get one
@@ -331,7 +347,7 @@ export function createControlPlaneClient({
return accountInstallations(accountToken);
},
- async ensureInstallation({ accountToken, currentCredential, clientInstanceId, name, platform, appVersion }) {
+ async ensureInstallation({ accountToken, currentCredential, clientInstanceId, name, platform, appVersion, kind }) {
if (
!validClientInstance(clientInstanceId)
) {
@@ -367,11 +383,11 @@ export function createControlPlaneClient({
method: "POST",
token: accountToken,
})
- : await request("/v1/installations", {
+ : await withKind(kind, (extra) => request("/v1/installations", {
method: "POST",
token: accountToken,
- body: { clientInstanceId, name, platform, appVersion },
- });
+ body: { clientInstanceId, name, platform, appVersion, ...extra },
+ }));
const installation = existing ?? validatedInstallation(result.payload.installation);
const credential = stringValue(result.payload.credential);
if (!installation || credential === null || !INSTALLATION_CREDENTIAL.test(credential)) {
@@ -390,7 +406,7 @@ export function createControlPlaneClient({
/** `legacyDevices`: paired phones that can't use the encrypted connection; a relay-capable desktop with none gets
* `409 relay_capable` instead of a new tunnel. The error's `tunnel` is "retired" when old phone apps no longer
* get one and "full" when every account is at its limit; otherwise null. */
- async ensureEndpoint(installationCredential, { appVersion, legacyDevices } = {}) {
+ async ensureEndpoint(installationCredential, { appVersion, legacyDevices, kind } = {}) {
if (
typeof installationCredential !== "string" ||
!INSTALLATION_CREDENTIAL.test(installationCredential)
@@ -399,11 +415,13 @@ export function createControlPlaneClient({
}
const version = reportableAppVersion(appVersion);
const legacy = Number.isSafeInteger(legacyDevices) && legacyDevices >= 0 && legacyDevices <= 100 ? legacyDevices : null;
- const body = { ...(version === null ? {} : { appVersion: version }), ...(legacy === null ? {} : { legacyDevices: legacy }) };
- const { payload } = await request("/v1/installations/self/endpoint", {
- method: "POST",
- token: installationCredential,
- ...(Object.keys(body).length ? { body } : {}),
+ const { payload } = await withKind(kind, (extra) => {
+ const body = { ...(version === null ? {} : { appVersion: version }), ...(legacy === null ? {} : { legacyDevices: legacy }), ...extra };
+ return request("/v1/installations/self/endpoint", {
+ method: "POST",
+ token: installationCredential,
+ ...(Object.keys(body).length ? { body } : {}),
+ });
});
const endpoint = validatedEndpoint(payload.endpoint);
const connectorToken = boundedSecret(payload.connectorToken, 16_384);
@@ -413,17 +431,17 @@ export function createControlPlaneClient({
/** MausBot Relay: `{token, hostId, nodes, expiresAt, refreshAfter}`, or `relay_unavailable` (503) while this
* computer is outside the rollout. */
- async relayToken(installationCredential, { appVersion, devices }) {
+ async relayToken(installationCredential, { appVersion, devices, kind }) {
if (typeof installationCredential !== "string" || !INSTALLATION_CREDENTIAL.test(installationCredential)) {
throw new ControlPlaneError("signed_out", 401);
}
const version = reportableAppVersion(appVersion);
if (version === null) throw new ControlPlaneError("invalid_request");
- const { payload } = await request("/v1/installations/self/relay-token", {
+ const { payload } = await withKind(kind, (extra) => request("/v1/installations/self/relay-token", {
method: "POST",
token: installationCredential,
- body: { appVersion: version, devices: { e2e: devices.e2e, legacy: devices.legacy } },
- });
+ body: { appVersion: version, devices: { e2e: devices.e2e, legacy: devices.legacy }, ...extra },
+ }));
return payload;
},
diff --git a/electron/control-plane-client.test.mjs b/electron/control-plane-client.test.mjs
index 6a93473307..e16c25abd7 100644
--- a/electron/control-plane-client.test.mjs
+++ b/electron/control-plane-client.test.mjs
@@ -274,6 +274,61 @@ describe("control-plane desktop client", () => {
expect(fetchImpl).toHaveBeenCalledTimes(9);
});
+ it("says a self-hosted server is one only when told to, on registration, its address and its relay token", async () => {
+ const fetchImpl = vi.fn(async (url) => {
+ const path = new URL(url).pathname;
+ if (path === "/v1/installations" ) return jsonResponse({ installation: { id: INSTALL_ID, clientInstanceId: "server-1", name: "vps", platform: "linux" }, credential: INSTALL }, { status: 201 });
+ if (path === "/v1/installations/self/endpoint") return jsonResponse({ endpoint: { url: "https://c-opaque.mausbot.si" }, connectorToken: `eyJ${"x".repeat(80)}` });
+ return jsonResponse({ token: "a.b", hostId: "h", nodes: [], expiresAt: 1, refreshAfter: 1 });
+ });
+ const client = createControlPlaneClient({ baseURL: "https://accounts.openmausbot.com", fetchImpl });
+ const body = () => JSON.parse(fetchImpl.mock.lastCall[1].body);
+ const register = (kind) => client.ensureInstallation({ accountToken: ACCOUNT, currentCredential: "", clientInstanceId: "server-1", name: "vps", platform: "linux", appVersion: "0.1.153", kind });
+ fetchImpl.mockImplementationOnce(async () => jsonResponse({ installations: [] }));
+ await register("server");
+ expect(body()).toEqual({ clientInstanceId: "server-1", name: "vps", platform: "linux", appVersion: "0.1.153", kind: "server" });
+ fetchImpl.mockImplementationOnce(async () => jsonResponse({ installations: [] }));
+ await register(undefined);
+ expect(body()).toEqual({ clientInstanceId: "server-1", name: "vps", platform: "linux", appVersion: "0.1.153" });
+ await client.ensureEndpoint(INSTALL, { appVersion: "0.1.153", kind: "server" });
+ expect(body()).toEqual({ appVersion: "0.1.153", kind: "server" });
+ await client.ensureEndpoint(INSTALL, { appVersion: "0.1.153", kind: "laptop" });
+ expect(body()).toEqual({ appVersion: "0.1.153" });
+ await client.relayToken(INSTALL, { appVersion: "0.1.153", devices: { e2e: 1, legacy: 0 }, kind: "server" });
+ expect(body()).toEqual({ appVersion: "0.1.153", devices: { e2e: 1, legacy: 0 }, kind: "server" });
+ await client.relayToken(INSTALL, { appVersion: "0.1.153", devices: { e2e: 1, legacy: 0 } });
+ expect(body()).toEqual({ appVersion: "0.1.153", devices: { e2e: 1, legacy: 0 } });
+ });
+
+ it("asks once more without its kind when a control plane older than the field refuses it, and only then", async () => {
+ const bodies = [];
+ let answers = [];
+ const fetchImpl = vi.fn(async (_url, init) => {
+ bodies.push(init.body === undefined ? undefined : JSON.parse(init.body));
+ const next = answers.shift() ?? 200;
+ return next === 200
+ ? jsonResponse({ endpoint: { url: "https://c-opaque.mausbot.si" }, connectorToken: `eyJ${"x".repeat(80)}`, token: "a.b" })
+ : jsonResponse({ error: next === 400 ? "invalid_request" : "rate_limited" }, { status: next });
+ });
+ const client = createControlPlaneClient({ baseURL: "https://accounts.openmausbot.com", fetchImpl });
+
+ answers = [400];
+ await client.ensureEndpoint(INSTALL, { appVersion: "0.1.153", kind: "server" });
+ expect(bodies).toEqual([{ appVersion: "0.1.153", kind: "server" }, { appVersion: "0.1.153" }]);
+ bodies.length = 0;
+ answers = [400];
+ await client.relayToken(INSTALL, { appVersion: "0.1.153", devices: { e2e: 1, legacy: 0 }, kind: "server" });
+ expect(bodies).toEqual([{ appVersion: "0.1.153", devices: { e2e: 1, legacy: 0 }, kind: "server" }, { appVersion: "0.1.153", devices: { e2e: 1, legacy: 0 } }]);
+
+ // Once only, only for that refusal, and never for a request that carried no kind.
+ for (const [kind, refusals, calls] of [["server", [400, 400], 2], ["server", [429], 1], [undefined, [400], 1]]) {
+ bodies.length = 0;
+ answers = refusals;
+ await expect(client.ensureEndpoint(INSTALL, { appVersion: "0.1.153", kind })).rejects.toBeInstanceOf(ControlPlaneError);
+ expect(bodies, `${kind} ${refusals}`).toHaveLength(calls);
+ }
+ });
+
it("reads why a relay-capable computer goes without a tunnel, and nothing else from the body", async () => {
for (const [body, tunnel] of [
[{ error: "relay_capable", tunnel: "retired" }, "retired"],
diff --git a/electron/relay-token.d.mts b/electron/relay-token.d.mts
new file mode 100644
index 0000000000..5d27c7e8c1
--- /dev/null
+++ b/electron/relay-token.d.mts
@@ -0,0 +1,28 @@
+// Types for relay-token.mjs as the headless server uses it (server/phone-relay.ts). Keep in step with the implementation.
+export interface RelayGrant {
+ token: string;
+ hostId: string;
+ nodes: string[];
+ expiresAt: number;
+ refreshAfter: number;
+}
+
+export declare function validRelayGrant(payload: unknown): RelayGrant | null;
+
+export interface RelayTokenService {
+ readonly grant: RelayGrant | null;
+ readonly running: boolean;
+ start(): void;
+ stop(): void;
+ refreshNow(): Promise<void>;
+}
+
+export declare function createRelayTokenService(options: {
+ fetchGrant: () => Promise<unknown>;
+ onGrant: (grant: RelayGrant | null) => void;
+ setTimer?: (callback: () => void, milliseconds: number) => unknown;
+ clearTimer?: (handle: unknown) => void;
+ now?: () => number;
+ random?: () => number;
+ log?: (line: string) => void;
+}): RelayTokenService;
diff --git a/scripts/docker-image.test.ts b/scripts/docker-image.test.ts
index 5efd0825fd..48d84fbd98 100644
--- a/scripts/docker-image.test.ts
+++ b/scripts/docker-image.test.ts
@@ -339,6 +339,9 @@ describe("container images", () => {
for (const [file, caddyfile] of [["../compose.yaml", "../deploy/local/Caddyfile"], ["../deploy/docker-compose.yml", "../deploy/Caddyfile"]]) {
const { services, volumes } = parse(readFileSync(new URL(file, import.meta.url), "utf8"));
expect(services.caddy.network_mode, file).toBeUndefined();
+ // `OMB_PHONE_RELAY=1` in .env reaches the server, never Caddy.
+ expect(Object.keys(services.omb.environment), file).toContain("OMB_PHONE_RELAY");
+ expect(Object.keys(services.caddy.environment ?? {}), file).not.toContain("OMB_PHONE_RELAY");
expect(services.omb.ports, file).toBeUndefined();
expect(services.caddy.ports.length, file).toBeGreaterThan(0);
expect(services.omb.volumes, file).toContain("edge:/run/openmausbot");
diff --git a/scripts/server-installer.test.ts b/scripts/server-installer.test.ts
index 366413847d..57f6423444 100644
--- a/scripts/server-installer.test.ts
+++ b/scripts/server-installer.test.ts
@@ -590,7 +590,7 @@ describe.skipIf(!posix)("deploy/install.sh", () => {
const settings = (text: string) => [...text.matchAll(/^ {6}(OMB_[A-Z_]+:.*)$/gm)].map((match) => match[1]);
expect(settings(written)).toEqual(settings(manual));
// The sign-in lists and mail server are passed only when .env sets them: an empty one would still be set.
- for (const name of ["OMB_SIGNIN_EMAILS", "OMB_SIGNIN_MEMBER_EMAILS", "OMB_SIGNIN_SMTP_URL", "OMB_SIGNIN_SMTP_FROM"]) expect(settings(written)).toContain(`${name}:`);
+ for (const name of ["OMB_SIGNIN_EMAILS", "OMB_SIGNIN_MEMBER_EMAILS", "OMB_SIGNIN_SMTP_URL", "OMB_SIGNIN_SMTP_FROM", "OMB_PHONE_RELAY"]) expect(settings(written)).toContain(`${name}:`);
for (const line of ['test: ["CMD-SHELL", "curl -sf http://127.0.0.1:8799/api/health | grep -q openmausbot"]', "init: true", "shm_size: 512m", '- "80:80"', '- "443:443"',
"- edge:/run/openmausbot", "type: tmpfs"]) {
expect(written).toContain(line);
diff --git a/server/bot-box/env.test.ts b/server/bot-box/env.test.ts
index 8c959a6900..74d0191f6a 100644
--- a/server/bot-box/env.test.ts
+++ b/server/bot-box/env.test.ts
@@ -43,7 +43,7 @@ const SERVER_ONLY_OMB: ReadonlySet<string> = new Set([
"OMB_JEV_API_KEY", "OMB_LAN", "OMB_LICENSE_KEY", "OMB_LINUX_GPU", "OMB_LIVE_PROVIDER", "OMB_LOCAL_VM_UPDATE_WAIT_MS",
"OMB_LOOPBACK_TRUST", "OMB_LOOP_GUARD", "OMB_LOOP_GUARD_STOP_AT", "OMB_META_API_KEY", "OMB_MODELGO_API_KEY", "OMB_OPENAI_API_KEY",
"OMB_OPENAI_IMAGE_KEY", "OMB_OPENAI_LIVE_KEY", "OMB_OPENAI_LIVE_URL", "OMB_OPENROUTER_API_KEY",
- "OMB_OPENROUTER_DECIDER_KEY", "OMB_PERSON_FIRST_MS", "OMB_PHONE_SECRET_PUBLIC_KEY", "OMB_PORT", "OMB_POSTIZ_API_KEY",
+ "OMB_OPENROUTER_DECIDER_KEY", "OMB_PERSON_FIRST_MS", "OMB_PHONE_RELAY", "OMB_PHONE_RELAY_URL", "OMB_PHONE_SECRET_PUBLIC_KEY", "OMB_PORT", "OMB_SERVES_TUNNEL", "OMB_POSTIZ_API_KEY",
"OMB_POSTIZ_CLOUD_URL", "OMB_PROCESS_ID", "OMB_PUBLIC_IPV4", "OMB_PUBLIC_URL", "OMB_QUOTA_SWITCH",
"OMB_REPLAY_TOOL_HISTORY", "OMB_ROOM_SESSIONS", "OMB_SAFETY_FLOOR", "OMB_SERVER_COMPILE_CACHE", "OMB_SERVER_NAME",
"OMB_SESSION_IDLE_MIN_MS", "OMB_SESSION_IDLE_MS", "OMB_SESSION_MAX_DAYS", "OMB_SESSION_TTL_DAYS",
diff --git a/server/cli-pairing.ts b/server/cli-pairing.ts
index ff45f1e7c5..cb9c95bb1b 100644
--- a/server/cli-pairing.ts
+++ b/server/cli-pairing.ts
@@ -3,6 +3,7 @@
import qrcode from "qrcode-terminal";
import { cliCommand } from "./cli-invocation.ts";
+import type { PhoneRelayStatus } from "./phone-relay.ts";
/** A clock time a code works until: "11:22", or "tomorrow 11:22" / a date when it runs past today. */
export function untilText(expiresAt: number, now = Date.now()): string {
@@ -78,3 +79,67 @@ export function formatSessions(sessions: Array<{ id: string; label: string; scop
const line = (r: string[]) => r.map((c, i) => c.padEnd(widths[i])).join(" ");
return [line(head), ...rows.map(line), "", `sign one out with: ${cliCommand("devices revoke <id>")}`].join("\n");
}
+
+const isStatus = (value: unknown): value is PhoneRelayStatus =>
+ typeof value === "object" && value !== null && typeof (value as PhoneRelayStatus).grant === "string" && typeof (value as PhoneRelayStatus).relay === "string";
+
+/** Until the control plane tells a server from a desktop, a machine that takes a relay token gives back its tunnel. */
+export const RELAY_NOT_WITH_TUNNEL = "--relay cannot be used on a machine whose saved choice is a tunnel address: a relay token would make the tunnel go for good. Start with --local, or use the relay on a machine signed in with `openmausbot login --relay`.";
+
+/** Why phones cannot pair through the relay yet, in words for the person at the terminal; empty when they can. */
+export function relayProblemLines(status: PhoneRelayStatus | null, prefix: string): string[] {
+ if (!status) return [`MausBot Relay is off on this server. Start it with: ${prefix} serve --relay`];
+ if (status.grant === "tunnel") return [`MausBot Relay stays off here: ${status.reason ?? "this machine holds a tunnel address"}. A relay token would make that tunnel go for good; use the relay on a machine signed in with ${prefix} login --relay.`];
+ if (status.grant === "signed-out") return [`MausBot Relay needs this machine signed in to a MausBot account: ${prefix} login --relay (then leave the server running; it connects within a minute).`];
+ if (status.grant === "unavailable") return ["MausBot Relay is not available for this machine right now. The server keeps working here; it asks again every half hour."];
+ if (status.grant === "failed") return ["The MausBot account service did not answer. The server keeps working here and keeps trying."];
+ if (status.grant === "waiting") return ["Still asking the MausBot account service for a relay pass…"];
+ if (status.relay !== "connected") return ["Can't reach MausBot Relay yet. The server keeps working here and keeps trying; phones pair once it connects."];
+ return [];
+}
+
+/** The relay block for a phone code, or null when the server did not answer with a relay link. */
+export function relayPairingBlock(body: Record<string, unknown>, chatOnly: boolean, prefix: string, now = Date.now()): string | null {
+ const invite = typeof body.inviteUrl === "string" && body.inviteUrl.includes("&e2e=") ? body.inviteUrl : null;
+ if (!chatOnly || !isStatus(body.relay) || !invite || typeof body.expiresAt !== "number") return null;
+ const lines = [
+ `Phone pairing works once, until ${untilText(body.expiresAt, now)} · chat and approvals`,
+ " Scan with the MausBot app. It connects through MausBot Relay, end-to-end encrypted: no address, open port or VPN needed.",
+ "",
+ qrToString(invite),
+ ...relayProblemLines(body.relay, prefix),
+ `Paired phones: ${body.relay.phones} of ${body.relay.maxPhones}. Remove one: ${prefix} devices revoke ID`,
+ ];
+ return lines.join("\n");
+}
+
+/** Waits for the relay to connect, then prints a phone code; otherwise says why not. True when it printed a code. A
+ * service's output lands in its log on every start, so the one-time credential is printed only at a terminal. */
+export async function showRelayPairing(input: {
+ tty: boolean;
+ status: () => Promise<unknown>;
+ mint: () => Promise<string>;
+ log: (line: string) => void;
+ prefix: string;
+ waitMs?: number;
+}): Promise<boolean> {
+ if (!input.tty) {
+ input.log(`Pair a phone: ${input.prefix} pair --phone`);
+ return false;
+ }
+ const deadline = Date.now() + (input.waitMs ?? 20_000);
+ let status: PhoneRelayStatus | null = null;
+ for (;;) {
+ const read = await input.status().catch(() => null);
+ status = isStatus(read) ? read : null;
+ if (!status || (status.grant === "ok" && status.relay === "connected") || Date.now() > deadline) break;
+ await new Promise((resolve) => setTimeout(resolve, 500));
+ }
+ if (status?.grant === "ok") {
+ input.log(await input.mint());
+ return true;
+ }
+ for (const line of relayProblemLines(status, input.prefix)) input.log(line);
+ if (status?.grant !== "tunnel") input.log(`Then: ${input.prefix} pair --phone`);
+ return false;
+}
diff --git a/server/cli-relay.test.ts b/server/cli-relay.test.ts
new file mode 100644
index 0000000000..c8034ecc50
--- /dev/null
+++ b/server/cli-relay.test.ts
@@ -0,0 +1,109 @@
+import { mkdtempSync, readFileSync, statSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { describe, expect, it, vi } from "vitest";
+
+import { applyStartupPreferences, parseArgs, runLogin, type CliOptions } from "./cli.ts";
+import { RELAY_NOT_WITH_TUNNEL, relayPairingBlock, relayProblemLines, showRelayPairing } from "./cli-pairing.ts";
+import { serviceServeArgs } from "./service-cli.ts";
+import type { PhoneRelayStatus } from "./phone-relay.ts";
+import { removeTempDir } from "./testing/cleanup.ts";
+import { startControlPlaneStub } from "./testing/control-plane-stub.ts";
+
+const status = (over: Partial<PhoneRelayStatus> = {}): PhoneRelayStatus => ({ relay: "connected", node: "relay1.openmausbot.com", grant: "ok", phones: 1, maxPhones: 20, ...over });
+const invite = "openmausbot://pair?address=relay-only.invalid%3A443&token=omb_pair_x&e2e=eyJ2IjoxfQ";
+
+describe("openmausbot serve --relay", () => {
+ it("is off unless asked for, joins any way in but --tunnel, and never a local start", () => {
+ expect(parseArgs(["serve"], {})).not.toHaveProperty("relay");
+ expect(parseArgs(["serve", "--relay"], {})).toMatchObject({ command: "serve", relay: true, tunnel: false });
+ expect(parseArgs(["serve", "--relay", "--domain", "maus.example.com"], {})).toMatchObject({ relay: true, domain: "maus.example.com" });
+ expect(parseArgs(["serve", "--tailscale", "--relay"], {})).toMatchObject({ relay: true, tailscale: true });
+ expect(parseArgs(["service", "install", "--relay"], {})).toMatchObject({ command: "service", relay: true });
+ expect(parseArgs(["serve", "--relay", "--tunnel"], {})).toEqual({ error: "choose one of --relay (phones through MausBot Relay) and --tunnel (a public address)" });
+ expect(parseArgs(["serve", "--tailscale", "--tunnel"], {})).toEqual({ error: "choose one of --tailscale (your tailnet) and --tunnel (a public address)" });
+ expect(parseArgs(["--local", "--relay"], {})).toEqual({ error: "--local cannot be combined with a remote-access option" });
+ });
+
+ it("prints the relay QR for a phone code, and the usual block for everything else", () => {
+ const body = { inviteUrl: invite, expiresAt: Date.now() + 600_000, relay: status() };
+ const block = relayPairingBlock(body, true, "openmausbot")!;
+ expect(block).toContain("Scan with the MausBot app. It connects through MausBot Relay, end-to-end encrypted");
+ expect(block).toContain("Paired phones: 1 of 20. Remove one: openmausbot devices revoke ID");
+ expect(relayPairingBlock(body, false, "openmausbot")).toBeNull();
+ expect(relayPairingBlock({ ...body, relay: undefined }, true, "openmausbot")).toBeNull();
+ expect(relayPairingBlock({ ...body, inviteUrl: "openmausbot://pair?address=https%3A%2F%2Fmaus.example.com&token=omb_pair_x" }, true, "openmausbot")).toBeNull();
+ });
+
+ it("says why a phone cannot pair yet, in the person's terms", () => {
+ expect(relayProblemLines(null, "openmausbot")).toEqual(["MausBot Relay is off on this server. Start it with: openmausbot serve --relay"]);
+ expect(relayProblemLines(status({ grant: "signed-out", relay: "off" }), "openmausbot")[0]).toMatch(/^MausBot Relay needs this machine signed in to a MausBot account: openmausbot login --relay/);
+ expect(relayProblemLines(status({ grant: "unavailable", relay: "off" }), "npx openmausbot")[0]).toMatch(/not available for this machine right now\. The server keeps working here/);
+ expect(relayProblemLines(status({ relay: "connecting", node: null }), "openmausbot")[0]).toMatch(/^Can't reach MausBot Relay yet\. The server keeps working here/);
+ expect(relayProblemLines(status(), "openmausbot")).toEqual([]);
+ expect(relayProblemLines(status({ grant: "tunnel", relay: "off", reason: "this server runs with --tunnel" }), "openmausbot")).toEqual([
+ "MausBot Relay stays off here: this server runs with --tunnel. A relay token would make that tunnel go for good; use the relay on a machine signed in with openmausbot login --relay.",
+ ]);
+ });
+
+ it("waits for the relay before making a code, and makes none it can't use", async () => {
+ const reads = [status({ grant: "waiting", relay: "off" }), status({ relay: "connecting" }), status()];
+ const lines: string[] = [];
+ let minted = 0;
+ const mint = async () => `code ${++minted}`;
+ expect(await showRelayPairing({ tty: true, status: async () => reads.shift() ?? status(), mint, log: (line) => lines.push(line), prefix: "openmausbot", waitMs: 5_000 })).toBe(true);
+ expect(lines).toEqual(["code 1"]);
+
+ lines.length = 0;
+ expect(await showRelayPairing({ tty: true, status: async () => status({ grant: "signed-out", relay: "off" }), mint, log: (line) => lines.push(line), prefix: "openmausbot", waitMs: 0 })).toBe(false);
+ expect(minted).toBe(1);
+ expect(lines[1]).toBe("Then: openmausbot pair --phone");
+ });
+
+ it("signs a machine in for the relay without reserving one of the scarce tunnel addresses", async () => {
+ const stub = await startControlPlaneStub();
+ const dataDir = mkdtempSync(join(tmpdir(), "omb-login-relay-"));
+ vi.stubEnv("OMB_CONTROL_PLANE_URL", stub.url);
+ try {
+ const lines: string[] = [];
+ const io = { log: (line: string) => lines.push(line), error: (line: string) => lines.push(`error: ${line}`), ask: async () => stub.otp };
+ const options = parseArgs(["login", "--relay", "--email", "[email protected]", "--data-dir", dataDir], {});
+ if ("error" in options) throw new Error(options.error);
+ expect(await runLogin(options, io)).toBe(0);
+ expect(lines).toEqual(["Signed in as [email protected].", "No public address reserved: phones reach this machine through MausBot Relay.", expect.stringMatching(/^Serve there with: {2}.*serve --relay$/)]);
+ expect(stub.calls).toContain("POST /v1/installations");
+ expect([...stub.installations.values()].map((installation) => installation.kind)).toEqual(["server"]);
+ expect(stub.calls.filter((call) => call.includes("/endpoint"))).toEqual([]);
+ const file = join(dataDir, "tunnel-account.json");
+ expect(JSON.parse(readFileSync(file, "utf8")).companionInstallationCredential).toMatch(/^omb_install_/);
+ if (process.platform !== "win32") expect(statSync(file).mode & 0o777).toBe(0o600);
+ } finally {
+ vi.unstubAllEnvs();
+ await stub.close();
+ await removeTempDir(dataDir);
+ }
+ });
+
+ it("never prints the one-time credential into a service's log", async () => {
+ const lines: string[] = [];
+ let minted = 0;
+ expect(await showRelayPairing({ tty: false, status: async () => status(), mint: async () => `code ${++minted}`, log: (line) => lines.push(line), prefix: "openmausbot" })).toBe(false);
+ expect(minted).toBe(0);
+ expect(lines).toEqual(["Pair a phone: openmausbot pair --phone"]);
+ });
+
+ it("keeps a saved tunnel choice and the relay apart, and passes --relay to a service", () => {
+ const start = (argv: string[]) => {
+ const parsed = parseArgs(argv, {});
+ if ("error" in parsed) throw new Error(parsed.error);
+ return parsed as CliOptions;
+ };
+ expect(() => applyStartupPreferences(start(["start", "--relay"]), { access: "tunnel" })).toThrow(RELAY_NOT_WITH_TUNNEL);
+ expect(applyStartupPreferences(start(["start", "--relay"]), { access: "local" })).toMatchObject({ relay: true, tunnel: false });
+ expect(applyStartupPreferences(start(["start", "--relay"]), undefined)).toMatchObject({ relay: true });
+ expect(applyStartupPreferences(start(["start"]), { access: "tunnel" })).toMatchObject({ tunnel: true });
+ expect(serviceServeArgs({ port: 8799, dataDir: "/d", relay: true })).toEqual(["--port", "8799", "--data-dir", "/d", "--relay"]);
+ expect(serviceServeArgs({ port: 8799, dataDir: "/d", domain: "maus.example.com", relay: true })).toEqual(["--port", "8799", "--data-dir", "/d", "--domain", "maus.example.com", "--relay"]);
+ expect(serviceServeArgs({ port: 8799, dataDir: "/d" })).toEqual(["--port", "8799", "--data-dir", "/d"]);
+ });
+});
diff --git a/server/cli-usage.ts b/server/cli-usage.ts
index 8389c2776c..584c841acf 100644
--- a/server/cli-usage.ts
+++ b/server/cli-usage.ts
@@ -32,12 +32,12 @@ export const USAGE = `openmausbot — your team of AI bots, ready in a few steps
openmausbot setup [--data-dir DIR]
openmausbot start [the same options as serve]
openmausbot serve [--port 8799] [--data-dir DIR] [--label NAME]
- [--public-url https://host | --domain HOST | --tunnel | --tailscale] [--lan]
+ [--public-url https://host | --domain HOST | --tunnel | --tailscale] [--lan] [--relay]
openmausbot pair [--label NAME] [--phone [ios|android]] [--ttl 24h] [--public-url https://host]
openmausbot devices [revoke ID]
openmausbot status
openmausbot --version
- openmausbot login [--email [email protected]]
+ openmausbot login [--email [email protected]] [--relay]
openmausbot logout
openmausbot access list | add EMAIL [--chat-only] | remove EMAIL
openmausbot service install [the same way-in options as serve] [--port N] [--data-dir DIR] | uninstall
@@ -62,7 +62,8 @@ devices lists paired devices; "devices revoke ID" signs one out
status the running server, the address others reach it at, and whether
that address answers as this server
login signs this machine in to an OpenMausBot account (an emailed code)
- and reserves its public address for --tunnel
+ and reserves its public address for --tunnel; with --relay it
+ reserves none, for serve --relay
logout releases that address and signs out
access who may sign in with an emailed code at /pair: an address or
@domain; --chat-only gives chat and approvals without settings.
@@ -103,6 +104,12 @@ Ways in (pick one; --lan can join any):
certificate itself. Point the domain's DNS at this machine and
open ports 80 and 443.
+--relay phones only, and it can join any of the above except --tunnel:
+ the MausBot phone app pairs by QR through MausBot Relay,
+ end-to-end encrypted, with no address, open port or VPN. Run
+ \`openmausbot login --relay\` once on this machine first. Not on a
+ machine with a tunnel address: the relay stays off there.
+
--no-open do not open a browser window
--no-pair do not print a pairing code
--local start locally this time, ignoring saved remote-access settings
diff --git a/server/cli.ts b/server/cli.ts
index ac4a505ceb..a687d1f1ba 100644
--- a/server/cli.ts
+++ b/server/cli.ts
@@ -3,11 +3,11 @@
// openmausbot setup [--data-dir ~/.openmausbot]
// openmausbot start [serve options]
// openmausbot serve [--port 8799] [--data-dir ~/.openmausbot] [--label "cab mini"]
-// [--public-url https://host] [--tailscale | --tunnel | --domain HOST] [--no-pair]
+// [--public-url https://host] [--tailscale | --tunnel | --domain HOST] [--relay] [--no-pair]
// openmausbot pair [--label "My MacBook"] [--client] [--public-url https://host]
// openmausbot sessions [revoke <id>]
// openmausbot status
-// openmausbot login [--email [email protected]]
+// openmausbot login [--email [email protected]] [--relay]
// openmausbot logout
// openmausbot run | send | wait | doctor | team apply | export | …
//
@@ -38,7 +38,7 @@ import { clearLeftoverTailscaleServe, explainTailscaleFailure, tailscaleServe, t
import { defaultSetupIo, SetupCancelled, type SetupIo } from "./cli-prompts.ts";
import { HEADLESS_VERB_NAMES, usage } from "./cli-usage.ts";
import { normalizePhoneOrigin, phonePairingInstructions, runPhoneSetup } from "./cli-phone-setup.ts";
-import { browserSignInLines, formatSessions, pairingBlock } from "./cli-pairing.ts";
+import { browserSignInLines, formatSessions, pairingBlock, RELAY_NOT_WITH_TUNNEL, relayPairingBlock, showRelayPairing } from "./cli-pairing.ts";
import { cliCommand, cliPrefix } from "./cli-invocation.ts";
import { checkReach, envPublicUrl, lanProblem, localLinkBase, noRouteLines, publicUrlProblem, reachLines, waitForReach, type Route } from "./cli-reach.ts";
import { lanUrl } from "./lan-address.ts";
@@ -77,6 +77,7 @@ export interface CliOptions {
domain?: string;
tailscale: boolean;
tunnel: boolean;
+ relay?: boolean;
/** `serve --lan`: every private address of this machine, plain http, each connection held to private ends. */
lan?: boolean;
client: boolean;
@@ -159,7 +160,7 @@ export function parseArgs(argv: string[], env: NodeJS.ProcessEnv = process.env):
if (typeof domain !== "string") return domain;
options.domain = domain;
}
- else if (arg === "--tunnel") options.tunnel = true;
+ else if (arg === "--tunnel" || arg === "--relay") options[arg === "--tunnel" ? "tunnel" : "relay"] = true;
else if (arg === "--client" || (options.command === "pair" && arg === "--chat-only")) options.client = true;
// Which phone will scan; only Android needs a different QR. `pair --phone` alone is a chat-only code for any phone.
else if (arg === "--phone") {
@@ -209,11 +210,11 @@ export function parseArgs(argv: string[], env: NodeJS.ProcessEnv = process.env):
if (!Number.isInteger(options.port) || options.port < 1 || options.port > 65_535) return { error: "--port must be 1-65535" };
const publicUrlRefusal = options.publicUrl ? publicUrlProblem(options.publicUrl) : null;
if (publicUrlRefusal) return { error: publicUrlRefusal };
- if (options.tailscale && options.tunnel) return { error: "choose one of --tailscale (your tailnet) and --tunnel (a public address)" };
+ if (options.tunnel && (options.tailscale || options.relay)) return { error: options.relay ? "choose one of --relay (phones through MausBot Relay) and --tunnel (a public address)" : "choose one of --tailscale (your tailnet) and --tunnel (a public address)" };
if (options.command === "access" && !options.accessAction) return { error: "access needs one of: list, add EMAIL [--chat-only], remove EMAIL" };
if (options.command === "service" && !options.serviceAction) return { error: "service needs one of: install [the same options as serve], uninstall" };
if (options.domain && (options.tailscale || options.tunnel || options.publicUrl)) return { error: "--domain already gives the server its address; drop --tailscale, --tunnel and --public-url" };
- if (options.local && (options.tailscale || options.tunnel || options.publicUrl || options.lan)) return { error: "--local cannot be combined with a remote-access option" };
+ if (options.local && (options.tailscale || options.tunnel || options.publicUrl || options.lan || options.relay)) return { error: "--local cannot be combined with a remote-access option" };
if (options.command === "browser" && !options.browserAction) return { error: "browser needs an action: install or status" };
if (options.command === "fleet") {
if (!options.fleetAction) return { error: "fleet needs one of: init --domain HOST [--operator USER], create NAME --admin EMAIL, list, users NAME add|remove EMAIL, suspend NAME, resume NAME, delete NAME --yes, upgrade, agent" };
@@ -318,7 +319,7 @@ export async function verifyPhoneEndpoint(port: number, origin: string): Promise
export function applyStartupPreferences(options: CliOptions, saved: AppConfig["cliStartup"]): CliOptions {
if (options.local) return { ...options, tunnel: false, tailscale: false, publicUrl: undefined, phone: undefined };
- if (!saved || options.tunnel || options.tailscale || options.publicUrl) return options;
+ if (!saved || options.tunnel || options.tailscale || options.publicUrl) return options; if (options.relay && saved.access === "tunnel") throw new Error(RELAY_NOT_WITH_TUNNEL);
if (saved.access === "public-url" && (!saved.publicUrl || !normalizePhoneOrigin(saved.publicUrl))) {
throw new Error(`The saved phone address is not a valid HTTPS origin. Run ${cliCommand("setup")} to correct it, or ${cliCommand("--local")} to start only on this computer.`);
}
@@ -342,6 +343,7 @@ function startupPreferences(options: CliOptions): NonNullable<AppConfig["cliStar
}
async function showPhonePairing(options: CliOptions, origin: string | undefined, log: (line: string) => void): Promise<boolean> {
+ if (options.relay) return showRelayPairing({ tty: process.stdout.isTTY === true, status: async () => (await api(options.port, "/api/auth/pairing")).body?.relay, mint: () => mintPairing(options.port, { client: true, label: options.label ?? (options.phone === "android" ? "Android" : "iPhone / iPad"), phone: options.phone ?? "ios" }), log, prefix: cliPrefix() });
const ready = !!origin && await verifyPhoneEndpoint(options.port, origin);
if (!ready) {
log("Phone access is not reachable yet. OpenMausBot is ready on this computer; no phone pairing code was created.");
@@ -362,12 +364,10 @@ async function mintPairing(port: number, options: { label?: string; client?: boo
if (status !== 200) throw new Error(`server refused to mint a pairing code: ${typeof body?.error === "string" ? body.error : status}`);
const reachable = options.publicUrl && !isLoopbackHost(new URL(options.publicUrl).hostname) ? options.publicUrl : null;
const link = reachable ? `${reachable}/pair#code=${body.code}` : typeof body.url === "string" && !isLoopbackHost(new URL(body.url).hostname) ? body.url : null;
- const invite = (reachable && typeof body.credential === "string"
- ? phonePairingLink({ address: reachable, token: body.credential, name: typeof body.serverName === "string" ? body.serverName : undefined })
- : null) ?? (typeof body.inviteUrl === "string" ? body.inviteUrl : null);
+ const invite = (reachable && typeof body.credential === "string" ? phonePairingLink({ address: reachable, token: body.credential, name: typeof body.serverName === "string" ? body.serverName : undefined }) : null) ?? (typeof body.inviteUrl === "string" ? body.inviteUrl : null);
const local = localLinkBase(options.publicUrl ?? null, port);
if (options.guided) return browserSignInLines(`${local.base}/pair#code=${body.code}`, body.code, body.expiresAt);
- return pairingBlock({ code: body.code, expiresAt: body.expiresAt, chatOnly, link, localLink: `${local.base}/pair#code=${body.code}`, localPlace: local.place, inviteUrl: invite, phone: options.phone, prefix: cliPrefix() });
+ return relayPairingBlock(body, chatOnly, cliPrefix()) ?? pairingBlock({ code: body.code, expiresAt: body.expiresAt, chatOnly, link, localLink: `${local.base}/pair#code=${body.code}`, localPlace: local.place, inviteUrl: invite, phone: options.phone, prefix: cliPrefix() });
}
/** Never asks anything: the running server's own address (its routes) goes in the link. */
@@ -510,7 +510,7 @@ export async function runAccess(options: CliOptions, io: CliIo = defaultIo()): P
}
export async function runLogin(options: CliOptions, io: CliIo = defaultIo()): Promise<number> {
- const account = createTunnelAccount({ dataDir: options.dataDir, version: serverVersion() });
+ const account = createTunnelAccount({ dataDir: options.dataDir, version: serverVersion(), relayOnly: options.relay === true });
if (fleetCredential()) io.log(`note: ${FLEET_CREDENTIAL_ENV} is set, so serve --tunnel will use that credential rather than this account`);
if (account.credentials.status === "unavailable") {
io.error(`${account.credentials.file} exists but could not be read; fix or remove it, then try again`);
@@ -542,13 +542,13 @@ export async function runLogin(options: CliOptions, io: CliIo = defaultIo()): Pr
return 1;
}
const signedIn = describeTunnelAccount(account.credentials.read());
- if (!signedIn.address) {
+ if (!signedIn.address && !(options.relay && signedIn.installationId)) {
io.error(`signed in, but no public address was issued${state.message ? `: ${state.message}` : ""}`);
return 1;
}
io.log(`Signed in as ${signedIn.email ?? email}.`);
- io.log(`This machine's public address: ${signedIn.address}`);
- io.log(`Serve there with: ${cliCommand("serve --tunnel")}`);
+ io.log(signedIn.address ? `This machine's public address: ${signedIn.address}` : "No public address reserved: phones reach this machine through MausBot Relay.");
+ io.log(`Serve there with: ${cliCommand(signedIn.address ? "serve --tunnel" : "serve --relay")}`);
return 0;
}
@@ -721,7 +721,7 @@ export async function runServe(options: CliOptions, log: (line: string) => void
...process.env,
OMB_DATA_DIR: options.dataDir,
OMB_PORT: String(options.port),
- OMB_WEBHOOK_PORT: process.env.OMB_WEBHOOK_PORT || String(options.port + 1),
+ OMB_WEBHOOK_PORT: process.env.OMB_WEBHOOK_PORT || String(options.port + 1), ...(options.relay ? { OMB_PHONE_RELAY: "1" } : {}),
};
if (options.local) delete env.OMB_PUBLIC_URL;
// The per-launch secret goes over stdin, not the environment that every engine the server starts inherits.
@@ -732,7 +732,7 @@ export async function runServe(options: CliOptions, log: (line: string) => void
if (entry.staticDir) env.OMB_STATIC_DIR = entry.staticDir;
if (entry.skillsDir && !process.env.OMB_SKILLS_DIR) env.OMB_SKILLS_DIR = entry.skillsDir;
if (options.label && !process.env.OMB_ENVIRONMENT_LABEL) env.OMB_ENVIRONMENT_LABEL = options.label;
- if (plan) env.OMB_TUNNEL_SOCKET = plan.origin.socketPath;
+ if (plan) Object.assign(env, { OMB_TUNNEL_SOCKET: plan.origin.socketPath, OMB_SERVES_TUNNEL: "1" });
const lanRefusal = options.lan ? lanProblem() : null;
if (lanRefusal) log(lanRefusal);
if (options.lan && !lanRefusal) env.OMB_LAN = "1";
@@ -874,7 +874,7 @@ export async function runServe(options: CliOptions, log: (line: string) => void
const reach = route && origin && route !== "lan" ? await waitForReach(options.port, origin, route === "public-url" ? 3_000 : 15_000) : undefined;
if (route && origin) for (const line of reachLines(route, origin, options.port, prefix, reach)) log(line);
const interactive = process.stdout.isTTY === true;
- if (options.pair && options.phone) {
+ if (options.pair && (options.phone || options.relay)) {
log("");
if (!stopping && exited === null) await showPhonePairing(options, publicUrl, log).catch((error: unknown) => log(`no pairing code: ${message(error)}`));
} else if (options.pair && (options.guided || ((route || serviceTrust) && interactive))) {
@@ -1010,7 +1010,7 @@ export async function main(argv = process.argv.slice(2)): Promise<number> {
case "service":
return runServiceCommand({
action: options.serviceAction ?? "install", dataDir: options.dataDir, port: options.port, domain: options.domain, tunnel: options.tunnel,
- tailscale: options.tailscale, publicUrl: options.publicUrl, lan: options.lan, label: options.label, sentinel: options.sentinel, script: process.argv[1] ?? "", node: process.execPath,
+ tailscale: options.tailscale, publicUrl: options.publicUrl, lan: options.lan, relay: options.relay, label: options.label, sentinel: options.sentinel, script: process.argv[1] ?? "", node: process.execPath,
}, { log: (line) => console.log(line), error: (line) => console.error(line) });
case "fleet":
if (options.fleetAction === "agent") {
diff --git a/server/index.ts b/server/index.ts
index 180e3a730b..030ed86253 100644
--- a/server/index.ts
+++ b/server/index.ts
@@ -544,6 +544,7 @@ import {
} from "./request-auth.ts";
import { cookieMaxAgeSeconds, formatPairingCode, pairingRequest, SessionRegistry, type SessionRecord } from "./sessions.ts";
import { ThreadStarters } from "./thread-starters.ts";
+import { startPhoneRelay } from "./phone-relay.ts";
import {
appendAdminAction,
BOT_AUDIT_FIELDS,
@@ -12652,6 +12653,7 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {
const credential = typeof body?.credential === "string" ? body.credential : typeof body?.code === "string" ? body.code : "";
const label = typeof body?.deviceName === "string" ? body.deviceName : "";
const attemptId = typeof body?.pairRequestId === "string" ? body.pairRequestId : undefined;
+ const relayRefusal = phoneRelay?.pairingRefusal(req, credential); if (relayRefusal) return json(res, 400, { error: relayRefusal });
const paired = sessions.exchange({ code: credential, label, attemptId, source: requestSource(req), fallbackLabel: labelFromUserAgent(req.headers["user-agent"]) });
if (!paired.ok) {
console.warn(`pairing refused from ${requestSource(req)}: ${paired.error}`);
@@ -12667,6 +12669,7 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {
lastSeenAt: paired.session.lastSeenAt,
},
serverName: cfg.computerName || environmentDescriptor({ environmentId: ENVIRONMENT_ID, ...TEAM_LABEL, desktopManaged: DESKTOP_MANAGED }).label,
+ ...phoneRelay?.pairedOver(req),
});
}
const gate = resolveRequestAuth(req, {
@@ -12778,7 +12781,7 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {
const code = formatPairingCode(opened.code);
// `inviteUrl` is the custom scheme the native companion scanners accept; they cannot take a typed code.
const serverName = cfg.computerName || environmentDescriptor({ environmentId: ENVIRONMENT_ID, ...TEAM_LABEL, desktopManaged: DESKTOP_MANAGED }).label;
- const invite = base ? phonePairingLink({ address: base, token: opened.credential, name: serverName }) : null;
+ const invite = phoneRelay?.invite(opened.credential, serverName, base) ?? (base ? phonePairingLink({ address: base, token: opened.credential, name: serverName }) : null);
return json(res, 200, {
id: opened.id,
code,
@@ -12786,13 +12789,13 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {
expiresAt: opened.expiresAt,
url: base ? `${base}/pair#code=${code}` : null,
inviteUrl: invite,
- serverName,
+ serverName, ...(phoneRelay ? { relay: phoneRelay.status() } : {}),
hint: base
? null
: "this server has no public address to put in a link: set OMB_PUBLIC_URL, or open /pair on the address you use and type the code",
});
}
- if (method === "GET" && path === "/api/auth/pairing") return json(res, 200, { pairings: sessions.openPairings(), publicUrl: publicUrl() });
+ if (method === "GET" && path === "/api/auth/pairing") return json(res, 200, { pairings: sessions.openPairings(), publicUrl: publicUrl(), ...(phoneRelay ? { relay: phoneRelay.status() } : {}) });
// Admin-only by request-auth's default deny; only future pairing links change.
if (path === "/api/settings/custom-domain") {
res.setHeader("cache-control", "no-store");
@@ -15411,6 +15414,10 @@ if (TUNNEL_SOCKET) {
console.log(`openmausbot tunnel listener on ${TUNNEL_SOCKET}`);
});
}
+// `serve --relay`: phones through MausBot Relay, each encrypted stream answered here as a remote request.
+const phoneRelay = startPhoneRelay({ env: process.env, dataDir: DATA_DIR, sessions, handle: handleRequest, version: serverVersion(), publicOrigin: publicUrl,
+ serverName: () => cfg.computerName || environmentDescriptor({ environmentId: ENVIRONMENT_ID, ...TEAM_LABEL, desktopManaged: DESKTOP_MANAGED }).label,
+ refusal: CLOUD_HOME ? "a MausBot Cloud home" : HOSTED_WORKSPACE ? "a hosted workspace" : DESKTOP_MANAGED ? "the desktop app, whose companion carries phones" : null });
/** A root the runtime holds is the runtime's to account for at the next start: a line here, with Retry, would start the job a second time. */
function noteTurnsCutByShutdown(): void {
@@ -15462,7 +15469,7 @@ const gracefulShutdown = createGracefulShutdown({
cacheKeepWarm.dispose(); warmSummaries.dispose();
skillReview.stop();
webhookIngress?.server.close(); webhookIngress?.socketServer?.close();
- tunnelListener?.close(); stopCloudHomeConnectedApps();
+ tunnelListener?.close(); phoneRelay?.stop(); stopCloudHomeConnectedApps();
},
async () => { await managedDesktop.close(); await registry.disposeAll(); },
async () => { await dataEngine.closeAll().catch((error) => console.warn("data: close failed", error)); },
diff --git a/server/phone-relay.e2e.test.ts b/server/phone-relay.e2e.test.ts
new file mode 100644
index 0000000000..e96f7398fa
--- /dev/null
+++ b/server/phone-relay.e2e.test.ts
@@ -0,0 +1,154 @@
+// The real server with OMB_PHONE_RELAY=1, a fake control plane and the fake relay, driven by the reference phone: the
+// pairing code the owner makes on the server is redeemed through the relay, and the phone is then a session like any.
+import { spawn, type ChildProcess } from "node:child_process";
+import { generateKeyPairSync, randomBytes } from "node:crypto";
+import { mkdirSync, mkdtempSync, openSync, closeSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import { createServer, type Server } from "node:http";
+import type { AddressInfo } from "node:net";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { afterAll, beforeAll, describe, expect, it, onTestFinished } from "vitest";
+
+import { verificationServerArgs, verificationServerEnvironment } from "../scripts/control-omb.ts";
+import { admission, b64u, credentialHash, ed25519RawPublicKey, fromB64u, keyId, mintRelayToken, psk } from "../companion/src/e2e/credentials.ts";
+import { TRANSPORT_RELAY } from "../companion/src/e2e/noise.ts";
+import { dial } from "../companion/src/e2e/phone.ts";
+import { startFakeRelay, type FakeRelay } from "../companion/test/e2e/fake-relay.ts";
+import { http, json, waitFor } from "../companion/test/e2e/rig.ts";
+import { removeTempDir, waitForExit } from "./testing/cleanup.ts";
+import { freePortBlock } from "./testing/ports.ts";
+
+const signingKey = generateKeyPairSync("ed25519").privateKey;
+const hostId = randomBytes(16);
+const credential = `omb_install_${randomBytes(16).toString("base64url")}.${randomBytes(32).toString("base64url")}`;
+const tokenRequests: unknown[] = [];
+
+let relay: FakeRelay;
+let controlPlane: Server;
+let child: ChildProcess;
+let dataDir: string;
+let logPath: string;
+let base: string;
+const others: Array<{ child: ChildProcess; dataDir: string }> = [];
+const dockerSocket = join(tmpdir(), `omb-relay-e2e-docker-${process.pid}.sock`);
+
+/** A real server in a new data dir, signed in for the relay as `login --relay` leaves it: a credential, no tunnel address. */
+async function boot(extra: Record<string, string> = {}) {
+ const port = await freePortBlock([0, 1]);
+ const dir = mkdtempSync(join(tmpdir(), "omb-phone-relay-e2e-"));
+ mkdirSync(join(dir, "tmp"), { recursive: true });
+ writeFileSync(join(dir, "tunnel-account.json"), JSON.stringify({ companionInstallationCredential: credential }), { mode: 0o600 });
+ const env = {
+ ...verificationServerEnvironment(process.env, dir, port),
+ OMB_PHONE_RELAY: "1",
+ OMB_PHONE_RELAY_URL: relay.url,
+ OMB_CONTROL_PLANE_URL: `http://127.0.0.1:${(controlPlane.address() as AddressInfo).port}`,
+ ...extra,
+ };
+ const log = join(dir, "server.log");
+ const fd = openSync(log, "a", 0o600);
+ const started = spawn(process.execPath, verificationServerArgs(env), { env, stdio: ["ignore", fd, fd] });
+ closeSync(fd);
+ const url = `http://127.0.0.1:${port}`;
+ await waitFor(async () => (await fetch(`${url}/api/health`).then((r) => r.json(), () => null) as { app?: string } | null)?.app === "openmausbot", 30_000);
+ return { child: started, dataDir: dir, logPath: log, base: url };
+}
+
+beforeAll(async () => {
+ relay = await startFakeRelay({ keys: new Map([["k1", ed25519RawPublicKey(signingKey)]]) });
+ controlPlane = createServer(async (req, res) => {
+ let raw = "";
+ for await (const chunk of req) raw += chunk;
+ if (req.method !== "POST" || req.url !== "/v1/installations/self/relay-token" || req.headers.authorization !== `Bearer ${credential}`) {
+ return void res.writeHead(401, { "content-type": "application/json" }).end(JSON.stringify({ error: "unauthorized" }));
+ }
+ tokenRequests.push(JSON.parse(raw));
+ const iat = Math.floor(Date.now() / 1000);
+ const token = mintRelayToken({ v: 1, kid: "k1", hid: b64u(hostId), iid: "test-install", iat, exp: iat + 43_200 }, signingKey);
+ res.writeHead(200, { "content-type": "application/json" }).end(JSON.stringify({
+ token, hostId: b64u(hostId), nodes: ["relay1.openmausbot.com"], expiresAt: (iat + 43_200) * 1000, refreshAfter: (iat + 3_600) * 1000,
+ }));
+ });
+ await new Promise<void>((resolve) => controlPlane.listen(0, "127.0.0.1", resolve));
+ // As Docker runs it: its Caddy reaches the server over this socket, which is no tunnel.
+ ({ child, dataDir, logPath, base } = await boot({ OMB_TUNNEL_SOCKET: dockerSocket }));
+}, 60_000);
+
+afterAll(async () => {
+ await waitForExit(child, { signal: "SIGTERM", graceMs: 15_000 });
+ rmSync(dockerSocket, { force: true });
+ for (const other of others) {
+ await waitForExit(other.child, { signal: "SIGTERM", graceMs: 15_000 });
+ await removeTempDir(other.dataDir);
+ }
+ await relay?.close();
+ await new Promise((resolve) => controlPlane?.close(resolve));
+ if (dataDir) await removeTempDir(dataDir);
+});
+
+const owner = async (path: string, init: RequestInit = {}) => {
+ const res = await fetch(`${base}${path}`, { ...init, headers: { "content-type": "application/json", ...init.headers } });
+ return { status: res.status, body: (await res.json()) as Record<string, any> };
+};
+
+describe("serve --relay", () => {
+ it("pairs a phone through the relay with the server's own pairing code, as a session of its own", async () => {
+ await waitFor(async () => (await owner("/api/auth/pairing")).body.relay?.relay === "connected", 15_000);
+ expect(readFileSync(logPath, "utf8")).toContain("phone relay: connected via relay1.openmausbot.com");
+ // The control plane hears exactly the fields its strict schema takes.
+ expect(tokenRequests[0]).toEqual({ appVersion: expect.stringMatching(/^\d+\.\d+\.\d+/), devices: { e2e: 0, legacy: 0 }, kind: "server" });
+
+ const minted = await owner("/api/auth/pairing", { method: "POST", body: JSON.stringify({ scopes: ["client"], label: "Pixel" }) });
+ expect(minted.status).toBe(200);
+ expect(minted.body.relay).toMatchObject({ relay: "connected", grant: "ok", phones: 0 });
+ const invite = new URL(minted.body.inviteUrl);
+ expect(invite.searchParams.get("token")).toBe(minted.body.credential);
+ const descriptor = JSON.parse(fromB64u(invite.searchParams.get("e2e")!)!.toString("utf8")) as { k: string; h: string; r: string[] };
+ expect(descriptor).toMatchObject({ h: b64u(hostId), r: ["relay1.openmausbot.com"] });
+ const k = fromB64u(descriptor.k)!;
+ const phone = (token: string) => dial({
+ url: `${relay.url}/v1/phone`, transportByte: TRANSPORT_RELAY, remoteStatic: k, psk: psk(credentialHash(token), keyId(k)), app: "test/1",
+ relay: { hostId, adm: admission(credentialHash(token), hostId) },
+ });
+
+ const pairing = await waitFor(() => phone(minted.body.credential).catch(() => null), 8_000);
+ const paired = await http(pairing, "POST", "/api/pair", { body: JSON.stringify({ credential: minted.body.credential, deviceName: "Pixel" }), headers: { "content-type": "application/json" } });
+ expect(paired.status).toBe(200);
+ const reply = json(paired) as { token: string; device: { id: string; name: string }; serverName: string; e2e: unknown };
+ expect(reply.device.name).toBe("Pixel");
+ expect(reply.e2e).toEqual(descriptor);
+ pairing.shutdown();
+
+ const session = await waitFor(() => phone(reply.token).catch(() => null), 8_000);
+ expect(json(await http(session, "GET", "/api/auth/session", { token: reply.token }))).toMatchObject({ kind: "session", id: reply.device.id, scopes: ["client"] });
+ // No session, a loopback Host and the CLI's owner header: still a remote request through the relay.
+ const spoofed = await http(session, "GET", "/api/auth/session", { headers: { host: base.slice("http://".length), "x-openmausbot-cli": "1" } });
+ expect(spoofed.status).toBe(403);
+ // Chat-only stays chat-only: the server's own scope rule answers.
+ expect((await http(session, "POST", "/api/auth/pairing", { token: reply.token, body: "{}", headers: { "content-type": "application/json" } })).status).toBe(403);
+
+ // `openmausbot devices revoke`: the phone hears it inside the encryption.
+ expect((await owner(`/api/auth/sessions/${reply.device.id}`, { method: "DELETE" })).status).toBe(200);
+ await session.closed;
+ expect(session.removed).toBe(true);
+ expect((await owner("/api/auth/pairing")).body.relay.phones).toBe(0);
+ }, 60_000);
+
+ it("stays off on a server that serves a tunnel or runs on a fleet credential, and asks the control plane nothing", async () => {
+ const asked = tokenRequests.length;
+ const socket = join(tmpdir(), `omb-relay-e2e-${process.pid}-${Date.now()}.sock`);
+ const tunnel = await boot({ OMB_SERVES_TUNNEL: "1", OMB_TUNNEL_SOCKET: socket });
+ others.push(tunnel);
+ onTestFinished(() => rmSync(socket, { force: true }));
+ const fleet = await boot({ OMB_INSTALLATION_CREDENTIAL: credential });
+ others.push(fleet);
+ for (const server of [tunnel, fleet]) {
+ const status = await (await fetch(`${server.base}/api/auth/pairing`)).json() as { relay?: { grant: string; reason?: string } };
+ expect(status.relay).toMatchObject({ grant: "tunnel", reason: expect.any(String) });
+ const minted = await (await fetch(`${server.base}/api/auth/pairing`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ scopes: ["client"] }) })).json() as { inviteUrl: string | null };
+ expect(minted.inviteUrl ?? "").not.toContain("e2e=");
+ expect(readFileSync(server.logPath, "utf8")).toMatch(/phone relay: off: .*login --relay/);
+ }
+ expect(tokenRequests.length).toBe(asked);
+ }, 90_000);
+});
diff --git a/server/phone-relay.test.ts b/server/phone-relay.test.ts
new file mode 100644
index 0000000000..2d49ea54a2
--- /dev/null
+++ b/server/phone-relay.test.ts
@@ -0,0 +1,452 @@
+// The server's side of MausBot Relay against the fake relay, driven by the reference phone: the server's own sessions
+// are the phones, and every relayed request reaches the handler as a remote one.
+import { generateKeyPairSync, randomBytes } from "node:crypto";
+import { mkdtempSync, readFileSync, statSync, writeFileSync } from "node:fs";
+import type { IncomingMessage, ServerResponse } from "node:http";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { afterEach, describe, expect, it } from "vitest";
+
+import { admission, admissionHash, b64u, credentialHash, ed25519RawPublicKey, fromB64u, keyId, mintRelayToken, psk } from "../companion/src/e2e/credentials.ts";
+import { TRANSPORT_RELAY } from "../companion/src/e2e/noise.ts";
+import { dial } from "../companion/src/e2e/phone.ts";
+import { SessionClosed, type E2ESession } from "../companion/src/e2e/session.ts";
+import { startFakeRelay, type FakeRelay } from "../companion/test/e2e/fake-relay.ts";
+import { http, json, waitFor } from "../companion/test/e2e/rig.ts";
+import { removeTempDir } from "./testing/cleanup.ts";
+import { MAX_RELAY_PHONES, MAX_SESSIONS_PER_PHONE, PHONE_RELAY_KEY_FILE, PHONE_RELAY_PHONES_FILE, startPhoneRelay, tunnelHolder, type PhoneRelay, type PhoneRelayOptions } from "./phone-relay.ts";
+import { requestSource, resolveRequestAuth } from "./request-auth.ts";
+import { SessionRegistry } from "./sessions.ts";
+
+const signingKey = generateKeyPairSync("ed25519").privateKey;
+const keys = new Map([["k1", ed25519RawPublicKey(signingKey)]]);
+const NODE = "relay1.openmausbot.com";
+
+const cleanup: Array<() => unknown> = [];
+afterEach(async () => {
+ for (const step of cleanup.splice(0).reverse()) await step();
+});
+
+function grantFor(hostId: Buffer) {
+ const iat = Math.floor(Date.now() / 1000);
+ const token = mintRelayToken({ v: 1, kid: "k1", hid: b64u(hostId), iid: "test-install", iat, exp: iat + 43_200 }, signingKey);
+ return { token, hostId: b64u(hostId), nodes: [NODE], expiresAt: (iat + 43_200) * 1000, refreshAfter: (iat + 3_600) * 1000 };
+}
+
+async function body(req: IncomingMessage): Promise<Record<string, string>> {
+ let raw = "";
+ for await (const chunk of req) raw += chunk;
+ return raw ? JSON.parse(raw) : {};
+}
+
+/** The parts of the server's handler a phone meets: `/api/pair` as the server answers it, and the real request gate. */
+function serverHandler(sessions: SessionRegistry, relay: () => PhoneRelay | null) {
+ return async (req: IncomingMessage, res: ServerResponse) => {
+ const url = new URL(req.url ?? "/", "http://server");
+ const send = (status: number, payload: unknown) => res.writeHead(status, { "content-type": "application/json" }).end(JSON.stringify(payload));
+ if (req.method === "POST" && url.pathname === "/api/pair") {
+ const input = await body(req);
+ const presented = input.credential ?? input.code ?? "";
+ const refusal = relay()?.pairingRefusal(req, presented);
+ if (refusal) return send(400, { error: refusal });
+ const paired = sessions.exchange({ code: presented, label: input.deviceName ?? "", source: requestSource(req) });
+ if (!paired.ok) return send(paired.status, { error: paired.error });
+ return send(200, { token: paired.token, device: { id: paired.session.id }, serverName: "VPS", ...relay()?.pairedOver(req) });
+ }
+ if (url.pathname === "/api/test-stream") {
+ // Like the event stream: answers for as long as the phone listens, and never reads the request.
+ res.writeHead(200, { "content-type": "text/event-stream" });
+ const tick = setInterval(() => res.write("data: tick\n\n"), 100);
+ res.once("close", () => clearInterval(tick));
+ return;
+ }
+ const gate = resolveRequestAuth(req, { sessions, cookieName: "omb_session", streamPath: "/api/events", url });
+ if (url.pathname === "/api/health" && !gate.auth) return send(200, { app: "openmausbot" });
+ if (!gate.auth) return send(gate.status, { error: gate.error });
+ return send(200, { kind: gate.auth.kind, id: gate.auth.kind === "session" ? gate.auth.session.id : null, source: requestSource(req), host: req.headers.host, via: gate.auth.kind === "session" ? gate.auth.via : null });
+ };
+}
+
+interface Server {
+ dir: string;
+ relay: FakeRelay;
+ sessions: SessionRegistry;
+ phoneRelay: PhoneRelay;
+ hostId: Buffer;
+ logs: string[];
+}
+
+async function startServer(input: Partial<PhoneRelayOptions> & { dir?: string; relay?: FakeRelay } = {}): Promise<Server> {
+ const { dir: givenDir, relay: givenRelay, ...overrides } = input;
+ const dir = givenDir ?? mkdtempSync(join(tmpdir(), "omb-phone-relay-"));
+ if (!givenDir) cleanup.push(() => removeTempDir(dir));
+ const relay = givenRelay ?? await startFakeRelay({ keys });
+ if (!givenRelay) cleanup.push(() => relay.close());
+ const sessions = new SessionRegistry({ file: join(dir, "sessions.json") });
+ cleanup.push(() => sessions.close());
+ const hostId = randomBytes(16);
+ const logs: string[] = [];
+ let phoneRelay: PhoneRelay | null = null;
+ phoneRelay = startPhoneRelay({
+ env: { OMB_PHONE_RELAY: "1", OMB_PHONE_RELAY_URL: relay.url },
+ dataDir: dir,
+ sessions,
+ handle: serverHandler(sessions, () => phoneRelay),
+ serverName: () => "VPS",
+ publicOrigin: () => null,
+ version: "0.1.152",
+ refusal: null,
+ fetchGrant: async () => grantFor(hostId),
+ log: (line) => logs.push(line),
+ ...overrides,
+ });
+ if (!phoneRelay) throw new Error(`the relay did not start: ${logs.join("; ")}`);
+ const started = phoneRelay;
+ cleanup.push(() => started.stop());
+ return { dir, relay, sessions, phoneRelay: started, hostId, logs };
+}
+
+function descriptorOf(link: string): { v: number; k: string; h?: string; r?: string[] } {
+ const value = new URL(link).searchParams.get("e2e");
+ if (!value) throw new Error("no e2e descriptor in the link");
+ return JSON.parse(fromB64u(value)!.toString("utf8"));
+}
+
+function viaRelay(server: Server, k: Buffer, token: string): Promise<E2ESession<never>> {
+ return dial({
+ url: `${server.relay.url}/v1/phone`,
+ transportByte: TRANSPORT_RELAY,
+ remoteStatic: k,
+ psk: psk(credentialHash(token), keyId(k)),
+ app: "test/1",
+ relay: { hostId: server.hostId, adm: admission(credentialHash(token), server.hostId) },
+ });
+}
+
+const connected = (server: Server) => waitFor(() => server.phoneRelay.status().relay === "connected", 5_000);
+
+async function pairPhone(server: Server): Promise<{ token: string; id: string; k: Buffer; session: E2ESession<never> }> {
+ const opened = server.sessions.openPairing({ scopes: ["client"] });
+ const link = server.phoneRelay.invite(opened.credential, "VPS", null);
+ if (!link) throw new Error("no relay invite");
+ const k = fromB64u(descriptorOf(link).k)!;
+ const session = await waitFor(() => viaRelay(server, k, opened.credential).catch(() => null), 6_000);
+ const paired = await http(session, "POST", "/api/pair", { body: JSON.stringify({ credential: opened.credential, deviceName: "Pixel" }), headers: { "content-type": "application/json" } });
+ if (paired.status !== 200) throw new Error(`pairing failed: ${paired.status} ${paired.body}`);
+ const reply = json(paired) as { token: string; device: { id: string } };
+ return { token: reply.token, id: reply.device.id, k, session };
+}
+
+describe("phones through MausBot Relay on a server", () => {
+ it("stays off unless asked for, and never runs where the desktop's companion or a Cloud carries phones", () => {
+ const dir = mkdtempSync(join(tmpdir(), "omb-phone-relay-off-"));
+ cleanup.push(() => removeTempDir(dir));
+ const sessions = new SessionRegistry({ file: join(dir, "sessions.json") });
+ cleanup.push(() => sessions.close());
+ const logs: string[] = [];
+ const base = { dataDir: dir, sessions, handle: () => {}, serverName: () => "VPS", publicOrigin: () => null, version: "0.1.152", log: (line: string) => logs.push(line) };
+ expect(startPhoneRelay({ ...base, env: {}, refusal: null })).toBeNull();
+ expect(startPhoneRelay({ ...base, env: { OMB_PHONE_RELAY: "true" }, refusal: null })).toBeNull();
+ expect(startPhoneRelay({ ...base, env: { OMB_PHONE_RELAY: "1" }, refusal: "a MausBot Cloud home" })).toBeNull();
+ expect(logs).toEqual(["phone relay: off on a MausBot Cloud home"]);
+ expect(() => statSync(join(dir, PHONE_RELAY_KEY_FILE))).toThrow();
+ });
+
+ it("pairs a phone by its QR through the relay, and the phone then signs in as its own session, never as this machine", async () => {
+ const server = await startServer();
+ await connected(server);
+ expect(server.logs).toContain(`phone relay: connected via ${NODE}`);
+ const opened = server.sessions.openPairing({ scopes: ["client"] });
+ const link = server.phoneRelay.invite(opened.credential, "VPS", null)!;
+ expect(link).toMatch(/^openmausbot:\/\/pair\?address=relay-only\.invalid%3A443&token=omb_pair_/);
+ const descriptor = descriptorOf(link);
+ expect(descriptor).toEqual({ v: 1, k: expect.any(String), h: b64u(server.hostId), r: [NODE] });
+ const k = fromB64u(descriptor.k)!;
+ // The open window's admission value reaches the relay, and nothing else does.
+ await waitFor(() => server.relay.admitted(b64u(server.hostId)).has(admissionHash(admission(credentialHash(opened.credential), server.hostId))));
+
+ const session = await waitFor(() => viaRelay(server, k, opened.credential).catch(() => null), 6_000);
+ expect(json(await http(session, "GET", "/api/health"))).toEqual({ app: "openmausbot" });
+ expect(await http(session, "GET", "/api/auth/session").then((reply) => [reply.status, json(reply).error])).toEqual([401, "pair this phone first"]);
+
+ const paired = await http(session, "POST", "/api/pair", { body: JSON.stringify({ credential: opened.credential, deviceName: "Pixel" }), headers: { "content-type": "application/json" } });
+ expect(paired.status).toBe(200);
+ const reply = json(paired) as { token: string; device: { id: string }; e2e: unknown };
+ expect(reply.e2e).toEqual(descriptor);
+ expect(server.phoneRelay.status()).toMatchObject({ relay: "connected", grant: "ok", phones: 1, maxPhones: MAX_RELAY_PHONES });
+ expect(JSON.parse(readFileSync(join(server.dir, PHONE_RELAY_PHONES_FILE), "utf8"))).toEqual({ v: 1, phones: [reply.device.id] });
+
+ // The same session now speaks for the new phone, with its own session.
+ expect(json(await http(session, "GET", "/api/auth/session", { token: reply.token }))).toEqual({ kind: "session", id: reply.device.id, source: `relay-${reply.device.id}`, host: "phone-relay.invalid", via: "bearer" });
+ // Whatever the phone writes, a relayed request is never this machine's.
+ const spoofed = await http(session, "GET", "/api/auth/session", { headers: { host: "127.0.0.1:8799", "x-openmausbot-cli-owner": "x", "x-forwarded-for": "127.0.0.1", cookie: "omb_session=x" } });
+ expect(spoofed.status).toBe(403);
+ expect(json(spoofed).error).toMatch(/proxy/);
+ // A token inside the session must be the one whose key opened it.
+ const other = server.sessions.issue({ label: "Laptop", scopes: ["admin", "client"] });
+ expect(await http(session, "GET", "/api/auth/session", { token: other.token }).then((r) => [r.status, json(r).error])).toEqual([401, "this connection belongs to another device"]);
+ expect(json(await http(session, "GET", "/api/companion/endpoints", { token: reply.token }))).toEqual({ serverName: "VPS", endpoints: [], e2e: descriptor });
+ session.shutdown();
+
+ // The window is spent; the phone's own key opens the next session, and a session the relay never admitted cannot.
+ const again = await waitFor(() => viaRelay(server, k, reply.token).catch(() => null), 6_000);
+ expect(json(await http(again, "GET", "/api/auth/session", { token: reply.token })).id).toBe(reply.device.id);
+ again.shutdown();
+ await expect(viaRelay(server, k, other.token)).rejects.toEqual(new SessionClosed(4404));
+ // The pairing session's admission lasts only as long as that session.
+ expect(await waitFor(async () => {
+ const outcome = await viaRelay(server, k, opened.credential).then((check) => (check.shutdown(), null), (error: unknown) => error);
+ return outcome instanceof SessionClosed && outcome.code === 4404 ? outcome : null;
+ }, 6_000)).toEqual(new SessionClosed(4404));
+ });
+
+ it("tells a removed phone so inside the encryption, then the relay admits it no more", async () => {
+ const server = await startServer();
+ await connected(server);
+ const phone = await pairPhone(server);
+ const live = await waitFor(() => viaRelay(server, phone.k, phone.token).catch(() => null), 6_000);
+ expect(server.sessions.revoke(phone.id)).toBe(true);
+ await live.closed;
+ expect(live.removed).toBe(true);
+ expect(server.phoneRelay.status().phones).toBe(0);
+ expect(JSON.parse(readFileSync(join(server.dir, PHONE_RELAY_PHONES_FILE), "utf8")).phones).toEqual([]);
+ const refused = await waitFor(async () => {
+ const outcome = await viaRelay(server, phone.k, phone.token).then((session) => (session.shutdown(), null), (error: unknown) => error);
+ return outcome instanceof SessionClosed && outcome.code === 4404 ? outcome : null;
+ }, 6_000);
+ expect(refused.code).toBe(4404);
+ });
+
+ it(`refuses a phone past the ${MAX_RELAY_PHONES} the relay admits for one server`, async () => {
+ const dir = mkdtempSync(join(tmpdir(), "omb-phone-relay-full-"));
+ cleanup.push(() => removeTempDir(dir));
+ const seed = new SessionRegistry({ file: join(dir, "sessions.json") });
+ const ids = Array.from({ length: MAX_RELAY_PHONES }, (_, n) => seed.issue({ label: `Phone ${n}`, scopes: ["client"] }).session.id);
+ seed.close();
+ writeFileSync(join(dir, PHONE_RELAY_PHONES_FILE), JSON.stringify({ v: 1, phones: [...ids, "a-session-long-gone"] }));
+ const server = await startServer({ dir });
+ await connected(server);
+ expect(server.phoneRelay.status().phones).toBe(MAX_RELAY_PHONES);
+ expect(JSON.parse(readFileSync(join(dir, PHONE_RELAY_PHONES_FILE), "utf8")).phones).toEqual(ids);
+ const opened = server.sessions.openPairing({ scopes: ["client"] });
+ const k = fromB64u(descriptorOf(server.phoneRelay.invite(opened.credential, "VPS", null)!).k)!;
+ const session = await waitFor(() => viaRelay(server, k, opened.credential).catch(() => null), 6_000);
+ const refused = await http(session, "POST", "/api/pair", { body: JSON.stringify({ credential: opened.credential }), headers: { "content-type": "application/json" } });
+ expect(refused.status).toBe(409);
+ expect(server.sessions.openPairings()).toHaveLength(1);
+ session.shutdown();
+ });
+
+ it("keeps its connection key, owner-only, across restarts, and never replaces one it cannot read", async () => {
+ const dir = mkdtempSync(join(tmpdir(), "omb-phone-relay-key-"));
+ cleanup.push(() => removeTempDir(dir));
+ const relay = await startFakeRelay({ keys });
+ cleanup.push(() => relay.close());
+ const first = await startServer({ dir, relay });
+ await connected(first);
+ const key = (server: Server) => descriptorOf(server.phoneRelay.invite(server.sessions.openPairing().credential, "VPS", null)!).k;
+ const k = key(first);
+ if (process.platform !== "win32") expect(statSync(join(dir, PHONE_RELAY_KEY_FILE)).mode & 0o777).toBe(0o600);
+ first.phoneRelay.stop();
+ first.sessions.close();
+ const second = await startServer({ dir, relay });
+ await connected(second);
+ expect(key(second)).toBe(k);
+ second.phoneRelay.stop();
+ second.sessions.close();
+
+ writeFileSync(join(dir, PHONE_RELAY_KEY_FILE), "{\"v\":1}\n");
+ const logs: string[] = [];
+ const sessions = new SessionRegistry({ file: join(dir, "sessions.json") });
+ cleanup.push(() => sessions.close());
+ expect(startPhoneRelay({ env: { OMB_PHONE_RELAY: "1" }, dataDir: dir, sessions, handle: () => {}, serverName: () => "VPS", publicOrigin: () => null, version: "0.1.152", refusal: null, log: (line) => logs.push(line) })).toBeNull();
+ expect(logs[0]).toMatch(/^phone relay: off: .*is not a connection key/);
+ expect(readFileSync(join(dir, PHONE_RELAY_KEY_FILE), "utf8")).toBe("{\"v\":1}\n");
+ });
+
+ it("says why phones can't pair yet, and makes no relay link until it can", async () => {
+ const signedOut = await startServer({ fetchGrant: async () => Promise.reject(Object.assign(new Error("signed out"), { code: "signed_out" })) });
+ await waitFor(() => signedOut.phoneRelay.status().grant === "signed-out");
+ expect(signedOut.phoneRelay.status()).toMatchObject({ relay: "off", grant: "signed-out" });
+ expect(signedOut.phoneRelay.invite(signedOut.sessions.openPairing().credential, "VPS", null)).toBeNull();
+
+ const unavailable = await startServer({ fetchGrant: async () => Promise.reject(Object.assign(new Error("relay_unavailable"), { code: "relay_unavailable", status: 503 })) });
+ await waitFor(() => unavailable.phoneRelay.status().grant === "unavailable");
+ expect(unavailable.phoneRelay.status().relay).toBe("off");
+
+ // The relay itself unreachable: it keeps dialling, and a link still works the moment it connects.
+ const gone = await startFakeRelay({ keys });
+ await gone.close();
+ const unreachable = await startServer({ relay: gone, env: { OMB_PHONE_RELAY: "1", OMB_PHONE_RELAY_URL: gone.url } });
+ await waitFor(() => unreachable.phoneRelay.status().grant === "ok");
+ expect(unreachable.phoneRelay.status().relay).toBe("connecting");
+ });
+
+ it("names the server's public HTTPS address for a phone without the encrypted connection", async () => {
+ const server = await startServer();
+ await connected(server);
+ const link = new URL(server.phoneRelay.invite(server.sessions.openPairing().credential, "VPS", "https://maus.example.com")!);
+ expect(link.searchParams.get("address")).toBe("maus.example.com:443");
+ expect(JSON.parse(fromB64u(link.searchParams.get("endpoints")!)!.toString("utf8"))).toEqual([{ url: "https://maus.example.com", kind: "hosted", priority: 0 }]);
+ expect(new URL(server.phoneRelay.invite(server.sessions.openPairing().credential, "VPS", "http://localhost:8080")!).searchParams.get("address")).toBe("relay-only.invalid:443");
+ });
+
+ it("never asks for a relay token on a machine that holds or needs a tunnel", async () => {
+ const dir = mkdtempSync(join(tmpdir(), "omb-phone-relay-tunnel-"));
+ cleanup.push(() => removeTempDir(dir));
+ const account = join(dir, "tunnel-account.json");
+ expect(tunnelHolder({}, dir)).toBeNull();
+ writeFileSync(account, JSON.stringify({ companionInstallationCredential: "omb_install_x" }));
+ expect(tunnelHolder({}, dir)).toBeNull();
+ expect(tunnelHolder({ OMB_SERVES_TUNNEL: "1", OMB_TUNNEL_SOCKET: join(dir, "t.sock") }, dir)).toBe("this server runs with --tunnel");
+ // Docker's Caddy reaches the server over a socket too: that is no tunnel.
+ expect(tunnelHolder({ OMB_TUNNEL_SOCKET: "/run/openmausbot/http.sock" }, dir)).toBeNull();
+ expect(tunnelHolder({ OMB_INSTALLATION_CREDENTIAL: "omb_install_y" }, dir)).toMatch(/^OMB_INSTALLATION_CREDENTIAL is set/);
+ writeFileSync(account, JSON.stringify({ companionInstallationCredential: "omb_install_x", managedCompanionEndpointUrl: "https://c-0123456789abcdef0123456789abcdef.openmausbot.com" }));
+ expect(tunnelHolder({}, dir)).toMatch(/holds a tunnel address/);
+ writeFileSync(account, "not json");
+ expect(tunnelHolder({}, dir)).toMatch(/could not be read/);
+
+ // `serve --tunnel` with OMB_PHONE_RELAY=1 in the environment, and a fleet container: off, and saying why.
+ writeFileSync(account, JSON.stringify({ companionInstallationCredential: "omb_install_x" }));
+ for (const env of [{ OMB_PHONE_RELAY: "1", OMB_SERVES_TUNNEL: "1", OMB_TUNNEL_SOCKET: join(dir, "t.sock") }, { OMB_PHONE_RELAY: "1", OMB_INSTALLATION_CREDENTIAL: "omb_install_y" }]) {
+ let asked = 0;
+ const logs: string[] = [];
+ const sessions = new SessionRegistry({ file: join(dir, "sessions.json") });
+ cleanup.push(() => sessions.close());
+ const relay = startPhoneRelay({ env, dataDir: dir, sessions, handle: () => {}, serverName: () => "VPS", publicOrigin: () => null, version: "0.1.152", refusal: null, fetchGrant: async () => (asked += 1, {}), log: (line) => logs.push(line) })!;
+ expect(relay.status()).toMatchObject({ relay: "off", grant: "tunnel", reason: expect.any(String) });
+ expect(relay.invite(sessions.openPairing().credential, "VPS", null)).toBeNull();
+ expect(logs[0]).toMatch(/^phone relay: off: .*login --relay/);
+ await new Promise((resolve) => setTimeout(resolve, 50));
+ expect(asked).toBe(0);
+ expect(() => statSync(join(dir, PHONE_RELAY_KEY_FILE))).toThrow();
+ sessions.close();
+ }
+ });
+
+ it("pairs only with the QR's credential: a typed code and the browser's pairing route are refused", async () => {
+ const server = await startServer();
+ await connected(server);
+ const opened = server.sessions.openPairing({ scopes: ["client"] });
+ const k = fromB64u(descriptorOf(server.phoneRelay.invite(opened.credential, "VPS", null)!).k)!;
+ const session = await waitFor(() => viaRelay(server, k, opened.credential).catch(() => null), 6_000);
+ const asJson = { "content-type": "application/json" };
+ const code = await http(session, "POST", "/api/pair", { body: JSON.stringify({ code: opened.code }), headers: asJson });
+ expect([code.status, json(code).error]).toEqual([400, "pair a phone with its QR code"]);
+ expect((await http(session, "POST", "/api/auth/pair", { body: JSON.stringify({ code: opened.code }), headers: asJson })).status).toBe(404);
+ expect(server.sessions.openPairings()).toHaveLength(1);
+ expect((await http(session, "POST", "/api/pair", { body: JSON.stringify({ credential: opened.credential }), headers: asJson })).status).toBe(200);
+ });
+
+ it("keeps one phone's wrong credentials from locking pairing for everyone, and still locks out a guesser", async () => {
+ const server = await startServer();
+ await connected(server);
+ const phone = await pairPhone(server);
+ phone.session.shutdown();
+ const wrong = () => JSON.stringify({ credential: `omb_pair_${randomBytes(32).toString("base64url")}` });
+ const asJson = { "content-type": "application/json" };
+ const paired = await waitFor(() => viaRelay(server, phone.k, phone.token).catch(() => null), 6_000);
+ const statuses = [];
+ for (let n = 0; n < 6; n += 1) statuses.push((await http(paired, "POST", "/api/pair", { token: phone.token, body: wrong(), headers: asJson })).status);
+ expect(statuses).toEqual([401, 401, 401, 401, 401, 429]);
+ // Another phone pairs at once.
+ const second = server.sessions.openPairing({ scopes: ["client"] });
+ server.phoneRelay.invite(second.credential, "VPS", null);
+ const other = await waitFor(() => viaRelay(server, phone.k, second.credential).catch(() => null), 6_000);
+ expect((await http(other, "POST", "/api/pair", { body: JSON.stringify({ credential: second.credential }), headers: asJson })).status).toBe(200);
+ // Whoever holds a pairing window's QR and guesses is locked out on that window, in every session it opens.
+ const third = server.sessions.openPairing({ scopes: ["client"] });
+ server.phoneRelay.invite(third.credential, "VPS", null);
+ const guesser = await waitFor(() => viaRelay(server, phone.k, third.credential).catch(() => null), 6_000);
+ for (let n = 0; n < 5; n += 1) await http(guesser, "POST", "/api/pair", { body: wrong(), headers: asJson });
+ guesser.shutdown();
+ const again = await waitFor(() => viaRelay(server, phone.k, third.credential).catch(() => null), 6_000);
+ expect((await http(again, "POST", "/api/pair", { body: JSON.stringify({ credential: third.credential }), headers: asJson })).status).toBe(429);
+ });
+
+ it(`holds at most ${MAX_SESSIONS_PER_PHONE} live sessions per phone, closing its oldest`, async () => {
+ const server = await startServer();
+ await connected(server);
+ const phone = await pairPhone(server);
+ phone.session.shutdown();
+ const sessions: E2ESession<never>[] = [];
+ for (let n = 0; n <= MAX_SESSIONS_PER_PHONE; n += 1) sessions.push(await waitFor(() => viaRelay(server, phone.k, phone.token).catch(() => null), 6_000));
+ await sessions[0].closed;
+ await new Promise((resolve) => setTimeout(resolve, 50));
+ expect(sessions.slice(1).map((session) => session.state)).toEqual(Array(MAX_SESSIONS_PER_PHONE).fill("open"));
+ expect((await http(sessions.at(-1)!, "GET", "/api/auth/session", { token: phone.token })).status).toBe(200);
+ });
+
+ it("ends a stream that stalls in its request headers or body", async () => {
+ const server = await startServer({ streamDeadlines: { headersMs: 300, requestMs: 600 } });
+ await connected(server);
+ const phone = await pairPhone(server);
+ const ended = (stream: ReturnType<E2ESession<never>["openStream"]>) => new Promise<number>((resolve) => {
+ const started = Date.now();
+ stream.on("data", () => {});
+ stream.on("error", () => {});
+ stream.once("end", () => resolve(Date.now() - started));
+ });
+ const headers = phone.session.openStream();
+ const headersEnded = ended(headers);
+ headers.write("GET /api/health HTTP/1.1\r\nHost: phone\r\n");
+ expect(await headersEnded).toBeGreaterThanOrEqual(250);
+ const body = phone.session.openStream();
+ const bodyEnded = ended(body);
+ body.write(`POST /api/pair HTTP/1.1\r\nHost: phone\r\nAuthorization: Bearer ${phone.token}\r\nContent-Type: application/json\r\nContent-Length: 100\r\n\r\n{"a"`);
+ expect(await bodyEnded).toBeGreaterThanOrEqual(550);
+ expect(phone.session.state).toBe("open");
+
+ // A long answer to a request that was complete is never cut: an event stream lives far past the body deadline.
+ const listening = phone.session.openStream();
+ let ticks = 0;
+ let gone = false;
+ listening.on("data", (chunk: Buffer) => (ticks += chunk.toString().split("data: tick").length - 1));
+ listening.on("error", () => {});
+ listening.once("end", () => (gone = true));
+ listening.write("GET /api/test-stream HTTP/1.1\r\nHost: phone\r\n\r\n");
+ await new Promise((resolve) => setTimeout(resolve, 2_000));
+ expect(gone).toBe(false);
+ const before = ticks;
+ await waitFor(() => ticks > before, 1_000);
+ expect(ticks).toBeGreaterThan(10);
+ listening.destroy();
+ expect((await http(phone.session, "GET", "/api/health")).status).toBe(200);
+ });
+
+ it("accepts a stream ticket only from the phone it belongs to", async () => {
+ const server = await startServer();
+ await connected(server);
+ const phone = await pairPhone(server);
+ const other = server.sessions.issue({ label: "Laptop", scopes: ["admin", "client"] });
+ const theirs = server.sessions.issueStreamTicket(other.session.id).ticket;
+ const refused = await http(phone.session, "GET", `/api/events?ticket=${theirs}`);
+ expect([refused.status, json(refused).error]).toEqual([401, "this connection belongs to another device"]);
+ expect(server.sessions.ticketOwner(theirs)).toBe(other.session.id);
+ const own = server.sessions.issueStreamTicket(phone.id).ticket;
+ expect(json(await http(phone.session, "GET", `/api/events?ticket=${own}`))).toMatchObject({ kind: "session", id: phone.id, via: "ticket" });
+ });
+
+ it("reports a grant only once it is valid, and keeps one it holds through a passing failure", async () => {
+ const invalid = await startServer({ fetchGrant: async () => ({ token: "not.a-grant" }) });
+ await waitFor(() => invalid.phoneRelay.status().grant === "failed");
+ expect(invalid.phoneRelay.status().relay).toBe("off");
+
+ // A token the relay refuses (4401) makes the server ask again; that request fails, and the grant it holds stands.
+ const stranger = generateKeyPairSync("ed25519").privateKey;
+ let asked = 0;
+ const holding = await startServer({
+ fetchGrant: async () => {
+ asked += 1;
+ if (asked > 1) throw Object.assign(new Error("fetch failed"), { code: "network" });
+ const iat = Math.floor(Date.now() / 1000);
+ const token = mintRelayToken({ v: 1, kid: "k1", hid: b64u(randomBytes(16)), iid: "test-install", iat, exp: iat + 43_200 }, stranger);
+ return { token, hostId: b64u(randomBytes(16)), nodes: [NODE], expiresAt: (iat + 43_200) * 1000, refreshAfter: (iat + 3_600) * 1000 };
+ },
+ });
+ await waitFor(() => asked >= 2, 6_000);
+ await new Promise((resolve) => setTimeout(resolve, 50));
+ expect(holding.phoneRelay.status()).toMatchObject({ grant: "ok", relay: "connecting" });
+ });
+});
diff --git a/server/phone-relay.ts b/server/phone-relay.ts
new file mode 100644
index 0000000000..b313e4b211
--- /dev/null
+++ b/server/phone-relay.ts
@@ -0,0 +1,384 @@
+// `serve --relay`: phones reach this server through MausBot Relay, end-to-end encrypted as they reach the desktop app.
+// The server dials out to the relay, the phone dials the relay, and the relay splices sealed bytes it cannot open. Every
+// encrypted stream lands in the server's own request handler as a remote request, so a phone signs in with its own session.
+import { AsyncLocalStorage } from "node:async_hooks";
+import { createHash, timingSafeEqual } from "node:crypto";
+import { existsSync, readFileSync } from "node:fs";
+import type { IncomingMessage, ServerResponse } from "node:http";
+import { join } from "node:path";
+import type { Duplex } from "node:stream";
+
+import { phonePairingLink, type CompanionEndpoint } from "../shared/pairing-link.ts";
+import { relayBaseUrlOverride } from "../companion/src/e2e/config.ts";
+import { b64u, fromB64u } from "../companion/src/e2e/credentials.ts";
+import type { E2EDescriptor } from "../companion/src/e2e/descriptor.ts";
+import { generateKeyPair, keyPairFromPrivate, TRANSPORT_RELAY, type KeyPair } from "../companion/src/e2e/noise.ts";
+import { createE2EOrigin, e2eContextOf, type E2EOriginDeadlines } from "../companion/src/e2e/origin.ts";
+import { E2ERegistry, type E2EContext, type E2EDevices, type Peer } from "../companion/src/e2e/registry.ts";
+import { RelayClient, type RelayStatus } from "../companion/src/e2e/relay-client.ts";
+import { COMPANION_INSTALLATION_CREDENTIAL_FIELD, resolveCompanionControlPlaneURL } from "../electron/companion-account-service.mjs";
+import { createControlPlaneClient } from "../electron/control-plane-client.mjs";
+import { MANAGED_COMPANION_ENDPOINT_FIELD } from "../electron/managed-companion-tunnel.mjs";
+import { createRelayTokenService, validRelayGrant, type RelayGrant } from "../electron/relay-token.mjs";
+import { isLoopbackHost } from "../electron/server-address.mjs";
+import { writeFileAtomic } from "./atomic.ts";
+import { bearerToken, PROXY_HEADERS } from "./request-auth.ts";
+import { isPairingCredential, type SessionRegistry } from "./sessions.ts";
+import { describeTunnelAccount, FLEET_CREDENTIAL_ENV, fleetCredential, openTunnelCredentials } from "./tunnel.ts";
+import type { E2ESession } from "../companion/src/e2e/session.ts";
+
+export const PHONE_RELAY_ENV = "OMB_PHONE_RELAY";
+/** `serve --tunnel` sets it. OMB_TUNNEL_SOCKET alone is no tunnel: Docker's Caddy reaches the server over that socket. */
+export const SERVES_TUNNEL_ENV = "OMB_SERVES_TUNNEL";
+export const PHONE_RELAY_KEY_FILE = "phone-relay-key.json";
+export const PHONE_RELAY_PHONES_FILE = "phone-relay-phones.json";
+/** The relay admits 32 per host; 20 phones, 2 pairing windows and the live pairing sessions stay under it. */
+export const MAX_RELAY_PHONES = 20;
+const MAX_PAIRING_WINDOWS = 2;
+/** A removed phone hears GoAway(3) inside its session before the relay drops it from the admission set. */
+const ADMISSION_SETTLE_MS = 300;
+/** RFC 6761 reserves `.invalid`: a QR with no public address names a host that never resolves, so only the relay works. */
+const RELAY_ONLY_ADDRESS = "relay-only.invalid";
+/** Live sessions one phone may hold, and sessions on one pairing window: the relay carries 16 per server. */
+export const MAX_SESSIONS_PER_PHONE = 4;
+const MAX_SESSIONS_PER_WINDOW = 2;
+const STREAM_DEADLINES: E2EOriginDeadlines = { headersMs: 30_000, requestMs: 300_000 };
+const PAIRING_SESSION_ROUTES = new Set(["POST /api/pair", "GET /api/health"]);
+
+/** `tunnel`: this machine holds or needs a tunnel address, so it never asks for a relay token (`reason` says why). */
+export type PhoneRelayGrantState = "waiting" | "ok" | "signed-out" | "unavailable" | "failed" | "tunnel";
+
+export interface PhoneRelayStatus {
+ relay: RelayStatus;
+ node: string | null;
+ grant: PhoneRelayGrantState;
+ reason?: string;
+ phones: number;
+ maxPhones: number;
+}
+
+export interface PhoneRelay {
+ status(): PhoneRelayStatus;
+ /** The phone-app link for one pairing credential, or null until the relay identity is known. */
+ invite(credential: string, name: string | undefined, publicOrigin: string | null): string | null;
+ /** What `POST /api/pair` adds for a phone that paired through the relay. */
+ pairedOver(req: IncomingMessage): { e2e?: E2EDescriptor };
+ /** Why `POST /api/pair` refuses this input, or null: through the relay only the QR's credential pairs, never a code. */
+ pairingRefusal(req: IncomingMessage, input: string): string | null;
+ stop(): void;
+}
+
+type Handler = (req: IncomingMessage, res: ServerResponse) => unknown;
+
+export interface PhoneRelayOptions {
+ env: NodeJS.ProcessEnv;
+ dataDir: string;
+ sessions: Pick<SessionRegistry, "bearerDigests" | "pairingDigests" | "onSessionIssued" | "onSessionRevoked" | "list" | "ticketOwner">;
+ handle: Handler;
+ serverName(): string;
+ publicOrigin(): string | null;
+ version: string;
+ /** Why this server never runs the relay (a Cloud home, a hosted workspace, the desktop app), or null. */
+ refusal: string | null;
+ /** Tests: the control plane's relay-token answer, and shorter stream deadlines. */
+ fetchGrant?: (devices: { e2e: number; legacy: number }) => Promise<unknown>;
+ streamDeadlines?: E2EOriginDeadlines;
+ log?: (line: string) => void;
+}
+
+const sha256Hex = (value: string) => createHash("sha256").update(value).digest("hex");
+
+function sameDigest(a: string, b: string): boolean {
+ const left = Buffer.from(a, "hex");
+ const right = Buffer.from(b, "hex");
+ return left.length === 32 && left.length === right.length && timingSafeEqual(left, right);
+}
+
+/** The pairing lockout's source for a relayed request: the device, or the pairing window the session holds. Every relayed
+ * request comes from the relay's address, and one phone must not lock pairing for every other. */
+function sourceOf(peer: Peer): string {
+ return peer.kind === "device" ? `relay-${peer.id.slice(0, 48)}` : `relay-window-${(peer.admHash ?? "none").slice(0, 22)}`;
+}
+
+/** Created once with mode 0600 and never replaced: every paired phone pinned its public half from the QR. */
+export function phoneRelayKey(dataDir: string): KeyPair {
+ const file = join(dataDir, PHONE_RELAY_KEY_FILE);
+ if (existsSync(file)) {
+ const parsed = JSON.parse(readFileSync(file, "utf8")) as { v?: unknown; privateKey?: unknown };
+ const raw = parsed.v === 1 && typeof parsed.privateKey === "string" ? fromB64u(parsed.privateKey) : null;
+ if (!raw || raw.length !== 32) throw new Error(`${file} is not a connection key; phones paired through the relay need it, so it was left as it is`);
+ return keyPairFromPrivate(raw);
+ }
+ const key = generateKeyPair();
+ writeFileAtomic(file, `${JSON.stringify({ v: 1, privateKey: b64u(key.privateKey) })}\n`, { mode: 0o600 });
+ return key;
+}
+
+function readPhones(dataDir: string): Set<string> {
+ try {
+ const parsed = JSON.parse(readFileSync(join(dataDir, PHONE_RELAY_PHONES_FILE), "utf8")) as { v?: unknown; phones?: unknown };
+ return new Set(parsed.v === 1 && Array.isArray(parsed.phones) ? parsed.phones.filter((id): id is string => typeof id === "string" && id.length <= 128) : []);
+ } catch {
+ return new Set();
+ }
+}
+
+/** The way in a QR names besides the relay: this server's public HTTPS address, which a phone without the encrypted
+ * connection uses and one with it never does, or a name that never resolves. */
+function qrRoute(publicOrigin: string | null): { address: string; port: number; hosts?: string[]; endpoints?: CompanionEndpoint[] } {
+ try {
+ const url = publicOrigin ? new URL(publicOrigin) : null;
+ if (url?.protocol === "https:" && !isLoopbackHost(url.host)) {
+ return { address: url.hostname, port: url.port ? Number(url.port) : 443, hosts: [url.hostname], endpoints: [{ url: url.origin, kind: "hosted", priority: 0 }] };
+ }
+ } catch {
+ // A malformed address is no way in.
+ }
+ return { address: RELAY_ONLY_ADDRESS, port: 443 };
+}
+
+function reply(res: ServerResponse, status: number, body: unknown): void {
+ const text = JSON.stringify(body);
+ res.writeHead(status, { "content-type": "application/json; charset=utf-8", "content-length": Buffer.byteLength(text), "cache-control": "no-store" });
+ res.end(text);
+}
+
+/** Why this machine must not take a relay token, or null. Security: the control plane does not yet tell a server from a
+ * desktop, and gives back the tunnel of any installation that recently took a relay token, then refuses it another. So
+ * a machine that serves a tunnel, runs on a fleet credential, or holds a tunnel address from `login` never asks. */
+export function tunnelHolder(env: NodeJS.ProcessEnv, dataDir: string): string | null {
+ if (env[SERVES_TUNNEL_ENV] === "1") return "this server runs with --tunnel";
+ if (fleetCredential(env)) return `${FLEET_CREDENTIAL_ENV} is set, and a fleet installation keeps its tunnel`;
+ const account = openTunnelCredentials(dataDir);
+ if (account.status === "unavailable") return `${account.file} could not be read, so this machine may hold a tunnel address`;
+ const document = account.read();
+ if (describeTunnelAccount(document).address || document[MANAGED_COMPANION_ENDPOINT_FIELD]) return "this machine holds a tunnel address from `openmausbot login`";
+ return null;
+}
+
+function offForTunnel(reason: string): PhoneRelay {
+ return {
+ status: () => ({ relay: "off", node: null, grant: "tunnel", reason, phones: 0, maxPhones: MAX_RELAY_PHONES }),
+ invite: () => null,
+ pairedOver: () => ({}),
+ pairingRefusal: () => null,
+ stop: () => {},
+ };
+}
+
+const TUNNEL_HELD = "tunnel_held";
+
+/** Null unless OMB_PHONE_RELAY=1, and when it cannot run here: the server works on without it either way. */
+export function startPhoneRelay(options: PhoneRelayOptions): PhoneRelay | null {
+ if (options.env[PHONE_RELAY_ENV] !== "1") return null;
+ const log = options.log ?? ((line: string) => console.log(line));
+ if (options.refusal) {
+ log(`phone relay: off on ${options.refusal}`);
+ return null;
+ }
+ const { sessions, dataDir } = options;
+ const holder = tunnelHolder(options.env, dataDir);
+ if (holder) {
+ log(`phone relay: off: ${holder}. Use the relay on a machine signed in with \`openmausbot login --relay\`, which holds no tunnel address.`);
+ return offForTunnel(holder);
+ }
+ let key: KeyPair;
+ try {
+ key = phoneRelayKey(dataDir);
+ } catch (error) {
+ log(`phone relay: off: ${error instanceof Error ? error.message : String(error)}`);
+ return null;
+ }
+ const phones = readPhones(dataDir);
+ const savePhones = () => writeFileAtomic(join(dataDir, PHONE_RELAY_PHONES_FILE), `${JSON.stringify({ v: 1, phones: [...phones] })}\n`, { mode: 0o600 });
+ const devices: E2EDevices = {
+ records: () => sessions.bearerDigests(phones),
+ pairingWindows: () => sessions.pairingDigests(MAX_PAIRING_WINDOWS).map((tokenHash) => ({ tokenHash })),
+ confirm: () => {},
+ markE2E: () => {},
+ };
+ const live = new Set(devices.records().map((record) => record.id));
+ if (live.size !== phones.size) {
+ for (const id of phones) if (!live.has(id)) phones.delete(id);
+ savePhones();
+ }
+ const e2e = new E2ERegistry(devices);
+ e2e.setKey(key);
+ log(`phone relay: on, connection key ${b64u(key.publicKey).slice(0, 8)}…`);
+
+ const pairing = new AsyncLocalStorage<E2EContext>();
+ let relay: RelayClient | null = null;
+ let grantState: PhoneRelayGrantState = "waiting";
+ let tunnelReason: string | null = null;
+ const baseUrl = relayBaseUrlOverride(options.env.OMB_PHONE_RELAY_URL);
+ const descriptor = () => e2e.descriptor(null);
+
+ const counts = () => {
+ const e2eCount = devices.records().length;
+ // A server's other devices reach it some other way: they are the devices the relay does not carry.
+ return { e2e: Math.min(e2eCount, 100), legacy: Math.min(Math.max(sessions.list().length - e2eCount, 0), 100) };
+ };
+ const controlPlane = resolveCompanionControlPlaneURL({ isPackaged: true, environment: options.env });
+ const client = controlPlane ? createControlPlaneClient({ baseURL: controlPlane }) : null;
+ const fetchGrant = options.fetchGrant ?? (async (devicesNow: { e2e: number; legacy: number }) => {
+ const document = openTunnelCredentials(dataDir).read();
+ const stored = document[COMPANION_INSTALLATION_CREDENTIAL_FIELD];
+ tunnelReason = tunnelHolder(options.env, dataDir);
+ if (tunnelReason) throw Object.assign(new Error(tunnelReason), { code: TUNNEL_HELD });
+ const credential = typeof stored === "string" ? stored : null;
+ if (!client || !credential) throw Object.assign(new Error("signed out"), { code: "signed_out" });
+ return client.relayToken(credential, { appVersion: options.version, devices: devicesNow, kind: "server" });
+ });
+
+ const tokens = createRelayTokenService({
+ fetchGrant: async () => {
+ try {
+ const grant = await fetchGrant(counts());
+ if (!validRelayGrant(grant)) throw Object.assign(new Error("invalid relay grant"), { code: "invalid_response" });
+ grantState = "ok";
+ return grant;
+ } catch (error) {
+ const failure = error as { code?: unknown; status?: unknown };
+ if (failure.code === TUNNEL_HELD) applyGrant(null);
+ const current = tokens.grant;
+ grantState = failure.code === TUNNEL_HELD ? "tunnel"
+ : failure.code === "relay_unavailable" ? "unavailable"
+ : failure.code === "signed_out" || failure.status === 401 ? "signed-out"
+ : current && current.expiresAt > Date.now() && relay ? "ok" : "failed";
+ throw error;
+ }
+ },
+ onGrant: (grant) => applyGrant(grant),
+ log: (line) => log(`phone relay: ${line}`),
+ });
+
+ const origin = createE2EOrigin((req, res) => relayed(req, res), (_req, socket) => refuseUpgrade(socket), options.streamDeadlines ?? STREAM_DEADLINES);
+
+ /** One phone (or one pairing window) holds a few live sessions; a new one closes its oldest, so a phone that lost its
+ * sessions without the relay noticing can still come back. */
+ const held = new Map<string, E2ESession<Peer>[]>();
+ const holdSession = (session: E2ESession<Peer>) => {
+ const peer = session.peer;
+ if (!peer) return;
+ const key = peer.kind === "device" ? `device ${peer.id}` : `window ${peer.admHash}`;
+ const list = held.get(key) ?? [];
+ list.push(session);
+ held.set(key, list);
+ const limit = peer.kind === "device" ? MAX_SESSIONS_PER_PHONE : MAX_SESSIONS_PER_WINDOW;
+ while (list.length > limit) list.shift()!.shutdown();
+ void session.closed.then(() => {
+ const index = list.indexOf(session);
+ if (index >= 0) list.splice(index, 1);
+ if (!list.length && held.get(key) === list) held.delete(key);
+ });
+ };
+
+ function applyGrant(grant: RelayGrant | null): void {
+ const hostId = grant ? fromB64u(grant.hostId) : null;
+ if (!grant || !hostId || !relay || !e2e.relay?.hostId.equals(hostId)) {
+ relay?.stop();
+ relay = null;
+ }
+ e2e.setRelay(grant && hostId ? { hostId, nodes: grant.nodes } : null);
+ if (!grant || !hostId) return;
+ if (relay) return relay.setToken(grant.token, grant.nodes);
+ relay = new RelayClient({
+ nodes: grant.nodes,
+ token: grant.token,
+ admissionSet: () => e2e.admissionSet(),
+ accept: (transport) => {
+ const session = e2e.accept(transport, TRANSPORT_RELAY, "relay", (context) => origin.connect(context));
+ void session?.ready.then(() => holdSession(session), () => {});
+ return session && { receive: (data, binary) => session.receive(data, binary), transportClosed: (code) => session.transportClosed(code) };
+ },
+ tokenRejected: () => void tokens.refreshNow(),
+ statusChanged: (status, node) => log(`phone relay: ${status}${node ? ` via ${node}` : ""}`),
+ baseUrl,
+ });
+ relay.start();
+ }
+
+ function refuseUpgrade(socket: Duplex): void {
+ socket.end("HTTP/1.1 501 Not Implemented\r\nconnection: close\r\ncontent-length: 0\r\n\r\n");
+ }
+
+ /** Security: a relayed request is never this machine's. It has no peer address, which the request gate always treats as
+ * remote, and whatever Host, proxy, cookie or owner headers the phone wrote are replaced: it needs a session of its own. */
+ function scrub(req: IncomingMessage, peer: Peer): void {
+ for (const name of Object.keys(req.headers)) {
+ if (name === "cookie" || name.startsWith("x-openmausbot-") || (PROXY_HEADERS as readonly string[]).includes(name)) delete req.headers[name];
+ }
+ req.headers.host = "phone-relay.invalid";
+ req.headers["x-forwarded-for"] = sourceOf(peer);
+ }
+
+ function relayed(req: IncomingMessage, res: ServerResponse): void {
+ const context = e2eContextOf(req.socket);
+ if (!context) return reply(res, 500, { error: "not a relayed request" });
+ const peer = context.peer;
+ scrub(req, peer);
+ const path = (req.url ?? "/").split("?")[0];
+ const method = req.method ?? "GET";
+ if (method === "POST" && path === "/api/auth/pair") return reply(res, 404, { error: "pair a phone with its QR code" });
+ if (peer.kind === "pairing") {
+ if (!PAIRING_SESSION_ROUTES.has(`${method} ${path}`)) return reply(res, 401, { error: "pair this phone first" });
+ if (method === "POST" && devices.records().length >= MAX_RELAY_PHONES) {
+ return reply(res, 409, { error: `This server has ${MAX_RELAY_PHONES} phones on MausBot Relay. Remove one (openmausbot devices revoke ID), then pair again.` });
+ }
+ } else {
+ const bearer = bearerToken(req.headers.authorization);
+ const own = devices.records().find((record) => record.id === peer.id);
+ if (bearer && (!own || !sameDigest(own.tokenHash, sha256Hex(bearer)))) return reply(res, 401, { error: "this connection belongs to another device" });
+ const ticket = new URL(req.url ?? "/", "http://phone-relay.invalid").searchParams.get("ticket");
+ if (ticket && sessions.ticketOwner(ticket) !== peer.id) return reply(res, 401, { error: "this connection belongs to another device" });
+ if (method === "GET" && path === "/api/companion/endpoints") {
+ if (!bearer) return reply(res, 401, { error: "pair this device first" });
+ const route = qrRoute(options.publicOrigin());
+ return reply(res, 200, { serverName: options.serverName(), endpoints: route.endpoints ?? [], ...(descriptor() ? { e2e: descriptor() } : {}) });
+ }
+ }
+ void pairing.run(context, () => Promise.resolve(options.handle(req, res))).catch(() => {
+ if (!res.headersSent) reply(res, 500, { error: "request failed" });
+ else res.destroy();
+ });
+ }
+
+ const stopIssued = sessions.onSessionIssued((session) => {
+ const context = pairing.getStore();
+ if (context?.peer.kind !== "pairing") return;
+ phones.add(session.id);
+ savePhones();
+ e2e.paired(context, session.id);
+ relay?.refreshAdmission();
+ });
+ const stopRevoked = sessions.onSessionRevoked((sessionId) => {
+ if (!phones.delete(sessionId)) return;
+ savePhones();
+ e2e.closeDevice(sessionId);
+ setTimeout(() => relay?.refreshAdmission(), ADMISSION_SETTLE_MS).unref();
+ });
+ e2e.onAdmissionChange(() => relay?.refreshAdmission());
+ tokens.start();
+
+ return {
+ status: () => ({ relay: relay?.status ?? "off", node: relay?.node ?? null, grant: grantState, ...(grantState === "tunnel" && tunnelReason ? { reason: tunnelReason } : {}), phones: devices.records().length, maxPhones: MAX_RELAY_PHONES }),
+ invite(credential, name, publicOrigin) {
+ const current = descriptor();
+ if (!current?.h || !current.r) return null;
+ relay?.refreshAdmission();
+ return phonePairingLink({ ...qrRoute(publicOrigin), token: credential, name, e2e: current });
+ },
+ pairedOver: (req) => {
+ const current = e2eContextOf(req.socket) ? descriptor() : null;
+ return current ? { e2e: current } : {};
+ },
+ pairingRefusal: (req, input) => (e2eContextOf(req.socket) && !isPairingCredential(input) ? "pair a phone with its QR code" : null),
+ stop() {
+ stopIssued();
+ stopRevoked();
+ tokens.stop();
+ e2e.closeAll();
+ origin.close();
+ },
+ };
+}
diff --git a/server/request-auth.ts b/server/request-auth.ts
index 09f08639a0..421897e107 100644
--- a/server/request-auth.ts
+++ b/server/request-auth.ts
@@ -180,7 +180,7 @@ export function requestOrigin(req: IncomingMessage): string | null {
}
/** Every header a reverse proxy uses to name its client, so one that sets only X-Real-IP is still not loopback. */
-const PROXY_HEADERS = [
+export const PROXY_HEADERS = [
"x-forwarded-for", "x-forwarded-proto", "x-forwarded-host", "forwarded",
"x-real-ip", "cf-connecting-ip", "true-client-ip", "x-client-ip",
] as const;
diff --git a/server/service-cli.ts b/server/service-cli.ts
index cb4f8be23f..de90cc7c03 100644
--- a/server/service-cli.ts
+++ b/server/service-cli.ts
@@ -19,6 +19,7 @@ export interface ServiceInstallInput {
tailscale?: boolean;
publicUrl?: string;
lan?: boolean;
+ relay?: boolean;
label?: string;
sentinel?: boolean;
/** Defaults to the platform's Sentinel folder. */
@@ -43,13 +44,14 @@ export interface ServiceIo {
/** The same `serve` flags the person gave, so the service reaches people the way `serve` did. Not a terminal, `serve`
* prints no pairing code into the service log. */
-export function serviceServeArgs(input: Pick<ServiceInstallInput, "port" | "dataDir" | "domain" | "tunnel" | "tailscale" | "publicUrl" | "lan" | "label">): string[] {
+export function serviceServeArgs(input: Pick<ServiceInstallInput, "port" | "dataDir" | "domain" | "tunnel" | "tailscale" | "publicUrl" | "lan" | "relay" | "label">): string[] {
const args = ["--port", String(input.port), "--data-dir", input.dataDir];
if (input.domain) args.push("--domain", input.domain);
else if (input.tunnel) args.push("--tunnel");
else if (input.tailscale) args.push("--tailscale");
if (input.publicUrl && !input.domain && !input.tunnel) args.push("--public-url", input.publicUrl);
if (input.lan) args.push("--lan");
+ if (input.relay && !input.tunnel) args.push("--relay");
if (input.label) args.push("--label", input.label);
return args;
}
diff --git a/server/sessions.ts b/server/sessions.ts
index 3b769afcb1..96d36de95f 100644
--- a/server/sessions.ts
+++ b/server/sessions.ts
@@ -701,6 +701,18 @@ export class SessionRegistry {
return this.sessions.map(publicSession);
}
+ /** The stored digest of each live bearer session among `ids`: the phone relay derives a phone's keys from it. */
+ bearerDigests(ids: ReadonlySet<string>): Array<{ id: string; tokenHash: string }> {
+ this.prune();
+ return this.sessions.filter((s) => ids.has(s.id) && !s.cookieOnly && !this.personal(s.scopes)).map((s) => ({ id: s.id, tokenHash: s.tokenHash }));
+ }
+
+ /** The credential digests of the newest open pairing windows a device may redeem (never a browser sign-in's). */
+ pairingDigests(max: number): string[] {
+ this.prune();
+ return this.pairings.filter((p) => !p.browser).sort((a, b) => b.createdAt - a.createdAt).slice(0, max).map((p) => p.credentialHash);
+ }
+
/** The live sessions a Team Cloud member's own codes opened: their phones. Never an Admin-signed pairing (an app). */
memberPhones(): PublicSession[] {
this.prune();
@@ -767,6 +779,12 @@ export class SessionRegistry {
return { ticket, expiresAt };
}
+ /** Whose a stream ticket is, without spending it. */
+ ticketOwner(ticket: string): string | null {
+ const entry = this.tickets.get(sha256(ticket));
+ return entry && entry.expiresAt > this.now() ? entry.sessionId : null;
+ }
+
redeemStreamTicket(ticket: string): SessionRecord | null {
this.prune();
const hash = sha256(ticket);
diff --git a/server/testing/control-plane-stub.ts b/server/testing/control-plane-stub.ts
index 2dc852134e..55795e9c00 100644
--- a/server/testing/control-plane-stub.ts
+++ b/server/testing/control-plane-stub.ts
@@ -10,6 +10,8 @@ interface StubInstallation {
platform: string;
appVersion: string | null;
credential: string;
+ /** What the installation last said it is (`kind`), if it said. */
+ kind?: string;
}
export interface ControlPlaneStub {
@@ -109,6 +111,7 @@ export async function startControlPlaneStub(options: { otp?: string; endpointUrl
platform: String(body.platform ?? "linux"),
appVersion: typeof body.appVersion === "string" ? body.appVersion : null,
credential: newCredential(),
+ ...(typeof body.kind === "string" ? { kind: body.kind } : {}),
};
installations.set(inst.id, inst);
return send(201, { installation: publicView(inst), credential: inst.credential, credentialExpiresAt: Date.now() + NINETY_DAYS });
@@ -132,6 +135,7 @@ export async function startControlPlaneStub(options: { otp?: string; endpointUrl
if (method === "POST") {
const body = await readJson(req);
if (typeof body.appVersion === "string") inst.appVersion = body.appVersion;
+ if (typeof body.kind === "string") inst.kind = body.kind;
if (reclaimedUntilProvision) issuedConnectorToken = reclaimedUntilProvision;
reclaimedUntilProvision = null;
return send(200, { endpoint: endpoint(), connectorToken: issuedConnectorToken });
diff --git a/server/tunnel.ts b/server/tunnel.ts
index 243b2a67b0..79240a253b 100644
--- a/server/tunnel.ts
+++ b/server/tunnel.ts
@@ -133,6 +133,8 @@ export function createTunnelAccount(options: {
fetchImpl?: typeof fetch;
machineName?: string;
recovery?: TunnelRecovery;
+ /** `login --relay`: sign in without reserving a public address; phones reach this machine through MausBot Relay. */
+ relayOnly?: boolean;
log?: (line: string) => void;
clock?: {
setTimer: (callback: () => void, milliseconds: number) => unknown;
@@ -149,9 +151,10 @@ export function createTunnelAccount(options: {
client,
readCredentials: () => credentials.read(),
updateCredentials: (derive, afterPersist) => credentials.update(derive, afterPersist),
- identity: { name: options.machineName ?? hostname(), platform: platformName(), appVersion: options.version },
+ identity: { name: options.machineName ?? hostname(), platform: platformName(), appVersion: options.version, kind: "server" },
newClientInstanceId: () => randomUUID(),
...(options.log ? { log: options.log } : {}),
+ ...(options.relayOnly ? { onDemand: true, managedEndpointNeeded: async () => false, relay: { capable: () => true, legacyDevices: async () => 0 } } : {}),
...(recovery
? {
autoRecover: true,
@@ -184,7 +187,7 @@ export async function fleetAccess(options: { credential: string; version?: strin
if (!controlPlane) throw new Error("OMB_CONTROL_PLANE_URL is set but is not an https address");
const client = createControlPlaneClient({ baseURL: controlPlane, fetchImpl: options.fetchImpl });
try {
- const { endpoint, connectorToken } = await client.ensureEndpoint(options.credential, { appVersion: options.version });
+ const { endpoint, connectorToken } = await client.ensureEndpoint(options.credential, { appVersion: options.version, kind: "server" });
return { endpoint: endpoint.url, token: connectorToken };
} catch (error) {
if (error instanceof ControlPlaneError && error.status === 401) {