Skip to content

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

Cloud browser fix round: relay-built browser actions only, ask the relay before any start, own key and old Admin stay home

milind-sonid3ffe4476606
diff --git a/server/cloud-browser/cloud-browser.test.ts b/server/cloud-browser/cloud-browser.test.ts
index e1b7461738..203ad46bf2 100644
--- a/server/cloud-browser/cloud-browser.test.ts
+++ b/server/cloud-browser/cloud-browser.test.ts
@@ -1,21 +1,18 @@
-// The Cloud's browser sandbox, against a fake provider (testing/fake-computer.ts): no real provider is called and no
-// billable resource is made.
-import { spawn } from "node:child_process";
-import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
-import { createServer, type Server } from "node:http";
+// The Cloud's browser sandbox, against a fake Admin relay and provider (testing/fake-computer.ts): no real provider is
+// called and no billable resource is made.
+import { mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-import WebSocket, { WebSocketServer } from "ws";
+import WebSocket from "ws";
import type { AppConfig } from "../config.ts";
import { ComputerIdleTimer } from "../computer-idle.ts";
+import { DOWNLOAD_NOTE, downloadNote, LOCAL_SCHEME_REFUSAL, localSchemeRefusal } from "./guards.ts";
import { CLOUD_BROWSER_IDLE_MS, createCloudBrowser, type CloudBrowserDeps } from "./index.ts";
import { CLOUD_BROWSER_BACKOFF_MS, createCloudBrowserRails } from "./rails.ts";
-import {
- BROWSER_SANDBOX_CHROMES, BROWSER_SANDBOX_OWNER, browserSandboxCreateBody, COMPUTER_BROWSER_DIR, doorSource, launchCommand, profileKey, providerOps, quitCommand, QUIT_ALL_COMMAND,
-} from "./remote.ts";
-import { OWN_KEY, RELAY_TOKEN, startFakeComputer, type FakeComputer } from "./testing/fake-computer.ts";
+import { BROWSER_SANDBOX_CHROMES, BROWSER_SANDBOX_OWNER, browserSandboxCreateBody, profileKey, providerOps } from "./remote.ts";
+import { RELAY_KEY, RELAY_TOKEN, startFakeComputer, type FakeComputer } from "./testing/fake-computer.ts";
let fake: FakeComputer;
let dir: string;
@@ -27,10 +24,10 @@ let browsers: ReturnType<typeof createCloudBrowser>[];
beforeEach(async () => {
fake = await startFakeComputer();
- vi.stubEnv("OMB_BOAT_API", `${fake.base}/api/v1`);
+ // MausBot Cloud's included credential, pointed at the fake relay: the only way a browser sandbox is ever made.
+ vi.stubEnv("OMB_CLOUD_BOAT_URL", `${fake.base}/api/v1`);
+ vi.stubEnv("OMB_CLOUD_BOAT_TOKEN", RELAY_KEY);
vi.stubEnv("OMB_CLOUD_BROWSER", undefined);
- vi.stubEnv("OMB_CLOUD_BOAT_URL", undefined);
- vi.stubEnv("OMB_CLOUD_BOAT_TOKEN", undefined);
dir = mkdtempSync(join(tmpdir(), "cloud-browser-"));
clock = Date.UTC(2026, 10, 24, 10, 0, 0);
used = [];
@@ -48,11 +45,10 @@ afterEach(async () => {
function browser(overrides: Partial<CloudBrowserDeps> & { budget?: number; awakeMinutes?: number } = {}) {
const now = () => clock;
- const cfg = { box: { token: OWN_KEY } } as AppConfig;
const { budget, awakeMinutes, ...rest } = overrides;
const created = createCloudBrowser({
dataDir: dir,
- ops: () => providerOps(() => cfg),
+ ops: () => providerOps(() => ({}) as AppConfig),
used: (owner, windowMs) => { used.push([owner, windowMs]); },
closeEngine: async (closed) => { engineClosed.push(closed); },
held: () => held,
@@ -86,6 +82,7 @@ const urlOf = (opened: { cdpUrl: string } | { home: string }): string => {
if (!("cdpUrl" in opened)) throw new Error(`expected the sandbox, got ${opened.home}`);
return opened.cdpUrl;
};
+const deletes = () => fake.requests.filter((one) => one.method === "DELETE");
describe("a personal Cloud's bot browsers in the Cloud's browser sandbox", () => {
it("opens there and carries every action over one held connection, through the relay's token and the door's secret", async () => {
@@ -104,7 +101,8 @@ describe("a personal Cloud's bot browsers in the Cloud's browser sandbox", () =>
}
const before = fake.requests.length;
await act(cdpUrl, 3);
- expect(fake.requests.length, "no provider call per action").toBe(before);
+ expect(fake.requests.length, "no relay call per action").toBe(before);
+ expect(fake.requests.filter((one) => one.path.endsWith("/commands")), "no shell command is ever sent").toEqual([]);
expect(cloud.busy(BROWSER_SANDBOX_OWNER)).toBe(true);
expect(cloud.busy("scout"), "never a bot's own computer").toBe(false);
expect(cloud.report()).toMatchObject({ sessions: { sandbox: 1, home: 0 }, resumes: 0 });
@@ -117,39 +115,80 @@ describe("a personal Cloud's bot browsers in the Cloud's browser sandbox", () =>
expect(cloud.dialed("bot-scout")).toBe(0);
});
- it("makes the sandbox the first time a bot needs a browser: small, no environment, named, one start", async () => {
+ it("two calls opening one session at once share the one open: a session never splits across two browsers", async () => {
+ fake.state = "archived";
+ const cloud = browser();
+ const [first, second] = await Promise.all([cloud.open(request()), cloud.open(request())]);
+ expect(urlOf(second)).toBe(urlOf(first));
+ expect(fake.launches()).toBe(1);
+ expect(fake.resumes()).toBe(1);
+ expect(cloud.report().sessions).toEqual({ sandbox: 1, home: 0 });
+ });
+
+ it("asks the relay before making anything, and makes the sandbox the first time a bot needs a browser: small, marked as the browser's, named, one start", async () => {
fake.exists = false;
const cloud = browser();
urlOf(await cloud.open(request()));
- expect(fake.creates()).toBe(1);
- const create = fake.requests.find((one) => one.method === "POST" && one.path === "/api/v1/sandboxes");
- expect(create?.body).toEqual({ ttlSeconds: 7200, noEnv: true, type: "small" });
+ const probe = fake.requests.findIndex((one) => one.path.endsWith("/browser-sandbox"));
+ const create = fake.requests.findIndex((one) => one.method === "POST" && one.path === "/api/v1/sandboxes");
+ expect(probe).toBeGreaterThan(-1);
+ expect(probe).toBeLessThan(create);
+ expect(fake.requests[create]?.body).toEqual({ noEnv: true, type: "small", purpose: "browser" });
+ expect(browserSandboxCreateBody()).toEqual({ noEnv: true, type: "small", purpose: "browser" });
expect(fake.requests.find((one) => one.method === "PATCH")?.body?.name).toMatch(/^ogb-[a-f0-9]{12}-browser-[a-f0-9]{6}$/);
expect(cloud.report().resumes).toBe(1);
- // Through the Cloud's relay the create says what it is, so the plan's computers and hours never count it.
- expect(browserSandboxCreateBody(true)).toEqual({ ttlSeconds: 7200, noEnv: true, type: "small", purpose: "browser" });
});
- it("through the Cloud's relay, keeps a sandbox only when the relay knows it is the browser's, and deletes one an older relay made", async () => {
- vi.stubEnv("OMB_CLOUD_BOAT_URL", `${fake.base}/api/v1`);
- vi.stubEnv("OMB_CLOUD_BOAT_TOKEN", OWN_KEY);
+ it("on an Admin from before the browser sandbox, makes nothing at all and stays in the home for a week", async () => {
fake.exists = false;
- fake.knowsPurpose = false;
- const viaRelay = browser({ ops: () => providerOps(() => ({}) as AppConfig) });
- expect(await viaRelay.open(request())).toEqual({ home: "no-route" });
- expect(fake.requests.find((one) => one.method === "POST" && one.path === "/api/v1/sandboxes")?.body).toMatchObject({ purpose: "browser" });
- expect(fake.requests.filter((one) => one.method === "DELETE")).toHaveLength(1);
- expect(fake.exists).toBe(false);
- expect(await viaRelay.open(request()), "no second create that day").toEqual({ home: "no-route" });
- expect(fake.creates()).toBe(1);
+ fake.oldRelay = true;
+ const cloud = browser();
+ expect(await cloud.open(request())).toEqual({ home: "old-relay" });
+ expect(fake.creates()).toBe(0);
+ clock += 6 * 24 * 60 * 60_000;
+ const asked = fake.requests.length;
+ expect(await cloud.open(request())).toEqual({ home: "old-relay" });
+ expect(fake.requests.length).toBe(asked);
+ clock += 24 * 60 * 60_000;
+ fake.oldRelay = false;
+ urlOf(await cloud.open(request()));
});
- it("through a relay that knows the browser sandbox, makes it and opens there", async () => {
- vi.stubEnv("OMB_CLOUD_BOAT_URL", `${fake.base}/api/v1`);
- vi.stubEnv("OMB_CLOUD_BOAT_TOKEN", OWN_KEY);
+ it("deletes at once a box a create made without the browser's mark", async () => {
fake.exists = false;
- urlOf(await browser({ ops: () => providerOps(() => ({}) as AppConfig) }).open(request()));
- expect(fake.requests.filter((one) => one.method === "DELETE")).toEqual([]);
+ // The probe answers, but the create comes back unmarked (an Admin rolled back between the two).
+ const realProbe = providerOps(() => ({}) as AppConfig);
+ const ops = { ...realProbe, probe: async () => { fake.oldRelay = true; return { kind: "available" as const, boxId: null }; } };
+ const guarded = browser({ ops: () => ops });
+ expect(await guarded.open(request())).toEqual({ home: "old-relay" });
+ expect(fake.creates()).toBe(1);
+ expect(deletes()).toHaveLength(1);
+ expect(fake.exists).toBe(false);
+ });
+
+ it("holds every start while the relay says the fleet's browser starts are spent, until its reset, without one start sent", async () => {
+ fake.state = "archived";
+ fake.available = false;
+ fake.unavailableReason = "fleet_starts";
+ fake.unavailableUntil = new Date(Date.UTC(2026, 10, 25)).toISOString();
+ const cloud = browser();
+ expect(await cloud.open(request())).toEqual({ home: "unavailable" });
+ expect(await cloud.open(request())).toEqual({ home: "unavailable" });
+ expect(fake.resumes() + fake.creates()).toBe(0);
+ expect(fake.requests.filter((one) => one.path.endsWith("/browser-sandbox"))).toHaveLength(1);
+ expect(cloud.report().held).toBe("unavailable");
+ clock = Date.UTC(2026, 10, 25, 0, 0, 1);
+ fake.available = true;
+ urlOf(await cloud.open(request()));
+ });
+
+ it("replaces a sandbox the provider reports broken: deleted first, a fresh one made and counted", async () => {
+ fake.state = "error";
+ const cloud = browser();
+ urlOf(await cloud.open(request()));
+ expect(deletes()).toHaveLength(1);
+ expect(fake.creates()).toBe(1);
+ expect(cloud.report().resumes).toBe(1);
});
it("wakes a stopped sandbox with exactly one resume, then reads only", async () => {
@@ -161,6 +200,12 @@ describe("a personal Cloud's bot browsers in the Cloud's browser sandbox", () =>
expect(cloud.report().resumes).toBe(1);
});
+ it("an awake sandbox needs no start and no question to the relay", async () => {
+ urlOf(await browser().open(request()));
+ expect(fake.requests.filter((one) => one.path.endsWith("/browser-sandbox"))).toEqual([]);
+ expect(fake.resumes() + fake.creates()).toBe(0);
+ });
+
it("gives each bot its own profile and Chrome, carries up to three at once, and keeps a fourth in the home", async () => {
fake.state = "archived";
const cloud = browser();
@@ -169,25 +214,10 @@ describe("a personal Cloud's bot browsers in the Cloud's browser sandbox", () =>
expect(fake.resumes(), "bots opening together share one wake").toBe(1);
for (const [i, bot] of bots.slice(0, 3).entries()) expect(await act(urlOf(opened[i]!), 1)).toEqual([`echo:${profileKey(bot)}:{"id":0}`]);
expect(new Set(fake.profiles())).toEqual(new Set(bots.slice(0, 3).map(profileKey)));
+ expect(profileKey("scout")).toMatch(/^[a-f0-9]{16}$/);
expect(await cloud.open(request("fourth"))).toEqual({ home: "sandbox-full" });
});
- it("keeps one profile per bot on the sandbox's disk, clearing a lock only when no Chrome of its own runs", () => {
- const key = profileKey("scout");
- expect(key).not.toBe(profileKey("writer"));
- const command = launchCommand(key, "a".repeat(48));
- expect(command).toContain(`K="$D/${key}"; P="$K/profile"`);
- expect(command).toContain('--user-data-dir="$P"');
- const guard = command.indexOf('if ! pgrep -f -- "--user-data-dir=$P"'), clear = command.indexOf('rm -f "$P/SingletonLock"');
- expect(guard).toBeGreaterThan(-1);
- expect(clear).toBeGreaterThan(guard);
- expect(command).toMatch(/env -i HOME="\$HOME" PATH="[^"]+" setsid nohup "\$B"/);
- expect(quitCommand(key)).toContain(`P="${COMPUTER_BROWSER_DIR}/${key}/profile"`);
- expect(QUIT_ALL_COMMAND).toContain(`pkill -TERM -f -- "--user-data-dir=$D/"`);
- expect(() => launchCommand("../../etc", "a".repeat(48))).toThrow();
- expect(() => launchCommand(key, "not hex; rm -rf /")).toThrow();
- });
-
it("reuses a bot's profile after the sandbox slept", async () => {
const cloud = browser();
await cloud.open(request());
@@ -213,11 +243,11 @@ describe("a personal Cloud's bot browsers in the Cloud's browser sandbox", () =>
expect(engineClosed, "a browser a turn holds stays").toEqual([]);
held = false;
await cloud.close("bot-writer");
- expect(fake.requests.at(-1)?.command, "the other bot's Chrome keeps running").toBe(quitCommand(profileKey("writer")));
+ expect(fake.quits().at(-1), "the other bot's Chrome keeps running").toBe(`quit:${profileKey("writer")}`);
expect(used.at(-1)).toEqual([BROWSER_SANDBOX_OWNER, CLOUD_BROWSER_IDLE_MS]);
await cloud.closeIdle();
expect(engineClosed).toEqual(["bot-writer", "bot-scout"]);
- expect(fake.requests.at(-1)?.command).toBe(QUIT_ALL_COMMAND);
+ expect(fake.quits().at(-1)).toBe("quit-all");
expect(cloud.busy(BROWSER_SANDBOX_OWNER)).toBe(false);
expect(used.at(-1)).toEqual([BROWSER_SANDBOX_OWNER, 1_000]);
});
@@ -299,7 +329,7 @@ describe("a personal Cloud's bot browsers in the Cloud's browser sandbox", () =>
urlOf(await cloud.open(request()));
});
- it("treats the relay's busy answer, or the provider's own 429, as the account's limit for the day", async () => {
+ it("treats the relay's busy answer as the account's limit for the day", async () => {
fake.state = "archived";
fake.startStatus = 429;
fake.startBody = { ok: false, code: "rate_limited", message: "Cloud computers are busy right now." };
@@ -309,37 +339,32 @@ describe("a personal Cloud's bot browsers in the Cloud's browser sandbox", () =>
expect(fake.resumes()).toBe(1);
});
- it("a session the caller rules out (a shared profile, another person's) makes no provider call", async () => {
+ it("a session the caller rules out (a shared profile, another person's, a person's own key) makes no relay call", async () => {
const cloud = browser();
expect(await cloud.open(request("scout", "not-eligible"))).toEqual({ home: "not-eligible" });
expect(fake.requests).toEqual([]);
});
- it("with no way to reach the door's port, stays in the home for the rest of the day without another start", async () => {
- fake.hostRoute = false;
+ it("with no protected way to reach the door's port, stays in the home for the rest of the day without another start", async () => {
+ fake.unprotected = true;
fake.state = "archived";
const cloud = browser();
expect(await cloud.open(request())).toEqual({ home: "no-route" });
- expect(fake.quits()).toBe(1);
+ expect(fake.upgrades, "an unprotected URL is never dialed").toEqual([]);
+ expect(fake.quits()).toEqual([`quit:${profileKey("scout")}`]);
expect(used.at(-1)).toEqual([BROWSER_SANDBOX_OWNER, 1_000]);
const asked = fake.requests.length;
expect(await cloud.open(request())).toEqual({ home: "no-route" });
expect(fake.requests.length).toBe(asked);
});
- it("uses the URL the sandbox printed when the provider's port route is refused", async () => {
- fake.hostRoute = false;
- fake.printUrl = true;
- urlOf(await browser().open(request()));
- });
-
it("a Chrome that does not start counts as a failure and opens in the home", async () => {
fake.chromeStarts = false;
expect(await browser().open(request())).toEqual({ home: "start-failed" });
expect(fake.upgrades).toEqual([]);
});
- it("OMB_CLOUD_BROWSER=home keeps every browser in the home without one provider call, and deletes the sandbox after a day of it", async () => {
+ it("OMB_CLOUD_BROWSER=home keeps every browser in the home without one relay call, and deletes the sandbox after a day of it", async () => {
vi.stubEnv("OMB_CLOUD_BROWSER", "home");
const cloud = browser();
expect(await cloud.open(request())).toEqual({ home: "lever" });
@@ -348,9 +373,9 @@ describe("a personal Cloud's bot browsers in the Cloud's browser sandbox", () =>
clock += 24 * 60 * 60_000 + 1;
cloud.report();
await vi.waitFor(() => expect(fake.exists).toBe(false));
- expect(fake.requests.filter((one) => one.method === "DELETE")).toHaveLength(1);
+ expect(deletes()).toHaveLength(1);
cloud.report();
- expect(fake.requests.filter((one) => one.method === "DELETE"), "at most once an hour").toHaveLength(1);
+ expect(deletes(), "at most once an hour").toHaveLength(1);
});
it("a sandbox an earlier run left awake gets its idle window on the Admin's first health poll, not at start", async () => {
@@ -385,57 +410,23 @@ describe("a personal Cloud's bot browsers in the Cloud's browser sandbox", () =>
});
});
-describe("the sandbox's door, run as it runs there", () => {
- let chrome: Server;
- let folder: string;
- afterEach(() => { chrome?.close(); rmSync(folder, { recursive: true, force: true }); });
-
- it("lets a request with a profile's secret through to that profile's Chrome as a local DevTools connection, and nothing else", async () => {
- folder = mkdtempSync(join(tmpdir(), "door-"));
- const seen: Array<{ url: string | undefined; host: string | undefined; origin: string | undefined }> = [];
- const wss = new WebSocketServer({ noServer: true });
- chrome = createServer();
- chrome.on("upgrade", (req, socket, head) => {
- seen.push({ url: req.url, host: req.headers.host, origin: req.headers.origin });
- wss.handleUpgrade(req, socket, head, (ws) => ws.on("message", (data) => ws.send(`chrome:${String(data)}`)));
- });
- await new Promise<void>((resolve) => chrome.listen(0, "127.0.0.1", resolve));
- const chromePort = (chrome.address() as { port: number }).port;
- const key = profileKey("scout"), secret = "b".repeat(48);
- mkdirSync(join(folder, key, "profile"), { recursive: true });
- writeFileSync(join(folder, key, "secret"), secret);
- writeFileSync(join(folder, key, "profile", "DevToolsActivePort"), `${chromePort}\n/devtools/browser/abc-123\n`);
- writeFileSync(join(folder, "door.mjs"), doorSource());
- const probe = createServer();
- await new Promise<void>((resolve) => probe.listen(0, "127.0.0.1", resolve));
- const doorPort = (probe.address() as { port: number }).port;
- await new Promise<void>((resolve) => probe.close(() => resolve()));
- const door = spawn(process.execPath, [join(folder, "door.mjs"), folder, String(doorPort)], { stdio: "ignore" });
- try {
- const open = async (path: string) => {
- for (let tries = 0; ; tries++) {
- const socket = new WebSocket(`ws://127.0.0.1:${doorPort}${path}`, { headers: { Origin: "https://evil.example", Host: "sandbox-39231.on.example" } });
- try {
- await new Promise<void>((resolve, reject) => { socket.once("open", () => resolve()); socket.once("error", reject); });
- return socket;
- } catch (error) {
- if (tries > 40 || !String(error).includes("ECONNREFUSED")) throw error;
- await new Promise((resolve) => setTimeout(resolve, 50));
- }
- }
- };
- const socket = await open(`/${key}/${secret}?_token=t`);
- const answer = new Promise<string>((resolve) => socket.once("message", (data) => resolve(String(data))));
- socket.send("hello");
- expect(await answer).toBe("chrome:hello");
- socket.close();
- expect(seen).toEqual([{ url: "/devtools/browser/abc-123", host: `127.0.0.1:${chromePort}`, origin: undefined }]);
- await expect(open(`/${key}/${"c".repeat(48)}`)).rejects.toThrow(/404/);
- await expect(open(`/${profileKey("writer")}/${secret}`)).rejects.toThrow(/404/);
- expect(seen).toHaveLength(1);
- } finally {
- door.kill();
+describe("what a browser in the sandbox is kept from", () => {
+ it("never opens a file, the browser's own pages or another local scheme, however the call names it", () => {
+ for (const url of ["file:///home/user/.omb-browser/", " FILE:///etc/passwd", "chrome://settings", "view-source:https://a.example", "devtools://devtools", "chrome-extension://x/y"]) {
+ expect(localSchemeRefusal({ name: "agent_browser_open", arguments: { url } }), url).toBe(LOCAL_SCHEME_REFUSAL);
}
+ expect(localSchemeRefusal({ name: "agent_browser_tab_new", arguments: { options: { url: "file:///tmp/x" } } })).toBe(LOCAL_SCHEME_REFUSAL);
+ expect(localSchemeRefusal({ name: "agent_browser_open", arguments: { url: "https://example.com/file:x" } })).toBeNull();
+ expect(localSchemeRefusal({ name: "agent_browser_snapshot", arguments: {} })).toBeNull();
+ });
+
+ it("says once, in the call's answer, that a download was not kept", () => {
+ const answer = { content: [{ type: "text", text: "Navigation failed: net::ERR_ABORTED" }] };
+ const noted = downloadNote(answer) as { content: Array<{ text: string }> };
+ expect(noted.content.at(-1)?.text).toBe(DOWNLOAD_NOTE);
+ expect(downloadNote(noted)).toBe(noted);
+ const page = { content: [{ type: "text", text: "button \"Download the app\"" }] };
+ expect(downloadNote(page), "a page's own words are not a download").toBe(page);
});
});
diff --git a/server/cloud-browser/guards.ts b/server/cloud-browser/guards.ts
new file mode 100644
index 0000000000..30219a6ce7
--- /dev/null
+++ b/server/cloud-browser/guards.ts
@@ -0,0 +1,33 @@
+// What a browser in the Cloud's browser sandbox is kept from, at the home before a call reaches it: every bot's Chrome
+// there runs as the same user, so a local page could read another bot's profile. Its downloads stay in the sandbox.
+
+/** Schemes that open what is on the sandbox's own disk or Chrome's own pages, never a website. */
+const LOCAL_SCHEME = /^\s*(file|chrome|chrome-untrusted|devtools|view-source|filesystem|chrome-extension):/i;
+
+export const LOCAL_SCHEME_REFUSAL = "This browser opens websites only: files and the browser's own pages (file:, chrome:, view-source: and the like) are not opened here.";
+
+/** Any string in a call's arguments that names a local scheme, however deep. */
+function namesLocal(value: unknown, depth = 0): boolean {
+ if (typeof value === "string") return LOCAL_SCHEME.test(value);
+ if (depth > 4 || !value || typeof value !== "object") return false;
+ return Object.values(value as Record<string, unknown>).some((item) => namesLocal(item, depth + 1));
+}
+
+/** The refusal for a tool call that would open a local scheme in the sandbox, or null. */
+export function localSchemeRefusal(params: unknown): string | null {
+ return namesLocal((params as { arguments?: unknown } | null)?.arguments) ? LOCAL_SCHEME_REFUSAL : null;
+}
+
+export const DOWNLOAD_NOTE = "This browser runs in the Cloud's browser sandbox, which doesn't save downloads yet: if that action started a download, the file was not kept. Tell the person in one sentence and ask them to download it themselves.";
+
+/** What the engine says when a navigation turned into a download (Chrome cancels the page load), not a page's own words. */
+const DOWNLOAD_SIGNS = /net::ERR_ABORTED|\bdownload (?:started|began|will begin|was blocked)\b/i;
+
+/** A call whose answer says a download started or a navigation was cut off by one gets the note, once, at its end. */
+export function downloadNote(result: unknown): unknown {
+ const content = (result as { content?: unknown } | null)?.content;
+ if (!Array.isArray(content)) return result;
+ const text = content.map((part) => (typeof (part as { text?: unknown }).text === "string" ? (part as { text: string }).text : "")).join("\n");
+ if (!DOWNLOAD_SIGNS.test(text) || text.includes(DOWNLOAD_NOTE)) return result;
+ return { ...(result as object), content: [...content, { type: "text", text: DOWNLOAD_NOTE }] };
+}
diff --git a/server/cloud-browser/index.ts b/server/cloud-browser/index.ts
index 94930b09dc..cc557d6ad6 100644
--- a/server/cloud-browser/index.ts
+++ b/server/cloud-browser/index.ts
@@ -8,15 +8,11 @@ import { randomBytes } from "node:crypto";
import { cloudFailureOf } from "../boat-limit.ts";
import { CloudBrowserDoors, dialable, probeDoor, type DoorTarget } from "./door.ts";
import { createCloudBrowserRails, type CloudBrowserRails, type HomeReason } from "./rails.ts";
-import {
- BROWSER_SANDBOX_CHROMES, BROWSER_SANDBOX_OWNER, COMPUTER_DOOR_PORT, launchAnswer, launchCommand, profileKey, quitCommand, QUIT_ALL_COMMAND,
- OldRelay, StaysHome, wakeSandbox, type ComputerOps,
-} from "./remote.ts";
+import { BROWSER_SANDBOX_CHROMES, BROWSER_SANDBOX_OWNER, COMPUTER_DOOR_PORT, OldRelay, profileKey, StaysHome, wakeSandbox, type ComputerOps } from "./remote.ts";
/** A browser in the sandbox with no activity this long is closed; the sandbox sleeps once none is left. */
export const CLOUD_BROWSER_IDLE_MS = 3 * 60_000;
const SWEEP_MS = 30_000;
-const LAUNCH_MS = 25_000;
const LEVER_CLEANUP_GAP_MS = 60 * 60_000;
export const cloudBrowserLever = (env: NodeJS.ProcessEnv = process.env): boolean => env.OMB_CLOUD_BROWSER?.trim() === "home";
@@ -50,6 +46,17 @@ export interface OpenRequest {
export type Opened = { cdpUrl: string } | { home: HomeReason };
+/** The relay says no browser sandbox may start now (the fleet's or this Cloud's day spent, or switched off). */
+class Unavailable extends Error {
+ readonly reason: string;
+ readonly resetsAt: string | null;
+ constructor(reason: string, resetsAt: string | null) {
+ super(reason);
+ this.reason = reason;
+ this.resetsAt = resetsAt;
+ }
+}
+
export function createCloudBrowser(deps: CloudBrowserDeps) {
const now = deps.now ?? Date.now;
const log = deps.log ?? ((line: string) => console.warn(line));
@@ -59,6 +66,8 @@ export function createCloudBrowser(deps: CloudBrowserDeps) {
const sessions = new Map<string, string>();
/** Bots whose browser is being opened now. */
const opening = new Set<string>();
+ /** A session's open under way: a second call for the same session waits on it, so one session never splits in two. */
+ const pendingSessions = new Map<string, Promise<Opened>>();
const closing = new Set<string>();
/** One wake of the sandbox at a time, shared by every bot opening meanwhile. */
let waking: Promise<{ id: string; started: boolean }> | null = null;
@@ -98,9 +107,17 @@ export function createCloudBrowser(deps: CloudBrowserDeps) {
rails.asleep();
}
+ /** Asked once before a start: an Admin that cannot mark the sandbox as the browser's gets no box at all. */
+ async function allowed(ops: ComputerOps): Promise<void> {
+ const said = await ops.probe();
+ if (said.kind === "old-relay") throw new OldRelay();
+ if (said.kind === "unavailable") throw new Unavailable(said.reason, said.resetsAt);
+ }
+
async function wake(ops: ComputerOps): Promise<{ id: string; started: boolean }> {
waking ??= wakeSandbox(ops, {
mayStart: () => rails.refusal(true) === null,
+ allowed: () => allowed(ops),
starting: () => rails.resumed(),
...(deps.pollMs ? { pollMs: deps.pollMs } : {}),
}).finally(() => { waking = null; });
@@ -116,17 +133,17 @@ export function createCloudBrowser(deps: CloudBrowserDeps) {
async function launch(request: OpenRequest, ops: ComputerOps): Promise<Opened> {
const key = profileKey(request.botId);
let box: { id: string; started: boolean } | null = null;
- const quit = async () => { if (box) await ops.run(box.id, quitCommand(key), 10_000).catch(() => undefined); };
+ const quit = async () => { if (box) await ops.quit(box.id, key).catch(() => undefined); };
try {
box = await wake(ops);
const secret = randomBytes(24).toString("hex");
- const answer = launchAnswer(await ops.run(box.id, launchCommand(key, secret), LAUNCH_MS));
+ const answer = await ops.launch(box.id, key, secret);
if (!answer.chrome) {
rails.failed();
await quit();
return home(request, "start-failed");
}
- const relay = await ops.host(box.id, COMPUTER_DOOR_PORT).catch(() => null) ?? answer.url;
+ const relay = await ops.host(box.id, COMPUTER_DOOR_PORT).catch(() => null);
const url = relay ? dialable(relay) : null;
if (!url) {
rails.noRoute();
@@ -147,7 +164,8 @@ export function createCloudBrowser(deps: CloudBrowserDeps) {
return { cdpUrl };
} catch (error) {
if (error instanceof StaysHome) return home(request, error.reason);
- if (error instanceof OldRelay) { rails.noRoute(); return home(request, "no-route"); }
+ if (error instanceof OldRelay) { rails.oldRelay(); return home(request, "old-relay"); }
+ if (error instanceof Unavailable) return home(request, rails.unavailable(error.reason, error.resetsAt));
await quit();
return home(request, refused(error));
}
@@ -169,9 +187,17 @@ export function createCloudBrowser(deps: CloudBrowserDeps) {
}
/** Where the session's browser opens: in the sandbox (`cdpUrl`, the engine's address for it), or in the home. */
- async function open(request: OpenRequest): Promise<Opened> {
+ function open(request: OpenRequest): Promise<Opened> {
const live = doors.url(request.session);
- if (live) return { cdpUrl: live };
+ if (live) return Promise.resolve({ cdpUrl: live });
+ const pending = pendingSessions.get(request.session);
+ if (pending) return pending;
+ const decided = decide(request).finally(() => pendingSessions.delete(request.session));
+ pendingSessions.set(request.session, decided);
+ return decided;
+ }
+
+ async function decide(request: OpenRequest): Promise<Opened> {
if (cloudBrowserLever(deps.env)) { leverCleanup(); return home(request, "lever"); }
rails.lever(false);
if (request.refusal) return home(request, request.refusal);
@@ -201,7 +227,7 @@ export function createCloudBrowser(deps: CloudBrowserDeps) {
doors.close(session);
sessions.delete(session);
const ops = deps.ops();
- if (ops && boxId) await ops.run(boxId, bots().size > 0 ? quitCommand(profileKey(botId)) : QUIT_ALL_COMMAND, 10_000).catch(() => undefined);
+ if (ops && boxId) await ops.quit(boxId, bots().size > 0 ? profileKey(botId) : null).catch(() => undefined);
letSleep();
log(`browser ${session}: closed in the Cloud's browser sandbox after ${Math.round(CLOUD_BROWSER_IDLE_MS / 60_000)} minutes unused`);
} finally {
diff --git a/server/cloud-browser/rails.ts b/server/cloud-browser/rails.ts
index 813ab0d22d..5e1bd92b56 100644
--- a/server/cloud-browser/rails.ts
+++ b/server/cloud-browser/rails.ts
@@ -16,8 +16,8 @@ export const CLOUD_BROWSER_BACKOFF_MS = 15 * 60_000;
/** Why a browser session opened in the home instead: names only, for the log and the health report. */
export type HomeReason =
- | "lever" | "team" | "not-eligible" | "not-set-up" | "busy" | "lent-connection"
- | "budget" | "minutes-used" | "sandbox-full" | "backoff" | "account-limit" | "hours-used" | "at-once" | "no-route" | "start-failed" | "unreachable";
+ | "lever" | "team" | "not-eligible" | "own-key" | "not-set-up" | "busy" | "lent-connection"
+ | "old-relay" | "unavailable" | "budget" | "minutes-used" | "sandbox-full" | "backoff" | "account-limit" | "hours-used" | "at-once" | "no-route" | "start-failed" | "unreachable";
interface Day {
day: string;
@@ -40,6 +40,10 @@ interface State extends Day {
noRouteDay: string | null;
/** Since when the sandbox was woken here and not yet let sleep; 0 when asleep. */
awakeSince: number;
+ /** The Cloud's relay does not know the browser sandbox: nothing is started before this. */
+ oldRelayUntil: number;
+ /** The relay said no browser sandbox may start (the fleet's day spent, switched off): nothing is started before this. */
+ unavailableUntil: number;
/** Since when the operator lever has kept every browser in the home; 0 when it does not. */
leverSince: number;
}
@@ -69,7 +73,7 @@ export function createCloudBrowserRails(options: CloudBrowserRailsOptions) {
const awakeCapMs = (options.awakeMinutes ?? CLOUD_BROWSER_DAILY_AWAKE_MINUTES) * 60_000;
const file = join(options.dataDir, "cloud-browser", "rails.json");
const fresh = (day: string): Day => ({ day, resumes: 0, awakeMs: 0, computer: 0, home: 0, fallbacks: {} });
- let state: State = { ...fresh(utcDay(now())), failuresInRow: 0, backoffUntil: 0, accountUntil: 0, hoursUntil: 0, noRouteDay: null, awakeSince: 0, leverSince: 0 };
+ let state: State = { ...fresh(utcDay(now())), failuresInRow: 0, backoffUntil: 0, accountUntil: 0, hoursUntil: 0, noRouteDay: null, awakeSince: 0, leverSince: 0, oldRelayUntil: 0, unavailableUntil: 0 };
try {
const saved = JSON.parse(readFileSync(file, "utf8")) as Partial<State>;
const number = (value: unknown) => (typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : 0);
@@ -81,6 +85,7 @@ export function createCloudBrowserRails(options: CloudBrowserRailsOptions) {
accountUntil: number(saved.accountUntil), hoursUntil: number(saved.hoursUntil),
noRouteDay: typeof saved.noRouteDay === "string" ? saved.noRouteDay : null,
awakeSince: number(saved.awakeSince), leverSince: number(saved.leverSince),
+ oldRelayUntil: number(saved.oldRelayUntil), unavailableUntil: number(saved.unavailableUntil),
};
} catch {
// None yet, or unreadable: a fresh day. The holds it may have had end by the next day anyway.
@@ -110,6 +115,8 @@ export function createCloudBrowserRails(options: CloudBrowserRailsOptions) {
/** Why no start may be sent for a browser now, or null. `resume`: this open needs one (the computer is stopped). */
refusal(resume: boolean): HomeReason | null {
const current = today(), at = now();
+ if (at < current.oldRelayUntil) return "old-relay";
+ if (at < current.unavailableUntil) return "unavailable";
if (at < current.accountUntil) return "account-limit";
if (at < current.hoursUntil) return "hours-used";
if (at < current.backoffUntil) return "backoff";
@@ -188,6 +195,19 @@ export function createCloudBrowserRails(options: CloudBrowserRailsOptions) {
current.backoffUntil = Math.max(current.backoffUntil, now() + CLOUD_BROWSER_BACKOFF_MS);
save();
},
+ /** An Admin from before the browser sandbox: asked again in a week. */
+ oldRelay(): void {
+ today().oldRelayUntil = now() + 7 * 24 * 60 * 60_000;
+ save();
+ },
+ /** The relay's no, until its `resetsAt` (else the next UTC day): the fleet's starts, this Cloud's, or switched off. */
+ unavailable(reason: string, resetsAt: string | null): HomeReason {
+ const current = today();
+ const limit = resetsAt ? { reason: "too_many_starts" as const, resetsAt } : undefined;
+ current.unavailableUntil = liftsAt(limit, now());
+ save();
+ return reason === "cloud_minutes" ? "minutes-used" : reason === "cloud_starts" ? "budget" : "unavailable";
+ },
noRoute(): void {
const current = today();
current.noRouteDay = current.day;
@@ -204,7 +224,8 @@ export function createCloudBrowserRails(options: CloudBrowserRailsOptions) {
awakeMinutes: Math.floor(awakeToday(current) / 60_000),
awakeMinutesCap: Math.round(awakeCapMs / 60_000),
fallbacks: { ...current.fallbacks },
- held: awakeToday(current) >= awakeCapMs ? "minutes-used" as const : at < current.accountUntil ? "account-limit" as const : at < current.hoursUntil ? "hours-used" as const
+ held: at < current.oldRelayUntil ? "old-relay" as const : at < current.unavailableUntil ? "unavailable" as const
+ : awakeToday(current) >= awakeCapMs ? "minutes-used" as const : at < current.accountUntil ? "account-limit" as const : at < current.hoursUntil ? "hours-used" as const
: at < current.backoffUntil ? "backoff" as const : current.noRouteDay === current.day ? "no-route" as const : null,
};
},
diff --git a/server/cloud-browser/remote.ts b/server/cloud-browser/remote.ts
index 9bdadd088f..2c7969308e 100644
--- a/server/cloud-browser/remote.ts
+++ b/server/cloud-browser/remote.ts
@@ -1,14 +1,14 @@
// The Cloud's browser sandbox at the provider: one small sandbox per personal Cloud home, made the first time a bot needs
-// a browser, shared by that Cloud's bots, each with a profile of its own on its disk. It is not a bot's cloud computer:
-// no bot runs commands in it, the computer screens never list it, and on MausBot Cloud the Admin's relay keeps it out of
-// the plan's computers and hours (`purpose: "browser"`) under limits of its own.
+// a browser, shared by that Cloud's bots, each with a profile and a Chrome of its own on its disk. It is not a bot's cloud
+// computer: no bot runs commands in it, the computer screens never list it, and it exists only through MausBot Cloud's
+// Admin relay, which keeps it out of the plan's computers and hours under limits of its own, and runs in it only the
+// fixed browser actions it builds itself (launch, quit). A person's own provider key never gets one.
// Woken with ONE resume and then only reads, never the resume loop of boat.ts's waitReady: a refused resume is billed.
import { createHash } from "node:crypto";
-import { boatAccount, boatFetch, boatNameFor, boatRefusal, findBoat, requestRecordedBoatDeletion, runCommand, SLEEPING_BOAT_STATES } from "../boat.ts";
+import { boatAccount, boatFetch, boatNameFor, boatRefusal, deadBoatOf, findBoat, requestRecordedBoatDeletion, SLEEPING_BOAT_STATES } from "../boat.ts";
import { beginBoatCreate, discardBoatCreate, rememberCreatedBoat, resolveBoatCreate } from "../boat-create-idempotency.ts";
import { relayBody } from "../boat-relay.ts";
-import type { CommandOutcome } from "../boat-command.ts";
import type { AppConfig } from "../config.ts";
const READY = new Set(["idle", "ready", "running"]);
@@ -19,27 +19,36 @@ export const BROWSER_SANDBOX_OWNER = "browser";
export const BROWSER_SANDBOX_TYPE = "small";
/** Chromes at once in one sandbox (one per bot browsing); past this a bot's browser opens in the home. */
export const BROWSER_SANDBOX_CHROMES = 3;
-/** The provider stops it by itself after this long if every stop path here died. */
-const BROWSER_SANDBOX_TTL_SECONDS = 2 * 60 * 60;
/** The port the sandbox's small door listens on, on its loopback only; the provider's relay reaches it there. */
export const COMPUTER_DOOR_PORT = 39231;
-/** Where the browsers keep their profiles and the door on the sandbox's disk. */
-export const COMPUTER_BROWSER_DIR = "$HOME/.omb-browser";
/** A bot's folder name in the sandbox: a hash, so the sandbox never holds a bot's id or name. */
export const profileKey = (botId: string): string => createHash("sha256").update(`omb-browser:${botId}`).digest("hex").slice(0, 16);
-/** What the browser needs from the provider; tests pass their own. */
+/** What the relay says before anything is started: whether a browser sandbox may start now, and until when it may not. */
+export type Availability =
+ | { kind: "old-relay" }
+ | { kind: "available"; boxId: string | null }
+ | { kind: "unavailable"; reason: string; resetsAt: string | null };
+
+/** What the browser needs from the relay; tests pass their own. */
export interface ComputerOps {
+ /** The relay's word on the browser sandbox; an Admin from before it answers 404 ("old-relay"). */
+ probe(): Promise<Availability>;
/** The Cloud's browser sandbox, or null when there is none yet. */
find(): Promise<{ id: string; state: string } | null>;
- /** Makes it (once: the create is journaled under one idempotency key) and names it. Throws the provider's or the Admin's refusal. */
+ /** A sandbox the provider reports broken (`error`), which never runs again, or null. */
+ dead(): string | null;
+ /** Makes it (once: the create is journaled under one idempotency key) and names it. Throws the relay's refusal. */
create(): Promise<{ id: string; state: string }>;
- /** One resume. Throws the provider's or the Admin's refusal (with its limit) on anything but a 2xx or a 409. */
+ /** One resume. Throws the relay's refusal (with its limit) on anything but a 2xx or a 409. */
resume(boxId: string): Promise<void>;
state(boxId: string): Promise<string | null>;
- run(boxId: string, command: string, timeoutMs: number): Promise<CommandOutcome>;
- /** The provider's way to put the door's port on a URL; null where it is refused. */
+ /** One bot's Chrome started on its profile, with this open's door secret. */
+ launch(boxId: string, key: string, secret: string): Promise<{ chrome: boolean }>;
+ /** One bot's Chrome asked to quit (it writes its cookies); `key` null: every Chrome and the door. */
+ quit(boxId: string, key: string | null): Promise<void>;
+ /** The door's port on a protected relay URL (one that needs its token); null where it is refused or unprotected. */
host(boxId: string, port: number): Promise<string | null>;
/** Deletes it, journaled like every deletion (boat-delete-journal.ts), so a failed delete is retried and never leaks. */
remove(boxId: string): Promise<boolean>;
@@ -51,24 +60,31 @@ async function json(cfg: AppConfig, path: string, init: RequestInit = {}) {
return { ok: res.ok && body?.ok !== false, status: res.status, body };
}
-const included = (cfg: AppConfig) => boatAccount(cfg)?.included === true;
+/** `purpose` tells the Admin's relay this is the Cloud's browser sandbox, outside the plan's computers and hours. */
+export const browserSandboxCreateBody = () => ({ noEnv: true, type: BROWSER_SANDBOX_TYPE, purpose: "browser" });
+
+/** The Cloud's relay does not know the browser sandbox (an Admin from before it): nothing is created. */
+export class OldRelay extends Error {}
+
+const HEX16 = /^[a-f0-9]{16}$/, HEX48 = /^[a-f0-9]{48}$/;
-/** `purpose` tells the Admin's relay this is the Cloud's browser sandbox, outside the plan's computers and hours; a
- * person's own key goes to the provider, which takes no such field. */
-export const browserSandboxCreateBody = (viaRelay: boolean) =>
- ({ ttlSeconds: BROWSER_SANDBOX_TTL_SECONDS, noEnv: true, type: BROWSER_SANDBOX_TYPE, ...(viaRelay ? { purpose: "browser" } : {}) });
+/** The relay URL only when it is protected: it carries the access token the relay checks. */
+function protectedUrl(raw: unknown): string | null {
+ if (typeof raw !== "string") return null;
+ try { return new URL(raw).searchParams.get("_token") ? raw : null; } catch { return null; }
+}
export function providerOps(cfg: () => AppConfig): ComputerOps {
async function create(): Promise<{ id: string; state: string }> {
const config = cfg();
- const body = JSON.stringify(browserSandboxCreateBody(included(config)));
+ const body = JSON.stringify(browserSandboxCreateBody());
let request = beginBoatCreate(BROWSER_SANDBOX_OWNER, body).request;
let answer = request.boxId ? await json(config, `/sandboxes/${request.boxId}`) : null;
let posted = false;
if (!answer?.ok) {
posted = true;
answer = await json(config, "/sandboxes", { method: "POST", headers: { "Idempotency-Key": request.idempotencyKey }, body, signal: AbortSignal.timeout(45_000) });
- // The relay already holds this Cloud's browser sandbox (a create whose answer was lost): that one is ours.
+ // The relay already holds this Cloud's live browser sandbox (a create whose answer was lost): that one is ours.
const existing = answer.body?.boxId ?? answer.body?.error?.boxId;
if (answer.status === 409 && (answer.body?.code ?? answer.body?.error?.code) === "browser_sandbox_exists" && typeof existing === "string") {
answer = { ok: true, status: 200, body: { sandbox: { id: existing, state: "unknown" } } };
@@ -78,40 +94,61 @@ export function providerOps(cfg: () => AppConfig): ComputerOps {
const boxId = answer.body?.sandbox?.id;
if (!answer.ok || typeof boxId !== "string") {
if (answer.status < 500 && answer.status !== 409) discardBoatCreate(request);
- throw boatRefusal(answer.status, "making the browser sandbox", answer.body, included(config));
+ throw boatRefusal(answer.status, "making the browser sandbox", answer.body, true);
}
request = rememberCreatedBoat(request, boxId);
- // A relay from before the browser sandbox made a plan computer instead, which would take the plan's slot: deleted at once.
- if (posted && included(config) && answer.body.sandbox.purpose !== "browser") {
+ // Checked before anything is created too (probe); this is the last guard: a box the relay did not mark is deleted at once.
+ if (posted && answer.body.sandbox.purpose !== "browser") {
resolveBoatCreate(request);
await requestRecordedBoatDeletion(config, { boxId, name: await boatNameFor(BROWSER_SANDBOX_OWNER), ownerBotId: BROWSER_SANDBOX_OWNER }).catch(() => "pending");
throw new OldRelay();
}
const named = await json(config, `/sandboxes/${boxId}`, { method: "PATCH", body: JSON.stringify({ name: await boatNameFor(BROWSER_SANDBOX_OWNER) }) });
- if (!named.ok) throw boatRefusal(named.status, "naming the browser sandbox", named.body, included(config));
+ if (!named.ok) throw boatRefusal(named.status, "naming the browser sandbox", named.body, true);
resolveBoatCreate(request);
return { id: boxId, state: typeof answer.body.sandbox.state === "string" ? answer.body.sandbox.state : "unknown" };
}
+ const action = async (boxId: string, body: Record<string, unknown>) => {
+ const answer = await json(cfg(), `/sandboxes/${boxId}/browser`, { method: "POST", body: JSON.stringify(body), signal: AbortSignal.timeout(30_000) });
+ if (!answer.ok) throw boatRefusal(answer.status, "the browser sandbox's browser", answer.body, true);
+ return answer.body;
+ };
return {
+ async probe() {
+ const answer = await json(cfg(), "/browser-sandbox");
+ if (answer.status === 404) return { kind: "old-relay" };
+ if (!answer.ok || typeof answer.body?.available !== "boolean") throw boatRefusal(answer.status, "asking about the browser sandbox", answer.body, true);
+ if (answer.body.available) return { kind: "available", boxId: typeof answer.body.boxId === "string" ? answer.body.boxId : null };
+ return { kind: "unavailable", reason: typeof answer.body.reason === "string" ? answer.body.reason : "unknown", resetsAt: typeof answer.body.resetsAt === "string" ? answer.body.resetsAt : null };
+ },
async find() {
const found = await findBoat(cfg(), BROWSER_SANDBOX_OWNER);
return found && typeof found.id === "string" ? { id: found.id, state: typeof found.state === "string" ? found.state : "unknown" } : null;
},
+ dead: () => deadBoatOf(BROWSER_SANDBOX_OWNER)?.boxId ?? null,
create,
async resume(boxId) {
const answer = await json(cfg(), `/sandboxes/${boxId}/resume`, { method: "POST" });
// 409: a wake already under way; it is waited for like this one.
- if (!answer.ok && answer.status !== 409) throw boatRefusal(answer.status, "waking the browser sandbox", answer.body, included(cfg()));
+ if (!answer.ok && answer.status !== 409) throw boatRefusal(answer.status, "waking the browser sandbox", answer.body, true);
},
async state(boxId) {
const answer = await json(cfg(), `/sandboxes/${boxId}`);
const state = answer.body?.sandbox?.state;
return typeof state === "string" ? state : null;
},
- run: (boxId, command, timeoutMs) => runCommand(cfg(), boxId, command, { timeoutMs }),
+ async launch(boxId, key, secret) {
+ if (!HEX16.test(key) || !HEX48.test(secret)) throw new Error("bad browser profile key or door secret");
+ return { chrome: (await action(boxId, { action: "launch", key, secret }))?.chrome === true };
+ },
+ async quit(boxId, key) {
+ if (key !== null && !HEX16.test(key)) throw new Error("bad browser profile key");
+ await action(boxId, key === null ? { action: "quit-all" } : { action: "quit", key });
+ },
async host(boxId, port) {
const answer = await json(cfg(), `/sandboxes/${boxId}/host`, { method: "POST", body: JSON.stringify({ port, localhost: true }) });
- return answer.ok && typeof answer.body?.url === "string" ? answer.body.url : null;
+ if (!answer.ok || answer.body?.isProtected === false || answer.body?.access === "public") return null;
+ return protectedUrl(answer.body?.url);
},
async remove(boxId) {
const name = await boatNameFor(BROWSER_SANDBOX_OWNER);
@@ -120,9 +157,6 @@ export function providerOps(cfg: () => AppConfig): ComputerOps {
};
}
-/** The Cloud's relay does not know the browser sandbox yet (an Admin from before it): no route today. */
-export class OldRelay extends Error {}
-
/** Not a failure of the sandbox: the browser opens in the home, and nothing is counted against it. */
export class StaysHome extends Error {
readonly reason: "busy" | "budget";
@@ -135,22 +169,30 @@ export class StaysHome extends Error {
export interface WakeOptions {
/** Asked before the one start (a create or a resume) is sent: false keeps it unsent (the day's budget, a hold). */
mayStart(): boolean;
+ /** The relay's word, asked once before a start: what it says decides whether one is sent at all. */
+ allowed(): Promise<void>;
/** Called just before the start goes out, so it counts whatever the answer. */
starting(): void;
budgetMs?: number;
pollMs?: number;
}
-/** The sandbox ready to take commands: made or woken with at most one start, then read until it says so. */
+/** The sandbox ready to take actions: made or woken with at most one start, then read until it says so. A sandbox the
+ * provider reports broken is deleted first and a fresh one made, counted like any start. */
export async function wakeSandbox(ops: ComputerOps, options: WakeOptions): Promise<{ id: string; started: boolean }> {
let found = await ops.find();
- if (found && TERMINAL.has(found.state)) throw new Error("the browser sandbox is broken at the provider");
if (found && READY.has(found.state)) return { id: found.id, started: false };
// Archiving: its snapshot must land before it can be resumed, and another stop path owns it now.
if (found?.state === "archiving") throw new StaysHome("busy");
+ const broken = found && TERMINAL.has(found.state) ? found.id : found ? null : ops.dead();
+ if (broken) {
+ await ops.remove(broken);
+ found = null;
+ }
let started = false;
if (!found || SLEEPING_BOAT_STATES.has(found.state)) {
if (!options.mayStart()) throw new StaysHome("budget");
+ await options.allowed();
options.starting();
started = true;
if (!found) found = await ops.create();
@@ -168,103 +210,3 @@ export async function wakeSandbox(ops: ComputerOps, options: WakeOptions): Promi
}
throw new Error("the browser sandbox did not become ready in time");
}
-
-const DOOR_SOURCE = String.raw`
-import net from "node:net"; import fs from "node:fs"; import { timingSafeEqual } from "node:crypto";
-const D = process.argv[2], PORT = Number(process.argv[3]);
-const read = (f) => { try { return fs.readFileSync(D + f, "utf8"); } catch { return ""; } };
-const same = (a, b) => a.length === b.length && a.length > 0 && timingSafeEqual(Buffer.from(a), Buffer.from(b));
-net.createServer((s) => {
- let buf = Buffer.alloc(0);
- const t = setTimeout(() => s.destroy(), 10000);
- s.on("error", () => s.destroy());
- const on = (c) => {
- buf = Buffer.concat([buf, c]);
- const e = buf.indexOf("\r\n\r\n");
- if (e < 0) { if (buf.length > 16384) s.destroy(); return; }
- s.off("data", on); clearTimeout(t);
- const head = buf.subarray(0, e).toString("latin1").split("\r\n"), rest = buf.subarray(e + 4);
- const [, key = "", secret = ""] = /^\/([a-f0-9]{16})\/([a-f0-9]+)$/.exec((head[0].split(" ")[1] || "").split("?")[0]) || [];
- const ports = key ? read("/" + key + "/profile/DevToolsActivePort").split("\n").map((x) => x.trim()) : [];
- if (!key || !same(secret, read("/" + key + "/secret").trim()) || !ports[1]) { s.end("HTTP/1.1 404 Not Found\r\nContent-Length: 0\r\n\r\n"); return; }
- const keep = head.slice(1).filter((h) => !/^(host|origin|forwarded|x-forwarded-[a-z-]*|x-real-ip):/i.test(h));
- const up = net.connect(Number(ports[0]), "127.0.0.1", () => {
- up.write(["GET " + ports[1] + " HTTP/1.1", "Host: 127.0.0.1:" + ports[0], ...keep, "", ""].join("\r\n"));
- if (rest.length) up.write(rest);
- s.pipe(up); up.pipe(s);
- });
- up.on("error", () => s.destroy()); up.on("close", () => s.destroy()); s.on("close", () => up.destroy());
- };
- s.on("data", on);
-}).listen(PORT, "127.0.0.1");
-`;
-
-/** The door's source, for its own test. */
-export const doorSource = (): string => DOOR_SOURCE;
-
-const check = (key: string, secret: string) => {
- if (!/^[a-f0-9]{16}$/.test(key)) throw new Error("bad profile key");
- if (!/^[a-f0-9]{32,128}$/.test(secret)) throw new Error("bad door secret");
-};
-
-/**
- * One command: write this open's secret for one bot's profile, start that profile's Chrome unless it already runs
- * (clearing a profile lock an earlier host left: nothing runs on it, so no live Chrome holds it), start the door unless it
- * runs, and put the door on the provider's relay. Prints one JSON line: whether Chrome answers, and the relay's URL when
- * the sandbox gave one. Chrome and the door start with an empty environment: no provider variable reaches a page. Each
- * bot's profile is its own folder (its own user-data-dir and Chrome), so no bot's pages see another's cookies.
- */
-export function launchCommand(key: string, secret: string, port = COMPUTER_DOOR_PORT): string {
- check(key, secret);
- const D = COMPUTER_BROWSER_DIR;
- const clean = 'env -i HOME="$HOME" PATH="/usr/local/bin:/usr/bin:/bin" setsid nohup';
- return [
- `D="${D}"; K="$D/${key}"; P="$K/profile"; mkdir -p "$P"; chmod 700 "$D" "$K"`,
- `umask 077; printf %s '${secret}' > "$K/secret"`,
- `if ! pgrep -f -- "--user-data-dir=$P" >/dev/null 2>&1; then`,
- ` rm -f "$P/SingletonLock" "$P/SingletonSocket" "$P/SingletonCookie" "$P/DevToolsActivePort"`,
- ` B=$(command -v google-chrome || command -v google-chrome-stable || command -v chromium || command -v chromium-browser)`,
- ` V=$("$B" --version 2>/dev/null | grep -o '[0-9][0-9.]*' | head -1)`,
- ` ${clean} "$B" --headless=new --remote-debugging-address=127.0.0.1 --remote-debugging-port=0 --user-data-dir="$P" --no-first-run --no-default-browser-check --password-store=basic --use-mock-keychain --disable-dev-shm-usage --window-size=1280,800 --user-agent="Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/$V Safari/537.36" about:blank >"$K/chrome.log" 2>&1 </dev/null &`,
- "fi",
- `for i in $(seq 1 80); do [ -s "$P/DevToolsActivePort" ] && break; sleep 0.1; done`,
- `if ! pgrep -f -- "$D/door.mjs" >/dev/null 2>&1; then`,
- ` cat > "$D/door.mjs" <<'OMB_DOOR'${DOOR_SOURCE}OMB_DOOR`,
- ` ${clean} node "$D/door.mjs" "$D" ${port} >"$D/door.log" 2>&1 </dev/null &`,
- "fi",
- `(host ${port} --localhost >/dev/null 2>&1 || true)`,
- `U=$(host url ${port} --localhost 2>/dev/null | grep -o 'https://[^[:space:]]*' | head -1)`,
- `C=false; [ -s "$P/DevToolsActivePort" ] && C=true`,
- `printf '{"chrome":%s,"url":"%s"}\\n' "$C" "$U"`,
- ].join("\n");
-}
-
-/** One bot's Chrome asked to quit, so it writes its cookies; the others keep running. */
-export function quitCommand(key: string): string {
- if (!/^[a-f0-9]{16}$/.test(key)) throw new Error("bad profile key");
- return [
- `P="${COMPUTER_BROWSER_DIR}/${key}/profile"`,
- `pkill -TERM -f -- "--user-data-dir=$P" 2>/dev/null || true`,
- `for i in $(seq 1 20); do pgrep -f -- "--user-data-dir=$P" >/dev/null 2>&1 || break; sleep 0.1; done`,
- ].join("\n");
-}
-
-/** Every Chrome and the door asked to quit, before the sandbox stops. */
-export const QUIT_ALL_COMMAND = [
- `D="${COMPUTER_BROWSER_DIR}"`,
- `pkill -TERM -f -- "--user-data-dir=$D/" 2>/dev/null || true`,
- `pkill -TERM -f -- "$D/door.mjs" 2>/dev/null || true`,
- `for i in $(seq 1 30); do pgrep -f -- "--user-data-dir=$D/" >/dev/null 2>&1 || break; sleep 0.1; done`,
-].join("\n");
-
-/** The launch's answer: whether Chrome answers, and the relay URL the sandbox printed (a secret: never logged). */
-export function launchAnswer(outcome: CommandOutcome): { chrome: boolean; url: string | null } {
- const line = outcome.stdout.trim().split("\n").at(-1) ?? "";
- try {
- const parsed = JSON.parse(line) as { chrome?: unknown; url?: unknown };
- const url = typeof parsed.url === "string" && parsed.url ? parsed.url : null;
- return { chrome: parsed.chrome === true, url };
- } catch {
- return { chrome: false, url: null };
- }
-}
diff --git a/server/cloud-browser/testing/fake-computer.ts b/server/cloud-browser/testing/fake-computer.ts
index f9ef1c712a..9046b244c9 100644
--- a/server/cloud-browser/testing/fake-computer.ts
+++ b/server/cloud-browser/testing/fake-computer.ts
@@ -1,15 +1,15 @@
-// A fake provider for the Cloud's browser sandbox: the provider's API (list, create, name, resume, state, commands, host,
-// delete) and the sandbox's door behind its relay, which answers a WebSocket upgrade as Chrome would and echoes every
-// frame. Nothing here reaches a real provider or starts a real sandbox.
+// A fake Admin relay and provider for the Cloud's browser sandbox: the relay's API (probe, list, create, name, resume,
+// state, browser actions, host, delete) and the sandbox's door behind its relay URL, which answers a WebSocket upgrade as
+// Chrome would and echoes every frame. Nothing here reaches a real provider or starts a real sandbox.
import { createHash } from "node:crypto";
import { createServer, type IncomingMessage, type Server } from "node:http";
import type { Duplex } from "node:stream";
import { WebSocketServer } from "ws";
-export const OWN_KEY = "boat_own-test-key";
+export const RELAY_KEY = "box_omb_relay-test-key";
export const RELAY_TOKEN = "relay-token-123";
-type Request = { method: string; path: string; command?: string; body?: Record<string, unknown> };
+type Request = { method: string; path: string; body?: Record<string, unknown> };
export interface FakeComputer {
base: string;
@@ -19,33 +19,39 @@ export interface FakeComputer {
/** Status the next resumes and creates answer with (a 2xx makes the sandbox ready). */
startStatus: number;
startBody: Record<string, unknown>;
- /** Whether the launch command prints the relay URL. */
- printUrl: boolean;
- /** Whether the provider's host route answers. */
+ /** Plays an Admin from before the browser sandbox: no probe route, and a create that does not say `purpose`. */
+ oldRelay: boolean;
+ /** The probe's answer while not old: available, or why not and until when. */
+ available: boolean;
+ unavailableReason: string;
+ unavailableUntil: string | null;
+ /** Whether the host route answers, and whether it says the URL is protected. */
hostRoute: boolean;
+ unprotected: boolean;
chromeStarts: boolean;
- /** Plays a relay that knows the browser sandbox: its create answer carries `purpose`. */
- knowsPurpose: boolean;
requests: Request[];
upgrades: Array<{ path: string; host: string | undefined; origin: string | undefined }>;
frames: string[];
+ boxId: string;
resumes(): number;
creates(): number;
launches(): number;
- quits(): number;
- /** The profile folders the launches named, in order. */
+ /** Each quit action, as `quit:<key>` or `quit-all`. */
+ quits(): string[];
+ /** The profile keys the launches named, in order. */
profiles(): string[];
close(): Promise<void>;
}
const legacyName = (owner: string) => `ogb-${owner.slice(0, 8).toLowerCase().replace(/[^a-z0-9]/g, "")}-${createHash("sha256").update(owner).digest("hex").slice(0, 6)}`;
-export async function startFakeComputer(boxId = "bx_23456789"): Promise<FakeComputer> {
+export async function startFakeComputer(): Promise<FakeComputer> {
const secrets = new Map<string, string>();
const wss = new WebSocketServer({ noServer: true });
+ let made = 0;
const fake = {
- base: "", state: "ready", exists: true, startStatus: 200, startBody: { ok: true }, printUrl: false, hostRoute: true, chromeStarts: true, knowsPurpose: true,
- requests: [], upgrades: [], frames: [],
+ base: "", state: "ready", exists: true, startStatus: 200, startBody: { ok: true }, oldRelay: false, available: true, unavailableReason: "fleet_starts",
+ unavailableUntil: null, hostRoute: true, unprotected: false, chromeStarts: true, requests: [], upgrades: [], frames: [], boxId: "bx_23456789",
} as unknown as FakeComputer;
const server: Server = createServer((req, res) => {
const url = new URL(req.url ?? "/", "http://fake");
@@ -53,36 +59,50 @@ export async function startFakeComputer(boxId = "bx_23456789"): Promise<FakeComp
req.on("data", (chunk) => { raw += chunk; });
req.on("end", () => {
const body = raw ? JSON.parse(raw) as Record<string, unknown> : {};
- fake.requests.push({ method: req.method ?? "GET", path: url.pathname, ...(typeof body.command === "string" ? { command: body.command } : {}), body });
+ fake.requests.push({ method: req.method ?? "GET", path: url.pathname, body });
const send = (status: number, payload: unknown) => { res.writeHead(status, { "content-type": "application/json", connection: "close" }); res.end(JSON.stringify(payload)); };
- if (req.headers.authorization !== `Bearer ${OWN_KEY}`) return send(401, { ok: false });
+ if (req.headers.authorization !== `Bearer ${RELAY_KEY}`) return send(401, { ok: false });
+ const boxId = fake.boxId;
const row = { id: boxId, name: legacyName("browser"), state: fake.state };
const rest = url.pathname.replace(/^\/api\/v1/, "");
+ if (rest === "/browser-sandbox") {
+ if (fake.oldRelay) return send(404, { ok: false, code: "not_found" });
+ return send(200, { ok: true, type: "browser.sandbox", available: fake.available, boxId: fake.exists ? boxId : null,
+ ...(fake.available ? {} : { reason: fake.unavailableReason, ...(fake.unavailableUntil ? { resetsAt: fake.unavailableUntil } : {}) }) });
+ }
if (rest === "/sandboxes" && req.method === "GET") return send(200, { ok: true, sandboxes: fake.exists ? [row] : [], pageInfo: { nextCursor: null } });
if (rest === "/sandboxes" && req.method === "POST") {
if (fake.startStatus >= 300) return send(fake.startStatus, fake.startBody);
+ made += 1;
+ fake.boxId = made === 1 ? fake.boxId : `bx_2345678${"abcdefgh"[made % 8]}`;
fake.exists = true;
fake.state = "ready";
- return send(202, { ok: true, sandbox: { id: boxId, state: "provisioning", ...(fake.knowsPurpose && body.purpose ? { purpose: body.purpose } : {}) } });
+ return send(202, { ok: true, sandbox: { id: fake.boxId, state: "provisioning", ...(!fake.oldRelay && body.purpose ? { purpose: body.purpose } : {}) } });
}
if (rest === `/sandboxes/${boxId}` && req.method === "PATCH") return send(200, { ok: true, sandbox: row });
if (rest === `/sandboxes/${boxId}` && req.method === "GET") return fake.exists ? send(200, { ok: true, sandbox: row }) : send(404, { ok: false });
- if (rest === `/sandboxes/${boxId}` && req.method === "DELETE") { fake.exists = false; return send(200, { ok: true, operation: { id: `bdop_${"a".repeat(32)}`, status: "completed", kind: "sandbox", targetId: boxId } }); }
+ if (rest === `/sandboxes/${boxId}` && req.method === "DELETE") {
+ fake.exists = false;
+ fake.state = "ready";
+ return send(200, { ok: true, operation: { id: `bdop_${"a".repeat(32)}`, status: "completed", kind: "sandbox", targetId: boxId } });
+ }
if (rest === `/sandboxes/${boxId}/resume`) {
if (fake.startStatus < 300) fake.state = "ready";
return send(fake.startStatus, fake.startBody);
}
- if (rest === `/sandboxes/${boxId}/host`) return fake.hostRoute ? send(200, { ok: true, url: `${fake.base}/door?_token=${RELAY_TOKEN}` }) : send(404, { ok: false, code: "not_found" });
- if (rest === `/sandboxes/${boxId}/commands`) {
- const command = String(body.command ?? "");
- const key = /K="\$D\/([a-f0-9]{16})"/.exec(command)?.[1], secret = /printf %s '([a-f0-9]+)'/.exec(command)?.[1];
- if (key && secret) {
- secrets.set(key, secret);
- const printed = fake.printUrl ? `${fake.base}/door?_token=${RELAY_TOKEN}` : "";
- return send(200, { exitCode: 0, stdout: `${JSON.stringify({ chrome: fake.chromeStarts, url: printed })}\n`, stderr: "" });
+ if (rest === `/sandboxes/${boxId}/host`) {
+ if (!fake.hostRoute) return send(404, { ok: false, code: "not_found" });
+ return send(200, fake.unprotected ? { ok: true, url: `${fake.base}/door`, isProtected: false, access: "public" }
+ : { ok: true, url: `${fake.base}/door?_token=${RELAY_TOKEN}`, isProtected: true, access: "private" });
+ }
+ if (rest === `/sandboxes/${boxId}/browser`) {
+ if (body.action === "launch" && typeof body.key === "string" && typeof body.secret === "string") {
+ secrets.set(body.key, body.secret);
+ return send(200, { ok: true, chrome: fake.chromeStarts, policy: true });
}
- return send(200, { exitCode: 0, stdout: "", stderr: "" });
+ return send(200, { ok: true });
}
+ if (rest === `/sandboxes/${boxId}/commands`) return send(404, { ok: false, code: "not_found" });
if (rest === `/sandboxes/${boxId}/stop`) { fake.state = "archived"; return send(200, { ok: true }); }
send(404, { ok: false, code: "not_found" });
});
@@ -101,15 +121,13 @@ export async function startFakeComputer(boxId = "bx_23456789"): Promise<FakeComp
});
await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
fake.base = `http://127.0.0.1:${(server.address() as { port: number }).port}`;
- const count = (test: (request: Request) => boolean) => fake.requests.filter(test).length;
- fake.resumes = () => count((request) => request.method === "POST" && request.path.endsWith("/resume"));
- fake.creates = () => count((request) => request.method === "POST" && request.path === "/api/v1/sandboxes");
- fake.launches = () => count((request) => request.command?.includes("printf %s") === true);
- fake.quits = () => count((request) => request.command?.includes("pkill -TERM") === true);
- fake.profiles = () => fake.requests.flatMap((request) => {
- const key = request.command?.includes("printf %s") ? /K="\$D\/([a-f0-9]{16})"/.exec(request.command)?.[1] : undefined;
- return key ? [key] : [];
- });
+ const actions = (name: string) => fake.requests.filter((request) => request.path.endsWith("/browser") && request.body?.action === name);
+ fake.resumes = () => fake.requests.filter((request) => request.method === "POST" && request.path.endsWith("/resume")).length;
+ fake.creates = () => fake.requests.filter((request) => request.method === "POST" && request.path === "/api/v1/sandboxes").length;
+ fake.launches = () => actions("launch").length;
+ fake.quits = () => fake.requests.flatMap((request) => !request.path.endsWith("/browser") ? []
+ : request.body?.action === "quit" ? [`quit:${String(request.body.key)}`] : request.body?.action === "quit-all" ? ["quit-all"] : []);
+ fake.profiles = () => actions("launch").map((request) => String(request.body?.key));
fake.close = async () => {
for (const client of wss.clients) client.terminate();
wss.close();
diff --git a/server/host/browser-cloud-sandbox.test.ts b/server/host/browser-cloud-sandbox.test.ts
index 32c0bfdb18..abfcf59fbf 100644
--- a/server/host/browser-cloud-sandbox.test.ts
+++ b/server/host/browser-cloud-sandbox.test.ts
@@ -10,7 +10,8 @@ import { BrowserUploadRefusal } from "../browser-upload.ts";
import { REDDIT_REFUSAL } from "../browser/egress/reddit.ts";
import { DATA_DIR, type AppConfig } from "../config.ts";
import type { Store } from "../store.ts";
-import { OWN_KEY, startFakeComputer, type FakeComputer } from "../cloud-browser/testing/fake-computer.ts";
+import { RELAY_KEY, startFakeComputer, type FakeComputer } from "../cloud-browser/testing/fake-computer.ts";
+import { LOCAL_SCHEME_REFUSAL } from "../cloud-browser/guards.ts";
import { CLOUD_BROWSER_NO_UPLOAD, createBrowserHost, type BrowserHostDeps } from "./browser.ts";
vi.mock("../browser-engine.ts", async (original) => {
@@ -39,7 +40,8 @@ beforeEach(async () => {
// Each test starts the day afresh: the rails keep their counts in the data folder.
rmSync(join(DATA_DIR, "cloud-browser"), { recursive: true, force: true });
fake = await startFakeComputer();
- vi.stubEnv("OMB_BOAT_API", `${fake.base}/api/v1`);
+ vi.stubEnv("OMB_CLOUD_BOAT_URL", `${fake.base}/api/v1`);
+ vi.stubEnv("OMB_CLOUD_BOAT_TOKEN", RELAY_KEY);
vi.stubEnv("OMB_CLOUD_BROWSER", undefined);
vi.mocked(browserEngineStatus).mockReturnValue({ kind: "ready", binaryPath: "/usr/local/bin/agent-browser", version: "0.37.0", managed: false });
vi.spyOn(BrowserRuntime.prototype, "agentRpc").mockImplementation(async (_session, _spec, _method, _params, beforeDispatch) => {
@@ -56,8 +58,8 @@ afterEach(async () => {
await fake.close();
});
-function setup({ desktop = false, cloudBrowser = true }: { desktop?: boolean; cloudBrowser?: boolean } = {}) {
- const cfg = { features: { browser: true }, box: { token: OWN_KEY } } as unknown as AppConfig;
+function setup({ desktop = false, cloudBrowser = true, ownKey = false }: { desktop?: boolean; cloudBrowser?: boolean; ownKey?: boolean } = {}) {
+ const cfg = { features: { browser: true }, ...(ownKey ? { box: { token: "boat_persons-own-key" } } : {}) } as unknown as AppConfig;
const bots = [{ id: botId, name: botId, browser: true }];
const used: Array<[string, number]> = [];
const deps: BrowserHostDeps = {
@@ -93,6 +95,9 @@ describe("a personal Cloud's bot browser opens in the Cloud's browser sandbox",
expect((await host.currentBrowserSpec(botId, undefined))?.spec.env.AGENT_BROWSER_CDP).toBe(browser.spec.env.AGENT_BROWSER_CDP);
expect((await host.browserIntegration(botId, undefined, undefined, "team", { opening: OPEN }))?.spec.env.AGENT_BROWSER_CDP).toBe(browser.spec.env.AGENT_BROWSER_CDP);
expect(fake.launches()).toBe(1);
+ // Files and the browser's own pages are never opened there: every bot's Chrome there runs as one user.
+ expect(await host.browserRuntime.agentRpc(browser.session, browser.spec, "tools/call", { name: OPEN, arguments: { url: "file:///home/user/.omb-browser/" } }))
+ .toEqual({ isError: true, content: [{ type: "text", text: LOCAL_SCHEME_REFUSAL }] });
// Reddit stays refused in the sandbox, as in the home.
expect(await host.browserRuntime.agentRpc(browser.session, browser.spec, "tools/call", { name: OPEN, arguments: { url: "https://www.reddit.com/" } }))
.toEqual({ isError: true, content: [{ type: "text", text: REDDIT_REFUSAL }] });
@@ -103,6 +108,14 @@ describe("a personal Cloud's bot browser opens in the Cloud's browser sandbox",
expect(host.cloudBrowserReport()).toMatchObject({ sessions: { sandbox: 1, home: 0 } });
});
+ it("a Cloud on the person's own provider key never gets a sandbox: it would bill their key with no cap", async () => {
+ const { host } = setup({ ownKey: true });
+ const browser = await host.browserIntegration(botId, undefined, undefined, "team", { opening: OPEN });
+ expect(browser?.spec.env.AGENT_BROWSER_CDP).toBeUndefined();
+ expect(fake.requests).toEqual([]);
+ expect(host.cloudBrowserReport()).toMatchObject({ fallbacks: { "own-key": 1 } });
+ });
+
it("a closing call never opens the sandbox", async () => {
const { host } = setup();
await host.browserIntegration(botId, undefined, undefined, "team", { opening: "agent_browser_close" });
diff --git a/server/host/browser.ts b/server/host/browser.ts
index 66490767a9..fe4d08db50 100644
--- a/server/host/browser.ts
+++ b/server/host/browser.ts
@@ -60,7 +60,8 @@ import type { EngineBrowsers } from "../engine-memory.ts";
import { createBrowserReclaim, reclaimable } from "./browser-reclaim.ts";
import { createCloudBrowser, type HomeReason } from "../cloud-browser/index.ts";
import { providerOps } from "../cloud-browser/remote.ts";
-import { boatConfigured } from "../boat.ts";
+import { boatAccount, boatConfigured } from "../boat.ts";
+import { downloadNote, localSchemeRefusal } from "../cloud-browser/guards.ts";
import { BrowserUploadRefusal } from "../browser-upload.ts";
import { BROWSER_TASKS, processBudget } from "../process-room.ts";
import { idleAfter } from "../drivers/session-idle.ts";
@@ -236,7 +237,8 @@ export function createBrowserHost(deps: BrowserHostDeps) {
// A tool call that would open Reddit from MausBot Cloud is refused before it reaches the browser. My Chrome is the
// person's own, outside the egress gate too; on My Cloud a call that can't reach it now says why instead.
const browserRuntime = new RuntimeRouter(agentBrowserRuntime, chromeEngine, {
- refusal: (session, spec, params) => (attachesToChrome(spec.env) && !cloudBrowser?.attached(session) ? null : browserEgress.callRefusal(params)),
+ refusal: (session, spec, params) => (cloudBrowser?.attached(session) ? localSchemeRefusal(params) ?? browserEgress.callRefusal(params)
+ : attachesToChrome(spec.env) ? null : browserEgress.callRefusal(params)),
// The opt-in engine's browsers wait for the server's room here; agent-browser's wait in browserRoom above. The
// person's own Chrome runs outside this server, and a close frees room.
room: (session, spec, params) => (!processRoom || attachesToChrome(spec.env) || (params as { name?: unknown } | null)?.name === "agent_browser_close"
@@ -253,7 +255,7 @@ export function createBrowserHost(deps: BrowserHostDeps) {
annotate: (spec, result) => passkeyAnnotation(chromeEngine.onPane(spec) ? "pane" : CLOUD_HOME ? "cloud" : DESKTOP_MANAGED ? "desktop" : "server")(spec, result),
// agent-browser's own error names only the CDP connection; the door knows what went wrong on the way.
afterCall: (session, spec, answer) => {
- const result = withCeilingNote(session, answer);
+ const result = cloudBrowser?.attached(session) ? downloadNote(withCeilingNote(session, answer)) : withCeilingNote(session, answer);
const failed = result as { isError?: unknown; content?: unknown };
const found = failed?.isError === true && viaDoor(session, spec) ? doors?.problem(session) : null;
// A door refused under an earlier holder says nothing about a caller that may use it.
@@ -278,7 +280,8 @@ export function createBrowserHost(deps: BrowserHostDeps) {
const computerOps = providerOps(() => cfg);
const cloudBrowser = deps.cloudBrowser && CLOUD_HOME && !DESKTOP_MANAGED ? createCloudBrowser({
dataDir: DATA_DIR,
- ops: () => (boatConfigured(cfg) ? computerOps : null),
+ // Only through MausBot Cloud's relay, which keeps the sandbox outside the plan under its own limits: never on a person's own key.
+ ops: () => (boatAccount(cfg)?.included === true ? computerOps : null),
used: (owner, windowMs) => deps.cloudBrowser?.used(owner, windowMs),
closeEngine: (session) => { const spec = usedBrowserSessions.get(session); return spec ? closeBrowser(session, spec) : Promise.resolve(true); },
held: (session) => !turnResources.free(`browser:${session}`),
@@ -297,6 +300,7 @@ export function createBrowserHost(deps: BrowserHostDeps) {
* profile per bot), and a session whose sites go out through the person's lent computer. */
function cloudBrowserRefusal(profile: string | undefined, session: string, audience: Audience): HomeReason | null {
if (profile || audienceBrowserSuffix(audience) !== "") return "not-eligible";
+ if (boatConfigured(cfg) && boatAccount(cfg)?.included !== true) return "own-key";
const lent = device?.(session);
return lent && "open" in lent ? "lent-connection" : null;
}