Skip to content

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

Antigravity sign-in on a Cloud: deliver a pasted redirect inside the bot box (#4678)

Milind Soni07884ca23e0a
diff --git a/docs/bot-box.md b/docs/bot-box.md
index 2b825c939b..3d500c574b 100644
--- a/docs/bot-box.md
+++ b/docs/bot-box.md
@@ -36,6 +36,15 @@ tokens and a few names a shell expects. Every `OMB_CLOUD_*` setting, the server'
A box with the host's network (`net: "shared"`, for a browser whose Chrome already goes through its own gate) has
neither bridge.
+## The sign-in relay
+
+An engine that signs in through a callback on `127.0.0.1` (Antigravity's Google sign-in) listens on the box's own
+loopback, which the server cannot reach. That box alone gets one more unix socket (`server/bot-box/relay.ts`), bound in
+at `/run/omb/relay.sock`: the in-box Node bridge dials out to it and keeps one connection waiting, and when someone
+pastes the redirect from another computer the server writes the callback's port on that connection and sends the
+request through it. Only the server ever chooses the port, the box reaches nothing new on the host, and the server never
+connects to a path inside the box.
+
## When it is on
`server/bot-box/detect.ts`: on by default on a Cloud home (`OMB_CLOUD_ROLE=home` or `team`), off everywhere else
diff --git a/server/bot-box/box-bridge.ts b/server/bot-box/box-bridge.ts
index a8350bb31f..9db683892e 100644
--- a/server/bot-box/box-bridge.ts
+++ b/server/bot-box/box-bridge.ts
@@ -1,22 +1,28 @@
-// Runs inside a bot box when the image has no socat: listens on loopback ports and forwards each connection to a unix
-// socket bound into the box, then runs the engine with the box's stdio and exits with its status.
-// node box-bridge.js --bridge=3128=/run/omb/egress.sock --bridge=8799=/run/omb/harness.sock -- claude -p ...
+// Runs inside a bot box when the image has no socat, or when the box has a relay: listens on loopback ports and forwards
+// each connection to a unix socket bound into the box, dials the relay socket, then runs the engine with the box's stdio
+// and exits with its status.
+// node box-bridge.js --bridge=3128=/run/omb/egress.sock --bridge=8799=/run/omb/harness.sock [--relay=/run/omb/relay.sock] -- claude -p ...
import { spawn } from "node:child_process";
import { connect, createServer, type Server } from "node:net";
+import { dialRelay } from "./relay.ts";
+
export interface BridgeSpec { port: number; socket: string }
-export function parseBridgeArgs(argv: readonly string[]): { bridges: BridgeSpec[]; command: string[] } {
+export function parseBridgeArgs(argv: readonly string[]): { bridges: BridgeSpec[]; relay?: string; command: string[] } {
const bridges: BridgeSpec[] = [];
+ let relay: string | undefined;
let index = 0;
for (; index < argv.length; index++) {
const arg = argv[index]!;
if (arg === "--") { index++; break; }
+ const relayMatch = /^--relay=(.+)$/.exec(arg);
+ if (relayMatch) { relay = relayMatch[1]!; continue; }
const match = /^--bridge=(\d{1,5})=(.+)$/.exec(arg);
if (!match) throw new Error(`box-bridge: unexpected argument ${arg}`);
bridges.push({ port: Number(match[1]), socket: match[2]! });
}
- return { bridges, command: argv.slice(index) };
+ return { bridges, ...(relay ? { relay } : {}), command: argv.slice(index) };
}
/** Listens on 127.0.0.1:port and pipes each connection to the socket; resolves once listening. */
@@ -36,10 +42,11 @@ export function openBridge(spec: BridgeSpec): Promise<Server> {
}
export async function runBridged(argv: readonly string[]): Promise<number> {
- const { bridges, command } = parseBridgeArgs(argv);
+ const { bridges, relay, command } = parseBridgeArgs(argv);
if (!command.length) throw new Error("box-bridge: no command after --");
const servers = await Promise.all(bridges.map(openBridge));
for (const server of servers) server.unref();
+ if (relay) dialRelay(relay);
const child = spawn(command[0]!, command.slice(1), { stdio: "inherit" });
for (const signal of ["SIGTERM", "SIGINT", "SIGHUP"] as const) process.on(signal, () => { try { child.kill(signal); } catch {} });
return new Promise((resolve) => {
diff --git a/server/bot-box/box.test.ts b/server/bot-box/box.test.ts
index c3105ba016..a04c252ef6 100644
--- a/server/bot-box/box.test.ts
+++ b/server/bot-box/box.test.ts
@@ -61,6 +61,19 @@ describe("BoxRunner.wrap", () => {
expect(wrapped.args.slice(wrapped.args.indexOf("--") + 1)).toEqual(["/opt/chrome", "--headless"]);
});
+ // The box's paths are POSIX paths inside it, which Windows' path module would write with drive letters and backslashes.
+ it.skipIf(process.platform === "win32")("a relay is bound in and dialed by the Node bridge, even where socat bridges the gates; a shared-network box has none", () => {
+ const runner = new BoxRunner({ bwrap: "/usr/bin/bwrap", bridge, setup, denyEnv: new Set() });
+ const relay = "/data/.openmausbot/box/relay-ab12.sock";
+ const wrapped = runner.wrap({ command: "/data/.openmausbot/tools/agy", args: ["--uid="], env: { PATH: "/usr/bin" }, relay });
+ expect(wrapped.args.join(" ")).toContain(`--bind ${relay} /run/omb/relay.sock`);
+ const inner = wrapped.args.slice(wrapped.args.indexOf("--") + 1);
+ expect(inner).toEqual([bridge.node, bridge.bridgeScript, "--bridge=3128=/run/omb/egress.sock", "--bridge=8799=/run/omb/harness.sock", "--relay=/run/omb/relay.sock", "--", "/data/.openmausbot/tools/agy", "--uid="]);
+ const shared = runner.wrap({ command: "/opt/chrome", args: [], env: {}, net: "shared", relay });
+ expect(shared.args).not.toContain(relay);
+ expect(shared.args.slice(shared.args.indexOf("--") + 1)).toEqual(["/opt/chrome"]);
+ });
+
it("the env-all mutation hands over the whole environment (so the self-check can prove the allow-list)", () => {
const runner = new BoxRunner({ bwrap: "/usr/bin/bwrap", bridge, setup: { ...setup, mutate: new Set(["env-all" as const]) }, denyEnv: new Set() });
expect(runner.wrap({ command: "x", args: [], env: { OMB_CLOUD_BOOTSTRAP_SECRET: "s", EMPTY: undefined } }).env).toMatchObject({ OMB_CLOUD_BOOTSTRAP_SECRET: "s" });
@@ -158,6 +171,18 @@ describe("BotBox", () => {
expect(box.report().checks).toEqual({ passed: 20, total: 21, failed: ["egress-public-allowed"], at: 1 });
expect(lines).toHaveLength(1);
expect(lines[0]).toMatch(/^bot box: on \(bubblewrap, node bridges, credential broker, seccomp (on|unsupported here)\)$/);
+ const relay = (await box.openRelay())!;
+ expect(relay.socketPath.startsWith(join(dataDir, "box", "relay-"))).toBe(true);
+ expect(existsSync(relay.socketPath)).toBe(true);
+ relay.close();
+ expect(existsSync(relay.socketPath)).toBe(false);
+ });
+
+ it("off: no relay", async () => {
+ const box = new BotBox();
+ boxes.push(box);
+ await box.start({ dataDir: temp(), home: temp(), port: 8799, denyEnv: new Set(), env: {}, log: () => {} });
+ expect(await box.openRelay()).toBeNull();
});
});
diff --git a/server/bot-box/box.ts b/server/bot-box/box.ts
index f45acd999a..c28a2c207d 100644
--- a/server/bot-box/box.ts
+++ b/server/bot-box/box.ts
@@ -2,6 +2,7 @@
// boxes reach through unix sockets (egress-gate.ts, harness-gate.ts), and wraps each bot spawn (server/procs.ts spawnCli
// with owner "bot") in bubblewrap by the plan (plan.ts). Nothing here changes a spawn when the box is off: the command,
// its arguments and its environment go through untouched, so every host that is not a Cloud home behaves as before.
+import { randomBytes } from "node:crypto";
import { existsSync, mkdirSync, openSync, rmSync, statSync, writeFileSync } from "node:fs";
import { dirname, join, resolve } from "node:path";
@@ -16,7 +17,8 @@ import { boxEnvironment } from "./env.ts";
import { openHarnessGate, type HarnessGate } from "./harness-gate.ts";
import { procHidepid } from "./hidepid.ts";
import { DENIED_SYSCALLS, seccompBytes, seccompSupported } from "./seccomp.ts";
-import { boxUploadsDir, bwrapArgs, planBox, taskWorkspaceIds, type BoxBridge, type BoxPlan, type BoxRequest, type BoxSetup } from "./plan.ts";
+import { RELAY_SOCKET_NAME, boxUploadsDir, bwrapArgs, inBoxSocket, planBox, taskWorkspaceIds, type BoxBridge, type BoxPlan, type BoxRequest, type BoxSetup } from "./plan.ts";
+import { openBoxRelay, type BoxRelay } from "./relay.ts";
/** The loopback port inside a box that reaches the egress gate. The harness gate sits at the server's own port. */
export const BOX_EGRESS_PORT = 3128;
@@ -108,7 +110,8 @@ export class BoxRunner {
for (const name of BOX_NO_PROXY_ENV) env[name] = "127.0.0.1,localhost,::1,[::1]";
}
const bridges = plan.net === "isolated" ? this.options.setup.bridges : [];
- const inner = bridgedCommand(this.options.bridge, bridges, request.command, request.args);
+ const relay = plan.net === "isolated" && request.relay ? inBoxSocket(RELAY_SOCKET_NAME) : undefined;
+ const inner = bridgedCommand(this.options.bridge, bridges, request.command, request.args, relay);
const brokered = this.broker(env, plan, request);
const vouched = (request.allowEnv ?? []).filter((name) => /(?:KEY|TOKEN|SECRET)$/.test(name) && brokered.env[name] !== undefined && brokered.env[name] === request.env[name]);
const unbrokered = [...new Set([...brokered.unbrokered, ...vouched])];
@@ -251,6 +254,12 @@ export class BotBox {
enabled(): boolean { return this.runner !== null; }
+ /** A relay for one boxed spawn (BoxRequest.relay), or null when bot spawns are not boxed here. */
+ async openRelay(): Promise<BoxRelay | null> {
+ if (!this.runner) return null;
+ return openBoxRelay(join(this.runner.setup.dataDir, "box", `relay-${randomBytes(6).toString("hex")}.sock`));
+ }
+
/** The box a bot's Chrome runs in: the system read-only, private /tmp and /run, the host's network (the browser's own
* gate filters it), `ro` paths, and nothing of HOME or the data folder; the launcher binds the one profile it starts
* Chrome on. bubblewrap's options before `--`; null when turns are not boxed here. */
diff --git a/server/bot-box/bridge.test.ts b/server/bot-box/bridge.test.ts
index 3eef0c3111..06184bff57 100644
--- a/server/bot-box/bridge.test.ts
+++ b/server/bot-box/bridge.test.ts
@@ -33,6 +33,14 @@ linuxBox("the in-box bridge command", () => {
expect(parseBridgeArgs(args.slice(1))).toEqual({ bridges: [{ port: 3128, socket: "/run/omb/egress.sock" }, { port: 8799, socket: "/run/omb/harness.sock" }], command: ["claude", "-p"] });
});
+ it("with a relay: the Node bridge even where socat is, so each connection the host sends names its own port", () => {
+ const { command, args } = bridgedCommand({ socat: "/usr/bin/socat", bridgeScript: "/app/box-bridge.js", node: "/usr/bin/node" }, bridges, "agy", ["--uid="], "/run/omb/relay.sock");
+ expect(command).toBe("/usr/bin/node");
+ expect(args).toEqual(["/app/box-bridge.js", "--bridge=3128=/run/omb/egress.sock", "--bridge=8799=/run/omb/harness.sock", "--relay=/run/omb/relay.sock", "--", "agy", "--uid="]);
+ expect(parseBridgeArgs(args.slice(1))).toEqual({ bridges: [{ port: 3128, socket: "/run/omb/egress.sock" }, { port: 8799, socket: "/run/omb/harness.sock" }], relay: "/run/omb/relay.sock", command: ["agy", "--uid="] });
+ expect(bridgedCommand({ socat: null, bridgeScript: "/b.js", node: "/n" }, [], "agy", [], "/run/omb/relay.sock")).toEqual({ command: "/n", args: ["/b.js", "--relay=/run/omb/relay.sock", "--", "agy"] });
+ });
+
it("no bridges (a shared-network box): the engine as is", () => {
expect(bridgedCommand({ socat: "/usr/bin/socat", bridgeScript: "/b.js", node: "/n" }, [], "chrome", ["--headless"])).toEqual({ command: "chrome", args: ["--headless"] });
});
diff --git a/server/bot-box/bridge.ts b/server/bot-box/bridge.ts
index 7cf9b56ca9..1d85608efe 100644
--- a/server/bot-box/bridge.ts
+++ b/server/bot-box/bridge.ts
@@ -12,10 +12,11 @@ export interface BridgeTools {
node: string;
}
-/** The command the box runs: the bridges first, then the engine. `$0` is the engine so its argv passes through unchanged. */
-export function bridgedCommand(tools: BridgeTools, bridges: readonly BoxBridge[], command: string, args: readonly string[]): { command: string; args: string[] } {
- if (!bridges.length) return { command, args: [...args] };
- if (tools.socat) {
+/** The command the box runs: the bridges first, then the engine. `$0` is the engine so its argv passes through unchanged.
+ * `relay` is the in-box path of a relay socket; socat cannot learn its target port per connection, so it takes the Node bridge. */
+export function bridgedCommand(tools: BridgeTools, bridges: readonly BoxBridge[], command: string, args: readonly string[], relay?: string): { command: string; args: string[] } {
+ if (!bridges.length && !relay) return { command, args: [...args] };
+ if (tools.socat && !relay) {
// Each bridge keeps none of the engine's stdio: its own messages never reach the driver's stderr, and a bridge that
// outlives the engine (only without a PID namespace) holds no pipe open.
const lines = bridges.map((bridge) =>
@@ -26,7 +27,7 @@ export function bridgedCommand(tools: BridgeTools, bridges: readonly BoxBridge[]
const script = [...lines, wait, 'exec "$0" "$@"'].join("\n");
return { command: "/bin/sh", args: ["-c", script, command, ...args] };
}
- return { command: tools.node, args: [tools.bridgeScript, ...bridges.map((bridge) => `--bridge=${bridge.port}=${inBoxSocket(bridge.name)}`), "--", command, ...args] };
+ return { command: tools.node, args: [tools.bridgeScript, ...bridges.map((bridge) => `--bridge=${bridge.port}=${inBoxSocket(bridge.name)}`), ...(relay ? [`--relay=${relay}`] : []), "--", command, ...args] };
}
/** A word for /bin/sh, single-quoted. */
diff --git a/server/bot-box/plan.test.ts b/server/bot-box/plan.test.ts
index 0e15cd0bea..08d84eb3dc 100644
--- a/server/bot-box/plan.test.ts
+++ b/server/bot-box/plan.test.ts
@@ -112,6 +112,17 @@ linuxBox("the box plan", () => {
expect(visibleInBox(plan, "/data/.openmausbot/messages.db")).toBe("none");
});
+ it("a relay socket goes in at /run/omb/relay.sock only for a box with its own network", () => {
+ const relay = `${dataDir}/box/relay-ab12.sock`;
+ const plan = planBox(setup(), { command: "/usr/bin/agy", args: [], cwd, env: { HOME: home }, relay });
+ expect(bwrapArgs(plan).join(" ")).toContain(`--bind ${relay} /run/omb/relay.sock`);
+ expect(visibleInBox(plan, "/run/omb/relay.sock")).toBe("rw");
+ expect(visibleInBox(plan, relay)).toBe("none");
+ expect(visibleInBox(plan, `${dataDir}/box/egress.sock`)).toBe("none");
+ const shared = planBox(setup(), { command: "/opt/chrome", args: [], env: {}, net: "shared", relay });
+ expect(bwrapArgs(shared).join(" ")).not.toContain(relay);
+ });
+
it("has the machine's CPU list read-only and nothing else of /sys, so a TCMalloc runtime (Antigravity) can start", () => {
// Measured on a Fly Cloud home (2, 4 and 8 shared CPUs): without `possible` Google's runtime stops at start with
// "tcmalloc/internal/sysinfo.h:76] CHECK in NumCPUs" and exit 134; with it, initialize answers.
diff --git a/server/bot-box/plan.ts b/server/bot-box/plan.ts
index 492e6527d1..bd42038aae 100644
--- a/server/bot-box/plan.ts
+++ b/server/bot-box/plan.ts
@@ -16,7 +16,8 @@
// - of /sys, only the machine's CPU list, read-only;
// - a network namespace with loopback only. Two loopback ports inside are bridged to unix sockets bound in from outside:
// the egress gate (every connection to the internet goes through it) and the harness gate (only /api/internal/
-// routes of this server). Nothing else on the server's loopback is reachable.
+// routes of this server). Nothing else on the server's loopback is reachable. A box that waits for a sign-in callback
+// also dials out to one more socket, through which the server reaches the box's own loopback, never the other way.
import { isAbsolute, join, relative, resolve, sep } from "node:path";
export type BoxNet = "isolated" | "shared";
@@ -71,6 +72,9 @@ export interface BoxRequest {
home?: string;
/** Files bound read-write over their names in `home`: the team's engine sign-ins. */
shared?: ReadonlyArray<{ source: string; target: string }>;
+ /** A host unix socket the box dials out to, so the server can reach a port the engine listens on inside the box's own
+ * network, such as a sign-in's callback. Only an isolated box has one. */
+ relay?: string;
}
export interface BoxPlan {
@@ -84,6 +88,7 @@ export interface BoxPlan {
}
export const IN_BOX_SOCKET_DIR = "/run/omb";
+export const RELAY_SOCKET_NAME = "relay";
export const BOX_HOSTNAME = "omb-box";
const ID = /^[A-Za-z0-9_-]{1,128}$/;
@@ -221,6 +226,7 @@ export function planBox(setup: BoxSetup, request: BoxRequest): BoxPlan {
options.push("--unshare-net");
mounts.push({ kind: "dir", target: IN_BOX_SOCKET_DIR });
for (const bridge of setup.bridges) mounts.push({ kind: "bind", source: bridge.socket, target: join(IN_BOX_SOCKET_DIR, `${bridge.name}.sock`) });
+ if (request.relay) mounts.push({ kind: "bind", source: resolve(request.relay), target: inBoxSocket(RELAY_SOCKET_NAME) });
}
if (cwd) options.push("--chdir", cwd);
return { mounts, options, net, writable, botId };
diff --git a/server/bot-box/relay.test.ts b/server/bot-box/relay.test.ts
new file mode 100644
index 0000000000..a3a9ce5898
--- /dev/null
+++ b/server/bot-box/relay.test.ts
@@ -0,0 +1,101 @@
+import { mkdtempSync, rmSync } from "node:fs";
+import { createServer, request, type Server } from "node:http";
+import { connect, createServer as createNetServer, type Socket } from "node:net";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { afterEach, describe, expect, it } from "vitest";
+
+import { dialRelay, openBoxRelay, type BoxRelay } from "./relay.ts";
+
+// The box runs only on a Linux Cloud home; the relay is a unix socket at a POSIX path, which Windows does not have.
+const linuxBox = describe.skipIf(process.platform === "win32");
+
+linuxBox("the relay into a box's own loopback", () => {
+ const cleanup: Array<() => void> = [];
+ afterEach(() => { for (const step of cleanup.splice(0).reverse()) step(); });
+
+ const relayAt = async (): Promise<BoxRelay> => {
+ const dir = mkdtempSync(join(tmpdir(), "omb-relay-"));
+ const relay = await openBoxRelay(join(dir, "relay.sock"));
+ cleanup.push(() => rmSync(dir, { recursive: true, force: true }), () => relay.close());
+ return relay;
+ };
+ const listener = async (): Promise<{ server: Server; port: number; seen: string[] }> => {
+ const seen: string[] = [];
+ const server = createServer((req, res) => {
+ seen.push(req.url ?? "");
+ res.writeHead(200, { "content-type": "text/plain" });
+ res.end("signed in");
+ });
+ await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
+ cleanup.push(() => server.close());
+ return { server, port: (server.address() as { port: number }).port, seen };
+ };
+ const get = (relay: BoxRelay, port: number, path: string) => relay.connect(port).then((socket) => new Promise<{ status: number; body: string }>((resolve, reject) => {
+ const req = request({ host: "127.0.0.1", port, path, createConnection: () => socket }, (res) => {
+ let body = "";
+ res.setEncoding("utf8").on("data", (chunk) => { body += chunk; }).on("end", () => resolve({ status: res.statusCode ?? 0, body }));
+ });
+ req.on("error", reject);
+ req.end();
+ }));
+
+ it("carries a request the host sends to the loopback port it names, through the connection the box dialed", async () => {
+ const relay = await relayAt();
+ const { port, seen } = await listener();
+ const box = dialRelay(relay.socketPath, 20);
+ cleanup.push(() => box.close());
+ expect(await get(relay, port, "/?state=s&code=c")).toEqual({ status: 200, body: "signed in" });
+ expect(seen).toEqual(["/?state=s&code=c"]);
+ // The box dialed again at once, so a second delivery needs no wait.
+ expect(await get(relay, port, "/again")).toEqual({ status: 200, body: "signed in" });
+ expect(seen).toEqual(["/?state=s&code=c", "/again"]);
+ });
+
+ it("waits for the box to dial in, and says so when it never does", async () => {
+ const relay = await relayAt();
+ const { port, seen } = await listener();
+ const late = get(relay, port, "/late");
+ setTimeout(() => { const box = dialRelay(relay.socketPath, 20); cleanup.push(() => box.close()); }, 50);
+ expect(await late).toEqual({ status: 200, body: "signed in" });
+ expect(seen).toEqual(["/late"]);
+
+ const silent = await relayAt();
+ await expect(silent.connect(port, 50)).rejects.toThrow(/did not answer/);
+ });
+
+ it("the box side drops a connection whose first line is not a port", async () => {
+ const dir = mkdtempSync(join(tmpdir(), "omb-relay-"));
+ cleanup.push(() => rmSync(dir, { recursive: true, force: true }));
+ const host = createNetServer();
+ const dialed: Socket[] = [];
+ host.on("connection", (socket) => dialed.push(socket));
+ await new Promise<void>((resolve) => host.listen(join(dir, "relay.sock"), resolve));
+ cleanup.push(() => host.close());
+ const box = dialRelay(join(dir, "relay.sock"), 20);
+ cleanup.push(() => box.close());
+ const next = async () => {
+ while (!dialed.length) await new Promise((resolve) => setTimeout(resolve, 5));
+ return dialed.shift()!;
+ };
+ for (const line of ["70000\n", "0\n", "abc\n", "1234567"]) {
+ const socket = await next();
+ const closed = new Promise<void>((resolve) => socket.once("close", () => resolve()));
+ socket.write(line);
+ await closed;
+ }
+ const relay = await relayAt();
+ await expect(relay.connect(0)).rejects.toThrow(/Not a port/);
+ });
+
+ it("keeps only a few connections waiting from the box", async () => {
+ const relay = await relayAt();
+ const sockets = Array.from({ length: 8 }, () => connect(relay.socketPath));
+ cleanup.push(() => { for (const socket of sockets) socket.destroy(); });
+ const closed = await Promise.all(sockets.map((socket) => new Promise<boolean>((resolve) => {
+ socket.once("close", () => resolve(true));
+ setTimeout(() => resolve(false), 300);
+ })));
+ expect(closed.filter(Boolean)).toHaveLength(4);
+ });
+});
diff --git a/server/bot-box/relay.ts b/server/bot-box/relay.ts
new file mode 100644
index 0000000000..af5ec6a9a2
--- /dev/null
+++ b/server/bot-box/relay.ts
@@ -0,0 +1,128 @@
+// How the server reaches a port an engine listens on inside a box with its own network, such as a sign-in's callback
+// listener: the box dials out to a host unix socket and keeps one connection waiting, and the server writes the port and
+// a newline on it before talking to that port. The server never connects to a path the box could have swapped.
+import { rmSync } from "node:fs";
+import { connect, createServer, type Socket } from "node:net";
+
+/** Connections the box may keep waiting; any more are closed. */
+const MAX_WAITING = 4;
+const MAX_PORT_LINE = 6;
+const RELAY_TIMEOUT_MS = 10_000;
+
+export interface BoxRelay {
+ /** The host socket to bind into the box. */
+ readonly socketPath: string;
+ /** A connection to `port` on the box's own loopback, once the box has dialed in. */
+ connect(port: number, timeoutMs?: number): Promise<Socket>;
+ close(): void;
+}
+
+export async function openBoxRelay(socketPath: string): Promise<BoxRelay> {
+ rmSync(socketPath, { force: true });
+ const waiting: Socket[] = [];
+ const takers: Array<(socket: Socket) => void> = [];
+ const server = createServer((socket) => {
+ socket.on("error", () => {});
+ const taker = takers.shift();
+ if (taker) return taker(socket);
+ if (waiting.length >= MAX_WAITING) return void socket.destroy();
+ waiting.push(socket);
+ socket.once("close", () => {
+ const at = waiting.indexOf(socket);
+ if (at >= 0) waiting.splice(at, 1);
+ });
+ });
+ await new Promise<void>((resolve, reject) => {
+ server.once("error", reject);
+ server.listen(socketPath, () => {
+ server.off("error", reject);
+ resolve();
+ });
+ });
+ return {
+ socketPath,
+ async connect(port, timeoutMs = RELAY_TIMEOUT_MS) {
+ if (!Number.isInteger(port) || port < 1 || port > 65535) throw new Error(`Not a port: ${port}`);
+ const socket = waiting.shift() ?? await new Promise<Socket>((resolve, reject) => {
+ const take = (dialed: Socket) => {
+ clearTimeout(timer);
+ resolve(dialed);
+ };
+ const timer = setTimeout(() => {
+ takers.splice(takers.indexOf(take), 1);
+ reject(new Error("The sign-in's box did not answer."));
+ }, timeoutMs);
+ takers.push(take);
+ });
+ socket.write(`${port}\n`);
+ return socket;
+ },
+ close() {
+ if (!server.listening) return;
+ server.close();
+ for (const socket of waiting.splice(0)) socket.destroy();
+ rmSync(socketPath, { force: true });
+ },
+ };
+}
+
+/** Inside the box: keeps one connection to the host's relay socket waiting, and carries each one the host takes to the
+ * loopback port it names. Nothing here keeps the process alive. */
+export function dialRelay(socketPath: string, retryMs = 1_000): { close(): void } {
+ let closed = false;
+ let waiting: Socket | null = null;
+ let retry: NodeJS.Timeout | undefined;
+ const dial = () => {
+ if (closed) return;
+ const host = connect(socketPath);
+ host.unref();
+ waiting = host;
+ let head = "";
+ let taken = false;
+ host.on("error", () => {});
+ host.once("close", () => {
+ if (taken || waiting !== host) return;
+ waiting = null;
+ if (closed) return;
+ retry = setTimeout(dial, retryMs);
+ retry.unref();
+ });
+ const onData = (chunk: Buffer) => {
+ head += chunk.toString("latin1");
+ const newline = head.indexOf("\n");
+ if (newline < 0) {
+ if (head.length > MAX_PORT_LINE) host.destroy();
+ return;
+ }
+ host.off("data", onData);
+ host.pause();
+ taken = true;
+ waiting = null;
+ dial();
+ const line = head.slice(0, newline);
+ const port = Number(line);
+ if (!/^[1-9]\d{0,4}$/.test(line) || port > 65535) return void host.destroy();
+ const rest = Buffer.from(head.slice(newline + 1), "latin1");
+ const local = connect({ host: "127.0.0.1", port });
+ local.unref();
+ local.on("error", () => host.destroy());
+ host.on("error", () => local.destroy());
+ local.once("connect", () => {
+ if (rest.length) local.write(rest);
+ host.pipe(local);
+ local.pipe(host);
+ });
+ local.once("close", () => host.destroy());
+ host.once("close", () => local.destroy());
+ };
+ host.on("data", onData);
+ };
+ dial();
+ return {
+ close() {
+ closed = true;
+ clearTimeout(retry);
+ waiting?.destroy();
+ },
+ };
+}
diff --git a/server/drivers/antigravity-acp.ts b/server/drivers/antigravity-acp.ts
index 50de24f232..f02e7d9011 100644
--- a/server/drivers/antigravity-acp.ts
+++ b/server/drivers/antigravity-acp.ts
@@ -7,6 +7,8 @@ import { delimiter, join, resolve } from "node:path";
import { DATA_DIR, stripWorkspaceCredentialEnv } from "../config.ts";
import { writeFileAtomic } from "../atomic.ts";
import { killCliTree, spawnCli } from "../procs.ts";
+import { botBox } from "../bot-box/box.ts";
+import type { BoxRelay } from "../bot-box/relay.ts";
import type { ModelCatalog } from "../contracts.ts";
import type { ChildProcess } from "node:child_process";
import type { AntigravityRuntime } from "./antigravity-runtime.ts";
@@ -231,13 +233,14 @@ export class AntigravityAcpClient {
profile: AntigravityProfile,
cwd: string,
onAuthorizationUrl?: (url: string) => void,
+ relay?: BoxRelay,
) {
this.onAuthorizationUrl = onAuthorizationUrl;
this.tempDirectory = profile.tempDirectory;
this.child = spawnCli(
runtime.executablePath,
process.platform === "linux" ? ["--uid="] : [],
- { cwd, env: profile.environment, stdio: ["pipe", "pipe", "pipe"] },
+ { cwd, env: profile.environment, stdio: ["pipe", "pipe", "pipe"], ...(relay ? { box: { relay: relay.socketPath } } : {}) },
"bot",
);
this.child.stdout!.setEncoding("utf8");
@@ -492,7 +495,10 @@ export function validateAntigravityCallbackUrl(
return callback;
}
-export function forwardAntigravityCallback(callback: URL): Promise<void> {
+/** Delivers the callback to the runtime's listener on 127.0.0.1, which is the box's own loopback when the runtime runs in
+ * a bot box with its own network: `relay` reaches it there. */
+export async function forwardAntigravityCallback(callback: URL, relay?: Pick<BoxRelay, "connect">): Promise<void> {
+ const socket = relay ? await relay.connect(Number(callback.port)) : null;
return new Promise((resolveForward, reject) => {
const req = httpRequest({
protocol: "http:",
@@ -500,7 +506,7 @@ export function forwardAntigravityCallback(callback: URL): Promise<void> {
port: callback.port,
path: `${callback.pathname}${callback.search}`,
method: "GET",
- agent: false,
+ ...(socket ? { createConnection: () => socket } : { agent: false }),
timeout: 10_000,
}, (response) => {
response.resume();
@@ -678,6 +684,7 @@ export interface AntigravityAuthStart {
interface AuthFlow {
id: string;
client: AntigravityAcpClient;
+ relay: BoxRelay | null;
completed: Promise<void>;
pending: { redirectUri: string; state: string };
expiresAt: number;
@@ -699,10 +706,21 @@ export class AntigravityAuthController {
foundUrl = resolveUrl;
failUrl = reject;
});
- const client = new AntigravityAcpClient(runtime, profile, profile.directory, (url) => {
- try { foundUrl(parseAntigravityAuthorizationUrl(url)); }
- catch (error) { failUrl(error instanceof Error ? error : new Error(String(error))); }
- });
+ const relay = await botBox.openRelay();
+ let client: AntigravityAcpClient;
+ try {
+ client = new AntigravityAcpClient(runtime, profile, profile.directory, (url) => {
+ try { foundUrl(parseAntigravityAuthorizationUrl(url)); }
+ catch (error) { failUrl(error instanceof Error ? error : new Error(String(error))); }
+ }, relay ?? undefined);
+ } catch (error) {
+ relay?.close();
+ throw error;
+ }
+ const closeAll = () => {
+ client.close();
+ relay?.close();
+ };
try {
await client.initialize();
const authenticated = client.request("authenticate", { methodId: "oauth-personal" }, AUTH_TIMEOUT_MS);
@@ -719,13 +737,14 @@ export class AntigravityAuthController {
if (startupTimer) clearTimeout(startupTimer);
});
if (outcome.kind === "done") {
- client.close();
+ closeAll();
this.onSignedIn();
return { phase: "succeeded", flowId: null, authorizationUrl: null, expiresAt: null };
}
const flow: AuthFlow = {
id: randomUUID(),
client,
+ relay,
completed: authenticated,
pending: { redirectUri: outcome.request.redirectUri, state: outcome.request.state },
expiresAt: Date.now() + AUTH_TIMEOUT_MS,
@@ -733,7 +752,7 @@ export class AntigravityAuthController {
this.flow = flow;
void authenticated.then(() => this.onSignedIn(), () => {}).finally(() => {
if (this.flow === flow) this.flow = null;
- client.close();
+ closeAll();
});
return {
phase: "waiting",
@@ -742,7 +761,7 @@ export class AntigravityAuthController {
expiresAt: new Date(flow.expiresAt).toISOString(),
};
} catch (error) {
- client.close();
+ closeAll();
throw error;
}
}
@@ -752,12 +771,13 @@ export class AntigravityAuthController {
if (!flow || flow.id !== flowId || Date.now() >= flow.expiresAt) {
throw new Error("This Google sign-in is no longer active. Start again.");
}
- await forwardAntigravityCallback(validateAntigravityCallbackUrl(flow.pending, callbackUrl));
+ await forwardAntigravityCallback(validateAntigravityCallbackUrl(flow.pending, callbackUrl), flow.relay ?? undefined);
await flow.completed;
}
cancel(): void {
this.flow?.client.close();
+ this.flow?.relay?.close();
this.flow = null;
}
}
diff --git a/server/drivers/antigravity-box.linux.test.ts b/server/drivers/antigravity-box.linux.test.ts
new file mode 100644
index 0000000000..540cf43f2e
--- /dev/null
+++ b/server/drivers/antigravity-box.linux.test.ts
@@ -0,0 +1,53 @@
+// Antigravity's Google sign-in in a real bot box, where one can run: Linux with an unprivileged bubblewrap (a Cloud home,
+// the Fly test machine). The runtime's OAuth callback listener is on the box's own loopback, so a redirect pasted from
+// another computer reaches it only through the box's relay. Elsewhere the suite says so and skips.
+import { chmodSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { dirname, join } from "node:path";
+import { fileURLToPath } from "node:url";
+import { afterAll, beforeAll, describe, expect, it } from "vitest";
+
+import { botBox } from "../bot-box/box.ts";
+import { detectBox } from "../bot-box/detect.ts";
+import { AntigravityAuthController, antigravityProfileAuthenticated, forwardAntigravityCallback, prepareAntigravityProfile } from "./antigravity-acp.ts";
+import { resolveAntigravityRuntime } from "./antigravity-runtime.ts";
+
+const detection = detectBox({ env: { ...process.env, OMB_BOT_BOX: "1" } });
+const available = detection.box === "bwrap" && detection.tools !== null;
+const FAKE_SIGNIN = join(dirname(fileURLToPath(import.meta.url)), "..", "testing", "fake-antigravity-signin.ts");
+
+describe.skipIf(!available)(`Antigravity's Google sign-in in a real box (${available ? "bubblewrap works here" : `skipped: ${detection.reason}`})`, () => {
+ const root = mkdtempSync(join(tmpdir(), "omb-ag-box-"));
+ const home = join(root, "home"), dataDir = join(home, ".openmausbot"), runtimeDir = join(home, "runtime");
+ beforeAll(async () => {
+ mkdirSync(dataDir, { recursive: true });
+ mkdirSync(runtimeDir, { recursive: true });
+ for (const name of ["fake-antigravity.ts", "localharness_external"]) {
+ writeFileSync(join(runtimeDir, name), readFileSync(FAKE_SIGNIN));
+ chmodSync(join(runtimeDir, name), 0o755);
+ }
+ await botBox.start({ dataDir, home, port: 18799, denyEnv: new Set(), env: { ...process.env, OMB_BOT_BOX: "1" }, log: () => {} });
+ });
+ afterAll(async () => {
+ await botBox.stop();
+ rmSync(root, { recursive: true, force: true });
+ });
+
+ it("delivers a redirect pasted from another computer to the listener inside the box, which the server's own loopback cannot reach", async () => {
+ expect(botBox.enabled()).toBe(true);
+ const runtime = await resolveAntigravityRuntime(join(runtimeDir, "fake-antigravity.ts"));
+ const profile = await prepareAntigravityProfile({ instanceId: "boxed-signin", runtime, baseDir: dataDir });
+ const controller = new AntigravityAuthController();
+ try {
+ const flow = await controller.start(runtime, profile);
+ const redirect = new URL(flow.authorizationUrl!).searchParams.get("redirect_uri")!;
+ const callback = `${redirect}?state=fixture&code=pasted`;
+ // What the server's own loopback answers on that port: nothing listens there.
+ await expect(forwardAntigravityCallback(new URL(callback))).rejects.toMatchObject({ code: "ECONNREFUSED" });
+ await controller.complete(flow.flowId!, callback);
+ expect(await antigravityProfileAuthenticated(profile)).toBe(true);
+ } finally {
+ controller.cancel();
+ }
+ }, 60_000);
+});
diff --git a/server/drivers/antigravity.test.ts b/server/drivers/antigravity.test.ts
index 33d28777da..9b8f1b742c 100644
--- a/server/drivers/antigravity.test.ts
+++ b/server/drivers/antigravity.test.ts
@@ -9,6 +9,8 @@ import { TurnNotStartedError, type ProviderInstance } from "../contracts.ts";
import { recordEvents, type EventRecorder } from "../testing/events.ts";
import { removeTempDir } from "../testing/cleanup.ts";
import * as procs from "../procs.ts";
+import { botBox } from "../bot-box/box.ts";
+import { dialRelay, openBoxRelay } from "../bot-box/relay.ts";
import * as envPath from "../env-path.ts";
import * as managedRuntime from "./antigravity-runtime.ts";
import {
@@ -42,6 +44,7 @@ import {
} from "./antigravity.ts";
const FAKE_ACP = join(dirname(fileURLToPath(import.meta.url)), "..", "testing", "fake-acp-cli.ts");
+const FAKE_SIGNIN = join(dirname(fileURLToPath(import.meta.url)), "..", "testing", "fake-antigravity-signin.ts");
const scratch: string[] = [];
function fakeRuntime(startupDelayMs = 0): { directory: string; executable: string; harness: string } {
@@ -256,6 +259,52 @@ createInterface({ input: process.stdin }).on('line', line => {
}
});
+ it("delivers a redirect pasted from another computer to the runtime's own callback listener, and the sign-in finishes", async () => {
+ const fake = fakeRuntime();
+ writeFileSync(fake.executable, readFileSync(FAKE_SIGNIN));
+ const runtime = await resolveAntigravityRuntime(fake.executable);
+ const profile = await prepareAntigravityProfile({ instanceId: "auth-pasted", runtime, baseDir: fake.directory });
+ const signedIn = vi.fn();
+ const controller = new AntigravityAuthController(signedIn);
+ try {
+ const flow = await controller.start(runtime, profile);
+ const redirect = new URL(flow.authorizationUrl!).searchParams.get("redirect_uri")!;
+ await controller.complete(flow.flowId!, `${redirect}?state=fixture&code=pasted`);
+ expect(await antigravityProfileAuthenticated(profile)).toBe(true);
+ expect(signedIn).toHaveBeenCalledOnce();
+ } finally {
+ controller.cancel();
+ }
+ });
+
+ // A Cloud home runs the runtime in a bot box with its own network, where only the box's relay reaches its listener
+ // (proved against a real box in antigravity-box.linux.test.ts); here the relay's box side runs in this process.
+ it.skipIf(process.platform === "win32")("delivers the redirect through the box's relay when sign-in runs in a bot box, and closes the relay after", async () => {
+ const fake = fakeRuntime();
+ writeFileSync(fake.executable, readFileSync(FAKE_SIGNIN));
+ const runtime = await resolveAntigravityRuntime(fake.executable);
+ const profile = await prepareAntigravityProfile({ instanceId: "auth-relayed", runtime, baseDir: fake.directory });
+ const relay = await openBoxRelay(join(fake.directory, "relay.sock"));
+ const inBox = dialRelay(relay.socketPath, 20);
+ const reach = vi.spyOn(relay, "connect");
+ vi.spyOn(botBox, "openRelay").mockResolvedValue(relay);
+ const spawned = vi.spyOn(procs, "spawnCli");
+ const controller = new AntigravityAuthController();
+ try {
+ const flow = await controller.start(runtime, profile);
+ expect(spawned.mock.calls[0]![2]).toMatchObject({ box: { relay: relay.socketPath } });
+ const redirect = new URL(new URL(flow.authorizationUrl!).searchParams.get("redirect_uri")!);
+ await controller.complete(flow.flowId!, `${redirect.href}?state=fixture&code=pasted`);
+ expect(reach).toHaveBeenCalledWith(Number(redirect.port));
+ expect(await antigravityProfileAuthenticated(profile)).toBe(true);
+ await vi.waitFor(() => expect(existsSync(relay.socketPath)).toBe(false));
+ } finally {
+ controller.cancel();
+ inBox.close();
+ relay.close();
+ }
+ });
+
it("reports a sign-in Google finishes on its own, so the account's models are read", async () => {
const fake = fakeRuntime();
const url = "https://accounts.google.com/o/oauth2/v2/auth?response_type=code&state=fixture&redirect_uri=http%3A%2F%2F127.0.0.1%3A54321%2F";
diff --git a/server/procs.ts b/server/procs.ts
index a51fe8f82c..ef2de4d7ba 100644
--- a/server/procs.ts
+++ b/server/procs.ts
@@ -160,7 +160,7 @@ export type CliOwner = "bot" | "openmausbot";
/** The bot box (server/bot-box): a `bot` spawn runs in it where it is on; `box` asks for one for another owner, with more
* paths or the host's network, and `false` keeps a spawn out of it. */
export interface BoxSpawnOptions {
- box?: boolean | Pick<BoxRequest, "rw" | "ro" | "net" | "botId" | "allowEnv">;
+ box?: boolean | Pick<BoxRequest, "rw" | "ro" | "net" | "botId" | "allowEnv" | "relay">;
/** On a Team Cloud, runs in its conversation's engine home though it is not a bot's engine (a keep-warm ping). */
engineHome?: boolean;
/** A bot's own work that is not its engine (its browser, a helper engine): memory runs out on it first, as on a `bot`
diff --git a/server/testing/fake-antigravity-signin.ts b/server/testing/fake-antigravity-signin.ts
new file mode 100644
index 0000000000..a2288a77c2
--- /dev/null
+++ b/server/testing/fake-antigravity-signin.ts
@@ -0,0 +1,39 @@
+#!/usr/bin/env node
+// Offline stand-in for Google's Antigravity ACP server during a Google sign-in: on `authenticate` it opens its OAuth
+// callback listener on 127.0.0.1 (a free port, as the runtime does), announces the Google link on stderr the way the
+// runtime does, and when the callback arrives with state `fixture` and a code it writes the profile's token file into
+// GEMINI_HOME and answers `authenticate`. Every other request gets an empty result. No network, no real credential.
+import { mkdirSync, writeFileSync } from "node:fs";
+import { createServer } from "node:http";
+import { join } from "node:path";
+import { createInterface } from "node:readline";
+
+const PREFIX = "Open the following link to authenticate the ACP server: ";
+const reply = (id: unknown, result: unknown) => process.stdout.write(`${JSON.stringify({ jsonrpc: "2.0", id, result })}\n`);
+let pending: unknown = null;
+
+const callback = createServer((req, res) => {
+ const url = new URL(req.url ?? "/", "http://127.0.0.1");
+ if (url.searchParams.get("state") !== "fixture" || !url.searchParams.get("code")) {
+ res.writeHead(400);
+ res.end();
+ return;
+ }
+ const directory = join(process.env.GEMINI_HOME!, "antigravity-acp");
+ mkdirSync(directory, { recursive: true });
+ writeFileSync(join(directory, "acp_token.json"), `${JSON.stringify({ fixture: "offline, not a credential" })}\n`, { mode: 0o600 });
+ res.writeHead(200, { "content-type": "text/plain" });
+ res.end("Signed in");
+ if (pending !== null) reply(pending, {});
+});
+
+createInterface({ input: process.stdin }).on("line", (line) => {
+ const message = JSON.parse(line) as { id?: unknown; method?: string };
+ if (message.method !== "authenticate") return void reply(message.id, {});
+ pending = message.id;
+ callback.listen(0, "127.0.0.1", () => {
+ const { port } = callback.address() as { port: number };
+ const redirect = encodeURIComponent(`http://127.0.0.1:${port}/`);
+ process.stderr.write(`${PREFIX}https://accounts.google.com/o/oauth2/v2/auth?response_type=code&state=fixture&redirect_uri=${redirect}\n`);
+ });
+});