Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Server CLI: one link per way in, --lan for this network, commands that paste (#4770)
Milind Soni6ac21809b3d7
diff --git a/.github/workflows/npm-package.yml b/.github/workflows/npm-package.ymlindex 044813778b..0ff7915e19 100644--- a/.github/workflows/npm-package.yml+++ b/.github/workflows/npm-package.yml@@ -48,23 +48,24 @@ jobs:HOME=/tmp/omb-pack/home node cli.js serve --no-pair --port 18799 --data-dir /tmp/omb-pack/data --label ci --public-url https://ci.example > serve.log 2>&1 &for i in $(seq 1 60); do curl -sf http://127.0.0.1:18799/api/health >/dev/null && break; sleep 1; done# The server answers /api/health before the CLI prints its "running" line, so wait for the line too.- for i in $(seq 1 30); do grep -q "reachable at https://ci.example" serve.log && break; sleep 1; done- grep -q "reachable at https://ci.example" serve.log- OMB_PORT=18799 node cli.js status | grep -q "ci ·"- OMB_PORT=18799 node cli.js pair --label "CI phone" | grep -q "open or scan: https://ci.example/pair#code="+ for i in $(seq 1 30); do grep -q "^Reach .*https://ci.example" serve.log && break; sleep 1; done+ grep -q "^Reach .*https://ci.example" serve.log+ grep -q "Get a pairing code: openmausbot pair" serve.log+ OMB_PORT=18799 node cli.js status | grep -q 'Server "ci"'+ OMB_PORT=18799 node cli.js pair --label "CI phone" | grep -q "Link https://ci.example/pair#code="OMB_PORT=18799 node cli.js sessions | grep -q "no paired devices yet"# the bundles also run directly by path (the image and docs do that), not only through cli.js:# a bundled module with a "run when executed directly" block would fire herenode dist-server/openmausbot.js --help | grep -q "openmausbot serve"OMB_PORT=1 node dist-server/pair-cli.js > pair.out 2>&1 || truecat pair.out- grep -q "no OpenMausBot server" pair.out+ grep -q "No MausBot server is running here" pair.out# --tunnel ships its own processes and fails closed without an accounttest -f dist-server/tunnel-guardian.js && test -f dist-server/prepare-cloudflared.js# the enterprise layer ships bundled (inert without a key) so a white-label key works on an npm installtest -f enterprise/server/index.js && test -f enterprise/LICENSEif HOME=/tmp/omb-pack/home node cli.js serve --tunnel --port 18798 --data-dir /tmp/omb-pack/data2 > tunnel.log 2>&1; then echo "serve --tunnel should refuse without login"; exit 1; fi- grep -q "run \`openmausbot login\` first" tunnel.log+ grep -q "run openmausbot login first" tunnel.logkill %1; wait %1 || true- name: Prove an npm install brings the Data engine's native modulesworking-directory: /tmp/omb-pack/packagediff --git a/Dockerfile b/Dockerfileindex 6d31e95b3e..46063d6786 100644--- a/Dockerfile+++ b/Dockerfile@@ -224,7 +224,10 @@ COPY --from=build --chown=maus:maus /src/dist-native/duckdb/target ./duckdbCOPY --from=build --chown=maus:maus /src/dist-server ./dist-serverCOPY --from=build --chown=maus:maus /src/dist ./distCOPY --from=build --chown=maus:maus /src/skills ./skills-ENV HOME=/data+# `docker compose exec omb openmausbot pair`: the commands the CLI prints start the same way.+RUN printf '#!/bin/sh\nexec node /app/dist-server/openmausbot.js "$@"\n' > /usr/local/bin/openmausbot && chmod 0755 /usr/local/bin/openmausbot+ENV HOME=/data \+ OMB_CLI_PREFIX="docker compose exec omb openmausbot"VOLUME ["/data"]USER mausHEALTHCHECK --interval=30s --timeout=5s --start-period=20s --retries=3 \diff --git a/companion/test/tailscale-cli.test.ts b/companion/test/tailscale-cli.test.tsindex f7cf9cb23a..16bec54ff4 100644--- a/companion/test/tailscale-cli.test.ts+++ b/companion/test/tailscale-cli.test.ts@@ -42,7 +42,7 @@ vi.mock("node:os", async (original) => ({import { createControlServer, type companionState } from "../src/control.ts";import { DeviceRegistry } from "../src/devices.ts";import { refreshTailnetName, tailnetName } from "../src/listener.ts";-import { tailscaleServe, tailscaleServeOff, tailscaleStatus } from "../../server/tailscale.ts";+import { tailscaleStatus } from "../../server/tailscale.ts";let control: Server | undefined;@@ -119,17 +119,10 @@ describe("Tailscale from a shell-less standalone macOS app", () => {expect(attempts.join("\n")).not.toContain("private diagnostic");});- it("also forces CLI mode for self-hosted status, HTTPS Serve, and Serve off", async () => {+ it("also forces CLI mode for the self-hosted server's status check", async () => {const result = await tailscaleStatus();expect(result).toHaveProperty("status");- if (!("status" in result)) throw new Error("fixture CLI not found");- expect(await tailscaleServe(result.status, 8799)).toEqual({ origin: "https://fixture.tail1234.ts.net" });- await tailscaleServeOff(result.status);- expect(fixture.calls.map(({ args }) => args)).toEqual([- ["status", "--json"],- ["serve", "--bg", "--https=443", "http://127.0.0.1:8799"],- ["serve", "--https=443", "off"],- ]);+ expect(fixture.calls.map(({ args }) => args)).toEqual([["status", "--json"]]);expect(fixture.calls.every(({ options }) => options.env?.TAILSCALE_BE_CLI === "1" && !options.shell)).toBe(true);});});diff --git a/compose.yaml b/compose.yamlindex cf6239f684..4f57dbaad5 100644--- a/compose.yaml+++ b/compose.yaml@@ -19,6 +19,8 @@ services:environment:OMB_PORT: "8799"OMB_WEBHOOK_PORT: "8800"+ # The name the desktop app shows for this server (a container's own hostname is a random id).+ 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}}}healthcheck:diff --git a/deploy/docker-compose.yml b/deploy/docker-compose.ymlindex ed9b89011e..8876a0dd94 100644--- a/deploy/docker-compose.yml+++ b/deploy/docker-compose.yml@@ -33,6 +33,7 @@ services:OMB_WEBHOOK_PUBLIC_URL: https://${DOMAIN}# pairing links for remote clients point here (docs/self-hosting.md)OMB_PUBLIC_URL: https://${DOMAIN}+ OMB_SERVER_NAME: ${OMB_SERVER_NAME:-${DOMAIN}}# Who may sign in with an emailed code at /pair (docs/self-hosting.md,# "Sign in with your email"). Empty means pairing codes only.OMB_SIGNIN_EMAILS: ${OMB_SIGNIN_EMAILS:-}diff --git a/deploy/local/README.md b/deploy/local/README.mdindex 97bf864faf..44475163b2 100644--- a/deploy/local/README.md+++ b/deploy/local/README.md@@ -31,7 +31,7 @@ Sign in and pair a browser:```shdocker compose exec omb codex login --device-auth-docker compose exec omb node dist-server/openmausbot.js pair+docker compose exec omb openmausbot pair```On Windows, `./maus.ps1` forwards arguments to Compose using the repositorydiff --git a/deploy/podman/README.md b/deploy/podman/README.mdindex f75f37d5a9..b869ee5b8d 100644--- a/deploy/podman/README.md+++ b/deploy/podman/README.md@@ -92,7 +92,7 @@ existing data.Caddy listens on loopback only. To use Tailscale Serve, route the tailnet HTTPSendpoint to `http://127.0.0.1:8080`, set `OMB_PUBLIC_URL` to that HTTPS URL and`OMB_HTTPS_HOST` to its hostname, then recreate the services with `up -d`.-Mint a pairing code with `maus.ps1 exec omb node dist-server/openmausbot.js pair`.+Mint a pairing code with `maus.ps1 exec omb openmausbot pair`.The proxy forwards the client address and scheme so the server's pairing checksremain in force. Do not publish the server, webhook listener, or Podman socketdirectly. For public-domain HTTPS, use the existing Docker deployment or designdiff --git a/docs/deploy-vps.md b/docs/deploy-vps.mdindex 80923f5a40..c1c0db4c06 100644--- a/docs/deploy-vps.md+++ b/docs/deploy-vps.md@@ -122,7 +122,7 @@ One container for the server plus Caddy for HTTPS at `https://maus.example.com`.In this path, every `npx openmausbot …` command below is run inside the container instead:```sh-docker compose exec omb node dist-server/openmausbot.js pair --label "My MacBook"+docker compose exec omb openmausbot pair --label "My MacBook"```## Path C: only your Tailscale networkdiff --git a/server/cli-invocation.test.ts b/server/cli-invocation.test.tsindex d94d88e984..80b0cc9b03 100644--- a/server/cli-invocation.test.ts+++ b/server/cli-invocation.test.ts@@ -5,7 +5,7 @@ import { cliCommand, cliPrefix } from "./cli-invocation.ts";describe("cliPrefix", () => {it("prints commands the way the CLI was started", () => {expect(cliPrefix({}, "/home/me/.npm/_npx/1a2b/node_modules/openmausbot/dist-server/openmausbot.js")).toBe("npx openmausbot");- expect(cliPrefix({ npm_command: "exec" }, "/x/openmausbot.js")).toBe("npx openmausbot");+ expect(cliPrefix({ npm_command: "exec" }, "/repo/node_modules/vitest/vitest.mjs"), "another tool run by npx").toBe("openmausbot");expect(cliPrefix({ npm_lifecycle_event: "omb" }, "/repo/server/openmausbot.ts")).toBe("pnpm omb");expect(cliPrefix({ OMB_CLI_PREFIX: "docker compose exec omb openmausbot" }, "/app/dist-server/openmausbot.js")).toBe("docker compose exec omb openmausbot");expect(cliPrefix({}, "/usr/lib/node_modules/openmausbot/dist-server/openmausbot.js")).toBe("openmausbot");diff --git a/server/cli-invocation.ts b/server/cli-invocation.tsindex 5627c6e1e9..8aa11ad4f3 100644--- a/server/cli-invocation.ts+++ b/server/cli-invocation.ts@@ -4,8 +4,8 @@ export function cliPrefix(env: NodeJS.ProcessEnv = process.env, script = processconst fixed = env.OMB_CLI_PREFIX?.trim();if (fixed) return fixed;if (env.npm_lifecycle_event === "omb") return "pnpm omb";- // npm 7+ runs `npx` packages from its cache's `_npx` folder and marks the run `npm_command=exec`.- if (/[\\/]_npx[\\/]/.test(script) || env.npm_command === "exec") return "npx openmausbot";+ // npm 7+ runs an `npx` package from its cache's `_npx` folder (npm_command=exec alone also marks `npx vitest`).+ if (/[\\/]_npx[\\/]/.test(script)) return "npx openmausbot";return "openmausbot";}diff --git a/server/cli-lifecycle.test.ts b/server/cli-lifecycle.test.tsindex bfe5b6be34..b4be4b8256 100644--- a/server/cli-lifecycle.test.ts+++ b/server/cli-lifecycle.test.ts@@ -14,7 +14,7 @@ const mocks = vi.hoisted(() => ({FLEET_CREDENTIAL_ENV: "OMB_INSTALLATION_CREDENTIAL",denyLogOpen: false,spawn: vi.fn(),- tailscaleStatus: vi.fn(), tailscaleServe: vi.fn(), tailscaleServeOff: vi.fn(),+ tailscaleStatus: vi.fn(), tailscaleServe: vi.fn(), tailscaleStop: vi.fn(), clearLeftoverTailscaleServe: vi.fn(),createTunnelAccount: vi.fn(), createTunnelOrigin: vi.fn(), cleanupTunnelOrigin: vi.fn(),describeTunnelAccount: vi.fn(), tunnelAccess: vi.fn(), ensureCloudflared: vi.fn(),guardianEntry: vi.fn(), startTunnel: vi.fn(),@@ -36,7 +36,7 @@ vi.mock("node:fs", async (original) => {});vi.mock("./tailscale.ts", () => ({tailscaleStatus: mocks.tailscaleStatus, tailscaleServe: mocks.tailscaleServe,- tailscaleServeOff: mocks.tailscaleServeOff, explainTailscaleFailure: (failure: string) => failure,+ clearLeftoverTailscaleServe: mocks.clearLeftoverTailscaleServe, explainTailscaleFailure: (failure: string) => failure,}));vi.mock("./tunnel.ts", () => ({ ...mocks, describeTunnelState: () => "Fixture tunnel" }));vi.mock("./browser-engine.ts", () => ({@@ -82,8 +82,9 @@ beforeEach(() => {signalListeners = new Map(["SIGINT", "SIGTERM"].map((signal) => [signal as NodeJS.Signals, new Set(process.listeners(signal))]));mocks.spawn.mockImplementation(() => childProcess());mocks.tailscaleStatus.mockResolvedValue({ status: { cli: "/fixture/tailscale", dnsName: "fixture.tail.test", addresses: [], backendState: "Running" } });- mocks.tailscaleServe.mockResolvedValue({ origin: "https://fixture.tail.test" });- mocks.tailscaleServeOff.mockResolvedValue(undefined);+ mocks.tailscaleServe.mockResolvedValue({ origin: "https://fixture.tail.test", stop: mocks.tailscaleStop });+ mocks.tailscaleStop.mockResolvedValue(undefined);+ mocks.clearLeftoverTailscaleServe.mockResolvedValue(false);mocks.createTunnelAccount.mockReturnValue({ credentials: { status: "available", read: () => ({}) }, service: { retry: async () => ({}), restore: async () => ({}), dispose: vi.fn() } });mocks.describeTunnelAccount.mockReturnValue({ email: "[email protected]" });mocks.tunnelAccess.mockReturnValue({ endpoint: "https://fixture.openmausbot.test" });@@ -116,7 +117,7 @@ describe("CLI startup lifecycle", () => {vi.stubGlobal("fetch", vi.fn().mockResolvedValue(Response.json({}, { status: 503 })));await expect(runServe({ ...options, tailscale: true }, vi.fn())).rejects.toMatchObject({ code: "EACCES" });expect(mocks.tailscaleServe).not.toHaveBeenCalled();- expect(mocks.tailscaleServeOff).not.toHaveBeenCalled();+ expect(mocks.tailscaleStop).not.toHaveBeenCalled();expect(mocks.spawn).not.toHaveBeenCalled();});@@ -125,14 +126,13 @@ describe("CLI startup lifecycle", () => {mocks.spawn.mockImplementation(() => { throw new Error("Fixture spawn failure"); });await expect(runServe({ ...options, tailscale: true }, vi.fn())).rejects.toThrow("Fixture spawn failure");expect(mocks.tailscaleServe).toHaveBeenCalledOnce();- expect(mocks.tailscaleServeOff).toHaveBeenCalledOnce();- expect(mocks.tailscaleServeOff).toHaveBeenCalledWith(expect.objectContaining({ dnsName: "fixture.tail.test" }));+ expect(mocks.tailscaleStop).toHaveBeenCalledOnce();});it.each([- { outcome: "success", result: { origin: "https://fixture.tail.test" } },- { outcome: "failure", result: { failure: "unknown" } },- ])("cleans up and never spawns when Tailscale returns $outcome after startup cancellation", async ({ result }) => {+ { outcome: "success", result: { origin: "https://fixture.tail.test", stop: mocks.tailscaleStop }, stops: 1 },+ { outcome: "failure", result: { failure: "unknown" }, stops: 0 },+ ])("cleans up and never spawns when Tailscale returns $outcome after startup cancellation", async ({ result, stops }) => {vi.stubGlobal("fetch", vi.fn().mockResolvedValue(Response.json({}, { status: 503 })));mocks.tailscaleServe.mockImplementation(async () => {await Promise.resolve();@@ -141,8 +141,7 @@ describe("CLI startup lifecycle", () => {});expect(await runServe({ ...options, tailscale: true }, vi.fn())).toBe(130);expect(mocks.tailscaleServe).toHaveBeenCalledOnce();- expect(mocks.tailscaleServeOff).toHaveBeenCalledOnce();- expect(mocks.tailscaleServeOff).toHaveBeenCalledWith(expect.objectContaining({ dnsName: "fixture.tail.test" }));+ expect(mocks.tailscaleStop).toHaveBeenCalledTimes(stops);expect(mocks.spawn).not.toHaveBeenCalled();for (const [signal, before] of signalListeners) {expect(process.listeners(signal).filter((handler) => !before.has(handler))).toEqual([]);@@ -220,7 +219,7 @@ describe("CLI startup lifecycle", () => {expect(await isWorkspaceRunning(options)).toBe(false);});- it.each([true, false])("prints a sign-in link for a browser on this computer (guided: %s)", async (guided) => {+ it.each([true, false])("with no way in: the guided start signs a browser here in; serve lists the ways in and mints nothing (guided: %s)", async (guided) => {let healthRequests = 0;const code = "ABCD-EFGH-JKLM";const pairings: unknown[] = [];@@ -229,18 +228,20 @@ describe("CLI startup lifecycle", () => {if (address.endsWith("/api/health")) {return ++healthRequests === 1 ? Response.json({}, { status: 503 }) : Response.json({ app: "openmausbot", pid: childPid });}+ if (address.endsWith("/.well-known/openmausbot/environment")) return Response.json({ environmentId: workspaceId, label: "fixture box" });expect(address).toBe(`http://127.0.0.1:${options.port}/api/auth/pairing`);expect(init?.method).toBe("POST");pairings.push(JSON.parse(String(init?.body)));- return Response.json({ code, url: null, expiresAt: Date.now() + 120_000, hint: "set OMB_PUBLIC_URL" });+ return Response.json({ code, url: null, expiresAt: Date.now() + 120_000 });}));- const log = vi.fn((line: string) => { if (line.includes(guided ? "Keep this terminal open" : "stop with Ctrl+C")) interrupt(); });+ const log = vi.fn((line: string) => { if (line.includes(guided ? "Keep this terminal open" : "Sign in from a browser on this machine")) interrupt(); });expect(await runServe({ ...options, guided, pair: true }, log)).toBe(0);const output = log.mock.calls.map(([line]) => line).join("\n");- expect(pairings).toEqual([{}]);- expect(output).toContain(`http://127.0.0.1:${options.port}/pair#code=${code}`);+ expect(output).toContain('server "fixture box"');+ expect(pairings).toEqual(guided ? [{}] : []);+ expect(output.includes(`http://127.0.0.1:${options.port}/pair#code=${code}`)).toBe(guided);expect(output.includes("Sign in from a browser on this computer")).toBe(guided);- expect(output.includes("pairing code:")).toBe(!guided);+ expect(output.includes("serve --lan this network only, not encrypted")).toBe(!guided);});it.each(["mismatched", "unreachable"])("never mints a phone code for a %s public endpoint", async (failure) => {@@ -303,9 +304,9 @@ describe("CLI startup lifecycle", () => {expect(requests).toContain(`${origin}/.well-known/openmausbot/environment`);expect(requests.indexOf(`${origin}/.well-known/openmausbot/environment`)).toBeLessThan(requests.indexOf(pairingRequest));const output = log.mock.calls.map(([line]) => line).join("\n");- expect(output).toContain(`pairing code: ${code}`);- expect(output).toContain(`expires: ${new Date(expiresAt).toLocaleTimeString()} (single use)`);- expect(output).toContain(`web browser: ${pairingUrl}`);+ expect(output).toContain(`Pairing code ${code} works once, until`);+ expect(output).toContain("· chat and approvals");+ expect(output).toContain(`Link ${pairingUrl}`);expect(output).toMatch(/[▀▄█]/);expect(output).toContain(`Or open ${origin}/pair on your phone and enter the code.`);expect(output).toContain("On Android, open the OpenMausBot app and scan the QR with its pairing scanner.");diff --git a/server/cli-pair.test.ts b/server/cli-pair.test.tsindex 02e9fb4913..99f04bf888 100644--- a/server/cli-pair.test.ts+++ b/server/cli-pair.test.ts@@ -2,7 +2,6 @@ import { mkdtempSync } from "node:fs";import { join } from "node:path";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import { runPair, type CliOptions } from "./cli.ts";-import { SetupCancelled } from "./cli-prompts.ts";import { removeTempDir } from "./testing/cleanup.ts";const mocks = vi.hoisted(() => ({@@ -16,7 +15,7 @@ vi.mock("./cli-prompts.ts", async (original) => ({}));vi.mock("./tailscale.ts", () => ({tailscaleStatus: mocks.tailscaleStatus,- tailscaleServe: vi.fn(), tailscaleServeOff: vi.fn(), explainTailscaleFailure: vi.fn(),+ tailscaleServe: vi.fn(), clearLeftoverTailscaleServe: vi.fn(), explainTailscaleFailure: vi.fn(),}));vi.mock("./tunnel.ts", () => ({createTunnelAccount: mocks.createTunnelAccount, describeTunnelAccount: mocks.describeTunnelAccount,@@ -80,143 +79,106 @@ afterEach(async () => {await removeTempDir(dataDir);});-function expectPhonePairing(origin: string): void {- const probes = fetchMock.mock.calls.filter(([url]) => String(url).startsWith("https://"));- expect(probes).toHaveLength(1);- expect(String(probes[0]![0])).toBe(`${origin}/.well-known/openmausbot/environment`);- expect(probes[0]![1]).not.toHaveProperty("body");- expect(probes[0]![1]).not.toHaveProperty("headers");- const invitations = fetchMock.mock.calls.filter(([, init]) => init?.method === "POST");- expect(invitations).toHaveLength(1);- expect(String(invitations[0]![0])).toBe(`http://127.0.0.1:${options.port}/api/auth/pairing`);- expect(JSON.parse(String(invitations[0]![1]?.body))).toMatchObject({ scopes: ["client"] });- const transcript = mocks.ui.log.mock.calls.map(([line]) => line).join("\n");- expect(transcript).toContain(`pairing code: ${code}`);- expect(transcript).toContain(`${origin}/pair#code=${code}`);- expect(transcript).toMatch(/[▀▄█]/);- expect(mocks.createTunnelAccount).not.toHaveBeenCalled();- expect(mocks.tailscaleStatus).not.toHaveBeenCalled();-}+const printed = () => vi.mocked(console.log).mock.calls.map(([line]) => String(line)).join("\n");-describe("guided phone pairing address discovery", () => {- it.each([- { access: "tunnel", phone: "ios" },- { access: "tailscale", phone: "android" },- { access: "public-url", publicUrl: "https://old-proxy.example.test", phone: "ios" },- ])("uses the running server's advertised origin instead of saved $access access", async (saved) => {- mocks.readCliStartup.mockReturnValue(saved);+describe("openmausbot pair", () => {+ it("never asks anything: one code, the running server's own link, a QR, and the phone command", async () => {expect(await runPair(options)).toBe(0);- expectPhonePairing(advertisedOrigin);+ expect(mocks.ui.choose).not.toHaveBeenCalled();+ expect(mocks.readCliStartup).not.toHaveBeenCalled();+ expect(mocks.tailscaleStatus).not.toHaveBeenCalled();+ const posted = fetchMock.mock.calls.find(([, init]) => init?.method === "POST");+ expect(JSON.parse(String(posted![1]!.body))).toEqual({});+ expect(printed()).toMatch(new RegExp(`Pairing code {3}${code} {3}works once, until .+ · everything`));+ expect(printed()).toContain(`Link ${advertisedOrigin}/pair#code=${code}`);+ expect(printed()).toMatch(/[▀▄█]/);+ expect(printed()).toContain("For a phone (chat and approvals only) openmausbot pair --phone");+ expect(printed()).not.toContain("doesn't reach");});- it("allows an explicit --public-url to override the advertised and saved addresses", async () => {- mocks.readCliStartup.mockReturnValue({ access: "tunnel", phone: "ios" });+ it("an explicit --public-url wins over the advertised address", async () => {expect(await runPair({ ...options, publicUrl: explicitOrigin })).toBe(0);- expectPhonePairing(explicitOrigin);+ expect(printed()).toContain(`Link ${explicitOrigin}/pair#code=${code}`);});- it.each([- "https://localhost",- "https://user:[email protected]",- "https://old.example.test/pair#code=stale-code",- undefined,- ])("ignores an invalid saved public URL (%s) when the server advertises a valid origin", async (savedUrl) => {- mocks.readCliStartup.mockReturnValue({ access: "public-url", publicUrl: savedUrl, phone: "ios" });- expect(await runPair(options)).toBe(0);- expectPhonePairing(advertisedOrigin);+ it("--phone mints a chat-only code", async () => {+ expect(await runPair({ ...options, phone: "ios" })).toBe(0);+ const posted = fetchMock.mock.calls.find(([, init]) => init?.method === "POST");+ expect(JSON.parse(String(posted![1]!.body))).toEqual({ scopes: ["client"] });+ expect(printed()).toContain("· chat and approvals");+ expect(printed()).not.toContain("For a phone");});- it("does not read stale or unreadable setup settings before using the running origin", async () => {- mocks.readCliStartup.mockImplementation(() => { throw new Error("Fixture config is stale or unreadable"); });+ it("still prints the code when the address answers as another server, and says what to fix", async () => {+ remoteWorkspaceId = "another-workspace";expect(await runPair(options)).toBe(0);- expect(mocks.readCliStartup).not.toHaveBeenCalled();- expectPhonePairing(advertisedOrigin);+ expect(printed()).toContain(`Link ${advertisedOrigin}/pair#code=${code}`);+ expect(printed()).toContain(`✗ ${advertisedOrigin} answers as a different server.`);+ expect(printed()).toContain("The code works once the address answers.");});- it("does not probe a fabricated origin when Tailscale has no MagicDNS name", async () => {+ it("with no way in: the browser on this machine, and the command that lists the ways in", async () => {publicUrl = null;- mocks.readCliStartup.mockReturnValue({ access: "tailscale", phone: "ios" });- mocks.tailscaleStatus.mockResolvedValue({ status: { dnsName: null } });- expect(await runPair(options)).toBe(1);- expect(mocks.ui.choose).not.toHaveBeenCalled();- expect(fetchMock.mock.calls.filter(([url]) => String(url).startsWith("https://"))).toHaveLength(0);- expect(fetchMock.mock.calls.filter(([, init]) => init?.method === "POST")).toHaveLength(0);- expect(console.log).toHaveBeenCalledWith(expect.stringContaining("running only on this computer"));+ fetchMock.mockImplementation(async (input, init) => {+ const url = String(input);+ if (url.endsWith("/api/health")) return Response.json({ app: "openmausbot", pid: 12345 });+ if (url.endsWith("/api/auth/pairing")) return init?.method === "POST" ? Response.json({ code, expiresAt: Date.now() + 600_000, url: null }) : Response.json({ pairings: [], publicUrl: null });+ throw new Error(`Unexpected fixture request: ${url}`);+ });+ expect(await runPair(options)).toBe(0);+ expect(printed()).toContain(`http://127.0.0.1:${options.port}/pair#code=${code}`);+ expect(printed()).toContain("pick a way in first: openmausbot serve --help");+ expect(printed()).not.toMatch(/[▀▄█]/);});- it("does not mint a code when the advertised endpoint identifies another workspace", async () => {- remoteWorkspaceId = "another-workspace";+ it("says how to start a server when none runs", async () => {+ fetchMock.mockImplementation(async () => { throw new Error("offline"); });expect(await runPair(options)).toBe(1);- expect(fetchMock.mock.calls.filter(([, init]) => init?.method === "POST")).toHaveLength(0);- expect(mocks.ui.log).toHaveBeenCalledWith(expect.stringContaining("no phone pairing code was created"));- });-- it.each([2, new SetupCancelled()])("does not mint a code when phone selection is cancelled (%s)", async (cancel) => {- if (cancel instanceof Error) mocks.ui.choose.mockRejectedValue(cancel);- else mocks.ui.choose.mockResolvedValue(cancel);- expect(await runPair(options)).toBe(cancel instanceof Error ? 130 : 0);- expect(fetchMock.mock.calls.filter(([, init]) => init?.method === "POST")).toHaveLength(0);- expect(fetchMock.mock.calls.filter(([url]) => String(url).startsWith("https://"))).toHaveLength(0);+ expect(console.error).toHaveBeenCalledWith(expect.stringContaining("No MausBot server is running here. Start it: openmausbot serve"));});});-// `openmausbot pair` talks to 127.0.0.1, so the server answers as its owner and builds the phone-app invite from its own-// public address; the CLI prints it as it is and builds its own only for --public-url.-describe("the phone-app link `openmausbot pair` prints", () => {+describe("the phone-app link `openmausbot pair --phone android` scans", () => {const credential = `omb_pair_${"b".repeat(43)}`;const serverName = "Miguel's computer";const pairingResponse = (fields: Record<string, unknown>) => {fetchMock.mockImplementation(async (input, init) => {- if (String(input) === `http://127.0.0.1:${options.port}/api/health`) return Response.json({ app: "openmausbot", pid: 12345 });- if (String(input) === `http://127.0.0.1:${options.port}/api/auth/pairing` && init?.method === "POST") {- return Response.json({ code, expiresAt: Date.now() + 300_000, credential, serverName, ...fields });+ const url = String(input);+ if (url === `http://127.0.0.1:${options.port}/api/health`) return Response.json({ app: "openmausbot", pid: 12345 });+ if (url === `http://127.0.0.1:${options.port}/api/auth/pairing`) {+ return init?.method === "POST" ? Response.json({ code, expiresAt: Date.now() + 300_000, credential, serverName, ...fields }) : Response.json({ pairings: [], publicUrl: null });}- throw new Error(`Unexpected fixture request: ${String(input)}`);+ throw new Error(`Unexpected fixture request: ${url}`);});};- const printed = () => vi.mocked(console.log).mock.calls.map(([line]) => String(line)).join("\n");-- it("prints the server's own invite unchanged", async () => {- const serverInvite = `openmausbot://pair?address=${encodeURIComponent(advertisedOrigin)}&token=${credential}&name=Miguel's%20computer`;- pairingResponse({ url: `${advertisedOrigin}/pair#code=${code}`, inviteUrl: serverInvite });- expect(await runPair({ ...options, label: "Pixel" })).toBe(0);- expect(printed()).toContain(`phone app: ${serverInvite}\n`);- });- it("builds the invite for --public-url from the server's credential and name", async () => {- pairingResponse({- url: `${advertisedOrigin}/pair#code=${code}`,- inviteUrl: `openmausbot://pair?address=${encodeURIComponent(advertisedOrigin)}&token=${credential}&name=Miguel's%20computer`,- });- expect(await runPair({ ...options, label: "Pixel", publicUrl: explicitOrigin })).toBe(0);- expect(printed()).toContain(- `phone app: openmausbot://pair?address=${encodeURIComponent(explicitOrigin)}&token=${credential}&name=Miguel's%20computer\n`,- );- expect(printed()).not.toContain(encodeURIComponent(advertisedOrigin));+ it("builds the invite for --public-url from the server's credential and name, and never prints it as text", async () => {+ pairingResponse({ url: null, inviteUrl: null });+ expect(await runPair({ ...options, phone: "android", publicUrl: explicitOrigin })).toBe(0);+ expect(printed()).not.toContain("openmausbot://");+ expect(printed()).not.toContain(credential);+ expect(printed()).toContain("scan this with the MausBot app");});- // OMB_PUBLIC_URL may name a path behind a proxy; phones dial an origin, so re-deriving an invite would point at the proxy's root.- it("prints no invite for a server whose public address has a path", async () => {+ it("keeps a proxy path in the web link", async () => {pairingResponse({ url: `https://proxy.example.test/omb/pair#code=${code}`, inviteUrl: null });expect(await runPair({ ...options, label: "Pixel" })).toBe(0);expect(printed()).toContain(`https://proxy.example.test/omb/pair#code=${code}`);- expect(printed()).not.toContain("phone app:");});});describe("pair --ttl", () => {- it("asks the server to keep the code open that long, skips the phone questions, and prints the day it ends", async () => {+ it("asks the server to keep the code open that long and says until when", async () => {const day = Date.now() + 86_400_000;fetchMock.mockImplementation(async (input, init) => {const url = String(input);if (url.endsWith("/api/health")) return Response.json({ app: "openmausbot", pid: 12345 });- if (url.endsWith("/api/auth/pairing") && init?.method === "POST") return Response.json({ code, expiresAt: day, url: null, hint: "set OMB_PUBLIC_URL" });+ if (url.endsWith("/api/auth/pairing")) return init?.method === "POST" ? Response.json({ code, expiresAt: day, url: null }) : Response.json({ pairings: [], publicUrl: null });throw new Error(`Unexpected fixture request: ${url}`);});expect(await runPair({ ...options, pairTtlMs: 86_400_000 })).toBe(0);const posted = fetchMock.mock.calls.find(([, init]) => init?.method === "POST");expect(JSON.parse(String(posted![1]!.body))).toEqual({ ttlMs: 86_400_000 });- expect(mocks.ui.choose).not.toHaveBeenCalled();- expect(vi.mocked(console.log).mock.calls.map(([line]) => String(line)).join("\n")).toContain(`expires: ${new Date(day).toLocaleString()} (single use)`);+ expect(printed()).toMatch(/until tomorrow /);});});diff --git a/server/cli-pairing.ts b/server/cli-pairing.tsindex 604fa64a53..ff45f1e7c5 100644--- a/server/cli-pairing.ts+++ b/server/cli-pairing.ts@@ -2,46 +2,51 @@// owner just by being here, so it signs in once with the link printed for it.import qrcode from "qrcode-terminal";-/** `url` opens the web app (browsers, the iOS app); `inviteUrl` (openmausbot://) is the only thing the Android app scans;- * `localUrl` signs in a browser on this computer. */+import { cliCommand } from "./cli-invocation.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 {+ const end = new Date(expiresAt);+ const time = end.toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" });+ const today = new Date(now);+ if (end.toDateString() === today.toDateString()) return time;+ const tomorrow = new Date(now + 86_400_000);+ return end.toDateString() === tomorrow.toDateString() ? `tomorrow ${time}` : `${end.toLocaleDateString()} ${time}`;+}++/**+ * What `serve` and `pair` print for one pairing code. `link`: the address other devices reach this server at, with the+ * code (null when it has no way in); `localLink`: a browser on this machine (or the Docker host, `localPlace`);+ * `inviteUrl`: the phone-app link only Android's scanner needs; `prefix`: how the CLI was started, so commands paste.+ */export function pairingBlock(input: {code: string;- url: string | null;- inviteUrl?: string | null;- localUrl?: string | null;expiresAt: number;- hint?: string | null;+ chatOnly: boolean;+ link: string | null;+ localLink?: string | null;+ localPlace?: "machine" | "docker";+ inviteUrl?: string | null;phone?: "ios" | "android";+ prefix: string;+ now?: number;}): string {- const expires = new Date(input.expiresAt);- const when = input.expiresAt - Date.now() > 12 * 3_600_000 ? expires.toLocaleString() : expires.toLocaleTimeString();- const lines = [`pairing code: ${input.code}`, `expires: ${when} (single use)`];- if (input.localUrl) lines.push(`this computer: ${input.localUrl}`);- if (!input.url && !input.inviteUrl) {- lines.push(`open: /pair on the address you use for this server, and type the code`);- if (input.hint) lines.push(` (${input.hint})`);+ const scope = input.chatOnly ? "chat and approvals" : "everything";+ const lines = [`Pairing code ${input.code} works once, until ${untilText(input.expiresAt, input.now)} · ${scope}`];+ if (!input.link) {+ lines.push("This server is reachable from this machine only, so there's no link for other devices.");+ if (input.localLink) lines.push(` ${input.localPlace === "docker" ? "Browser on the Docker host" : "Browser on this machine "} ${input.localLink}`);+ lines.push(` Other devices pick a way in first: ${input.prefix} serve --help`);return lines.join("\n");}- const scanInvite = input.phone === "android" && !!input.inviteUrl;- if (input.url) lines.push(scanInvite ? `web browser: ${input.url}` : `open or scan: ${input.url}`);- if (input.inviteUrl) lines.push(`phone app: ${input.inviteUrl}`);- const target = scanInvite ? input.inviteUrl! : input.url;- if (target) {- lines.push("");- lines.push(qrToString(target));- lines.push("");- if (scanInvite) {- lines.push(`Scan that in the OpenMausBot app. For a browser instead, open the web`);- lines.push(`address above and type the code.`);- } else if (input.phone === "android") {- lines.push(`That QR opens the web app. The Android app needs the phone-app link,`);- lines.push(`which this server cannot build without a public address: set`);- lines.push(`OMB_PUBLIC_URL, or open the web address above and type the code.`);- } else if (input.inviteUrl) {- lines.push(`Scan that with Camera for the browser, or paste the phone-app link`);- lines.push(`above into the OpenMausBot app.`);- }- }+ const scanInvite = input.phone === "android" && Boolean(input.inviteUrl);+ lines.push(`Link ${input.link}`);+ lines.push("");+ lines.push(" Desktop app + → Connect to a server, paste the link");+ lines.push(scanInvite ? " Phone scan this with the MausBot app" : " Phone scan with your camera or the MausBot app");+ lines.push("");+ lines.push(qrToString(scanInvite ? input.inviteUrl! : input.link));+ if (!input.chatOnly) lines.push(`For a phone (chat and approvals only) ${input.prefix} pair --phone`);return lines.join("\n");}@@ -50,7 +55,7 @@ export function browserSignInLines(localUrl: string, code: string, expiresAt: nureturn ["Sign in from a browser on this computer with this link (single use, until",`${new Date(expiresAt).toLocaleTimeString()}): ${localUrl}`,- `or type the code ${code} on the sign-in page. Later: openmausbot pair`,+ `or type the code ${code} on the sign-in page. Later: ${cliCommand("pair")}`,].join("\n");}@@ -71,5 +76,5 @@ export function formatSessions(sessions: Array<{ id: string; label: string; scopconst head = ["id", "device", "scope", "last seen", "expires"];const widths = head.map((h, i) => Math.max(h.length, ...rows.map((r) => r[i].length)));const line = (r: string[]) => r.map((c, i) => c.padEnd(widths[i])).join(" ");- return [line(head), ...rows.map(line), "", "revoke one with: openmausbot sessions revoke <id>"].join("\n");+ return [line(head), ...rows.map(line), "", `sign one out with: ${cliCommand("devices revoke <id>")}`].join("\n");}diff --git a/server/cli-printed-commands.test.ts b/server/cli-printed-commands.test.tsnew file mode 100644index 0000000000..2cfa7f8922--- /dev/null+++ b/server/cli-printed-commands.test.ts@@ -0,0 +1,72 @@+// Every command the CLI prints is a command it accepts: a person pastes them as they are.+import { describe, expect, it } from "vitest";++import { parseArgs } from "./cli.ts";+import { browserSignInLines, formatSessions, pairingBlock } from "./cli-pairing.ts";+import { noRouteLines, reachLines } from "./cli-reach.ts";+import { HEADLESS_VERB_NAMES, usage } from "./cli-usage.ts";++const PLACEHOLDERS: Record<string, string> = {+ "https://…": "https://maus.example.com", "<id>": "a1", ID: "a1", NAME: "kitchen", FILE: "team.yaml", EMAIL: "[email protected]",+ HOST: "maus.example.com", DIR: "/tmp/omb", N: "8800", CODE: "ABCD-EFGH-JKLM", BOT: "Chief", URL: "https://maus.example.com", "…": "",+};++/** Each `openmausbot …` a line prints, up to the end of the command (two spaces, a quote, a comma or the line's end). */+function printedCommands(text: string): string[][] {+ const found: string[][] = [];+ for (const line of text.split("\n")) {+ for (const match of line.matchAll(/(?:npx )?openmausbot((?: (?!openmausbot)[^\s,;()`'"]+)*)/g)) {+ const words = match[1]!.trim().split(/\s+/).filter(Boolean).map((word) => PLACEHOLDERS[word] ?? word.replace(/[.:]$/, "")).filter(Boolean);+ if (words.length && !/[[\]|]/.test(words.join(" "))) found.push(words);+ }+ }+ return found;+}++function accepted(words: string[]): string | null {+ if (HEADLESS_VERB_NAMES.has(words[0]!)) return null;+ const parsed = parseArgs(words, {});+ return "error" in parsed ? parsed.error : null;+}++describe("printed commands", () => {+ const now = Date.parse("2026-11-07T10:00:00");+ const outputs = [+ pairingBlock({ code: "ABCD-EFGH-JKLM", expiresAt: now + 600_000, chatOnly: false, link: "https://maus.example.com/pair#code=ABCD-EFGH-JKLM", prefix: "openmausbot", now }),+ pairingBlock({ code: "ABCD-EFGH-JKLM", expiresAt: now + 600_000, chatOnly: false, link: null, localLink: "http://127.0.0.1:8799/pair#code=X", prefix: "openmausbot", now }),+ noRouteLines(8799, "openmausbot").join("\n"),+ reachLines("public-url", "https://maus.example.com", 8799, "openmausbot", { ok: false, kind: "unreachable", reason: "connection refused" }).join("\n"),+ browserSignInLines("http://127.0.0.1:8799/pair#code=X", "X", now),+ formatSessions([{ id: "a1", label: "phone", scopes: ["client"], lastSeenAt: now, expiresAt: now }], now),+ ];++ it("finds the commands in what serve, pair and devices print", () => {+ const commands = outputs.flatMap(printedCommands);+ expect(commands.map((words) => words[0])).toEqual(expect.arrayContaining(["pair", "serve", "status", "devices"]));+ for (const words of commands) expect([words.join(" "), accepted(words)]).toEqual([words.join(" "), null]);+ });++ it("every flag the usage text lists is one its command takes", () => {+ let command: string | null = null;+ const checked: string[] = [];+ for (const line of usage().split("\n")) {+ const head = /^ {2}openmausbot ([a-z][a-z-]*)/.exec(line);+ if (head) command = head[1]!;+ else if (!/^ {10,}/.test(line) || /^ {2}openmausbot -/.test(line)) command = null;+ if (!command || HEADLESS_VERB_NAMES.has(command) || command === "fleet" || command === "sentinel") continue;+ for (const [flag] of line.matchAll(/--[a-z][a-z-]*/g)) {+ const bare = accepted([command, flag]);+ const valued = accepted([command, flag, flag === "--public-url" ? "https://maus.example.com" : flag === "--port" ? "8800" : flag === "--ttl" ? "24h" : flag === "--phone" ? "ios" : "x"]);+ const unknown = (error: string | null) => error !== null && error.includes("unknown argument");+ expect([command, flag, unknown(bare) && unknown(valued)]).toEqual([command, flag, false]);+ checked.push(`${command} ${flag}`);+ }+ }+ expect(checked).toEqual(expect.arrayContaining(["serve --lan", "serve --public-url", "pair --phone", "pair --ttl"]));+ });++ it("writes commands the way the CLI was started", () => {+ expect(usage("npx openmausbot")).toContain(" npx openmausbot pair [--label NAME]");+ expect(noRouteLines(8799, "docker compose exec omb openmausbot").join("\n")).toContain("docker compose exec omb openmausbot serve --lan");+ });+});diff --git a/server/cli-reach.test.ts b/server/cli-reach.test.tsnew file mode 100644index 0000000000..dadd0d0c7b--- /dev/null+++ b/server/cli-reach.test.ts@@ -0,0 +1,63 @@+import { describe, expect, it } from "vitest";++import { checkReach, envPublicUrl, lanProblem, localLinkBase, publicUrlProblem, reachLines, waitForReach } from "./cli-reach.ts";++const descriptor = (environmentId: string) => Response.json({ environmentId });++describe("ways in", () => {+ it("--public-url: https anywhere, http only on a private network", () => {+ expect(publicUrlProblem("https://maus.example.com")).toBeNull();+ expect(publicUrlProblem("http://192.168.1.20:8799")).toBeNull();+ expect(publicUrlProblem("http://box.tail1234.ts.net")).toBeNull();+ expect(publicUrlProblem("http://maus.example.com")).toContain("plain http isn't encrypted");+ expect(publicUrlProblem("maus.example.com")).toContain("must start with https://");+ });++ it("OMB_PUBLIC_URL counts as the address unless it is plain http on the open internet", () => {+ const said: string[] = [];+ expect(envPublicUrl({ OMB_PUBLIC_URL: "https://maus.example.com/" }, (line) => said.push(line))).toBe("https://maus.example.com");+ expect(envPublicUrl({ OMB_PUBLIC_URL: "http://maus.example.com" }, (line) => said.push(line))).toBeUndefined();+ expect(envPublicUrl({}, (line) => said.push(line))).toBeUndefined();+ expect(said).toEqual([expect.stringContaining("OMB_PUBLIC_URL is ignored")]);+ });++ it("--lan on a machine with only public addresses says so", () => {+ expect(lanProblem({ lan: ["192.168.1.20"], tailscale: [] })).toBeNull();+ expect(lanProblem({ lan: [], tailscale: [] })).toContain("no private network address");+ });++ it("a browser on the Docker host opens the published port; elsewhere this server's own", () => {+ expect(localLinkBase("http://localhost:8080", 8799, { OMB_CLI_PREFIX: "docker compose exec omb openmausbot" })).toEqual({ base: "http://localhost:8080", place: "docker" });+ expect(localLinkBase(null, 8799, {})).toEqual({ base: "http://127.0.0.1:8799", place: "machine" });+ expect(localLinkBase("https://maus.example.com", 8799, {})).toEqual({ base: "http://127.0.0.1:8799", place: "machine" });+ });+});++describe("the Reach line", () => {+ const fetching = (remote: () => Response) => (async (url: string | URL | Request) => (String(url).startsWith("http://127.0.0.1") ? descriptor("mine") : remote())) as typeof fetch;++ it("checks the address answers as this very server, with nothing secret sent", async () => {+ expect(await checkReach(8799, "https://maus.example.com", fetching(() => descriptor("mine")), () => 1)).toEqual({ ok: true, at: 1 });+ expect(await checkReach(8799, "https://maus.example.com", fetching(() => descriptor("someone-else")))).toEqual({ ok: false, kind: "other-server" });+ const refused = fetching(() => { throw Object.assign(new TypeError("fetch failed"), { cause: { code: "ECONNREFUSED" } }); });+ expect(await checkReach(8799, "https://maus.example.com", refused)).toEqual({ ok: false, kind: "unreachable", reason: "connection refused" });+ });++ it("says what to fix when it doesn't, as a command that pastes", () => {+ expect(reachLines("public-url", "https://maus.example.com", 8799, "npx openmausbot", { ok: false, kind: "unreachable", reason: "connection refused" })).toEqual([+ "Reach ✗ https://maus.example.com doesn't reach this server (connection refused).",+ " Point your tunnel or proxy at http://127.0.0.1:8799 (on another machine: add --lan and use this machine's address), then run: npx openmausbot status",+ ]);+ expect(reachLines("public-url", "https://maus.example.com", 8799, "openmausbot", { ok: false, kind: "other-server" })[0]).toContain("answers as a different server");+ expect(reachLines("lan", "http://192.168.1.20:8799", 8799, "openmausbot")).toEqual(["Reach http://192.168.1.20:8799 this network only, not encrypted"]);+ expect(reachLines("tailscale", "https://mini.tail1234.ts.net", 8799, "openmausbot", { ok: true, at: Date.parse("2026-11-07T11:04:00") })[0]).toMatch(/✓ answers as this server \(.+\) · your tailnet$/);+ });++ it("waits a while for a tunnel or certificate, then gives up on its budget", async () => {+ let clock = 0, calls = 0;+ const result = await waitForReach(8799, "https://maus.example.com", 3_000, async () => { calls += 1; return { ok: false, kind: "unreachable" }; }, async (ms) => { clock += ms; }, () => clock);+ expect([result.ok, calls]).toEqual([false, 3]);+ calls = 0;+ expect(await waitForReach(8799, "x", 3_000, async () => (++calls === 2 ? { ok: true, at: 1 } : { ok: false, kind: "unreachable" }), async () => {}, () => 0)).toEqual({ ok: true, at: 1 });+ });+});diff --git a/server/cli-reach.ts b/server/cli-reach.tsnew file mode 100644index 0000000000..9127cab498--- /dev/null+++ b/server/cli-reach.ts@@ -0,0 +1,100 @@+// How other devices reach a server `openmausbot serve` started, and the lines that say so. A route is chosen by a flag+// (or the saved setup); the link always uses the first one in ROUTE_ORDER.+import { allowedServerOrigin, isLoopbackHost } from "../electron/server-address.mjs";+import { reachableAddresses, type ReachableAddresses } from "./lan-address.ts";++export type Route = "public-url" | "domain" | "tunnel" | "tailscale" | "lan";++const DESCRIPTOR = "/.well-known/openmausbot/environment";++/** `--public-url`: https anywhere, or http on a private network; never plain http on the open internet. */+export function publicUrlProblem(url: string): string | null {+ if (!/^https?:\/\//i.test(url)) return "--public-url must start with https:// (or http:// on your own network)";+ if (allowedServerOrigin(new URL(url).origin)) return null;+ return `--public-url ${url} is on the open internet, where plain http isn't encrypted: use its https:// address, or --lan for this network only`;+}++/** OMB_PUBLIC_URL set in the environment: the address a server behind the person's own proxy or tunnel prints. */+export function envPublicUrl(env: NodeJS.ProcessEnv, log: (line: string) => void): string | undefined {+ const raw = env.OMB_PUBLIC_URL?.trim().replace(/\/+$/, "");+ if (!raw) return undefined;+ const problem = publicUrlProblem(raw);+ if (problem) log(`OMB_PUBLIC_URL is ignored: ${problem.replace(/^--public-url /, "")}`);+ return problem ? undefined : raw;+}++/** `--lan` on a machine with no private address: say so, and serve on loopback only. */+export function lanProblem(addresses: ReachableAddresses = reachableAddresses()): string | null {+ return addresses.lan.length ? null : "--lan: this machine has no private network address, so --lan would reach nobody. Use --public-url, --domain or --tailscale.";+}++export type ReachCheck = { ok: true; at: number } | { ok: false; kind: "other-server" | "unreachable"; reason?: string };++/** Whether `origin` answers with this server's own descriptor; never sends a code or a credential. */+export async function checkReach(port: number, origin: string, fetchImpl: typeof fetch = fetch, now = Date.now): Promise<ReachCheck> {+ try {+ const local = await (await fetchImpl(`http://127.0.0.1:${port}${DESCRIPTOR}`, { signal: AbortSignal.timeout(3_000) })).json() as { environmentId?: unknown };+ const response = await fetchImpl(`${origin}${DESCRIPTOR}`, { signal: AbortSignal.timeout(5_000), redirect: "error", cache: "no-store" });+ const remote = await response.json().catch(() => null) as { environmentId?: unknown } | null;+ if (typeof local.environmentId !== "string") return { ok: false, kind: "unreachable", reason: "this server didn't answer" };+ if (remote?.environmentId === local.environmentId) return { ok: true, at: now() };+ return remote?.environmentId ? { ok: false, kind: "other-server" } : { ok: false, kind: "unreachable", reason: `HTTP ${response.status}` };+ } catch (error) {+ const code = (error as { cause?: { code?: string } })?.cause?.code;+ return { ok: false, kind: "unreachable", reason: code === "ECONNREFUSED" ? "connection refused" : code === "ENOTFOUND" ? "no such name yet" : code ?? "no answer" };+ }+}++/** Checks again for up to `budgetMs`: a tunnel, a certificate or a tailnet name can take a few seconds to answer. */+export async function waitForReach(port: number, origin: string, budgetMs = 15_000, check = checkReach, pause = (ms: number) => new Promise((done) => setTimeout(done, ms)), now = Date.now): Promise<ReachCheck> {+ const deadline = now() + budgetMs;+ let last: ReachCheck = { ok: false, kind: "unreachable" };+ do {+ last = await check(port, origin);+ if (last.ok || last.kind === "other-server") return last;+ await pause(1_000);+ } while (now() < deadline);+ return last;+}++const clock = (at: number) => new Date(at).toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" });++const NOTE: Record<Route, string> = {+ "public-url": "",+ domain: "",+ tunnel: "MausBot web address",+ tailscale: "your tailnet",+ lan: "this network only, not encrypted",+};++/** The Reach line (and its fix, when the address doesn't answer as this server). `check` is absent for the LAN. */+export function reachLines(route: Route, origin: string, port: number, prefix: string, check?: ReachCheck): string[] {+ if (!check) return [`Reach ${origin} ${NOTE[route]}`.trimEnd()];+ if (check.ok) return [`Reach ${origin} ✓ answers as this server (${clock(check.at)})${NOTE[route] ? ` · ${NOTE[route]}` : ""}`];+ if (check.kind === "other-server") return [`Reach ✗ ${origin} answers as a different server.`, ` Check your tunnel or proxy points at this machine's port ${port}.`];+ if (route === "domain") return [`Reach … ${origin} doesn't answer yet (${check.reason ?? "no answer"}).`, " Check the domain's DNS points at this machine and ports 80 and 443 are open; the certificate follows."];+ return [`Reach ✗ ${origin} doesn't reach this server (${check.reason ?? "no answer"}).`, ` Point your tunnel or proxy at http://127.0.0.1:${port} (on another machine: add --lan and use this machine's address), then run: ${prefix} status`];+}++/** `serve` with no way in: nothing to pair from elsewhere yet, so no code; the ways in, as commands that paste. */+export function noRouteLines(port: number, prefix: string): string[] {+ return [+ `Listening on 127.0.0.1:${port}, reachable from this machine only.`,+ "",+ "Pick a way in and run again:",+ ` ${prefix} serve --public-url https://… you already have HTTPS in front (cloudflared, Caddy)`,+ ` ${prefix} serve --domain maus.example.com we get the certificate (ports 80, 443)`,+ ` ${prefix} serve --tailscale your tailnet (needs Tailscale)`,+ ` ${prefix} serve --lan this network only, not encrypted`,+ ` ${prefix} serve --tunnel a free MausBot web address; sign in first: ${prefix} login`,+ `Sign in from a browser on this machine with the link from: ${prefix} pair`,+ ];+}++/** Where a browser on the same machine opens a code's link: the configured loopback address (Docker's published port),+ * or this server's own port. */+export function localLinkBase(publicUrl: string | null, port: number, env: NodeJS.ProcessEnv = process.env): { base: string; place: "machine" | "docker" } {+ const docker = Boolean(env.OMB_CLI_PREFIX?.includes("docker"));+ if (publicUrl && isLoopbackHost(new URL(publicUrl).hostname)) return { base: publicUrl, place: docker ? "docker" : "machine" };+ return { base: `http://127.0.0.1:${port}`, place: "machine" };+}diff --git a/server/cli-service-trust.e2e.test.ts b/server/cli-service-trust.e2e.test.tsindex e53620691a..5f71d581d6 100644--- a/server/cli-service-trust.e2e.test.ts+++ b/server/cli-service-trust.e2e.test.ts@@ -44,7 +44,7 @@ describe.skipIf(process.platform === "win32")("openmausbot serve under service lserve.stdout!.on("data", (chunk) => (output += chunk));serve.stderr!.on("data", (chunk) => (output += chunk));const deadline = Date.now() + 40_000;- while (!output.includes("stop with Ctrl+C")) {+ while (!output.includes("access add [email protected]")) {if (serve.exitCode !== null) throw new Error(`serve exited:\n${output}`);if (Date.now() > deadline) throw new Error(`serve never finished starting:\n${output}`);await new Promise((resolve) => setTimeout(resolve, 200));@@ -56,10 +56,10 @@ describe.skipIf(process.platform === "win32")("openmausbot serve under service lawait removeTempDir(home);});- it("prints a pairing code for the CLI that started the server and keeps running", async () => {+ it("not in a terminal, prints no code into a log; points at email sign-in, and keeps running", async () => {expect(output).toContain("local requests: service trust (OMB_LOOPBACK_TRUST)");- expect(output).toMatch(/pairing code: {2}[A-Z0-9]{4}-[A-Z0-9]{4}-[A-Z0-9]{4}/);- expect(output).not.toContain("no pairing code");+ expect(output).not.toMatch(/Pairing code {3}[A-Z0-9]{4}-/);+ expect(output).toContain("Let people sign in with their email: openmausbot access add [email protected]");expect(serve.exitCode).toBeNull();expect((await fetch(`http://127.0.0.1:${PORT}/api/health`)).status).toBe(200);});diff --git a/server/cli-usage.ts b/server/cli-usage.tsindex a36d90f5e4..8389c2776c 100644--- a/server/cli-usage.ts+++ b/server/cli-usage.ts@@ -21,21 +21,26 @@ export const HEADLESS_USAGE = `Drive a running workspace (scripts, CI, other ageToken: OPENMAUSBOT_TOKEN or --token-file FILE. --json prints one JSON document;progress goes to stderr (--quiet drops it). openmausbot help VERB for the details.`;+/** The usage text, its commands written the way this CLI was started (`npx openmausbot …`). */+export function usage(prefix = "openmausbot"): string {+ return USAGE.split("\n").map((line) => line.replace(/^(\s+)openmausbot(?= )/, `$1${prefix}`)).join("\n");+}+export const USAGE = `openmausbot — your team of AI bots, ready in a few stepsopenmausbot set up once, then open your workspaceopenmausbot setup [--data-dir DIR]openmausbot start [the same options as serve]openmausbot serve [--port 8799] [--data-dir DIR] [--label NAME]- [--public-url https://host] [--tailscale | --tunnel | --domain HOST] [--no-pair]- openmausbot pair [--label NAME] [--client] [--phone ios|android] [--ttl 24h]- [--public-url https://host]- openmausbot sessions [revoke ID]+ [--public-url https://host | --domain HOST | --tunnel | --tailscale] [--lan]+ openmausbot pair [--label NAME] [--phone [ios|android]] [--ttl 24h] [--public-url https://host]+ openmausbot devices [revoke ID]openmausbot status+ openmausbot --versionopenmausbot login [--email [email protected]]openmausbot logoutopenmausbot access list | add EMAIL [--chat-only] | remove EMAIL- openmausbot service install [--domain HOST | --tunnel | --tailscale] [--port N] [--data-dir DIR] | uninstall+ openmausbot service install [the same way-in options as serve] [--port N] [--data-dir DIR] | uninstall[--sentinel] (the health scan below, every two minutes, instead of the server)openmausbot sentinel [--data-dir DIR] [--out DIR] [--once] [--json] (read-only health scan; see --help)openmausbot browser install [--with-deps] | status@@ -47,11 +52,15 @@ export const USAGE = `openmausbot — your team of AI bots, ready in a few stepssetup choose AI access and optional phone access; keep existing bots and chatsstart same as openmausbot: use your saved settings and open the workspace-serve starts the server without prompts and prints a pairing link + QR code-pair mints a pairing code against a running server (--client: chat only;- --ttl keeps it open up to 24h, still single use)-sessions lists paired devices; "sessions revoke ID" signs one out-status what the server says about itself+serve starts the server without prompts; in a terminal it prints a pairing+ code, the link to paste into the desktop app (+ → Connect to a+ server) and a QR for a phone+pair a new pairing code for the running server, with its link and QR+ (--phone: chat and approvals only; --ttl keeps it open up to 24h,+ still single use)+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 serverlogin signs this machine in to an OpenMausBot account (an emailed code)and reserves its public address for --tunnellogout releases that address and signs out@@ -60,8 +69,8 @@ access who may sign in with an emailed code at /pair: an address orTakes effect at once, no restart.service keep the server running across reboots: writes a systemd unit(Linux) or a launchd agent (macOS) for the same serve options and- prints the commands that install it. Install the package- permanently first (npm install -g openmausbot).+ prints the commands that install it. Run from npx, it first+ installs a copy of this version next to your data for the service.browser install: the bots' browser engine (agent-browser, pinned) into thedata dir, and Chrome for Testing into the user's browser cache.--with-deps also installs@@ -76,9 +85,16 @@ fleet many client workspaces on one Linux server, each its own account,on a Unix socket only USER may open, so the workspace running asUSER manages the others from Settings → Installations.+Ways in (pick one; --lan can join any):+--public-url you already have HTTPS in front (cloudflared, Caddy, nginx):+ the link uses that address, after checking it reaches this+ server. http:// is accepted only for a private network address.+--lan this network only, plain http: listens on this machine's+ private addresses and answers nobody on the open internet--tailscale serve over your tailnet: Tailscale terminates HTTPS and thelink uses this machine's MagicDNS name (needs Tailscale signed in- and HTTPS certificates enabled for the tailnet)+ and HTTPS certificates enabled for the tailnet); the share ends+ when serve stops--tunnel serve at a public https://c-… address through aCloudflare tunnel: no domain, no proxy, no open port. Run\`openmausbot login\` once on this machine first.@@ -88,7 +104,7 @@ fleet many client workspaces on one Linux server, each its own account,open ports 80 and 443.--no-open do not open a browser window---no-pair skip phone setup and do not print a pairing code+--no-pair do not print a pairing code--local start locally this time, ignoring saved remote-access settings${HEADLESS_USAGE}diff --git a/server/cli.test.ts b/server/cli.test.tsindex bc63e2da2c..6e59a7084d 100644--- a/server/cli.test.ts+++ b/server/cli.test.ts@@ -1,4 +1,4 @@-import { spawn, type ChildProcess } from "node:child_process";+import { spawn, spawnSync, type ChildProcess } from "node:child_process";import { existsSync, mkdirSync, mkdtempSync, readFileSync, writeFileSync } from "node:fs";import { tmpdir } from "node:os";import { dirname, join, resolve } from "node:path";@@ -6,7 +6,8 @@ import { fileURLToPath } from "node:url";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import { applyStartupPreferences, parseArgs, runAccess, runLogin, runOnboardingCommand, serverEntry, type CliOptions, verifyPhoneEndpoint } from "./cli.ts";-import { browserSignInLines, formatSessions, pairingBlock, qrToString } from "./cli-pairing.ts";+import { browserSignInLines, formatSessions, pairingBlock, qrToString, untilText } from "./cli-pairing.ts";+import { reachableAddresses } from "./lan-address.ts";import { readAdminActivityRange } from "./admin-activity.ts";import { SetupCancelled } from "./cli-prompts.ts";import { removeTempDir, waitForExit } from "./testing/cleanup.ts";@@ -48,7 +49,7 @@ describe("openmausbot command line", () => {expect(parseArgs(["dance"], {})).toEqual({ error: 'unknown command "dance"' });expect(parseArgs(["serve", "--port"], {})).toEqual({ error: "--port needs a value" });expect(parseArgs(["serve", "--port", "70000"], {})).toEqual({ error: "--port must be 1-65535" });- expect(parseArgs(["pair", "--public-url", "mini.example"], {})).toEqual({ error: "--public-url must start with http:// or https://" });+ expect(parseArgs(["pair", "--public-url", "mini.example"], {})).toEqual({ error: "--public-url must start with https:// (or http:// on your own network)" });expect(parseArgs(["serve", "--bogus"], {})).toEqual({ error: 'unknown argument "--bogus"' });expect(parseArgs(["serve", "--tunnel"], {})).toMatchObject({ command: "serve", tunnel: true });expect(parseArgs(["setup", "--data-dir", "/tmp/cli-setup"], {})).toMatchObject({ command: "setup", dataDir: resolve("/tmp/cli-setup") });@@ -73,64 +74,71 @@ describe("openmausbot command line", () => {expect(parseArgs(["serve", "--domain", "maus.example.com", "--tunnel"], {})).toEqual({ error: expect.stringContaining("--domain already gives") });});- it("takes the phone kind non-interactively, because a scripted pair never sees the chooser", () => {+ it("takes the phone kind non-interactively; --phone alone is a chat-only code for any phone", () => {expect(parseArgs(["pair", "--phone", "android"], {})).toMatchObject({ command: "pair", phone: "android" });expect(parseArgs(["pair", "--phone", "iOS"], {})).toMatchObject({ phone: "ios" });- expect(parseArgs(["pair", "--phone", "blackberry"], {})).toEqual({ error: expect.stringContaining("ios or android") });+ expect(parseArgs(["pair", "--phone"], {})).toMatchObject({ phone: "ios" });+ expect(parseArgs(["pair", "--chat-only"], {})).toMatchObject({ client: true });+ expect(parseArgs(["pair", "--phone", "blackberry"], {})).toEqual({ error: expect.stringContaining("blackberry") });+ expect(parseArgs(["serve", "--phone", "blackberry"], {})).toEqual({ error: expect.stringContaining("ios or android") });+ expect(parseArgs(["devices", "revoke", "a1"], {})).toMatchObject({ command: "sessions", revoke: "a1" });+ expect(parseArgs(["--version"], {})).toMatchObject({ command: "version" });});- it("prints a scannable block with the link, or says where to type the code", () => {- const block = pairingBlock({ code: "ABCD-EFGH-JKLM", url: "https://mini.example/pair#code=ABCD-EFGH-JKLM", expiresAt: Date.now() + 60_000 });- expect(block).toContain("pairing code: ABCD-EFGH-JKLM");- expect(block).toContain("open or scan: https://mini.example/pair#code=ABCD-EFGH-JKLM");- expect(block).toMatch(/[▀▄█]/);- const noUrl = pairingBlock({ code: "ABCD-EFGH-JKLM", url: null, expiresAt: Date.now(), hint: "set OMB_PUBLIC_URL" });- expect(noUrl).toContain("/pair on the address you use");- expect(noUrl).toContain("set OMB_PUBLIC_URL");- expect(qrToString("https://example.com").length).toBeGreaterThan(200);+ it("--public-url takes https, or http on a private network only", () => {+ expect(parseArgs(["serve", "--public-url", "https://maus.example.com"], {})).toMatchObject({ publicUrl: "https://maus.example.com" });+ expect(parseArgs(["serve", "--public-url", "http://192.168.1.20:8799"], {})).toMatchObject({ publicUrl: "http://192.168.1.20:8799" });+ expect(parseArgs(["serve", "--public-url", "http://maus.example.com"], {})).toEqual({ error: expect.stringContaining("plain http isn't encrypted") });+ expect(parseArgs(["serve", "--lan"], {})).toMatchObject({ lan: true });+ expect(parseArgs(["serve", "--lan", "--local"], {})).toEqual({ error: expect.stringContaining("--local") });});- it("adds a link that signs in a browser on this computer, which is no longer the owner by being here", () => {- const local = "http://127.0.0.1:8799/pair#code=ABCD-EFGH-JKLM";- const block = pairingBlock({ code: "ABCD-EFGH-JKLM", url: null, localUrl: local, expiresAt: Date.now() + 60_000, hint: "set OMB_PUBLIC_URL" });- expect(block).toContain(`this computer: ${local}`);- expect(block).toContain("/pair on the address you use");- expect(block).not.toContain(qrToString(local));- const guided = browserSignInLines(local, "ABCD-EFGH-JKLM", Date.now() + 60_000);- expect(guided).toContain(local);- expect(guided).toContain("ABCD-EFGH-JKLM");- expect(guided).toContain("openmausbot pair");- });+ describe("the pairing block", () => {+ const now = Date.parse("2026-11-07T10:00:00");+ const link = "https://mini.example/pair#code=ABCD-EFGH-JKLM";+ const base = { code: "ABCD-EFGH-JKLM", expiresAt: now + 10 * 60_000, chatOnly: false, link, prefix: "npx openmausbot", now };++ it("shows one code, its link to paste into the desktop app, a QR, and the phone command the way the CLI was started", () => {+ const out = pairingBlock(base);+ expect(out).toMatch(/^Pairing code {3}ABCD-EFGH-JKLM {3}works once, until .+ · everything$/m);+ expect(out).toContain(`Link ${link}`);+ expect(out).toContain("+ → Connect to a server, paste the link");+ expect(out).toContain(qrToString(link));+ expect(out).toContain("For a phone (chat and approvals only) npx openmausbot pair --phone");+ expect(out).not.toMatch(/omb_pair_|phone app:|this computer:/);+ expect(pairingBlock({ ...base, chatOnly: true })).toContain("· chat and approvals");+ });- describe("the two links one pairing window has", () => {- const url = "https://mini.example/pair#code=ABCD-EFGH-JKLM";- const invite = `openmausbot://pair?address=https%3A%2F%2Fmini.example&token=omb_pair_${"a".repeat(43)}&name=mini`;- const block = (over: Record<string, unknown> = {}) =>- pairingBlock({ code: "ABCD-EFGH-JKLM", url, inviteUrl: invite, expiresAt: Date.now() + 60_000, ...over });+ it("with no way in: no link and no QR, the browser on this machine, and the command that lists the ways in", () => {+ const local = "http://127.0.0.1:8799/pair#code=ABCD-EFGH-JKLM";+ const out = pairingBlock({ ...base, link: null, localLink: local });+ expect(out).toContain("reachable from this machine only");+ expect(out).toContain(`Browser on this machine ${local}`);+ expect(out).toContain("pick a way in first: npx openmausbot serve --help");+ expect(out).not.toMatch(/[▀▄█]/);+ expect(pairingBlock({ ...base, link: null, localLink: "http://localhost:8080/pair#code=X", localPlace: "docker" })).toContain("Browser on the Docker host http://localhost:8080/pair#code=X");+ });it("gives an Android phone the app-scheme QR, because its scanner rejects https", () => {- const out = block({ phone: "android" });+ const invite = `openmausbot://pair?address=https%3A%2F%2Fmini.example&token=omb_pair_${"a".repeat(43)}&name=mini`;+ const out = pairingBlock({ ...base, chatOnly: true, inviteUrl: invite, phone: "android" });expect(out).toContain(qrToString(invite));- expect(out).not.toContain(qrToString(url));- expect(out).toContain("Scan that in the OpenMausBot app");- expect(out).toContain(`web browser: ${url}`);- expect(out).not.toContain("open or scan:");+ expect(out).not.toContain(qrToString(link));+ expect(out).not.toContain(invite);+ expect(pairingBlock({ ...base, inviteUrl: invite, phone: "ios" })).toContain(qrToString(link));});- it("gives everyone else the web QR, and still prints the app link rather than only naming it", () => {- const out = block({ phone: "ios" });- expect(out).toContain(qrToString(url));- expect(out).not.toContain(qrToString(invite));- expect(out).toContain(`phone app: ${invite}`);- expect(out).toContain(`open or scan: ${url}`);+ it("says until when as a clock time, and tomorrow when a code outlives today", () => {+ expect(untilText(now + 10 * 60_000, now)).not.toMatch(/tomorrow|minutes/);+ expect(untilText(now + 24 * 3_600_000, now)).toMatch(/^tomorrow /);});- it("says plainly when an Android phone asked for an app link this server cannot build", () => {- const out = block({ phone: "android", inviteUrl: null });- expect(out).toContain(qrToString(url));- expect(out).toContain("The Android app needs the phone-app link");- expect(out).toContain("OMB_PUBLIC_URL");- expect(out).not.toContain("Scan that in the OpenMausBot app");+ it("signs a browser on this computer in during the guided start", () => {+ const local = "http://127.0.0.1:8799/pair#code=ABCD-EFGH-JKLM";+ const guided = browserSignInLines(local, "ABCD-EFGH-JKLM", Date.now() + 60_000);+ expect(guided).toContain(local);+ expect(guided).toContain("ABCD-EFGH-JKLM");+ expect(guided).toContain("openmausbot pair");});});@@ -144,7 +152,7 @@ describe("openmausbot command line", () => {expect(table).toContain("(unnamed)");expect(table).toMatch(/a1\s+My MacBook\s+admin\s+just now/);expect(table).toMatch(/b2\s+\(unnamed\)\s+client\s+3 h ago/);- expect(table).toContain("sessions revoke <id>");+ expect(table).toContain("devices revoke <id>");expect(formatSessions([{ id: "c3", label: "Nightly CI", scopes: ["client"], lastSeenAt: now, expiresAt: now, token: true }], now)).toContain("Nightly CI (token)");});@@ -168,11 +176,17 @@ describe("openmausbot command line", () => {child.stderr.on("data", (c) => (out += String(c)));try {const deadline = Date.now() + 60_000;- while (!out.includes("open or scan:") && Date.now() < deadline && child.exitCode === null) await new Promise((r) => setTimeout(r, 200));- expect(out).toContain(`OpenMausBot is running on http://127.0.0.1:${port}, reachable at https://mini.example`);- expect(out).toMatch(/pairing code: [A-Z2-9]{4}-[A-Z2-9]{4}-[A-Z2-9]{4}/);- expect(out).toContain("open or scan: https://mini.example/pair#code=");- expect(out).toMatch(/[▀▄█]/);+ while (!out.includes("Get a pairing code:") && Date.now() < deadline && child.exitCode === null) await new Promise((r) => setTimeout(r, 200));+ expect(out).toContain('server "cli test"');+ expect(out).toMatch(/Reach {4}✗ https:\/\/mini\.example doesn't reach this server/);+ expect(out, "not a terminal: no code goes into a log").not.toMatch(/Pairing code {3}[A-Z2-9]{4}-/);+ expect(out).toContain("Get a pairing code: openmausbot pair");+ expect(out).not.toContain("Ctrl+C");+ const paired = spawnSync(process.execPath, ["--experimental-strip-types", join(SERVER_DIR, "openmausbot.ts"), "pair", "--port", String(port)], { cwd: join(SERVER_DIR, ".."), env: { PATH: process.env.PATH ?? "", HOME: home }, encoding: "utf8" });+ expect(paired.stdout).toMatch(/Pairing code {3}[A-Z2-9]{4}-[A-Z2-9]{4}-[A-Z2-9]{4} {3}works once, until .+ · everything/);+ expect(paired.stdout).toContain("Link https://mini.example/pair#code=");+ expect(paired.stdout).toMatch(/[▀▄█]/);+ expect(paired.stdout).toContain("The code works once the address answers.");const descriptor: any = await (await fetch(`http://127.0.0.1:${port}/.well-known/openmausbot/environment`)).json();expect(descriptor.label).toBe("cli test");const pairing: any = await (await fetch(`http://127.0.0.1:${port}/api/auth/pairing`)).json();@@ -192,6 +206,39 @@ describe("openmausbot command line", () => {}, 90_000);});+describe("serve --lan", () => {+ it("answers on this network's address, never as the owner to another machine, and links to that address", async () => {+ const lan = reachableAddresses().lan[0];+ const home = mkdtempSync(join(tmpdir(), "omb-cli-lan-"));+ const port = workerPort(21000, 9000);+ const child = spawn(process.execPath, ["--experimental-strip-types", join(SERVER_DIR, "openmausbot.ts"), "serve", "--lan", "--port", String(port), "--data-dir", join(home, "data")], {+ cwd: join(SERVER_DIR, ".."),+ env: { PATH: process.env.PATH ?? "", HOME: home, USERPROFILE: home, OMB_WEBHOOK_PORT: String(port + 1), OMB_BROWSER_CONNECTION: join(home, "browser-connection.json") },+ stdio: ["ignore", "pipe", "pipe"],+ });+ let out = "";+ child.stdout.on("data", (c) => (out += String(c)));+ child.stderr.on("data", (c) => (out += String(c)));+ try {+ const deadline = Date.now() + 60_000;+ while (!/Get a pairing code:|Pick a way in/.test(out) && Date.now() < deadline && child.exitCode === null) await new Promise((r) => setTimeout(r, 200));+ if (!lan) {+ expect(out).toContain("--lan: this machine has no private network address");+ return;+ }+ expect(out).toContain(`Reach http://${lan}:${port} this network only, not encrypted`);+ const spoofed = await fetch(`http://${lan}:${port}/api/bots`, { headers: { host: `127.0.0.1:${port}` } });+ expect(spoofed.status, "a LAN peer that writes a loopback Host is still a stranger").toBe(403);+ const pairing: any = await (await fetch(`http://127.0.0.1:${port}/api/auth/pairing`, { method: "POST", headers: { "content-type": "application/json" }, body: "{}" })).json();+ expect(pairing.url).toBe(`http://${lan}:${port}/pair#code=${pairing.code}`);+ } finally {+ child.kill("SIGTERM");+ await waitForExit(child, { signal: "SIGTERM" });+ await removeTempDir(home);+ }+ }, 90_000);+});+describe("terminal onboarding commands", () => {const inputTty = Object.getOwnPropertyDescriptor(process.stdin, "isTTY");const outputTty = Object.getOwnPropertyDescriptor(process.stdout, "isTTY");@@ -414,7 +461,7 @@ describe.skipIf(process.platform === "win32")("serve --tunnel", () => {child.stderr?.on("data", (chunk) => (err += String(chunk)));try {expect(await exited(child)).toBe(1);- expect(err).toContain("run `openmausbot login` first");+ expect(err).toContain("run openmausbot login first");let dead = false;try {await fetch(`http://127.0.0.1:${port}/api/health`);@@ -464,9 +511,9 @@ describe.skipIf(process.platform === "win32")("serve --tunnel", () => {const gateway = `http://127.0.0.1:${originPort}`;try {const deadline = Date.now() + 60_000;- while (!out.includes("OpenMausBot is running") && Date.now() < deadline && child.exitCode === null) await new Promise((r) => setTimeout(r, 200));+ while (!/^Reach /m.test(out) && Date.now() < deadline && child.exitCode === null) await new Promise((r) => setTimeout(r, 200));expect(out).toContain("using the installation credential from OMB_INSTALLATION_CREDENTIAL");- expect(out).toContain(`reachable at ${stub.endpointUrl}`);+ expect(out).toMatch(new RegExp(`^Reach .*${stub.endpointUrl.replace(/[.]/g, "\\.")}`, "m"));expect(existsSync(join(dataDir, "tunnel-account.json"))).toBe(false);let status = 0;const gatewayDeadline = Date.now() + 20_000;@@ -516,9 +563,11 @@ describe.skipIf(process.platform === "win32")("serve --tunnel", () => {const gateway = `http://127.0.0.1:${originPort}`;try {const deadline = Date.now() + 60_000;- while (!out.includes("open or scan:") && Date.now() < deadline && child.exitCode === null) await new Promise((r) => setTimeout(r, 200));- expect(out).toContain(`OpenMausBot is running on http://127.0.0.1:${port}, reachable at ${stub.endpointUrl}`);- expect(out).toContain(`open or scan: ${stub.endpointUrl}/pair#code=`);+ while (!out.includes("Get a pairing code:") && Date.now() < deadline && child.exitCode === null) await new Promise((r) => setTimeout(r, 200));+ expect(out).toContain('server "tunnel test"');+ expect(out).toMatch(new RegExp(`^Reach .*${stub.endpointUrl.replace(/[.]/g, "\\.")}`, "m"));+ const pairOut = spawnSync(process.execPath, ["--experimental-strip-types", join(SERVER_DIR, "openmausbot.ts"), "pair", "--port", String(port), "--data-dir", dataDir], { cwd: join(SERVER_DIR, ".."), env: { PATH: process.env.PATH ?? "", HOME: home }, encoding: "utf8" }).stdout;+ expect(pairOut).toContain(`Link ${stub.endpointUrl}/pair#code=`);expect(stub.calls).toContain("POST /v1/installations/self/endpoint");let descriptor: Response | null = null;@@ -539,7 +588,7 @@ describe.skipIf(process.platform === "win32")("serve --tunnel", () => {expect(((await stranger.json()) as { error: string }).error).toMatch(/through a proxy/);expect(await (await fetch(`${gateway}/api/health`)).json()).toEqual({ app: "openmausbot" });expect(typeof ((await (await fetch(`http://127.0.0.1:${port}/api/health`)).json()) as { pid: unknown }).pid).toBe("number");- const match = /pairing code: ([A-Z2-9-]+)/.exec(out);+ const match = /Pairing code {3}([A-Z2-9-]+)/.exec(pairOut);expect(match).toBeTruthy();const paired = await fetch(`${gateway}/api/auth/pair`, {method: "POST",@@ -623,10 +672,11 @@ describe.skipIf(process.platform === "win32")("serve --domain", () => {child.stderr?.on("data", (chunk) => (out += String(chunk)));try {const deadline = Date.now() + 60_000;- while (!out.includes("open or scan:") && Date.now() < deadline && child.exitCode === null) await new Promise((r) => setTimeout(r, 200));- expect(out).toContain(`OpenMausBot is running on http://127.0.0.1:${port}, reachable at https://omb.example.test`);+ while (!out.includes("Get a pairing code:") && Date.now() < deadline && child.exitCode === null) await new Promise((r) => setTimeout(r, 200));expect(out).toContain("https: Caddy serves https://omb.example.test");- expect(out).toContain("open or scan: https://omb.example.test/pair#code=");+ expect(out).toMatch(/^Reach {4}… https:\/\/omb\.example\.test doesn't answer yet/m);+ const pairOut = spawnSync(process.execPath, ["--experimental-strip-types", join(SERVER_DIR, "openmausbot.ts"), "pair", "--port", String(port), "--data-dir", dataDir], { cwd: join(SERVER_DIR, ".."), env: { PATH: process.env.PATH ?? "", HOME: home }, encoding: "utf8" }).stdout;+ expect(pairOut).toContain("Link https://omb.example.test/pair#code=");const args = readFileSync(join(home, "caddy-args.txt"), "utf8").trim();expect(args).toMatch(/^run --config .*Caddyfile --adapter caddyfile$/);const caddyfile = readFileSync(join(dataDir, "caddy", "Caddyfile"), "utf8");diff --git a/server/cli.ts b/server/cli.tsindex 99caa59778..2682c18613 100644--- a/server/cli.ts+++ b/server/cli.ts@@ -34,11 +34,15 @@ import { runSentinelCli } from "./sentinel/cli.ts";import { runFleetCommand, type FleetInput } from "./fleet-cli.ts";import { startFleetAgent } from "./fleet-agent.ts";import { fleetLayout } from "./fleet.ts";-import { explainTailscaleFailure, tailscaleServe, tailscaleServeOff, tailscaleStatus, type TailscaleStatus } from "./tailscale.ts";+import { clearLeftoverTailscaleServe, explainTailscaleFailure, tailscaleServe, tailscaleStatus, type TailscaleStatus } from "./tailscale.ts";import { defaultSetupIo, SetupCancelled, type SetupIo } from "./cli-prompts.ts";-import { HEADLESS_VERB_NAMES, USAGE } from "./cli-usage.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 { 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";+import { isLoopbackHost } from "../electron/server-address.mjs";import { parseDuration } from "./headless/args.ts";import type { AppConfig } from "./config.ts";import {@@ -64,7 +68,7 @@ import {const HERE = dirname(fileURLToPath(import.meta.url));export interface CliOptions {- command: "setup" | "start" | "serve" | "pair" | "sessions" | "status" | "login" | "logout" | "access" | "service" | "browser" | "fleet" | "help";+ command: "setup" | "start" | "serve" | "pair" | "sessions" | "status" | "login" | "logout" | "access" | "service" | "browser" | "fleet" | "help" | "version";port: number;dataDir: string;label?: string;@@ -73,6 +77,8 @@ export interface CliOptions {domain?: string;tailscale: boolean;tunnel: boolean;+ /** `serve --lan`: every private address of this machine, plain http, each connection held to private ends. */+ lan?: boolean;client: boolean;pair: boolean;revoke?: string;@@ -113,16 +119,16 @@ export interface CliOptions {pairTtlMs?: number;}-const COMMANDS = ["setup", "start", "serve", "pair", "sessions", "status", "login", "logout", "access", "service", "browser", "fleet", "help", "--help", "-h"];+const COMMANDS = ["setup", "start", "serve", "pair", "sessions", "devices", "status", "login", "logout", "access", "service", "browser", "fleet", "help", "--help", "-h", "--version", "-v", "version"];export function parseArgs(argv: string[], env: NodeJS.ProcessEnv = process.env): CliOptions | { error: string } {- const implicitStart = !argv.length || (argv[0]!.startsWith("--") && argv[0] !== "--help");+ const implicitStart = !argv.length || (argv[0]!.startsWith("--") && argv[0] !== "--help" && argv[0] !== "--version");const [command = "start", ...rest] = implicitStart ? ["start", ...argv] : argv;if (!COMMANDS.includes(command)) {return { error: `unknown command "${command}"` };}const options: CliOptions = {- command: command === "--help" || command === "-h" ? "help" : (command as CliOptions["command"]),+ command: command === "--help" || command === "-h" ? "help" : command === "--version" || command === "-v" ? "version" : command === "devices" ? "sessions" : (command as CliOptions["command"]),port: Number(env.OMB_PORT || 8799),dataDir: env.OMB_DATA_DIR || join(homedir(), ".openmausbot"),tailscale: false,@@ -147,26 +153,29 @@ export function parseArgs(argv: string[], env: NodeJS.ProcessEnv = process.env):else if (arg === "--label") options.label = value();else if (arg === "--public-url") options.publicUrl = value().replace(/\/+$/, "");else if (arg === "--tailscale") options.tailscale = true;+ else if (arg === "--lan") options.lan = true;else if (arg === "--domain") {const domain = normalizeDomainOption(value());if (typeof domain !== "string") return domain;options.domain = domain;}else if (arg === "--tunnel") options.tunnel = true;- else if (arg === "--client") options.client = true;- // Which phone will scan, for runs nobody types into; only Android needs a different QR.+ 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") {- const kind = value().toLowerCase();- if (kind !== "ios" && kind !== "android") return { error: "--phone takes ios or android" };- options.phone = kind;+ const kind = rest[i + 1]?.toLowerCase();+ if (kind === "ios" || kind === "android") { options.phone = kind; i += 1; }+ else if (options.command === "pair") options.phone = "ios";+ else return { error: "--phone takes ios or android" };}else if (options.command === "pair" && arg === "--ttl") options.pairTtlMs = parseDuration(value(), "--ttl", { min: 60_000 });+ else if (arg === "--help" || arg === "-h") options.command = "help";else if (arg === "--no-pair") options.pair = false;else if (arg === "--no-open") options.open = false;else if (arg === "--local") options.local = true;else if (arg === "--json") options.json = true;else if (arg === "--email") options.email = value();- else if (options.command === "sessions" && arg === "revoke") options.revoke = value();+ else if (options.command === "sessions" && (arg === "revoke" || arg === "list")) { if (arg === "revoke") options.revoke = value(); }else if (options.command === "access" && !options.accessAction && (arg === "list" || arg === "add" || arg === "remove")) {options.accessAction = arg;if (arg !== "list") options.email = value();@@ -198,12 +207,13 @@ 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" };- if (options.publicUrl && !/^https?:\/\//.test(options.publicUrl)) return { error: "--public-url must start with http:// or https://" };+ 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.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)) return { error: "--local cannot be combined with a remote-access option" };+ if (options.local && (options.tailscale || options.tunnel || options.publicUrl || options.lan)) 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" };@@ -298,24 +308,19 @@ export async function openDashboard(port: number, env = process.env): Promise<bo});}+/** Something already answers there as a MausBot server (before this one has started). */+const answersAsMausBot = async (origin: string) => typeof (await fetch(`${origin}/.well-known/openmausbot/environment`, { signal: AbortSignal.timeout(3_000) }).then((r) => r.json() as Promise<{ environmentId?: unknown }>).catch(() => null))?.environmentId === "string";+/** Its public descriptor must identify this exact server; never sends a pairing code or credential. */export async function verifyPhoneEndpoint(port: number, origin: string): Promise<boolean> {- if (!normalizePhoneOrigin(origin)) return false;- try {- const local = await api(port, "/.well-known/openmausbot/environment");- const remote = await fetch(`${origin}/.well-known/openmausbot/environment`, { signal: AbortSignal.timeout(5000), redirect: "error" });- if (local.status !== 200 || !remote.ok) return false;- const descriptor = await remote.json() as { environmentId?: unknown };- return typeof local.body?.environmentId === "string" && local.body.environmentId.length > 0- && descriptor.environmentId === local.body.environmentId;- } catch { return false; }+ return Boolean(normalizePhoneOrigin(origin)) && (await checkReach(port, origin)).ok;}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.access === "public-url" && (!saved.publicUrl || !normalizePhoneOrigin(saved.publicUrl))) {- throw new Error("The saved phone address is not a valid HTTPS origin. Run openmausbot setup to correct it, or openmausbot --local to start only on this computer.");+ 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.`);}return {...options,@@ -340,7 +345,7 @@ async function showPhonePairing(options: CliOptions, origin: string | undefined,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.");- log("Check the HTTPS connection, then run openmausbot pair again with the same --data-dir and --port.");+ log(`Check the HTTPS connection, then run ${cliCommand("pair")} again with the same --data-dir and --port.`);return false;}for (const line of phonePairingInstructions(options.phone ?? "ios", { origin: origin!, ready })) log(line);@@ -350,57 +355,34 @@ async function showPhonePairing(options: CliOptions, origin: string | undefined,}async function mintPairing(port: number, options: { label?: string; client?: boolean; publicUrl?: string; phone?: "ios" | "android"; guided?: boolean; ttlMs?: number }): Promise<string> {- const request = { ...(options.label ? { label: options.label } : {}), ...(options.client ? { scopes: ["client"] } : {}), ...(options.ttlMs ? { ttlMs: options.ttlMs } : {}) };+ const chatOnly = Boolean(options.client || options.phone);+ const request = { ...(options.label ? { label: options.label } : {}), ...(chatOnly ? { scopes: ["client"] } : {}), ...(options.ttlMs ? { ttlMs: options.ttlMs } : {}) };const { status, body } = await api(port, "/api/auth/pairing", { method: "POST", body: JSON.stringify(request) });if (refusedAsService(status, body)) throw new Error(SERVICE_TRUST_HELP);if (status !== 200) throw new Error(`server refused to mint a pairing code: ${typeof body?.error === "string" ? body.error : status}`);- const url = options.publicUrl ? `${options.publicUrl}/pair#code=${body.code}` : typeof body.url === "string" ? body.url : null;- const invite = (options.publicUrl && typeof body.credential === "string"- ? phonePairingLink({ address: options.publicUrl, token: body.credential, name: typeof body.serverName === "string" ? body.serverName : undefined })+ 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 localUrl = options.phone ? null : `http://127.0.0.1:${port}/pair#code=${body.code}`;- if (options.guided && localUrl) return browserSignInLines(localUrl, body.code, body.expiresAt);- return pairingBlock({ code: body.code, url, inviteUrl: invite, localUrl, expiresAt: body.expiresAt, hint: typeof body.hint === "string" ? body.hint : null, phone: options.phone });+ 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() });}+/** Never asks anything: the running server's own address (its routes) goes in the link. */export async function runPair(options: CliOptions): Promise<number> {if (!(await serverUp(options.port))) {- console.error(`no OpenMausBot server on http://127.0.0.1:${options.port}; start one with \`openmausbot serve\` or set OMB_PORT`);+ console.error(`No MausBot server is running here. Start it: ${cliCommand("serve")}${options.port !== 8799 ? ` (or name its port: --port ${options.port})` : ""}`);return 1;}- if (process.stdin.isTTY && process.stdout.isTTY && !options.label && !options.client && !options.pairTtlMs) {- const advertised = await api(options.port, "/api/auth/pairing");- let launch = options;- let origin = options.publicUrl ?? (typeof advertised.body?.publicUrl === "string" ? advertised.body.publicUrl : undefined);- if (!origin) {- const { readCliStartup } = await import("./cli-setup.ts");- launch = applyStartupPreferences(options, readCliStartup(options.dataDir));- origin = launch.publicUrl;- if (launch.tunnel) origin = describeTunnelAccount(createTunnelAccount({ dataDir: options.dataDir, version: serverVersion() }).credentials.read()).address ?? undefined;- if (launch.tailscale) {- const status = await tailscaleStatus();- if (!("failure" in status) && status.status.dnsName) origin = `https://${status.status.dnsName}`;- }- }- if (!origin || !normalizePhoneOrigin(origin)) {- console.log("Your workspace is running only on this computer. A phone cannot use its localhost address.");- console.log("Stop the server, run openmausbot setup and choose phone access, then start openmausbot again.");- return 1;- }- const ui = defaultSetupIo();- try {- const selected = await ui.choose("Which phone are you connecting?", ["iPhone / iPad — app or Safari", "Android — app or browser", "Cancel"], 0);- if (selected === 2) return 0;- launch = { ...launch, phone: selected === 0 ? "ios" : "android" };- return await showPhonePairing(launch, origin, ui.log) ? 0 : 1;- } catch (error) {- if (!(error instanceof SetupCancelled)) throw error;- console.log("Pairing cancelled. Existing devices are unchanged.");- return 130;- }+ const advertised = await api(options.port, "/api/auth/pairing").catch(() => ({ status: 0, body: {} as any }));+ const origin = options.publicUrl ?? (typeof advertised.body?.publicUrl === "string" ? advertised.body.publicUrl : undefined);+ console.log(await mintPairing(options.port, { label: options.label, client: options.client, publicUrl: origin, phone: options.phone, ttlMs: options.pairTtlMs }));+ if (origin && origin.startsWith("https:") && !isLoopbackHost(new URL(origin).hostname)) {+ const reach = await checkReach(options.port, origin);+ if (!reach.ok) for (const line of [...reachLines("public-url", origin, options.port, cliPrefix(), reach), "The code works once the address answers."]) console.log(line);}- console.log(await mintPairing(options.port, { label: options.label, client: options.client, publicUrl: options.publicUrl, phone: options.phone, ttlMs: options.pairTtlMs }));- if (options.client) console.log("(client scope: chat and approvals only; cannot change settings or pair others)");return 0;}@@ -437,7 +419,7 @@ export async function runSessions(options: CliOptions): Promise<number> {return 0;}if (!sessions.length) {- console.log("no paired devices yet: run `openmausbot pair`");+ console.log(`no paired devices yet: run ${cliCommand("pair")}`);return 0;}console.log(formatSessions(sessions));@@ -445,21 +427,21 @@ export async function runSessions(options: CliOptions): Promise<number> {}export async function runStatus(options: CliOptions, io: CliIo = defaultIo()): Promise<number> {- let code = 0;- try {- const res = await fetch(`http://127.0.0.1:${options.port}/.well-known/openmausbot/environment`);- const body: any = await res.json();- io.log(options.json ? JSON.stringify(body, null, 2) : `${body.label} · OpenMausBot ${body.version} on ${body.platform} · id ${body.environmentId}`);- } catch {- io.error(`no OpenMausBot server on http://127.0.0.1:${options.port}`);- code = 1;+ const body: any = await fetch(`http://127.0.0.1:${options.port}/.well-known/openmausbot/environment`).then((r) => r.json()).catch(() => null);+ if (body && options.json) io.log(JSON.stringify(body, null, 2));+ if (!body) io.error(`No MausBot server is running here. Start it: ${cliCommand("serve")}`);+ if (body && !options.json) {+ io.log(`Server "${body.label}" running · MausBot ${body.version} on ${body.platform}\n Local 127.0.0.1:${options.port}`);+ const address = await api(options.port, "/api/auth/pairing").then((r) => (typeof r.body?.publicUrl === "string" ? r.body.publicUrl as string : null)).catch(() => null);+ if (!address || isLoopbackHost(new URL(address).hostname)) io.log(` Address none: reachable from this machine only. Ways in: ${cliCommand("serve --help")}`);+ else for (const line of reachLines(address.startsWith("http:") ? "lan" : "public-url", address, options.port, cliPrefix(), address.startsWith("http:") ? undefined : await checkReach(options.port, address))) io.log(` ${line.replace(/^Reach /, "Address ")}`);+ const sessions = await api(options.port, "/api/auth/sessions").catch(() => null);+ if (Array.isArray(sessions?.body?.sessions)) io.log(`Paired ${sessions.body.sessions.length} device${sessions.body.sessions.length === 1 ? "" : "s"} ${cliCommand("devices")}`);}- if (!options.json) {- const account = describeTunnelAccount(createTunnelAccount({ dataDir: options.dataDir, version: serverVersion() }).credentials.read());- if (fleetCredential()) io.log(`public address: managed by the fleet (${FLEET_CREDENTIAL_ENV} is set; the address is fetched when serve --tunnel starts)`);- else if (account.address) io.log(`public address: ${account.address} (signed in as ${account.email ?? "?"}; serve it with --tunnel)`);- }- return code;+ const account = options.json ? null : describeTunnelAccount(createTunnelAccount({ dataDir: options.dataDir, version: serverVersion() }).credentials.read());+ if (!options.json && fleetCredential()) io.log(`MausBot web address: managed by the fleet (${FLEET_CREDENTIAL_ENV} is set)`);+ else if (account?.address) io.log(`MausBot web address: ${account.address} (signed in as ${account.email ?? "?"}; serve it with ${cliCommand("serve --tunnel")})`);+ return body ? 0 : 1;}/** Edits the sign-in allow-list in config.json, server live or stopped (read per request); OMB_SIGNIN_EMAILS wins when set. */@@ -518,7 +500,7 @@ export async function runAccess(options: CliOptions, io: CliIo = defaultIo()): Preturn 1;}await write({ admins: without(admins), members: without(members) });- io.log(`${entry} can no longer sign in (existing sessions stay until they expire or are revoked with \`openmausbot sessions revoke\`)`);+ io.log(`${entry} can no longer sign in (existing sessions stay until they expire or are revoked with ${cliCommand("devices revoke ID")})`);return 0;}await write(options.chatOnly ? { admins: without(admins), members: [...without(members), entry] } : { admins: [...without(admins), entry], members: without(members) });@@ -542,7 +524,7 @@ export async function runLogin(options: CliOptions, io: CliIo = defaultIo()): Prif (existing.address) io.log(`already signed in as ${existing.email ?? "?"} (${existing.address}); signing in again refreshes it`);const email = (options.email ?? (await io.ask("Email for your OpenMausBot account: "))).trim();if (!email) {- io.error("an email address is needed: openmausbot login --email [email protected]");+ io.error(`an email address is needed: ${cliCommand("login --email [email protected]")}`);return 1;}try {@@ -566,7 +548,7 @@ export async function runLogin(options: CliOptions, io: CliIo = defaultIo()): Pr}io.log(`Signed in as ${signedIn.email ?? email}.`);io.log(`This machine's public address: ${signedIn.address}`);- io.log("Serve there with: openmausbot serve --tunnel");+ io.log(`Serve there with: ${cliCommand("serve --tunnel")}`);return 0;}@@ -621,11 +603,11 @@ export async function runBrowser(options: CliOptions, io: CliIo = defaultIo()):await ensureChrome(binary, { withDeps: options.withDeps === true, log: io.log });} catch (error) {io.error(`Chrome is not ready: ${message(error)}`);- if (process.platform === "linux" && !options.withDeps) io.error("on Linux, install Chrome's system libraries with `sudo openmausbot browser install --with-deps`, then retry `openmausbot browser install` as the user running serve");+ if (process.platform === "linux" && !options.withDeps) io.error(`on Linux, install Chrome's system libraries with: sudo ${cliCommand("browser install --with-deps")}, then retry ${cliCommand("browser install")} as the user running serve`);return 1;}io.log("browser installed for this user and data directory; run serve as the same user, then enable it under Settings → Computers and per bot");- if (process.platform === "linux" && options.withDeps) io.log("if serve runs as another user, run `openmausbot browser install` from that user's login shell too");+ if (process.platform === "linux" && options.withDeps) io.log(`if serve runs as another user, run ${cliCommand("browser install")} from that user's login shell too`);return 0;}@@ -670,18 +652,18 @@ async function planTunnel(options: CliOptions, log: (line: string) => void, recoaccount = createTunnelAccount({ dataDir: options.dataDir, version: serverVersion(), recovery, log: (line) => log(`tunnel: ${line}`) });if (account.credentials.status === "unavailable") return fail(`${account.credentials.file} exists but could not be read; fix or remove it`);if (!describeTunnelAccount(account.credentials.read()).email) {- return fail("no account on this machine yet: run `openmausbot login` first, then `openmausbot serve --tunnel`");+ return fail(`no account on this machine yet: run ${cliCommand("login")} first, then ${cliCommand("serve --tunnel")}`);}try {const state = await account.service.retry();const saved = tunnelAccess(account.credentials.read()) !== null;- if (state.status === "signed-out") log(`tunnel: the sign-in on this machine expired; run \`openmausbot login\` to renew it${saved ? " (serving the saved address until then)" : ""}`);+ if (state.status === "signed-out") log(`tunnel: the sign-in on this machine expired; run ${cliCommand("login")} to renew it${saved ? " (serving the saved address until then)" : ""}`);else if (state.message) log(`tunnel: ${state.message}${saved ? " Serving the saved address for now." : ""}`);} catch (error) {log(`tunnel: control plane not reachable right now (${message(error)}); using the saved address`);}access = tunnelAccess(account.credentials.read());- if (!access) return fail("this machine has no public address; run `openmausbot login` again");+ if (!access) return fail(`this machine has no public address; run ${cliCommand("login")} again`);}let binary: string;try {@@ -697,11 +679,12 @@ async function planTunnel(options: CliOptions, log: (line: string) => void, recoexport async function runServe(options: CliOptions, log: (line: string) => void = console.log): Promise<number> {const { browserEngineStatus, describeBrowserEngine } = await import("./browser-engine.ts");if (await serverUp(options.port)) {- console.error(`something already answers on http://127.0.0.1:${options.port}; use \`openmausbot pair\` against it, or --port for a second server`);+ console.error(`something already answers on http://127.0.0.1:${options.port}; use ${cliCommand("pair")} against it, or --port for a second server`);return 1;}- let publicUrl = options.publicUrl;+ let publicUrl = options.publicUrl ?? (options.local ? undefined : envPublicUrl(process.env, log));let tailscale: TailscaleStatus | null = null;+ if (await clearLeftoverTailscaleServe(options.dataDir) && !options.tailscale) log(`Turned off a Tailscale share an earlier run left on. Add --tailscale to share again.`);if (options.tailscale) {const probe = await tailscaleStatus();if ("failure" in probe) {@@ -750,10 +733,13 @@ export async function runServe(options: CliOptions, log: (line: string) => voidif (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;+ const lanRefusal = options.lan ? lanProblem() : null;+ if (lanRefusal) log(lanRefusal);+ if (options.lan && !lanRefusal) env.OMB_LAN = "1";+ else delete env.OMB_LAN;let logPath: string | undefined;let logFd: number | undefined;- let tailscaleServing = false;- let tailscaleAttempted = false;+ let tailscaleShare: { origin: string; stop(): Promise<void> } | null = null;let startupCancelled = false;const cancelStartup = () => { startupCancelled = true; };process.on("SIGINT", cancelStartup);@@ -768,11 +754,10 @@ export async function runServe(options: CliOptions, log: (line: string) => voidlog("\nStarting your workspace…");}if (tailscale) {- tailscaleAttempted = true;- const served = await tailscaleServe(tailscale, options.port);+ const served = await tailscaleServe(tailscale, options.port, { dataDir: options.dataDir, otherServer: answersAsMausBot });+ if (!("failure" in served)) tailscaleShare = served;if (startupCancelled) throw new SetupCancelled();if ("failure" in served) throw new Error(`--tailscale: ${explainTailscaleFailure(served.failure)}`);- tailscaleServing = true;publicUrl = served.origin;log(`tailscale: serving https://${tailscale.dnsName} → http://127.0.0.1:${options.port} (only your tailnet can reach it)`);}@@ -785,7 +770,7 @@ export async function runServe(options: CliOptions, log: (line: string) => voidserveOwnerToken = ownerToken;}} catch (error) {- if ((tailscaleServing || (startupCancelled && tailscaleAttempted)) && tailscale) await tailscaleServeOff(tailscale).catch(() => undefined);+ await tailscaleShare?.stop().catch(() => undefined);plan?.account?.service.dispose();if (plan) cleanupTunnelOrigin(plan.origin);if (error instanceof SetupCancelled) {@@ -813,7 +798,7 @@ export async function runServe(options: CliOptions, log: (line: string) => void// The gateway and the edge stop accepting before the server they forward to goes away.if (tunnel) await tunnel.stop().catch(() => undefined);if (caddy) await caddy.stop().catch(() => undefined);- if (tailscaleServing && tailscale) await tailscaleServeOff(tailscale).catch(() => undefined);+ await tailscaleShare?.stop().catch(() => undefined);if (exited === null) {child.kill("SIGTERM");const timer = setTimeout(() => child.kill("SIGKILL"), 10_000);@@ -872,39 +857,43 @@ export async function runServe(options: CliOptions, log: (line: string) => voidserving.tunnel = tunnel;void plan.account?.service.restore().catch(() => undefined);}+ const prefix = cliPrefix();+ const described = await api(options.port, "/.well-known/openmausbot/environment").catch(() => null);+ const route: Route | null = plan ? "tunnel" : options.domain ? "domain" : tailscaleShare ? "tailscale" : publicUrl ? "public-url" : env.OMB_LAN === "1" ? "lan" : null;+ const origin = route === "lan" ? lanUrl(options.port, env) : publicUrl ?? null;log("");- log(`OpenMausBot is running on http://127.0.0.1:${options.port}${publicUrl ? `, reachable at ${publicUrl}` : ""}`);+ log(`MausBot ${serverVersion()} · server "${described?.body?.label ?? options.label ?? "this machine"}"`);if (options.guided) {log("Your bots and conversations are saved automatically.");log(`Details if you need help: ${logPath}`);- if (options.open !== false && !await openDashboard(options.port)) log("Open the local address above in a browser on this computer.");+ if (options.open !== false && !await openDashboard(options.port)) log(`Open http://127.0.0.1:${options.port} in a browser on this computer.`);} else {log(`data: ${options.dataDir}`);log(describeBrowserEngine(browserEngineStatus({ dataDir: options.dataDir })));}+ 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) {log("");- if (tunnel) {- // No pairing secret is created or sent to the public address until its identity is verified.- log("Preparing the phone connection…");- let timer: ReturnType<typeof setTimeout> | undefined;- await Promise.race([tunnel.started.catch(() => undefined), childExit,- new Promise((done) => { timer = setTimeout(done, 15_000); })]);- if (timer) clearTimeout(timer);- }if (!stopping && exited === null) await showPhonePairing(options, publicUrl, log).catch((error: unknown) => log(`no pairing code: ${message(error)}`));- } else if (options.pair) {+ } else if (options.pair && (options.guided || ((route || serviceTrust) && interactive))) {log("");try {- log(await mintPairing(options.port, { label: options.label ? `${options.label} owner` : undefined, client: options.client, publicUrl: publicUrl ?? undefined, guided: options.guided }));- if (!options.guided) log("\nanother device later: openmausbot pair --label \"Kitchen iPad\"");+ log(await mintPairing(options.port, { label: options.label ? `${options.label} owner` : undefined, client: options.client, publicUrl: origin ?? undefined, guided: options.guided && !route }));+ if (reach && !reach.ok) log("The code works once the address answers.");} catch (error) {log(`no pairing code: ${message(error)}`);- log("start without one next time: openmausbot serve --no-pair");}+ } else if (!route) {+ log("");+ for (const line of noRouteLines(options.port, prefix)) log(line);+ } else if (!serviceTrust) {+ log(`Get a pairing code: ${prefix} pair`);}- log(options.guided ? "\nKeep this terminal open while using your bots. Ctrl+C stops the server, not your saved work." : "stop with Ctrl+C");- if (options.guided) log("Next time: openmausbot · Change AI or phone setup: openmausbot setup · Pair another phone: openmausbot pair");+ if (serviceTrust && !(options.pair && interactive)) log(`This shared server takes no pairing commands from this machine. Let people sign in with their email: ${prefix} access add [email protected]`);+ if (interactive && !options.guided) log(`New code later ${prefix} pair\nStop with Ctrl+C`);+ if (options.guided) log(`\nKeep this terminal open while using your bots. Ctrl+C stops the server, not your saved work.\nNext time: ${prefix} · Change AI or phone setup: ${prefix} setup · Pair another device: ${prefix} pair`);return await childExit;} finally {serveOwnerToken = undefined;@@ -935,7 +924,7 @@ export async function runOnboardingCommand(): Promise<number> {const interactive = process.stdin.isTTY === true && process.stdout.isTTY === true;if (options.command === "setup" && !interactive) {- io.error("Setup needs an interactive terminal. Run `npx openmausbot setup` in a terminal, then use `npx openmausbot serve` for unattended starts.");+ io.error(`Setup needs an interactive terminal. Run ${cliCommand("setup")} in a terminal, or start unattended with ${cliCommand("serve")}.`);return 1;}process.env.OMB_DATA_DIR = options.dataDir;@@ -954,11 +943,11 @@ export async function runOnboardingCommand(try {if (options.command === "setup" || !(await isSetupComplete(options.dataDir))) {if (!interactive) {- io.error("No completed setup was found. Run `npx openmausbot setup` in an interactive terminal first, or use `npx openmausbot serve` with an existing configuration.");+ io.error(`No setup yet. Run ${cliCommand("setup")} in an interactive terminal first, or start unattended with ${cliCommand("serve")}.`);return 1;}if (!(await runSetup({ dataDir: options.dataDir, port: options.port }))) {- io.log("Setup cancelled. Run openmausbot when you're ready.");+ io.log(`Setup cancelled. Run ${cliPrefix()} when you're ready.`);return 130;}}@@ -978,7 +967,7 @@ export async function runOnboardingCommand(saveCliStartup(options.dataDir, startupPreferences(launch));}if (options.command === "setup") {- io.log("\nAll set. Start with: openmausbot (or npx openmausbot without a global install).");+ io.log(`\nAll set. Start with: ${cliPrefix()}`);if (options.dataDir !== join(homedir(), ".openmausbot") || options.port !== 8799) {io.log(`Use the same --data-dir (${options.dataDir}) and --port (${options.port}) options when starting.`);}@@ -988,7 +977,7 @@ export async function runOnboardingCommand(return startServer({ ...launch, guided: interactive });} catch (error) {if (!(error instanceof SetupCancelled)) throw error;- io.log("\nSetup stopped. Any AI setup already saved is kept; no server was started. Run openmausbot setup to continue.");+ io.log(`\nSetup stopped. Any AI setup already saved is kept; no server was started. Run ${cliCommand("setup")} to continue.`);return 130;}}@@ -998,7 +987,7 @@ export async function main(argv = process.argv.slice(2)): Promise<number> {if (HEADLESS_VERB_NAMES.has(argv[0] ?? "") || (argv[0] === "help" && HEADLESS_VERB_NAMES.has(argv[1] ?? ""))) return (await import("./headless/main.ts")).runHeadless(argv);const options = parseArgs(argv);if ("error" in options) {- console.error(`${options.error}\n\n${USAGE}`);+ console.error(`${options.error}\nAll commands and options: ${cliCommand("--help")}`);return 2;}process.env.OMB_DATA_DIR = options.dataDir;@@ -1021,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, label: options.label, sentinel: options.sentinel, script: process.argv[1] ?? "", node: process.execPath,+ tailscale: options.tailscale, publicUrl: options.publicUrl, lan: options.lan, 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") {@@ -1061,10 +1050,13 @@ export async function main(argv = process.argv.slice(2)): Promise<number> {}, { log: (line) => console.log(line), error: (line) => console.error(line) });case "logout":return runLogout(options);+ case "version":+ console.log(serverVersion());+ return 0;case "browser":return runBrowser(options);default:- console.log(USAGE);+ console.log(usage(cliPrefix()));return 0;}}diff --git a/server/environment.ts b/server/environment.tsindex 6df8f4c189..8f8bbed296 100644--- a/server/environment.ts+++ b/server/environment.ts@@ -145,7 +145,7 @@ export function serverVersion(root = SERVER_ROOT): string {export function environmentDescriptor(input: { environmentId: string; desktopManaged: boolean; emailSignIn?: boolean; sharedComputers?: boolean; cloudHome?: boolean; cloudTeam?: boolean; ownHome?: boolean; label?: string }): EnvironmentDescriptor {return {environmentId: input.environmentId,- label: input.label?.trim() || process.env.OMB_ENVIRONMENT_LABEL?.trim() || hostname(),+ label: input.label?.trim() || process.env.OMB_ENVIRONMENT_LABEL?.trim() || process.env.OMB_SERVER_NAME?.trim() || hostname(),platform: process.platform,version: serverVersion(),capabilities: {diff --git a/server/exit.ts b/server/exit.tsindex 2e911c8188..e87cd71fb1 100644--- a/server/exit.ts+++ b/server/exit.ts@@ -5,3 +5,13 @@ export function exitAfterFlush(code: number): void {const flushed = (stream: NodeJS.WriteStream) => new Promise<void>((done) => stream.write("", () => done()));void Promise.all([flushed(process.stdout), flushed(process.stderr)]).then(() => process.exit(code));}++/** `openmausbot status | head` closes the pipe early: that ends the output, it is not a crash. */+export function endQuietlyOnClosedPipe(): void {+ for (const stream of [process.stdout, process.stderr]) {+ stream.on("error", (error: NodeJS.ErrnoException) => {+ if (error.code !== "EPIPE") throw error;+ process.exit(process.exitCode ?? 0);+ });+ }+}diff --git a/server/headless/connect.ts b/server/headless/connect.tsindex e55986e51e..73049e8af2 100644--- a/server/headless/connect.ts+++ b/server/headless/connect.ts@@ -11,7 +11,7 @@ import type { VerbContext, VerbOutcome } from "./context.ts";type Rec = Record<string, any>;/** The command that makes a pairing code on a server, whichever way that server was installed. */-const PAIR_ON_SERVER = "npx openmausbot pair (Docker: docker compose exec omb node dist-server/openmausbot.js pair)";+const PAIR_ON_SERVER = "npx openmausbot pair (Docker: docker compose exec omb openmausbot pair)";const isLoopback = (origin: string) => /^https?:\/\/(?:127\.0\.0\.1|localhost|\[::1\])(?::\d+)?$/i.test(origin);diff --git a/server/index.ts b/server/index.tsindex bde6bbf5e6..e8d4107bfc 100644--- a/server/index.ts+++ b/server/index.ts@@ -530,7 +530,7 @@ import { applyPendingWorkspaceRestore, readLastWorkspaceRestore, type WorkspaceRimport { repairMovedWorkspacePaths } from "./moved-paths-repair.ts";import { createCustomDomainVerifier, customDomainIpv4, normalizeCustomDomain } from "./custom-domain.ts";import { allowedScopes, createEmailSignIn, parseAllowList } from "./account-signin.ts";-import { pairingLinkBase, signInMailTarget } from "./pairing-base.ts";+import { pairingLinkBase, signInMailTarget } from "./pairing-base.ts"; import { lanUrl, listenHost } from "./lan-address.ts";import { ProviderAuthSessions } from "./provider-auth-sessions.ts";import {clearSessionCookie,@@ -801,7 +801,7 @@ function savedCustomDomain(): string | null {try { return normalizeCustomDomain(cfg.customDomain); }catch { return null; }}-function publicUrl(): string | null { return savedCustomDomain() ?? FALLBACK_PUBLIC_URL; }+function publicUrl(): string | null { return savedCustomDomain() ?? FALLBACK_PUBLIC_URL ?? lanUrl(PORT); }function customDomainStatus() {return {customDomain: savedCustomDomain(), publicUrl: publicUrl(), fallbackUrl: FALLBACK_PUBLIC_URL,@@ -15503,7 +15503,7 @@ if (CLOUD_HOME) registerCloudPower(cloudPower = createCloudPower({ dataDir: DATAliveCall: () => liveCalls.current() !== null, computer: () => cloudComputerPower.awake() || boatLifecycleBusyBots.size > 0, nextDueAt: () => { const due = [routines?.nextDueAt() ?? null, proactive.brief.nextWakeAt(), botWaits.nextWakeAt()].filter((at): at is number => at !== null); return due.length ? Math.min(...due) : null; },maintenance: () => workspaceMaintenance.active || providerFleetReloading || providerAuthSessions.active || browserEngineInstall !== null } }));-server.listen(PORT, "127.0.0.1", async () => {+server.listen(PORT, listenHost(server), async () => {companyRuntimeReady();console.log(`openmausbot server on http://127.0.0.1:${PORT}`);personWaits.boot(); browserSweep.start(); startCloudTeamPolicy({ cloudHome: CLOUD_HOME, dataDir: DATA_DIR, managed: managedPolicy, sessions }); moveFreeze.hold(() => appTriggers.start(), () => void appTriggers.stop()); startCloudHomeConnectedApps({ cloudHome: CLOUD_HOME !== null, dataDir: DATA_DIR, cloudGrant: CLOUD_ENV.OMB_CLOUD_CONNECTED_APPS_GRANT, apply: (access) => { composio.setManagedBrokerAccess(access); broadcast({ kind: "config", ...configStatus() }); } });diff --git a/server/lan-address.test.ts b/server/lan-address.test.tsindex 9868d14e3b..65f02168a1 100644--- a/server/lan-address.test.ts+++ b/server/lan-address.test.ts@@ -1,7 +1,9 @@+import { EventEmitter } from "node:events";+import type { Server } from "node:http";import type { NetworkInterfaceInfo } from "node:os";-import { expect, it } from "vitest";+import { describe, expect, it } from "vitest";-import { reachableAddresses } from "./lan-address.ts";+import { lanUrl, listenHost, privateConnection, reachableAddresses } from "./lan-address.ts";const v4 = (address: string, internal = false) => ({ address, family: "IPv4", internal, netmask: "255.255.255.0", mac: "00:00:00:00:00:00", cidr: null }) as NetworkInterfaceInfo;const v6 = (address: string) => ({ address, family: "IPv6", internal: false, netmask: "ffff::", mac: "00:00:00:00:00:00", cidr: null, scopeid: 0 }) as NetworkInterfaceInfo;@@ -33,3 +35,35 @@ it("counts 100.64/10 as Tailscale only on Tailscale's interface, and prefers theit("a VPS with only a public address has no LAN address", () => {expect(reachableAddresses({ eth0: [v4("198.51.100.4")], docker0: [v4("172.17.0.1")] })).toEqual({ lan: [], tailscale: [] });});++describe("the LAN listener", () => {+ it("answers only when both ends of a connection are private", () => {+ expect(privateConnection("192.168.1.20", "192.168.1.50")).toBe(true);+ expect(privateConnection("::ffff:10.0.0.2", "::ffff:10.0.0.9")).toBe(true);+ expect(privateConnection("100.101.102.103", "100.64.0.7")).toBe(true);+ expect(privateConnection("192.168.1.20", "203.0.113.9")).toBe(false);+ expect(privateConnection("198.51.100.4", "10.0.0.9")).toBe(false);+ expect(privateConnection(undefined, "10.0.0.9")).toBe(false);+ });++ it("listens on loopback unless OMB_LAN=1, then drops every connection with a public end", () => {+ const loopback = new EventEmitter() as unknown as Server;+ expect(listenHost(loopback, {})).toBe("127.0.0.1");+ expect((loopback as unknown as EventEmitter).listenerCount("connection")).toBe(0);+ const lan = new EventEmitter();+ expect(listenHost(lan as unknown as Server, { OMB_LAN: "1" })).toBe("0.0.0.0");+ const socket = (localAddress: string, remoteAddress: string) => ({ localAddress, remoteAddress, destroyed: false, destroy() { this.destroyed = true; } });+ const stranger = socket("192.168.1.20", "203.0.113.9");+ const neighbour = socket("192.168.1.20", "192.168.1.50");+ lan.emit("connection", stranger);+ lan.emit("connection", neighbour);+ expect([stranger.destroyed, neighbour.destroyed]).toEqual([true, false]);+ });++ it("links to this network's address with OMB_LAN=1 only", () => {+ const addresses = () => ({ lan: ["192.168.1.20", "100.70.0.1"], tailscale: [] });+ expect(lanUrl(8799, { OMB_LAN: "1" }, addresses)).toBe("http://192.168.1.20:8799");+ expect(lanUrl(8799, {}, addresses)).toBeNull();+ expect(lanUrl(8799, { OMB_LAN: "1" }, () => ({ lan: [], tailscale: [] }))).toBeNull();+ });+});diff --git a/server/lan-address.ts b/server/lan-address.tsindex a9d1832786..c7724da32e 100644--- a/server/lan-address.ts+++ b/server/lan-address.ts@@ -1,3 +1,5 @@+import type { Server } from "node:http";+import type { Socket } from "node:net";import { networkInterfaces, type NetworkInterfaceInfo } from "node:os";import { isPrivateHost } from "../shared/private-host.ts";@@ -38,3 +40,27 @@ export function reachableAddresses(interfaces: NodeJS.Dict<NetworkInterfaceInfo[}return { lan: [...lan, ...shared], tailscale };}++const plain = (address: string | undefined) => (address ?? "").replace(/^::ffff:/i, "");++/** Both ends of a connection on a network the person runs: a LAN listener answers nobody on the open internet. */+export function privateConnection(localAddress: string | undefined, remoteAddress: string | undefined): boolean {+ return isPrivateHost(plain(localAddress)) && isPrivateHost(plain(remoteAddress));+}++/** Where the server listens: loopback, or with OMB_LAN=1 every IPv4 address with each connection held to private ends,+ * so a new Wi-Fi network or DHCP lease needs no restart. */+export function listenHost(server: Server, env: NodeJS.ProcessEnv = process.env): string {+ if (env.OMB_LAN !== "1") return "127.0.0.1";+ server.on("connection", (socket: Socket) => {+ if (!privateConnection(socket.localAddress, socket.remoteAddress)) socket.destroy();+ });+ return "0.0.0.0";+}++/** With OMB_LAN=1, the address other devices on this network use, read afresh for each link; else null. */+export function lanUrl(port: number, env: NodeJS.ProcessEnv = process.env, addresses: () => ReachableAddresses = reachableAddresses): string | null {+ if (env.OMB_LAN !== "1") return null;+ const address = addresses().lan[0];+ return address ? `http://${address}:${port}` : null;+}diff --git a/server/openmausbot.ts b/server/openmausbot.tsindex 94af4899c4..c97850d6ad 100644--- a/server/openmausbot.ts+++ b/server/openmausbot.ts@@ -1,8 +1,9 @@import { main } from "./cli.ts";-import { exitAfterFlush } from "./exit.ts";+import { endQuietlyOnClosedPipe, exitAfterFlush } from "./exit.ts";// The sentinel, run from here, reads the server's own lines back in every language it writes them in.import "./server-line-packs.ts";+endQuietlyOnClosedPipe();main().then(exitAfterFlush, (error) => {console.error(error instanceof Error ? error.message : String(error));exitAfterFlush(1);diff --git a/server/pair-cli.ts b/server/pair-cli.tsindex 00f28b87a5..9d353cc906 100644--- a/server/pair-cli.ts+++ b/server/pair-cli.ts@@ -1,7 +1,8 @@// Alias for `openmausbot pair`: docs and images reference dist-server/pair-cli.js.import { main } from "./cli.ts";-import { exitAfterFlush } from "./exit.ts";+import { endQuietlyOnClosedPipe, exitAfterFlush } from "./exit.ts";+endQuietlyOnClosedPipe();main(["pair", ...process.argv.slice(2)]).then(exitAfterFlush, (error) => {console.error(error instanceof Error ? error.message : String(error));exitAfterFlush(1);diff --git a/server/request-auth.test.ts b/server/request-auth.test.tsindex e66fbc1ff9..a6b57183db 100644--- a/server/request-auth.test.ts+++ b/server/request-auth.test.ts@@ -542,6 +542,28 @@ describe("resolveRequestAuth", () => {});});+describe("a listener on the local network (openmausbot serve --lan)", () => {+ // SAFETY: only headers, method and the socket peer are read+ const fromPeer = (remoteAddress: string, headers: Record<string, string>) => ({ headers, method: "GET", socket: { remoteAddress } }) as unknown as IncomingMessage;+ const gate = (dir: string) => ({ sessions: new SessionRegistry({ file: join(dir, "sessions.json") }), cookieName: "omb_session_test", streamPath: "/api/events", url: new URL("/api/bots", "http://x") });++ it("never makes another machine the owner, whatever Host it writes", () => {+ const dir = mkdtempSync(join(tmpdir(), "omb-auth-lan-"));+ try {+ for (const peer of ["192.168.1.50", "::ffff:192.168.1.50", "100.101.102.103", "fd12::5"]) {+ const spoofed = resolveRequestAuth(fromPeer(peer, { host: "127.0.0.1:8799" }), gate(dir));+ expect([peer, spoofed.auth]).toEqual([peer, null]);+ expect(isProxied(fromPeer(peer, { host: "localhost" }))).toBe(true);+ }+ for (const peer of ["127.0.0.1", "::1", "::ffff:127.0.0.1"]) {+ expect(resolveRequestAuth(fromPeer(peer, { host: "127.0.0.1:8799" }), gate(dir)).auth?.kind, peer).toBe("loopback");+ }+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+ });+});+describe("an IPC listener (openmausbot serve --tunnel) is remote by construction", () => {// SAFETY: only headers, method and the socket peer are read; a unix-socket peer has no addressconst overSocket = (headers: Record<string, string>) => ({ headers, method: "GET", socket: {} }) as unknown as IncomingMessage;diff --git a/server/request-auth.ts b/server/request-auth.tsindex de6a89e7c0..14a3eab488 100644--- a/server/request-auth.ts+++ b/server/request-auth.ts@@ -176,10 +176,19 @@ export function requestOrigin(req: IncomingMessage): string | null {return `${proto}://${host.toLowerCase()}`;}-/** A proxy that hands the server a loopback Host must not turn a remote client into the owner. */+/** Security: loopback trust rests on the Host header, which any client writes, so a request is remote (never the owner)+ * when it came through a proxy, over the IPC socket, or from another machine's address, as on a LAN listener. */export function isProxied(req: IncomingMessage): boolean {const h = req.headers;- return ipcPeer(req) || Boolean(h["x-forwarded-for"] || h["x-forwarded-proto"] || h["x-forwarded-host"] || h["forwarded"]);+ return ipcPeer(req) || networkPeer(req) || Boolean(h["x-forwarded-for"] || h["x-forwarded-proto"] || h["x-forwarded-host"] || h["forwarded"]);+}++const LOOPBACK_PEER = /^(?:127\.|::1$|::ffff:127\.)/;++/** A TCP peer other than this machine. */+export function networkPeer(req: IncomingMessage): boolean {+ const address = req.socket?.remoteAddress;+ return typeof address === "string" && !LOOPBACK_PEER.test(address);}/** An IPC listener's only peer is a forwarding gateway, so its requests are remote: never loopback trust. */diff --git a/server/service-cli.test.ts b/server/service-cli.test.tsindex 20928d6b50..dcb3d627c6 100644--- a/server/service-cli.test.ts+++ b/server/service-cli.test.ts@@ -18,12 +18,13 @@ describe("openmausbot service", () => {});afterEach(() => removeTempDir(dir));- it("repeats the serve options, one access mode at a time", () => {- expect(serviceServeArgs({ port: 8799, dataDir: "/d", domain: "a.example.com", tunnel: true, label: "x" })).toEqual(["--port", "8799", "--data-dir", "/d", "--no-pair", "--domain", "a.example.com", "--label", "x"]);- expect(serviceServeArgs({ port: 1, dataDir: "/d", tailscale: true })).toEqual(["--port", "1", "--data-dir", "/d", "--no-pair", "--tailscale"]);+ it("repeats the serve options the person gave, --public-url and --lan included", () => {+ expect(serviceServeArgs({ port: 8799, dataDir: "/d", domain: "a.example.com", tunnel: true, label: "x" })).toEqual(["--port", "8799", "--data-dir", "/d", "--domain", "a.example.com", "--label", "x"]);+ expect(serviceServeArgs({ port: 1, dataDir: "/d", tailscale: true })).toEqual(["--port", "1", "--data-dir", "/d", "--tailscale"]);+ expect(serviceServeArgs({ port: 1, dataDir: "/d", publicUrl: "https://maus.example.com", lan: true })).toEqual(["--port", "1", "--data-dir", "/d", "--public-url", "https://maus.example.com", "--lan"]);});- it("writes the unit next to the data and prints how to install it; refuses an npx cache", () => {+ it("writes the unit next to the data and prints how to install it; under npx, runs a copy kept beside the data", () => {const code = runServiceCommand({ action: "install", dataDir: dir, port: 8799, domain: "maus.example.com", script: "/usr/lib/node_modules/openmausbot/cli.js", node: "/usr/bin/node", platform: "linux", home: "/home/maus", user: "maus" }, io);expect(code).toBe(0);const unit = readFileSync(join(dir, "openmausbot.service"), "utf8");@@ -33,10 +34,19 @@ describe("openmausbot service", () => {expect(out.join("\n")).toContain("no setcap is needed");out.length = 0;- const refused = runServiceCommand({ action: "install", dataDir: join(dir, "x"), port: 8799, script: "/home/maus/.npm/_npx/deadbeef/node_modules/openmausbot/cli.js", node: "/usr/bin/node", platform: "linux" }, io);- expect(refused).toBe(1);- expect(err.join("\n")).toMatch(/npm install -g openmausbot/);+ const npx = { action: "install" as const, dataDir: join(dir, "x"), port: 8799, publicUrl: "https://maus.example.com", script: "/home/maus/.npm/_npx/deadbeef/node_modules/openmausbot/dist-server/openmausbot.js", node: "/usr/bin/node", platform: "linux" as const, home: "/home/maus", user: "maus" };+ const installs: string[] = [];+ expect(runServiceCommand({ ...npx, installCopy: (prefix) => { installs.push(prefix); return false; } }, io)).toBe(1);+ expect(err.join("\n")).toContain(`npm install --prefix ${join(dir, "x", "app", "latest")} openmausbot@latest`);expect(existsSync(join(dir, "x", "openmausbot.service"))).toBe(false);+ expect(runServiceCommand({ ...npx, installCopy: (prefix) => { installs.push(prefix); return true; }, exists: () => true }, io)).toBe(0);+ const pinned = readFileSync(join(dir, "x", "openmausbot.service"), "utf8");+ const script = join(dir, "x", "app", "latest", "node_modules", "openmausbot", "dist-server", "openmausbot.js");+ expect(pinned).toContain(`ExecStart=/usr/bin/node ${/[\s"\\]/.test(script) ? `"${script.replace(/[\\"]/g, "\\$&")}"` : script} serve`);+ expect(pinned).toContain("--public-url https://maus.example.com");+ expect(pinned).not.toContain("--no-pair");+ expect(pinned).toContain('Environment="OMB_CLI_PREFIX=npx openmausbot"');+ expect(installs).toEqual([join(dir, "x", "app", "latest"), join(dir, "x", "app", "latest")]);});it("writes a launchd agent on macOS and explains uninstall on both", () => {diff --git a/server/service-cli.ts b/server/service-cli.tsindex fd3431fb5d..cb4f8be23f 100644--- a/server/service-cli.ts+++ b/server/service-cli.ts@@ -1,12 +1,14 @@+import { spawnSync } from "node:child_process";import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";import { homedir } from "node:os";-import { join } from "node:path";+import { dirname, join } from "node:path";import {currentUser, launchdPlist, sentinelCommand, sentinelLaunchdPlist, sentinelServicePlan, sentinelSystemdService, sentinelSystemdTimer,servicePlan, shippedSentinelCli, systemdUnit, unstableInstallWarning,} from "./service-unit.ts";import { defaultSentinelOut, outRefusal } from "./sentinel/paths.ts";+import { cliCommand } from "./cli-invocation.ts";export interface ServiceInstallInput {action: "install" | "uninstall";@@ -15,6 +17,8 @@ export interface ServiceInstallInput {domain?: string;tunnel?: boolean;tailscale?: boolean;+ publicUrl?: string;+ lan?: boolean;label?: string;sentinel?: boolean;/** Defaults to the platform's Sentinel folder. */@@ -25,6 +29,8 @@ export interface ServiceInstallInput {hasSentinel?: (script: string) => boolean;script: string;node: string;+ /** Under npx: installs `openmausbot@version` into `prefix` and resolves whether npm succeeded. */+ installCopy?: (prefix: string, version: string) => boolean;platform?: NodeJS.Platform;home?: string;user?: string;@@ -35,11 +41,15 @@ export interface ServiceIo {error(line: string): void;}-export function serviceServeArgs(input: Pick<ServiceInstallInput, "port" | "dataDir" | "domain" | "tunnel" | "tailscale" | "label">): string[] {- const args = ["--port", String(input.port), "--data-dir", input.dataDir, "--no-pair"];+/** 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[] {+ 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.label) args.push("--label", input.label);return args;}@@ -58,20 +68,22 @@ export function runServiceCommand(input: ServiceInstallInput, io: ServiceIo): nufor (const line of plan.deactivate) io.log(` ${line}`);return 0;}- const warning = unstableInstallWarning(input.script);- if (warning) {- io.error(warning);- return 1;+ let script = input.script;+ if (unstableInstallWarning(script)) {+ const pinned = pinnedCopy(input, io);+ if (!pinned) return 1;+ script = pinned;}const spec = {node: input.node,- script: input.script,+ script,serveArgs: serviceServeArgs(input),dataDir: input.dataDir,user: input.user ?? currentUser(),home,bindsLowPorts: Boolean(input.domain),...(input.label ? { label: input.label } : {}),+ ...(script !== input.script ? { cliPrefix: "npx openmausbot" } : {}),};const rendered = platform === "darwin" ? launchdPlist(spec) : systemdUnit(spec);mkdirSync(input.dataDir, { recursive: true, mode: 0o700 });@@ -83,10 +95,34 @@ export function runServiceCommand(input: ServiceInstallInput, io: ServiceIo): nuio.log("");if (input.domain && platform === "linux") io.log("the unit grants Caddy the capability for ports 80 and 443, so no setcap is needed under the service");io.log(`logs: ${platform === "darwin" ? `${input.dataDir}/logs/service.log` : "journalctl -u openmausbot -f"}`);- io.log(`change options later by running \`openmausbot service install\` again with the new ones, then: ${platform === "darwin" ? plan.activate[1] : "sudo systemctl daemon-reload && sudo systemctl restart openmausbot"}`);+ io.log(`change options later by running \`${cliCommand("service install")}\` again with the new ones, then: ${platform === "darwin" ? plan.activate[1] : "sudo systemctl daemon-reload && sudo systemctl restart openmausbot"}`);return 0;}+/** npm prunes its npx cache, so a service runs a copy of this exact version kept beside the data instead. */+function pinnedCopy(input: ServiceInstallInput, io: ServiceIo): string | null {+ let version: string | undefined;+ try {+ version = JSON.parse(readFileSync(join(dirname(input.script), "..", "package.json"), "utf8")).version;+ } catch {+ version = undefined;+ }+ const prefix = join(input.dataDir, "app", version ?? "latest");+ const command = `npm install --prefix ${prefix} openmausbot@${version ?? "latest"}`;+ io.log(`this run comes from npx's cache, which npm prunes: installing openmausbot ${version ?? ""} into ${prefix} for the service`.replace(" ", " "));+ const installed = (input.installCopy ?? installWithNpm)(prefix, version ?? "latest");+ const script = join(prefix, "node_modules", "openmausbot", "dist-server", "openmausbot.js");+ if (installed && (input.exists ?? existsSync)(script)) return script;+ io.error(`could not install that copy. Run this, then the same service install command again from it:\n ${command}\n node ${script} service install …`);+ return null;+}++function installWithNpm(prefix: string, version: string): boolean {+ mkdirSync(prefix, { recursive: true, mode: 0o700 });+ const npm = process.platform === "win32" ? "npm.cmd" : "npm";+ return spawnSync(npm, ["install", "--prefix", prefix, `openmausbot@${version}`, "--no-audit", "--no-fund"], { stdio: "inherit" }).status === 0;+}+function bundleHasSentinel(script: string): boolean {try {return readFileSync(script, "utf8").includes("--check-install");diff --git a/server/service-unit.ts b/server/service-unit.tsindex d60d95ca0f..ef5337a40d 100644--- a/server/service-unit.ts+++ b/server/service-unit.ts@@ -13,6 +13,8 @@ export interface ServiceSpec {home: string;bindsLowPorts: boolean;label?: string;+ /** How the person runs the CLI by hand, when it isn't `openmausbot` (a copy installed for the service). */+ cliPrefix?: string;}export const SYSTEMD_UNIT_NAME = "openmausbot.service";@@ -45,6 +47,7 @@ export function systemdUnit(spec: ServiceSpec): string {`WorkingDirectory=${spec.home}`,`Environment=HOME=${spec.home}`,`Environment=OMB_DATA_DIR=${spec.dataDir}`,+ ...(spec.cliPrefix ? [`Environment=${quoteSystemd(`OMB_CLI_PREFIX=${spec.cliPrefix}`)}`] : []),`ExecStart=${serviceCommand(spec).map(quoteSystemd).join(" ")}`,"Restart=always","RestartSec=3",@@ -83,6 +86,7 @@ export function launchdPlist(spec: ServiceSpec): string {`\t\t<string>${xml(spec.home)}</string>`,"\t\t<key>OMB_DATA_DIR</key>",`\t\t<string>${xml(spec.dataDir)}</string>`,+ ...(spec.cliPrefix ? ["\t\t<key>OMB_CLI_PREFIX</key>", `\t\t<string>${xml(spec.cliPrefix)}</string>`] : []),"\t\t<key>PATH</key>","\t\t<string>/usr/local/bin:/opt/homebrew/bin:/usr/bin:/bin</string>","\t</dict>",diff --git a/server/tailscale.test.ts b/server/tailscale.test.tsindex 823ddcd108..1e98ca3139 100644--- a/server/tailscale.test.ts+++ b/server/tailscale.test.ts@@ -1,14 +1,20 @@+import { EventEmitter } from "node:events";+import { existsSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";import { describe, expect, it } from "vitest";-import { classifyTailscaleStderr, explainTailscaleFailure, parseTailscaleStatus } from "./tailscale.ts";+import { classifyTailscaleStderr, clearLeftoverTailscaleServe, explainTailscaleFailure, parseTailscaleStatus, tailscaleMarker, tailscaleServe, type TailscaleStatus } from "./tailscale.ts";describe("tailscale helpers", () => {it("reads the MagicDNS name, addresses and state from status --json", () => {const status = parseTailscaleStatus("/usr/bin/tailscale", JSON.stringify({BackendState: "Running",+ CertDomains: ["mini.tail1234.ts.net"],Self: { DNSName: "mini.tail1234.ts.net.", TailscaleIPs: ["100.64.0.7", "fd7a:115c:a1e0::7"] },}));- expect(status).toEqual({ cli: "/usr/bin/tailscale", dnsName: "mini.tail1234.ts.net", addresses: ["100.64.0.7", "fd7a:115c:a1e0::7"], backendState: "Running" });+ expect(status).toEqual({ cli: "/usr/bin/tailscale", dnsName: "mini.tail1234.ts.net", addresses: ["100.64.0.7", "fd7a:115c:a1e0::7"], backendState: "Running", httpsEnabled: true });+ expect(parseTailscaleStatus("t", JSON.stringify({ BackendState: "Running" }))?.httpsEnabled).toBe(false);expect(parseTailscaleStatus("t", "{}")?.dnsName).toBeNull();expect(parseTailscaleStatus("t", "not json")).toBeNull();});@@ -25,3 +31,67 @@ describe("tailscale helpers", () => {}});});++describe("serve --tailscale", () => {+ const status: TailscaleStatus = { cli: "/usr/bin/tailscale", dnsName: "mini.tail1234.ts.net", addresses: [], backendState: "Running", httpsEnabled: true };+ const fakeServe = (exitCode: number | null, stderr = "") => {+ const calls: string[][] = [];+ const children: Array<EventEmitter & { kill(signal: string): void; killed: string[] }> = [];+ const spawnImpl = ((_cli: string, args: string[]) => {+ calls.push(args);+ const child: EventEmitter & { stderr: EventEmitter; killed: string[]; kill(signal: string): void } = Object.assign(new EventEmitter(), {+ stderr: new EventEmitter(), killed: [] as string[], kill(signal: string) { child.killed.push(signal); setImmediate(() => child.emit("exit", null)); },+ });+ children.push(child);+ if (exitCode !== null) setImmediate(() => { child.stderr.emit("data", Buffer.from(stderr)); child.emit("exit", exitCode); });+ return child;+ }) as never;+ return { calls, children, spawnImpl };+ };++ it("serves in the foreground, notes it, and turns it off when serve stops", async () => {+ const dir = mkdtempSync(join(tmpdir(), "omb-ts-"));+ try {+ const fake = fakeServe(null);+ const served = await tailscaleServe(status, 8799, { dataDir: dir, settleMs: 20, spawnImpl: fake.spawnImpl });+ if ("failure" in served) throw new Error(served.failure);+ expect(served.origin).toBe("https://mini.tail1234.ts.net");+ expect(fake.calls).toEqual([["serve", "--https=443", "http://127.0.0.1:8799"]]);+ expect(fake.calls[0]).not.toContain("--bg");+ expect(existsSync(tailscaleMarker(dir))).toBe(true);+ await served.stop();+ expect(fake.children[0]!.killed).toEqual(["SIGTERM"]);+ expect(existsSync(tailscaleMarker(dir))).toBe(false);+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+ });++ it("checks first: HTTPS certificates on, and no other MausBot server already on this name; a serve that exits says why", async () => {+ const dir = mkdtempSync(join(tmpdir(), "omb-ts-"));+ try {+ const fake = fakeServe(null);+ expect(await tailscaleServe({ ...status, httpsEnabled: false }, 8799, { dataDir: dir, spawnImpl: fake.spawnImpl })).toEqual({ failure: "https-not-enabled" });+ expect(await tailscaleServe(status, 8799, { dataDir: dir, spawnImpl: fake.spawnImpl, otherServer: async () => true })).toEqual({ failure: "other-server" });+ expect(fake.calls).toEqual([]);+ const refused = fakeServe(1, "Access denied: serve config denied");+ expect(await tailscaleServe(status, 8799, { dataDir: dir, settleMs: 500, spawnImpl: refused.spawnImpl })).toEqual({ failure: "needs-operator" });+ expect(existsSync(tailscaleMarker(dir))).toBe(false);+ expect(explainTailscaleFailure("other-server")).toContain("different MausBot server");+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+ });++ it("turns off a share a crashed run left behind, and nothing without its note", async () => {+ const dir = mkdtempSync(join(tmpdir(), "omb-ts-"));+ try {+ expect(await clearLeftoverTailscaleServe(dir)).toBe(false);+ writeFileSync(tailscaleMarker(dir), JSON.stringify({ cli: process.execPath, httpsPort: 443, localPort: 8799 }));+ expect(await clearLeftoverTailscaleServe(dir)).toBe(true);+ expect(existsSync(tailscaleMarker(dir))).toBe(false);+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+ });+});diff --git a/server/tailscale.ts b/server/tailscale.tsindex aa9bca8434..41f2695a82 100644--- a/server/tailscale.ts+++ b/server/tailscale.ts@@ -1,5 +1,7 @@// Never log Tailscale's raw stderr (it can contain auth keys and node names): failures are classified into a closed set.-import { execFile } from "node:child_process";+import { execFile, spawn } from "node:child_process";+import { readFileSync, rmSync, writeFileSync } from "node:fs";+import { join } from "node:path";import { tailscaleCandidates, tailscaleEnvironment } from "../companion/src/listener.ts";@@ -8,6 +10,8 @@ export interface TailscaleStatus {dnsName: string | null;addresses: string[];backendState: string;+ /** The tailnet hands out HTTPS certificates (`CertDomains` in `tailscale status --json`). */+ httpsEnabled: boolean;}export type TailscaleFailure =@@ -17,6 +21,7 @@ export type TailscaleFailure =| "no-magicdns"| "needs-operator"| "https-not-enabled"+ | "other-server"| "unknown";export function classifyTailscaleStderr(text: string): TailscaleFailure {@@ -42,7 +47,9 @@ export function explainTailscaleFailure(reason: TailscaleFailure): string {case "needs-operator":return "Tailscale refused: on Linux run `sudo tailscale set --operator=$USER` once, then try again";case "https-not-enabled":- return "HTTPS certificates are off for this tailnet: enable them in the admin console (DNS → HTTPS Certificates)";+ return "HTTPS certificates are off for this tailnet: enable them at https://login.tailscale.com/admin/dns (HTTPS Certificates), then try again";+ case "other-server":+ return "this machine's tailnet name already fronts a different MausBot server: stop that one, or pass --port for this one";default:return "Tailscale reported an error; run `tailscale status` and `tailscale serve status` to see it";}@@ -73,11 +80,13 @@ export function parseTailscaleStatus(cli: string, stdout: string): TailscaleStatconst dns = Reflect.get(Object(self), "DNSName");const ips = Reflect.get(Object(self), "TailscaleIPs");const state = Reflect.get(Object(parsed), "BackendState");+ const certDomains = Reflect.get(Object(parsed), "CertDomains");return {cli,dnsName: typeof dns === "string" && dns ? dns.replace(/\.$/, "") : null,addresses: Array.isArray(ips) ? ips.filter((v): v is string => typeof v === "string") : [],backendState: typeof state === "string" ? state : "unknown",+ httpsEnabled: Array.isArray(certDomains) && certDomains.length > 0,};}@@ -98,17 +107,52 @@ export async function tailscaleStatus(): Promise<{ status: TailscaleStatus } | {return { failure: sawCli ? "unknown" : "not-installed" };}+/** Where a run that shares over Tailscale notes it, so the next start can turn off a share a crash left behind. */+export const tailscaleMarker = (dataDir: string) => join(dataDir, "tailscale-serve.marker");++/**+ * `tailscale serve` in the foreground: the share ends with this process. Before serving, the tailnet must have HTTPS+ * certificates (`CertDomains`), or serve waits on an enablement link forever; and the name must not already front a+ * different MausBot server. Resolves once serve has run for `settleMs` without exiting.+ */export async function tailscaleServe(status: TailscaleStatus,localPort: number,- httpsPort = 443,-): Promise<{ origin: string } | { failure: TailscaleFailure }> {+ options: { dataDir: string; httpsPort?: number; settleMs?: number; spawnImpl?: typeof spawn; otherServer?: (origin: string) => Promise<boolean> },+): Promise<{ origin: string; stop(): Promise<void> } | { failure: TailscaleFailure }> {+ const httpsPort = options.httpsPort ?? 443;if (!status.dnsName) return { failure: "no-magicdns" };- const result = await run(status.cli, ["serve", "--bg", `--https=${httpsPort}`, `http://127.0.0.1:${localPort}`], 20_000);- if (!result.ok) return { failure: classifyTailscaleStderr(result.stderr || result.stdout) };- return { origin: httpsPort === 443 ? `https://${status.dnsName}` : `https://${status.dnsName}:${httpsPort}` };+ if (!status.httpsEnabled) return { failure: "https-not-enabled" };+ const origin = httpsPort === 443 ? `https://${status.dnsName}` : `https://${status.dnsName}:${httpsPort}`;+ if (await (options.otherServer ?? (() => Promise.resolve(false)))(origin)) return { failure: "other-server" };+ const child = (options.spawnImpl ?? spawn)(status.cli, ["serve", `--https=${httpsPort}`, `http://127.0.0.1:${localPort}`], { stdio: ["ignore", "ignore", "pipe"], env: tailscaleEnvironment() });+ let stderr = "";+ child.stderr?.on("data", (chunk: Buffer) => { stderr = (stderr + chunk.toString()).slice(-4096); });+ const exited = new Promise<number | null>((done) => { child.once("exit", (code) => done(code)); child.once("error", () => done(-1)); });+ const early = await Promise.race([exited, new Promise<"running">((done) => setTimeout(() => done("running"), options.settleMs ?? 2_500))]);+ if (early !== "running") return { failure: early === -1 ? "not-installed" : classifyTailscaleStderr(stderr) };+ writeFileSync(tailscaleMarker(options.dataDir), JSON.stringify({ cli: status.cli, httpsPort, localPort }), { mode: 0o600 });+ return {+ origin,+ async stop() {+ child.kill("SIGTERM");+ const timer = setTimeout(() => child.kill("SIGKILL"), 3_000);+ await exited;+ clearTimeout(timer);+ rmSync(tailscaleMarker(options.dataDir), { force: true });+ },+ };}-export async function tailscaleServeOff(status: TailscaleStatus, httpsPort = 443): Promise<void> {- await run(status.cli, ["serve", `--https=${httpsPort}`, "off"], 10_000);+/** Turns off a share a run of ours left on (its marker says so), never one the person made. True when it did. */+export async function clearLeftoverTailscaleServe(dataDir: string): Promise<boolean> {+ let marker: { cli?: unknown; httpsPort?: unknown };+ try {+ marker = JSON.parse(readFileSync(tailscaleMarker(dataDir), "utf8"));+ } catch {+ return false;+ }+ if (typeof marker.cli === "string" && Number.isInteger(marker.httpsPort)) await run(marker.cli, ["serve", `--https=${marker.httpsPort}`, "off"], 10_000);+ rmSync(tailscaleMarker(dataDir), { force: true });+ return true;}diff --git a/server/tunnel.test.ts b/server/tunnel.test.tsindex a1b3558e23..2cbd90cd20 100644--- a/server/tunnel.test.ts+++ b/server/tunnel.test.ts@@ -104,7 +104,7 @@ describe("login and logout against the control plane", () => {const status = fakeIo([]);await runStatus(options(dir, { command: "status" }), status.io);- expect(status.out.join("\n")).toContain(`public address: ${stub.endpointUrl}`);+ expect(status.out.join("\n")).toContain(`MausBot web address: ${stub.endpointUrl}`);const bye = fakeIo([]);expect(await runLogout(options(dir, { command: "logout" }), bye.io)).toBe(0);diff --git a/shared/private-host.ts b/shared/private-host.tsindex 02b70255e4..6166f820a1 100644--- a/shared/private-host.ts+++ b/shared/private-host.ts@@ -1,18 +1 @@-/** A host only this machine or its own network reaches: loopback, RFC 1918, CGNAT 100.64/10 (Tailscale), link-local,- * IPv6 unique-local (fc00::/7), `*.ts.net`, `*.local` and single-label names. Plain http to one of these stays on a- * network the person runs; anything else is the open internet. */-export function isPrivateHost(rawHost: string): boolean {- const host = rawHost.trim().toLowerCase().replace(/^\[|\]$/g, "").replace(/\.$/, "");- if (!host) return false;- const v4 = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/.exec(host);- if (v4) {- const [a, b] = [Number(v4[1]), Number(v4[2])];- if (v4.slice(1).some((part) => Number(part) > 255)) return false;- return a === 127 || a === 10 || (a === 172 && b >= 16 && b <= 31) || (a === 192 && b === 168) || (a === 169 && b === 254) || (a === 100 && b >= 64 && b <= 127);- }- if (host.includes(":")) {- return host === "::1" || /^f[cd][0-9a-f]{0,2}:/.test(host) || /^fe[89ab][0-9a-f]?:/.test(host);- }- if (host === "localhost" || host.endsWith(".localhost") || host.endsWith(".ts.net") || host.endsWith(".local")) return true;- return !host.includes(".") && /^[a-z0-9-]+$/.test(host);-}+export { isPrivateHost } from "../electron/server-address.mjs";