Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Team on your own server: a home with no inbound port runs its own Cloudflare tunnel
milind-sonif84a980dc227
diff --git a/.github/workflows/docker.yml b/.github/workflows/docker.ymlindex c9ad18853c..e2fd8fbc25 100644--- a/.github/workflows/docker.yml+++ b/.github/workflows/docker.yml@@ -223,7 +223,7 @@ jobs:if docker exec -u maus home grep -qaF -- "$value" "/proc/$spid/environ"; then echo "a secret is in the server's environment"; exit 1; fidone# The root launcher runs only code maus cannot change; maus owns only the volume.- docker exec -u maus home sh -c 'for f in /app /app/dist-server /app/dist-server/index.js /app/dist-server/cloud-home-start.js /app/cloud/Caddyfile /app/cloud/Caddyfile.tls /app/cloud/edge-routes.caddy /usr/local/bin/caddy; do if test -w "$f"; then echo "maus can write $f"; exit 1; fi; done; test -w /data'+ docker exec -u maus home sh -c 'for f in /app /app/dist-server /app/dist-server/index.js /app/dist-server/cloud-home-start.js /app/cloud/Caddyfile /app/cloud/Caddyfile.tls /app/cloud/Caddyfile.tunnel /app/cloud/edge-routes.caddy /usr/local/bin/caddy /usr/local/bin/cloudflared; do if test -w "$f"; then echo "maus can write $f"; exit 1; fi; done; test -w /data'test "$(docker exec home stat -c %U /app/dist-server/index.js)" = root# The shell tools bots use on a Cloud, as the user their engines run as.docker exec -u maus home sh -c 'python3 -c "import json, sqlite3, zipfile, csv" && pdftotext -v 2>&1 | grep -q pdftotext && unzip -v | grep -q UnZip'@@ -370,6 +370,40 @@ jobs:docker rm -f tls >/dev/nulldocker volume rm omb-tls-ci >/dev/null+ # No inbound port: the home runs its tunnel's connector itself, as omb-tunnel, whose environment (the token) maus+ # cannot read. Only the tunnel's loopback listener, :8812, believes Cf-Connecting-IP. The token here is well+ # formed but names no tunnel, so Cloudflare refuses it and cloudflared keeps trying.+ token=$(printf '{"a":"0123456789abcdef0123456789abcdef","t":"11111111-2222-3333-4444-555555555555","s":"%s"}' "$(openssl rand -base64 32)" | base64 -w0)+ thost=c-0123456789abcdef0123456789abcdef.example.com+ run_home tunnel omb-tunnel-ci 18085 -e "OMB_PUBLIC_URL=https://$thost" -e "OMB_CLOUD_TUNNEL_TOKEN=$token"+ healthy tunnel 18085+ grep -qF "caddy run --config /app/cloud/Caddyfile.tunnel --adapter caddyfile" <<<"$(docker top tunnel -eo pid,uid,args)"+ for i in $(seq 1 15); do cpid=$(docker exec tunnel sh -c 'for p in /proc/[0-9]*; do case "$(tr "\0" " " < "$p/cmdline" 2>/dev/null)" in *"cloudflared tun""nel"*) echo "${p#/proc/}";; esac; done'); [ -n "$cpid" ] && break; sleep 1; done+ test -n "$cpid"+ test "$(docker exec tunnel stat -c %u "/proc/$cpid")" = "$(docker exec tunnel id -u omb-tunnel)"+ if docker exec -u maus tunnel cat "/proc/$cpid/environ" >/dev/null 2>&1; then echo "maus can read the tunnel's token"; exit 1; fi+ if docker exec tunnel sh -c "tr '\\0' ' ' < /proc/$cpid/cmdline" | grep -qF "$token"; then echo "the token is in cloudflared's command line"; exit 1; fi+ for p in $(docker exec tunnel sh -c 'for p in /proc/[0-9]*; do case "$(tr "\0" " " < "$p/cmdline" 2>/dev/null)" in *"dist-server/in""dex.js"*|*"caddy r""un"*) echo "${p#/proc/}";; esac; done'); do+ if docker exec -u maus tunnel grep -qaF "$token" "/proc/$p/environ"; then echo "the token is in a maus process's environment"; exit 1; fi+ done+ if docker logs tunnel 2>&1 | grep -qF "$token"; then echo "the token reached the log"; exit 1; fi+ from_tunnel() { # port [curl options...]: as cloudflared reaches the edge, from the home's loopback+ local port=$1; shift; local signed; mapfile -t signed < <(bad_pair_headers | sed "s/^Host: .*/Host: $thost/")+ docker exec tunnel curl -s -o /dev/null -w '%{http_code}' --max-time 5 -X POST "${signed[@]}" "$@" --data-binary '{}' "http://127.0.0.1:$port/api/cloud/pairing"+ }+ for i in $(seq 1 10); do test "$(from_tunnel 8812 -H 'Cf-Connecting-IP: 198.51.100.1')" = 401; done+ test "$(from_tunnel 8812 -H 'Cf-Connecting-IP: 198.51.100.1')" = 429+ test "$(from_tunnel 8812 -H 'Cf-Connecting-IP: 198.51.100.2')" = 401+ for i in $(seq 1 10); do test "$(from_tunnel 8080 -H "Cf-Connecting-IP: 198.51.100.$((i + 10))")" = 401; done+ test "$(from_tunnel 8080 -H 'Cf-Connecting-IP: 198.51.100.30')" = 429+ docker rm -f tunnel >/dev/null+ docker volume rm omb-tunnel-ci >/dev/null+ # Two ways to reach one home never serve.+ if timeout 60 docker run --name home-bad -v omb-bad-ci:/data "${contract[@]}" -e OMB_CLOUD_EDGE_TLS=1 -e "OMB_CLOUD_TUNNEL_TOKEN=$token" omb-cloud-home:ci; then echo "TLS and a tunnel served"; exit 1; fi+ grep -q "set one" <<<"$(docker logs home-bad 2>&1)"+ docker rm -f home-bad >/dev/null+ docker volume rm omb-bad-ci >/dev/null+# Fly: the proxy's private address names the client in Fly-Client-IP, exactly as before.run_home fly omb-fly-ci 18082 -e FLY_APP_NAME=omb-t-cihealthy fly 18082@@ -429,6 +463,8 @@ jobs:assert len(caddy) == 1, f"Caddy is written {len(caddy)} times"assert caddy[0].uid == 0, f"Caddy belongs to uid {caddy[0].uid}"assert not any(key.startswith("SCHILY.xattr.security.") for key in caddy[0].pax_headers), "Caddy keeps a file capability"+ tunnel = files["usr/local/bin/cloudflared"]+ assert len(tunnel) == 1 and tunnel[0].uid == 0 and tunnel[0].mode & 0o7777 == 0o755, "cloudflared is not one root-owned 0755 binary"grok = files["usr/local/bin/grok"]assert len(grok) == 1 and grok[0].uid == 0 and grok[0].mode & 0o7777 == 0o755, "Grok is not one root-owned 0755 binary"installer = sorted(name for name in files if re.match(r"(data|root)/\.grok/|usr/local/bin/agent$", name))diff --git a/Dockerfile b/Dockerfileindex 31df980aa9..6d31e95b3e 100644--- a/Dockerfile+++ b/Dockerfile@@ -31,6 +31,14 @@ FROM caddy:2.10.2 AS edge# capability (and the build user's ownership).RUN cp /usr/bin/caddy /caddy+# The Cloudflare tunnel's connector, for a Cloud home on a server with no+# inbound port: the release pinned in scripts/prepare-cloudflared.mjs, checked+# against its digest and run once on the image's own CPU before it is copied.+FROM node:24-bookworm-slim AS tunnel+COPY scripts/prepare-cloudflared.mjs /stage/prepare-cloudflared.mjs+RUN node /stage/prepare-cloudflared.mjs --current --root /stage \+ && cp /stage/dist-native/cloudflared/linux-*/cloudflared /cloudflared+# The JavaScript build is the same for every CPU, so it runs once on the build# host's own; only the Data engine's native tree below follows the image's CPU.FROM --platform=$BUILDPLATFORM node:24-bookworm-slim AS build@@ -142,6 +150,9 @@ RUN apt-get update \# Caddy and Grok are pinned, so they sit beneath the engines, which change# more often.COPY --from=edge /caddy /usr/local/bin/caddy+COPY --from=tunnel /cloudflared /usr/local/bin/cloudflared+# cloudflared's own user: its token rides its environment, which maus can't read.+RUN useradd --system --no-create-home --home-dir /nonexistent --shell /usr/sbin/nologin omb-tunnel# Grok Build, the grok.com subscription engine: xAI's own installer, pinned to# the version the Grok driver is verified against (server/drivers/acp/grok.ts).# People sign it in from the app with a device code; its login lands in@@ -169,7 +180,7 @@ ARG ENGINES_CACHE_TAG=""RUN echo "engines: ${CLOUD_HOME_ENGINES:-none} ${ENGINES_CACHE_TAG}" \&& if [ -n "$CLOUD_HOME_ENGINES" ]; then HOME=/tmp/omb-build-home npm install -g $CLOUD_HOME_ENGINES; fi \&& rm -rf /tmp/omb-build-home /tmp/node-compile-cache-COPY deploy/fly/Caddyfile deploy/fly/Caddyfile.tls deploy/fly/edge-routes.caddy /app/cloud/+COPY deploy/fly/Caddyfile deploy/fly/Caddyfile.tls deploy/fly/Caddyfile.tunnel deploy/fly/edge-routes.caddy /app/cloud/# The root supervisor runs /app's code and hands the server its secrets, so# no file there may be one `maus` can change: unlike the server image's, these# copies stay root's. Only the /data volume is maus's; the launcher refuses to@@ -181,12 +192,14 @@ COPY --from=build /src/dist ./dist# The bundled skills (server/skill-library.ts reads ./skills from /app).COPY --from=build /src/skills ./skillsRUN export HOME=/tmp/omb-build-home \- && chmod go-w /app/cloud /app/cloud/Caddyfile /app/cloud/Caddyfile.tls /app/cloud/edge-routes.caddy \+ && chmod go-w /app/cloud /app/cloud/Caddyfile /app/cloud/Caddyfile.tls /app/cloud/Caddyfile.tunnel /app/cloud/edge-routes.caddy \&& caddy version \+ && cloudflared version \&& OMB_CLOUD_PUBLIC_HOST=validate.fly.dev caddy validate --config /app/cloud/Caddyfile --adapter caddyfile \&& OMB_CLOUD_PUBLIC_HOST=validate.example.com OMB_CLOUD_EDGE_STORAGE=/tmp/omb-build-home/edge caddy validate --config /app/cloud/Caddyfile.tls --adapter caddyfile \+ && OMB_CLOUD_PUBLIC_HOST=validate.example.com caddy validate --config /app/cloud/Caddyfile.tunnel --adapter caddyfile \&& test -f /app/dist-server/cloud-home-start.js \- && untrusted="$(find /app /usr/local/bin/caddy \( ! -user root -o ! -type l -perm /022 \) -print)" \+ && untrusted="$(find /app /usr/local/bin/caddy /usr/local/bin/cloudflared \( ! -user root -o ! -type l -perm /022 \) -print)" \&& if [ -n "$untrusted" ]; then echo "not root's, or writable by others:" >&2; echo "$untrusted" >&2; exit 1; fi \&& rm -rf /tmp/omb-build-homeENV HOME=/datadiff --git a/deploy/fly/Caddyfile.tunnel b/deploy/fly/Caddyfile.tunnelnew file mode 100644index 0000000000..4d9fd8aa73--- /dev/null+++ b/deploy/fly/Caddyfile.tunnel@@ -0,0 +1,32 @@+# Edge for a Cloud home on a server reached through a Cloudflare tunnel+# (docs/cloud-pro.md, "On your own server"): the same routes as Caddyfile on+# :8080, for the connector, and on 127.0.0.1:8812, where the control plane+# points the tunnel. cloudflared runs in this home, as maus (the launcher+# starts it: server/cloud-home-start.ts), and connects only from loopback, so+# that listener alone believes Cf-Connecting-IP, which Cloudflare's edge sets;+# :8080 trusts only the proxies the owner names. The address feeds the pairing+# lockout, never authorization.+{+ admin off+ auto_https off+ persist_config off+ servers :8080 {+ trusted_proxies static {$OMB_CLOUD_EDGE_TRUSTED_PROXIES}+ trusted_proxies_strict+ client_ip_headers {$OMB_CLOUD_EDGE_CLIENT_IP_HEADER}+ }+ servers 127.0.0.1:8812 {+ trusted_proxies static 127.0.0.1/32+ trusted_proxies_strict+ client_ip_headers Cf-Connecting-IP+ }+}++:8080 {+ import edge-routes.caddy+}++:8812 {+ bind 127.0.0.1+ import edge-routes.caddy+}diff --git a/docs/cloud-pro.md b/docs/cloud-pro.mdindex 0efe44ff86..b5ede22ebd 100644--- a/docs/cloud-pro.md+++ b/docs/cloud-pro.md@@ -1064,8 +1064,11 @@ layers (Node, Chrome's libraries, agent-browser and its Chrome) and adds:- Caddy, as the only listener the network can reach: `0.0.0.0:8080` with`deploy/fly/Caddyfile`, and also 443 for the home's own domain with- `deploy/fly/Caddyfile.tls` (both import the same routes,+ `deploy/fly/Caddyfile.tls`, or a loopback listener for the home's own+ tunnel with `deploy/fly/Caddyfile.tunnel` (all import the same routes,`deploy/fly/edge-routes.caddy`);+- `cloudflared`, pinned and digest-checked by `scripts/prepare-cloudflared.mjs`,+ run only for a home reached through its own tunnel, as the `omb-tunnel` user;- Grok Build (`/usr/local/bin/grok`) from xAI's own installer, pinned by`GROK_VERSION` to the version the Grok driver is verified against. Thebuild fails if the installer cannot be reached, rather than shipping an@@ -1261,6 +1264,7 @@ start.| `OMB_CLOUD_EDGE_TLS` | `1`: the edge gets and renews a Let's Encrypt certificate for that name and serves it on 443. Unset or `0`: the edge serves only `:8080`, for the agent, and something else ends TLS. || `OMB_CLOUD_TRUSTED_PROXIES` | Only when the owner's own proxy stands in front: its addresses or ranges (`10.0.0.5`, `10.0.0.0/24`, `private_ranges`), separated by spaces or commas, at most 32. Unset: none. A `/0` range, a host name or anything else stops the home with a message naming the variable. || `OMB_CLOUD_CLIENT_IP_HEADER` | The header those proxies put the client's address in. Default `X-Forwarded-For`; it needs `OMB_CLOUD_TRUSTED_PROXIES`. |+| `OMB_CLOUD_TUNNEL_TOKEN` | For a server with no inbound port: the connector token of the home's own Cloudflare tunnel. `OMB_PUBLIC_URL` is then the tunnel's address. Not with `OMB_CLOUD_EDGE_TLS`. |**Its own domain (`OMB_CLOUD_EDGE_TLS=1`).** The agent publishes thecontainer's 443 (and 80 if the owner opens it). Let's Encrypt checks the name@@ -1294,6 +1298,26 @@ no port is published on `[::]` (Docker's proxy sends IPv6 clients from theretoo). Only the named peers are believed, and only the last address they add,so a client's own `X-Forwarded-For` or `Cf-Connecting-IP` changes nothing.+**No inbound port: a Cloudflare tunnel.** The same managed tunnel as+`openmausbot serve --tunnel`, one per server: the control plane's+`ensureEndpoint`, called with the server's installation credential+(`fleetAccess` in `server/tunnel.ts`), returns the address+(`https://c-<32 hex>.<zone>`) and the connector token, which go into+`OMB_PUBLIC_URL` and `OMB_CLOUD_TUNNEL_TOKEN`. The home then runs the pinned+`cloudflared` from its image (`/usr/local/bin/cloudflared`, the release+`scripts/prepare-cloudflared.mjs` checks) as its own user, `omb-tunnel`: the+token rides that process's environment, which `maus`, and so no bot or engine,+can read. If it stops, the launcher starts it again after 5 s, doubling to+5 minutes. The control plane points every tunnel at `127.0.0.1:8812`, where+the edge (`deploy/fly/Caddyfile.tunnel`) listens on loopback only and believes+`Cf-Connecting-IP`, which Cloudflare's edge sets, so each member is counted+on their own; `:8080` still believes no header. The home lives in one+container, so a restart brings its tunnel back with it. Cloudflare decrypts+the traffic at its edge, which EU customers are told plainly. A boxed turn has+its own loopback, but a process that shares the home's (a bot's browser, or+a turn when the box is off) could name any address to `:8812`. That changes+only whose lockout its own failed codes count toward, never who is signed in.+**Private, on a tailnet.** `tailscale serve --bg --https=443http://127.0.0.1:8080` on the server serves `https://<machine>.<tailnet>.ts.net`to the tailnet; set `OMB_PUBLIC_URL` to that name, and name the bridge'sdiff --git a/scripts/docker-image.test.ts b/scripts/docker-image.test.tsindex 8ae999f3ea..3c6cc806fd 100644--- a/scripts/docker-image.test.ts+++ b/scripts/docker-image.test.ts@@ -40,7 +40,7 @@ function chain(target: string): Step[] {if (!stage) throw new Error(`the Dockerfile has no ${target} stage`);return [...(all.some(s => s.name === stage.from) ? chain(stage.from) : []), ...stage.steps];}-const shipped = () => all.filter(s => s.name !== "build" && s.name !== "edge").flatMap(s => s.steps);+const shipped = () => all.filter(s => s.name !== "build" && s.name !== "edge" && s.name !== "tunnel").flatMap(s => s.steps);const npmInstall = (step: Step) => step.op === "RUN" && /\bnpm install\b/.test(step.args);const browserRun = () => chain("runtime").find(step => step.op === "RUN" && step.args.includes("agent-browser install"))!;const grokRun = (steps: Step[]) => steps.findIndex(step => step.op === "RUN" && step.args.includes("https://x.ai/cli/install.sh"));@@ -65,7 +65,7 @@ describe("container images", () => {for (const target of ["server", "cloud-home"]) {const steps = chain(target);const heavy = steps.flatMap((step, i) => (npmInstall(step) ? [i] : []));- const app = steps.flatMap((step, i) => (step.op === "COPY" && !step.args.includes("--from=edge") ? [i] : []));+ const app = steps.flatMap((step, i) => (step.op === "COPY" && !/--from=(?:edge|tunnel) /.test(step.args) ? [i] : []));// agent-browser + Chrome, then (Cloud home only) pnpm in the tools layer, then the engines, then the app files// (and the Cloud home's Caddyfile)expect(heavy, target).toHaveLength(target === "cloud-home" ? 3 : 2);@@ -106,6 +106,12 @@ describe("container images", () => {// pinned, so beneath the engines: an engine release does not re-pull itexpect(home.findIndex(step => step.args.startsWith("--from=edge "))).toBeLessThan(home.findLastIndex(npmInstall));expect(home.filter(step => step.op === "RUN" && /\b(cp|mv)\b[^&]*caddy/.test(step.args))).toEqual([]);+ // The tunnel's connector: the release scripts/prepare-cloudflared.mjs pins and checks, once, beneath the engines.+ expect(all.find(s => s.name === "tunnel")!.steps.find(step => step.op === "RUN")!.args).toMatch(/^node \/stage\/prepare-cloudflared\.mjs --current --root \/stage /);+ expect(home.filter(step => step.args.includes("/usr/local/bin/cloudflared") && step.op === "COPY")).toEqual([+ { op: "COPY", args: "--from=tunnel /cloudflared /usr/local/bin/cloudflared" },+ ]);+ expect(home.findIndex(step => step.args.startsWith("--from=tunnel "))).toBeLessThan(home.findLastIndex(npmInstall));expect(home.filter(step => step.args.includes("--from=build")).map(step => step.args)).toEqual(["/src/dist-native/duckdb/target ./duckdb", "/src/dist-server ./dist-server", "/src/dist ./dist", "/src/skills ./skills",].map(path => `--from=build ${path}`));diff --git a/server/cloud-home-address.test.ts b/server/cloud-home-address.test.tsindex 5593c28793..718661951c 100644--- a/server/cloud-home-address.test.ts+++ b/server/cloud-home-address.test.ts@@ -5,7 +5,8 @@ import { join, posix } from "node:path";import { afterEach, expect, it } from "vitest";import { cloudHomeConfiguration, cloudRequestSignature, createCloudPairing } from "./cloud-home.ts";import {- cloudHomeChildEnvironments, edgeCertificateStorage, edgeClientAddress, edgeConfigFiles, edgeTerminatesTls, OWN_SERVER_EDGE_KEYS, trustedProxyList,+ cloudHomeChildEnvironments, edgeCertificateStorage, edgeClientAddress, edgeConfigFiles, edgeTerminatesTls, edgeTunnelToken, OWN_SERVER_EDGE_KEYS,+ trustedProxyList, tunnelCommand, tunnelRestartDelay, TUNNEL_USER,} from "./cloud-home-start.ts";import { requestSource } from "./request-auth.ts";import { LOCKOUT, SessionRegistry } from "./sessions.ts";@@ -82,6 +83,34 @@ it("serves HTTPS on the home's own domain only when asked, with the certificateexpect(() => edgeOf(ownServer({ OMB_CLOUD_EDGE_TLS: "on" }))).toThrow(/OMB_CLOUD_EDGE_TLS/);});+it("reaches a home with no open port through its own tunnel, whose token only cloudflared reads", () => {+ const token = `eyJhIjoi${"x".repeat(120)}==`;+ expect(edgeTunnelToken({})).toBeNull();+ expect(edgeTunnelToken({ OMB_CLOUD_TUNNEL_TOKEN: ` ${token} ` })).toBe(token);+ for (const bad of ["short", `${token}\n--url http://evil`, `${token} x`]) expect(() => edgeTunnelToken({ OMB_CLOUD_TUNNEL_TOKEN: bad }), bad).toThrow(/connector token/);+ expect(() => edgeTunnelToken({ OMB_CLOUD_TUNNEL_TOKEN: token, OMB_CLOUD_EDGE_TLS: "1" })).toThrow(/set one/);++ const tunnel = edgeOf(ownServer({ OMB_PUBLIC_URL: "https://c-0123456789abcdef0123456789abcdef.example.com", OMB_CLOUD_TUNNEL_TOKEN: token }));+ expect(tunnel.edgeFiles).toEqual({ config: "/app/cloud/Caddyfile.tunnel", routes: "/app/cloud/edge-routes.caddy" });+ expect(tunnel.tunnelToken).toBe(token);+ // :8080 still trusts nobody; only the tunnel's own listener believes Cf-Connecting-IP (Caddyfile.tunnel).+ expect(tunnel.edge).toMatchObject({ OMB_CLOUD_EDGE_TRUSTED_PROXIES: "", OMB_CLOUD_EDGE_CLIENT_IP_HEADER: "X-Forwarded-For" });+ for (const env of [tunnel.server, tunnel.edge, tunnel.secrets]) expect(JSON.stringify(env)).not.toContain(token);+ expect(edgeOf(ownServer()).tunnelToken).toBeNull();++ const command = tunnelCommand("/usr/local/bin/cloudflared", token);+ expect(command.args).toEqual(["tunnel", "--no-autoupdate", "--loglevel", "info", "run"]);+ expect(command.args.join(" ")).not.toContain(token);+ expect(command.env).toEqual({ PATH: "/usr/local/bin:/usr/bin:/bin", HOME: "/nonexistent", TUNNEL_TOKEN: token });+ expect(TUNNEL_USER).not.toBe("maus");++ expect(tunnelRestartDelay(0, 1_000)).toBe(5_000);+ expect(tunnelRestartDelay(5_000, 1_000)).toBe(10_000);+ expect(tunnelRestartDelay(240_000, 1_000)).toBe(300_000);+ expect(tunnelRestartDelay(300_000, 1_000)).toBe(300_000);+ expect(tunnelRestartDelay(300_000, 10 * 60_000)).toBe(5_000);+});+/** A request as the server receives it: the edge on loopback, with X-Forwarded-For set to the address it trusts. */const fromEdge = (client: string) =>// SAFETY: only headers and the socket peer are readdiff --git a/server/cloud-home-start.ts b/server/cloud-home-start.tsindex c2a7a774a2..246b1e1927 100644--- a/server/cloud-home-start.ts+++ b/server/cloud-home-start.ts@@ -53,7 +53,7 @@ export function edgeHold(raw: string | undefined): string {}/** How a home on its owner's server is reached (docs/cloud-pro.md, "On your own server"); never set on Fly. */-export const OWN_SERVER_EDGE_KEYS = ["OMB_CLOUD_EDGE_TLS", "OMB_CLOUD_TRUSTED_PROXIES", "OMB_CLOUD_CLIENT_IP_HEADER"] as const;+export const OWN_SERVER_EDGE_KEYS = ["OMB_CLOUD_EDGE_TLS", "OMB_CLOUD_TRUSTED_PROXIES", "OMB_CLOUD_CLIENT_IP_HEADER", "OMB_CLOUD_TUNNEL_TOKEN"] as const;const EDGE_CONFIG_DIR = "/app/cloud";export const EDGE_ROUTES_FILE = "edge-routes.caddy";const MAX_TRUSTED_PROXIES = 32;@@ -71,6 +71,18 @@ export function edgeTerminatesTls(env: NodeJS.ProcessEnv): boolean {return raw === "1";}+/**+ * OMB_CLOUD_TUNNEL_TOKEN: the connector token of this home's Cloudflare tunnel, for a server with no inbound port. The+ * home runs cloudflared itself and OMB_PUBLIC_URL is the tunnel's address. Only cloudflared ever reads the token.+ */+export function edgeTunnelToken(env: NodeJS.ProcessEnv): string | null {+ const token = env.OMB_CLOUD_TUNNEL_TOKEN?.trim() ?? "";+ if (!token) return null;+ if (!/^[A-Za-z0-9+/_=-]{32,4096}$/.test(token)) invalidEdge("OMB_CLOUD_TUNNEL_TOKEN must be the tunnel's connector token");+ if (edgeTerminatesTls(env)) invalidEdge("OMB_CLOUD_EDGE_TLS and OMB_CLOUD_TUNNEL_TOKEN are two ways to reach the home; set one");+ return token;+}+/*** The proxies an owner puts in front of the home, from OMB_CLOUD_TRUSTED_PROXIES: addresses, CIDR ranges or Caddy's* `private_ranges`, separated by spaces or commas. Each is written into the edge's config as a token, so anything else is@@ -114,7 +126,8 @@ export function edgeClientAddress(env: NodeJS.ProcessEnv): { OMB_CLOUD_EDGE_CLIE/** The edge's config, and the file every config imports: both run as root's trusted code. */export function edgeConfigFiles(env: NodeJS.ProcessEnv): { config: string; routes: string } {- const config = env.OMB_CLOUD_EDGE_CONFIG || posix.join(EDGE_CONFIG_DIR, edgeTerminatesTls(env) ? "Caddyfile.tls" : "Caddyfile");+ const name = edgeTunnelToken(env) ? "Caddyfile.tunnel" : edgeTerminatesTls(env) ? "Caddyfile.tls" : "Caddyfile";+ const config = env.OMB_CLOUD_EDGE_CONFIG || posix.join(EDGE_CONFIG_DIR, name);return { config, routes: posix.join(posix.dirname(config), EDGE_ROUTES_FILE) };}@@ -123,6 +136,24 @@ export function edgeCertificateStorage(home: string): string {return posix.join(home, ".omb-edge", "caddy");}+export function tunnelRestartDelay(previousMs: number, ranForMs: number): number {+ if (ranForMs >= 10 * 60_000 || previousMs <= 0) return 5_000;+ return Math.min(previousMs * 2, 5 * 60_000);+}++/** The user cloudflared runs as. Its token rides its environment (TUNNEL_TOKEN), which only that user and root can read:+ * never `maus`, whose bots could otherwise copy it and serve the home's address elsewhere. cloudflared 2026.10 can't+ * read --token-file from an inherited socket, which is all Node's stdio gives a child. */+export const TUNNEL_USER = "omb-tunnel";++export function tunnelCommand(bin: string, token: string): { command: string; args: string[]; env: NodeJS.ProcessEnv } {+ return {+ command: bin,+ args: ["tunnel", "--no-autoupdate", "--loglevel", "info", "run"],+ env: { PATH: "/usr/local/bin:/usr/bin:/bin", HOME: "/nonexistent", TUNNEL_TOKEN: token },+ };+}+/** The server's data directory on the volume. */export function cloudHomeDataDir(env: NodeJS.ProcessEnv, home: string): string {return env.OMB_DATA_DIR || posix.join(home, ".openmausbot");@@ -195,7 +226,7 @@ export function cloudHomeChildEnvironments(config: CloudHomeConfig, env: NodeJS....edgeClientAddress(env),...(edgeTerminatesTls(env) ? { OMB_CLOUD_EDGE_STORAGE: edgeCertificateStorage(home) } : {}),};- return { server, edge, edgeFiles: edgeConfigFiles(env), secrets: cloudHomeSecrets(env), dropped };+ return { server, edge, edgeFiles: edgeConfigFiles(env), tunnelToken: edgeTunnelToken(env), secrets: cloudHomeSecrets(env), dropped };}/** What root does to the machine before anything runs as `maus` (docs/bot-box.md, "What each layer stops"): /proc hides@@ -251,7 +282,7 @@ export function startCloudHome(env: NodeJS.ProcessEnv = process.env) {// Logged here once: the server child never sees what they are about.for (const warning of config.warnings) console.warn(`cloud home: ${warning}`);const home = env.HOME || "/data";- const { server, edge, edgeFiles, secrets, dropped } = cloudHomeChildEnvironments(config, env, home);+ const { server, edge, edgeFiles, tunnelToken, secrets, dropped } = cloudHomeChildEnvironments(config, env, home);const prepare = () => prepareCloudHomeData(home, cloudHomeDataDir(env, home), config.machineId);let prepared: ReturnType<typeof prepare>;let ids: { uid: number; gid: number } | null = null;@@ -277,8 +308,12 @@ export function startCloudHome(env: NodeJS.ProcessEnv = process.env) {for (const record of prepared.cleared) console.log(`cloud home: cleared a stale data-directory record machine ${record.host} (process ${record.pid}) left on this volume: ${record.path}`);const here = dirname(fileURLToPath(import.meta.url));const edgeBin = env.OMB_CLOUD_EDGE_BIN || "/usr/local/bin/caddy";+ const tunnelBin = env.OMB_CLOUD_TUNNEL_BIN || "/usr/local/bin/cloudflared";+ const tunnelIds = ids && tunnelToken ? passwdIds(readFileSync("/etc/passwd", "utf8"), TUNNEL_USER) : null;+ if (ids && tunnelToken && !tunnelIds) throw new Error(`The ${TUNNEL_USER} user is missing from this image, so its tunnel cannot start.`);if (ids) {- const problem = codeTrustProblem([process.execPath, fileURLToPath(import.meta.url), join(here, "index.js"), edgeBin, edgeFiles.config, edgeFiles.routes], home);+ const problem = codeTrustProblem([process.execPath, fileURLToPath(import.meta.url), join(here, "index.js"), edgeBin, edgeFiles.config, edgeFiles.routes,+ ...(tunnelToken ? [tunnelBin] : [])], home);if (problem) throw new Error(`This image's code is not safe to run as root: ${problem}. Rebuild it with docker build --target cloud-home.`);}// Names only, never values: what the server does not get from here.@@ -312,6 +347,29 @@ export function startCloudHome(env: NodeJS.ProcessEnv = process.env) {runServer();watch(spawnWithOomScore(OOM_SCORE.edge, () => spawn(edgeBin, ["run", "--config", edgeFiles.config, "--adapter", "caddyfile"],{ env: edge, stdio: "inherit", ...(ids ? { uid: ids.uid, gid: ids.gid } : {}) })));+ if (tunnelToken) {+ const tunnel = tunnelCommand(tunnelBin, tunnelToken);+ let delay = 0;+ const runTunnel = () => {+ if (stopping) return;+ const started = Date.now();+ const child = spawnWithOomScore(OOM_SCORE.edge, () => spawn(tunnel.command, tunnel.args,+ { env: tunnel.env, stdio: ["ignore", "inherit", "inherit"], ...(tunnelIds ? { uid: tunnelIds.uid, gid: tunnelIds.gid } : {}) }));+ children.push(child);+ const ended = (code: number | null) => {+ const index = children.indexOf(child);+ if (index < 0) return;+ children.splice(index, 1);+ if (stopping) return;+ delay = tunnelRestartDelay(delay, Date.now() - started);+ console.warn(`cloud home: the tunnel's connector stopped (${code ?? "signal"}); starting it again in ${delay / 1000} s`);+ setTimeout(runTunnel, delay).unref();+ };+ child.once("error", () => ended(null));+ child.once("exit", ended);+ };+ runTunnel();+ }process.once("SIGTERM", () => stop(false));process.once("SIGINT", () => stop(false));}diff --git a/server/cloud-home.test.ts b/server/cloud-home.test.tsindex 87c1bc3c29..151edaba2e 100644--- a/server/cloud-home.test.ts+++ b/server/cloud-home.test.ts@@ -441,13 +441,17 @@ it("ships an edge and a Fly template that keep the server private", () => {expect(edgeFile("Caddyfile")).toMatch(/^:8080 \{\n\timport edge-routes\.caddy\n\}\n/m);expect(edgeFile("Caddyfile")).toMatch(/^\tauto_https off$/m);expect(edgeFile("Caddyfile.tls")).toMatch(/^http:\/\/:8080 \{\n\timport edge-routes\.caddy\n\}\n\n\{\$OMB_CLOUD_PUBLIC_HOST\} \{\n\timport edge-routes\.caddy\n\}\n/m);- for (const config of [edgeFile("Caddyfile"), edgeFile("Caddyfile.tls")]) {+ expect(edgeFile("Caddyfile.tunnel")).toMatch(/^:8080 \{\n\timport edge-routes\.caddy\n\}\n\n:8812 \{\n\tbind 127\.0\.0\.1\n\timport edge-routes\.caddy\n\}\n/m);+ // The tunnel's listener, on loopback alone, believes Cloudflare's header; :8080 believes only what the launcher says.+ expect(edgeFile("Caddyfile.tunnel")).toMatch(/^\tservers 127\.0\.0\.1:8812 \{\n\t\ttrusted_proxies static 127\.0\.0\.1\/32\n\t\ttrusted_proxies_strict\n\t\tclient_ip_headers Cf-Connecting-IP\n\t\}$/m);+ expect(edgeFile("Caddyfile.tunnel").match(/^\s*(?:trusted_proxies|client_ip_headers)\b/gm)).toHaveLength(4);+ for (const config of [edgeFile("Caddyfile"), edgeFile("Caddyfile.tls"), edgeFile("Caddyfile.tunnel")]) {expect(config.match(/^(?!#)\S[^\n]* \{$/gm)?.length, "every site imports the same routes").toBe(config.match(/^\timport edge-routes\.caddy$/gm)?.length);expect(config).not.toMatch(/reverse_proxy|respond/);- // Who may name the client, and in which header, is the launcher's to say (edgeClientAddress); no file names either.+ // Who may name the client on :8080 and 443, and in which header, is the launcher's to say (edgeClientAddress).expect(config).toMatch(/^\t\ttrusted_proxies static \{\$OMB_CLOUD_EDGE_TRUSTED_PROXIES\}\r?\n\t\ttrusted_proxies_strict\r?\n\t\tclient_ip_headers \{\$OMB_CLOUD_EDGE_CLIENT_IP_HEADER\}\r?\n/m);- expect(config.match(/^\s*(?:trusted_proxies|client_ip_headers)\b/gm)).toHaveLength(2);}+ for (const config of [edgeFile("Caddyfile"), edgeFile("Caddyfile.tls")]) expect(config.match(/^\s*(?:trusted_proxies|client_ip_headers)\b/gm)).toHaveLength(2);expect(caddy).not.toMatch(/trusted_proxies|client_ip_headers/);const upstreams = [...caddy.matchAll(/reverse_proxy (\S+)/g)].map(match => match[1]);expect(new Set(upstreams)).toEqual(new Set(["127.0.0.1:8799", "127.0.0.1:8800"]));@@ -462,11 +466,11 @@ it("ships an edge and a Fly template that keep the server private", () => {// The root supervisor's code is root's, maus owns only the volume; the image's last step refuses to build otherwise.const dockerfile = readFileSync(join(import.meta.dirname, "../Dockerfile"), "utf8");const image = dockerfile.slice(dockerfile.indexOf("FROM runtime AS cloud-home"), dockerfile.indexOf("FROM runtime AS server"));- const check = image.indexOf('untrusted="$(find /app /usr/local/bin/caddy \\( ! -user root -o ! -type l -perm /022 \\) -print)"');+ const check = image.indexOf('untrusted="$(find /app /usr/local/bin/caddy /usr/local/bin/cloudflared \\( ! -user root -o ! -type l -perm /022 \\) -print)"');expect(image.slice(check)).toMatch(/^untrusted=.*\n && if \[ -n "\$untrusted" \]; then .*exit 1; fi \\\n/);expect(check).toBeGreaterThan(image.lastIndexOf("COPY "));expect(check).toBeLessThan(image.indexOf("CMD ["));- expect(image).toContain("COPY deploy/fly/Caddyfile deploy/fly/Caddyfile.tls deploy/fly/edge-routes.caddy /app/cloud/");+ expect(image).toContain("COPY deploy/fly/Caddyfile deploy/fly/Caddyfile.tls deploy/fly/Caddyfile.tunnel deploy/fly/edge-routes.caddy /app/cloud/");// The bot box (server/bot-box) needs bubblewrap and socat in the image; pnpm is what bots' projects ask for.expect(image).toMatch(/apt-get install -y --no-install-recommends [^\n]*\bbubblewrap\b[^\n]*\bsocat\b/);expect(image).toMatch(/npm install -g pnpm@10\.33\.0/);