Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Cloud browser sandbox: sign-in backups and bounded write-back, address guard, prompt erase of deleted bots, unresumable sandbox replaced, files without links (#7791)
Milind Sonie1cc6a290d02
diff --git a/server/browser-engine.test.ts b/server/browser-engine.test.tsindex 7d9e7fc589..20891df428 100644--- a/server/browser-engine.test.ts+++ b/server/browser-engine.test.ts@@ -188,8 +188,8 @@ describe("deleting one browser session's saved logins", () => {it("removes only exact state/backup/candidate files and never calls state clear", async () => {const { directory, options } = fixture();- const removed = ["work-work.json", "work-work.json.enc", "work-work.json.previous", "work-work.json.enc.previous", ".tmp/work-work-candidate-123.json.enc", `${browserRestoreKey("work")}-work.json.enc`, `${browserRestoreKey("work")}-work.json.enc.previous`, `.tmp/${browserRestoreKey("work")}-work-candidate-123.json.enc`];- const preserved = ["work-client-work-client.json.enc", "personal-personal.json", "work-another.json", "notes.json", ".tmp/work-client-work-client-candidate-123.json.enc", `${browserRestoreKey("work-client")}-work-client.json.enc`];+ const removed = ["work-work.json", "work-work.json.enc", "work-work.json.previous", "work-work.json.enc.previous", ".tmp/work-work-candidate-123.json.enc", `${browserRestoreKey("work")}-work.json.enc`, `${browserRestoreKey("work")}-work.json.enc.previous`, `.tmp/${browserRestoreKey("work")}-work-candidate-123.json.enc`, "home-backup-work-1764200000000.json.enc", "home-backup-work-1764300000000.json.enc"];+ const preserved = ["home-backup-work-client-1764200000000.json.enc", "home-backup-work-123.json.enc", "work-client-work-client.json.enc", "personal-personal.json", "work-another.json", "notes.json", ".tmp/work-client-work-client-candidate-123.json.enc", `${browserRestoreKey("work-client")}-work-client.json.enc`];for (const name of [...removed, ...preserved]) writeFileSync(join(directory, name), "fixture state");expect(await clearBrowserSessionState("fixture-browser", "work", options)).toBe(true);for (const name of removed) expect(existsSync(join(directory, name)), name).toBe(false);diff --git a/server/browser-engine.ts b/server/browser-engine.tsindex be955aa021..f681a6dc81 100644--- a/server/browser-engine.ts+++ b/server/browser-engine.ts@@ -33,6 +33,34 @@ export function browserRestoreKey(session: string): string {return `omb-${createHash("sha256").update(session).digest("hex")}`;}+/** The session's saved sign-ins as they were when a session in the Cloud's browser sandbox opened (browser-sites.ts+ * backupSignIns): one file per such session, named by its time in ms (its id), encrypted like the restore file and named+ * apart from it, so agent-browser never restores it. They go wherever the sign-ins are cleared. */+export function signInsBackupFile(session: string, id: string): string {+ if (!/^[A-Za-z0-9_.-]{1,96}$/.test(session) || !/^\d{13}$/.test(id)) throw new Error("Invalid browser session.");+ return `home-backup-${session}-${id}.json.enc`;+}++/** The id of one of this session's backups from its file name, or null for any other file (another session's included). */+export function signInsBackupId(session: string, name: string): string | null {+ const prefix = `home-backup-${session}-`;+ if (!name.startsWith(prefix) || !name.endsWith(".json.enc")) return null;+ const id = name.slice(prefix.length, -".json.enc".length);+ return /^\d{13}$/.test(id) ? id : null;+}++/** Every backup of the session's sign-ins, removed. */+export function removeSignInsBackups(directory: string, session: string): void {+ let names: string[] = [];+ try { names = readdirSync(directory); }+ catch (error) { if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error; }+ for (const name of names) {+ if (signInsBackupId(session, name) === null) continue;+ try { unlinkSync(join(directory, name)); }+ catch (error) { if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error; }+ }+}+const PROFILES_DIR = "agent-browser-profiles";/** Where every saved session's Chrome profile lives. */@@ -729,6 +757,7 @@ export async function clearBrowserSessionState(};try {for (const base of bases) for (const suffix of [".json", ".json.enc", ".json.previous", ".json.enc.previous"]) remove(join(directory, base + suffix));+ removeSignInsBackups(directory, session);const pendingDirectory = join(directory, ".tmp");let pendingFiles: string[] = [];try { pendingFiles = readdirSync(pendingDirectory); }diff --git a/server/browser-sites.ts b/server/browser-sites.tsindex 3422dd0336..0485546a84 100644--- a/server/browser-sites.ts+++ b/server/browser-sites.ts@@ -2,11 +2,11 @@// it autosaves (`<restore key>-<session>.json.enc`, cli/src/native/state.rs: AES-256-GCM under SHA-256 of the key text,// 12-byte nonce first, 16-byte tag last); signing out clears all three. The key stays in this server process; no bot or page ever sees it.import { createCipheriv, createDecipheriv, createHash, randomBytes, randomUUID } from "node:crypto";-import { existsSync, mkdirSync, mkdtempSync, readFileSync, renameSync, rmSync, statSync, unlinkSync, writeFileSync } from "node:fs";+import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, renameSync, rmSync, statSync, unlinkSync, writeFileSync } from "node:fs";import { tmpdir } from "node:os";import { join } from "node:path";-import { browserRestoreKey, browserSessionsDirectory, closeBrowserSession, inRunningBrowser, startBrowserSession } from "./browser-engine.ts";+import { browserRestoreKey, browserSessionsDirectory, closeBrowserSession, inRunningBrowser, removeSignInsBackups, signInsBackupFile, signInsBackupId, startBrowserSession } from "./browser-engine.ts";import { browserRuntimeEnv } from "./browser-runtime.ts";export interface SignedInSite {@@ -209,6 +209,8 @@ function rewriteSavedState(directory: string, session: string, key: string, sitecatch (error) { if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error; }}}+ // The copies kept from before the browser sandbox's sessions hold the old logins too.+ removeSignInsBackups(directory, session);}/** A session's saved sign-ins (its newest restore file) and when they last changed, for the Cloud's browser sandbox to carry@@ -236,6 +238,66 @@ export function writeSignIns(directory: string, session: string, key: string, coreturn modified(path);}+// What a session in the Cloud's browser sandbox writes back is what its Chrome reports, so the home keeps the copy it had+// when each such session opened: a few, for a week, so the owner can put a session's sign-ins back as they were before it+// (routes/browser-sign-in-backups.ts). They are removed with the sign-ins (a sign-out, a reset, the bot's deletion).++/** Backups older than this are removed at the next backup. */+export const SIGN_IN_BACKUP_MS = 7 * 24 * 60 * 60_000;+/** At most this many per session, newest kept. */+export const SIGN_IN_BACKUPS_KEPT = 5;+/** And at most this many bytes of them per session, newest kept. */+export const SIGN_IN_BACKUPS_MAX_BYTES = 16 * 1024 * 1024;++export interface SignInBackup { id: string; takenAt: number; bytes: number }++/** The session's backups, newest first. */+export function signInBackups(directory: string, session: string): SignInBackup[] {+ let names: string[] = [];+ try { names = readdirSync(directory); } catch { return []; }+ return names.flatMap((name) => {+ const id = signInsBackupId(session, name);+ if (id === null) return [];+ try { return [{ id, takenAt: Number(id), bytes: statSync(join(directory, name)).size }]; } catch { return []; }+ }).sort((a, b) => b.takenAt - a.takenAt);+}++/** Old backups past the week, the count or the bytes, removed (newest kept). */+function pruneSignInBackups(directory: string, session: string, now: number): void {+ let bytes = 0;+ signInBackups(directory, session).forEach((backup, index) => {+ bytes += backup.bytes;+ const keep = index < SIGN_IN_BACKUPS_KEPT && now - backup.takenAt <= SIGN_IN_BACKUP_MS && (index === 0 || bytes <= SIGN_IN_BACKUPS_MAX_BYTES);+ if (keep) return;+ try { unlinkSync(join(directory, signInsBackupFile(session, backup.id))); }+ catch (error) { if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error; }+ });+}++/** The home's copy of the session's sign-ins kept as a backup now (a session in the browser sandbox opening). Returns its+ * id, or null when there is nothing readable to keep. */+export function backupSignIns(directory: string, session: string, key: string, now = Date.now()): string | null {+ const current = readSignIns(directory, session, key);+ if (!current || current === "unreadable") return null;+ const id = String(Math.max(1e12, Math.min(9_999_999_999_999, Math.floor(now))));+ const path = join(directory, signInsBackupFile(session, id));+ if (!existsSync(path)) writeState(path, current.state, key);+ pruneSignInBackups(directory, session, now);+ return id;+}++/** The session's sign-ins put back as one backup holds them. The copy they replace is kept as a backup first, so a restore+ * can itself be undone. False when there is no such backup or it cannot be read. */+export function restoreSignIns(directory: string, session: string, key: string, id: string, now = Date.now()): boolean {+ if (!/^\d{13}$/.test(id)) return false;+ let state: SavedState;+ try { state = readState(join(directory, signInsBackupFile(session, id)), key); } catch { return false; }+ backupSignIns(directory, session, key, Math.max(now, Number(id) + 1));+ mkdirSync(directory, { recursive: true, mode: 0o700 });+ writeState(join(directory, `${stateBases(session)[0]}.json.enc`), state, key);+ return true;+}+export function connectCdp(url: string, timeoutMs = 10_000, listeners: CdpListeners = {}): Promise<Cdp> {return new Promise((resolve, reject) => {const socket = new WebSocket(url);diff --git a/server/browser/engines.ts b/server/browser/engines.tsindex 00edc92e2b..a9b5770301 100644--- a/server/browser/engines.ts+++ b/server/browser/engines.ts@@ -245,6 +245,9 @@ export class ChromeEngine {export interface RuntimeRouterOptions {/** What a tool call is told instead of reaching either engine, or null to run it. */refusal?(session: string, spec: BrowserSpawnSpec, params: unknown): string | null;+ /** Asked next, only for a session it returns a check for (null runs the call as before): what a tool call is told after+ * a check that has to wait (a name looked up), or null to run it. */+ vet?(session: string, spec: BrowserSpawnSpec, params: unknown): Promise<string | null> | null;/** Asked next, before an opt-in engine's tool call that may open the session's browser: what it is told while the server* has no room to run one (a self-hosted server's pids limit), or null once it has. agent-browser's calls ask the same* room through its BrowserRoom, after its count of browsers. */@@ -275,6 +278,7 @@ export class RuntimeRouter {readonly #old: BrowserRuntime;readonly #chrome: ChromeEngine;readonly #refusal: RuntimeRouterOptions["refusal"];+ readonly #vet: RuntimeRouterOptions["vet"];readonly #room: RuntimeRouterOptions["room"];readonly #afterClaim: RuntimeRouterOptions["afterClaim"];readonly #annotate: RuntimeRouterOptions["annotate"];@@ -288,6 +292,7 @@ export class RuntimeRouter {this.#old = old;this.#chrome = chrome;this.#refusal = options.refusal;+ this.#vet = options.vet;this.#room = options.room;this.#afterClaim = options.afterClaim;this.#annotate = options.annotate;@@ -306,6 +311,9 @@ export class RuntimeRouter {};const refusal = method === "tools/call" ? this.#refusal?.(session, spec, params) : null;if (refusal) return refuse(refusal);+ const vetting = method === "tools/call" ? this.#vet?.(session, spec, params) ?? null : null;+ const vetted = vetting ? await vetting : null;+ if (vetted) return refuse(vetted);const full = method === "tools/call" && target ? await this.#room?.(session, spec, params) : null;if (full) return refuse(full, "no_room");const afterClaim = method === "tools/call" ? this.#afterClaim : undefined;diff --git a/server/cloud-browser/companion.ts b/server/cloud-browser/companion.tsindex f069b073fd..e63868745e 100644--- a/server/cloud-browser/companion.ts+++ b/server/cloud-browser/companion.ts@@ -8,8 +8,8 @@ import type { Cdp, CdpEvent } from "../browser-sites.ts";import { DOWNLOAD_LIMITS, safeFileName } from "../browser/cdp/downloads.ts";import type { CloudBrowserRails } from "./rails.ts";import type { ComputerOps } from "./remote.ts";-import { carryIn, carryOut, type SavedCookie } from "./sign-ins.ts";-import { mergeAtOpen, mergeInSession, prints, sandboxHolds, type SyncStore } from "./sync.ts";+import { carryIn, carryOut, cookieId, type SavedCookie } from "./sign-ins.ts";+import { agreed, MAX_SIGN_IN_BYTES, openMerge, prints, sandboxHolds, writeBack, type SyncStore } from "./sync.ts";/** Where a download lands in the bot's working folder. */export const DOWNLOADS_SUBFOLDER = "downloads";@@ -21,12 +21,15 @@ export const SESSION_DOWNLOAD_BYTES = 2 * 1024 ** 3;const KEEP_FREE_BYTES = 1024 ** 3;/** A long session's sign-ins are written home this often when they changed, so an unclean end loses minutes at most. */export const SIGN_IN_SYNC_MS = 10 * 60_000;+const MAX_SIGN_IN_MIB = MAX_SIGN_IN_BYTES / 1024 / 1024;export interface SignInStore {/** The home's saved sign-ins for a session, when they last changed; null when none; "unreadable" when not readable now. */load(session: string): { state: { cookies: unknown[]; origins: unknown[] }; modified: number } | null | "unreadable";/** The sandbox's cookies saved as the session's; returns when the file changed. */save(session: string, cookies: unknown[]): number;+ /** The home's copy kept as a backup as a session opens, before anything of the sandbox's is written to it. */+ backup?(session: string): void;}export interface CompanionDeps {@@ -80,6 +83,8 @@ export class SandboxCompanion {#baseline: SavedCookie[] | null = null;#syncedAt = 0;#syncing = false;+ /** Cookies of this session were left out of the home's copy (sync.ts's bounds): said once in the log. */+ #droppedLogged = false;constructor(deps: CompanionDeps) { this.#deps = deps; }@@ -95,6 +100,10 @@ export class SandboxCompanion {const { session, signIns } = this.#deps;const loaded = signIns ? signIns.load(session) : null;if (loaded === "unreadable") throw new SignInsUnreadable();+ if (signIns && loaded) {+ try { signIns.backup?.(session); }+ catch (error) { this.#deps.log(`browser ${session}: could not keep a backup of the home's sign-ins (${error instanceof Error ? error.name : "error"})`); }+ }this.#cdp = await this.#deps.connect(cdpUrl, { event: (message) => this.#event(message) });if (signIns) await this.#syncAtOpen(this.#cdp, signIns, loaded);this.#syncedAt = this.#now();@@ -108,7 +117,8 @@ export class SandboxCompanion {const last = sync.load(this.#stamp);const sandbox = await carryOut(cdp);const home = loaded?.state.cookies ?? [];- const { merged, fromSandbox } = mergeAtOpen(home, sandbox, last);+ const { merged, fromSandbox, dropped } = openMerge(home, sandbox, last);+ this.#leftOut(dropped);let homeAt = loaded?.modified ?? 0;if (fromSandbox > 0) {homeAt = signIns.save(session, merged);@@ -125,10 +135,17 @@ export class SandboxCompanion {this.#deps.log(`browser ${session}: carried ${took} of ${merged.length} saved cookies${carried.refused ? ` (${carried.refused} refused by Chrome)` : ""} and ${carried.origins} sites' storage into the browser sandbox`);}rails.setCarried(this.#stamp, homeAt);- sync.save(this.#stamp, { home: prints(merged), sandbox: prints(held) });+ sync.save(this.#stamp, { home: prints(merged), sandbox: agreed(held, dropped) });this.#baseline = held;}+ /** One log line a session, with the count, for cookies of the sandbox's left out of the home's copy. */+ #leftOut(dropped: readonly string[]): void {+ if (dropped.length === 0 || this.#droppedLogged) return;+ this.#droppedLogged = true;+ this.#deps.log(`browser ${this.#deps.session}: left ${dropped.length} of the browser sandbox's cookies out of the home's sign-ins: larger than a browser keeps, or past the ${MAX_SIGN_IN_MIB} MiB the home keeps`);+ }+/** Writes the session's own cookie changes into the home's copy: set, changed and removed since what Chrome really held* at the open (a cookie Chrome dropped by itself is no removal), except a cookie the home changed meanwhile. */async syncSignIns(): Promise<void> {@@ -141,10 +158,19 @@ export class SandboxCompanion {const home = signIns.load(session);if (home === "unreadable") return;const last = sync.load(this.#stamp);- const { merged, changed } = mergeInSession(home?.state.cookies ?? [], this.#baseline, current, last);- this.#baseline = current;+ const { merged, changed, dropped } = writeBack(home?.state.cookies ?? [], this.#baseline, current, last);+ this.#leftOut(dropped);+ // A cookie left out stays as it was in the baseline, so the next write-back weighs it again.+ const out = new Set(dropped);+ const before = new Map(this.#baseline.map((cookie) => [cookieId(cookie), cookie]));+ this.#baseline = current.flatMap((cookie) => {+ const id = cookieId(cookie);+ if (!out.has(id)) return [cookie];+ const was = before.get(id);+ return was ? [was] : [];+ });if (changed > 0) rails.setCarried(this.#stamp, signIns.save(session, merged));- sync.save(this.#stamp, { home: prints(merged), sandbox: prints(current) });+ sync.save(this.#stamp, { home: prints(merged), sandbox: agreed(current, dropped) });} finally {this.#syncing = false;}@@ -164,7 +190,8 @@ export class SandboxCompanion {if (size > UPLOAD_MAX_BYTES) return { error: `${shown} is over ${UPLOAD_MAX_BYTES / 1024 / 1024} MiB, which this browser can't take from the Cloud yet. Tell the person in one sentence and ask them to upload it themselves.` };const target = `${this.#deps.home}/.omb-browser/.uploads/${this.#deps.key}/${safeFileName(name ?? shown) || "upload"}`;const sent = await this.#deps.ops.sendFile(this.#deps.boxId, dirname(file), shown, target);- return "error" in sent ? { error: `${shown} could not be given to the browser: ${sent.error}` } : { path: target };+ if (!("error" in sent)) return { path: target };+ return { error: `${shown} could not be given to the browser: ${sent.error}${sent.final ? " Tell the person in one sentence and ask them to upload it themselves." : ""}` };}/** A clean close: downloads still waiting are tried once more, and the sandbox's cookies are saved as the home's. */@@ -232,6 +259,13 @@ export class SandboxCompanion {if (disk.free - pending.bytes < Math.max(KEEP_FREE_BYTES, disk.total / 10)) return failed("the Cloud's disk is too full for it");const to = unusedName(folder, pending.name);const fetched = await ops.fetchFile(boxId, `${this.downloadDir}/${pending.guid}`, folder, to).catch((error: unknown) => ({ error: error instanceof Error ? error.message : "it failed" }));+ if ("error" in fetched && "final" in fetched && fetched.final) {+ // Never copyable this way (too large while the sandbox takes no direct connections): not kept, nor tried again.+ this.#pending.delete(pending.guid);+ await ops.removeDownload(boxId, key, pending.guid).catch(() => undefined);+ this.#notes.push(`"${pending.name}" was downloaded in the browser but could not be brought to your working folder: ${fetched.error}`);+ return;+ }if ("error" in fetched) return failed(fetched.error);this.#pending.delete(pending.guid);this.#delivered += fetched.bytes;diff --git a/server/cloud-browser/guards.ts b/server/cloud-browser/guards.tsindex 252576a00c..ac08ef94fb 100644--- a/server/cloud-browser/guards.ts+++ b/server/cloud-browser/guards.ts@@ -1,5 +1,9 @@// 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.+import { lookup } from "node:dns/promises";+import { BlockList, isIP } from "node:net";++import { addressClass } from "../browser/egress/policy.ts";/** 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;@@ -17,3 +21,89 @@ function namesLocal(value: unknown, depth = 0): boolean {export function localSchemeRefusal(params: unknown): string | null {return namesLocal((params as { arguments?: unknown } | null)?.arguments) ? LOCAL_SCHEME_REFUSAL : null;}++// What a tool call for a browser in the sandbox may open, checked at the home before the call reaches it: the same address+// classes the home's own browsers are kept from (browser/egress/policy.ts), since the sandbox has its own loopback (every+// bot's Chrome and its debugging port), the provider's metadata address and its network. This checks only the call's own+// `url` arguments. It does not stop a page's redirects or its own requests, a link a bot clicks, script a bot runs in a+// page, or a name that resolves differently at the provider than here: nothing in the sandbox's Chrome blocks those today+// (its managed policy blocks only file://, chrome://, chrome-untrusted://, devtools:// and view-source:).++export const PRIVATE_ADDRESS_REFUSAL = "This browser opens public websites only: the browser computer's own services, local or private network addresses and cloud metadata addresses are not opened here.";+export const UNREADABLE_ADDRESS_REFUSAL = "This browser could not read that address. Give the full address, starting with https://.";++/** Names that are never a public website: loopback by rule, private-use and local top-level names, and the metadata services'. */+const LOCAL_NAME = /(?:^|\.)(?:localhost|local|localdomain|internal|intranet|lan|home\.arpa|corp)\.?$/i;+const METADATA_NAME = /^(?:metadata|metadata\.google\.internal|metadata\.goog|instance-data(?:\.ec2\.internal)?)\.?$/i;+const NETWORK_SCHEMES = new Set(["http:", "https:", "ws:", "wss:", "ftp:"]);+/** No address of this machine is "this machine" for a browser elsewhere: an empty list keeps every class as it is. */+const NO_OWN = new BlockList();+/** How long a call waits for the home's resolver on a name not asked in the last minute: past it the call goes ahead, and+ * the answer, when it comes, is kept for the rest of that minute. */+export const RESOLVE_MS = 1_500;+const RESOLVED_TTL_MS = 60_000;+const RESOLVED_MAX = 500;+/** Deeper than any tool's arguments go. */+const MAX_DEPTH = 12;++export type Resolve = (host: string) => Promise<readonly string[]>;+const systemResolve: Resolve = async (host) => (await lookup(host, { all: true, verbatim: true })).map((entry) => entry.address);++/** The addresses a call opens: every `url` argument, however deep. */+function opened(value: unknown, depth = 0, key = ""): string[] {+ if (typeof value === "string") return key === "url" ? [value] : [];+ if (depth > MAX_DEPTH || !value || typeof value !== "object") return [];+ return Object.entries(value as Record<string, unknown>).flatMap(([name, item]) => opened(item, depth + 1, Array.isArray(value) ? key : name));+}++/** The host a `url` value opens: written with a scheme (`http:127.0.0.1` included) it is read as it is; without one (or as+ * `host:port`) it is opened as https://. A value that is no address at all (about:blank, data:) opens no host. */+function hostOf(raw: string): { host: string } | "none" | "unreadable" {+ const text = raw.trim();+ if (!text) return "none";+ const hostAndPort = /^[a-z0-9.-]+:\d+(?:[/?#]|$)/i.test(text);+ const schemed = !hostAndPort && /^[a-z][a-z0-9+.-]*:/i.test(text);+ let url: URL;+ try { url = new URL(schemed ? text : `https://${text}`); } catch { return "unreadable"; }+ if (!NETWORK_SCHEMES.has(url.protocol)) return "none";+ const host = url.hostname.replace(/^\[|\]$/g, "").toLowerCase();+ return host ? { host } : "unreadable";+}++const publicAddress = (address: string) => addressClass(address, NO_OWN) === "public";++/** The refusal for a tool call that would open a non-public address from the sandbox, or null. Names are resolved by the+ * home's own resolver, all of a call's at once; answers (a failed one too) are kept a minute, and a late one is kept for+ * that minute when it comes. */+export function addressGuard(resolve: Resolve = systemResolve, now: () => number = Date.now, waitMs = RESOLVE_MS) {+ const resolved = new Map<string, { at: number; open?: boolean }>();+ async function nameOpens(host: string): Promise<boolean> {+ const known = resolved.get(host);+ // Still unanswered from an earlier call: not waited for again (the home cannot tell yet).+ if (known && now() - known.at < RESOLVED_TTL_MS) return known.open ?? true;+ const entry: { at: number; open?: boolean } = { at: now() };+ if (resolved.size >= RESOLVED_MAX) resolved.delete(resolved.keys().next().value!);+ resolved.set(host, entry);+ // Not resolvable here: the home cannot tell, so it does not refuse.+ const answer = resolve(host).then((addresses) => addresses.every(publicAddress), () => true)+ .then((open) => { entry.open = open; return open; });+ let timer: ReturnType<typeof setTimeout> | undefined;+ const late = new Promise<null>((done) => { timer = setTimeout(() => done(null), waitMs); timer.unref?.(); });+ const open = await Promise.race([answer, late]).finally(() => clearTimeout(timer));+ return open ?? true;+ }+ return async (params: unknown): Promise<string | null> => {+ const names = new Set<string>();+ for (const raw of opened((params as { arguments?: unknown } | null)?.arguments)) {+ const read = hostOf(raw);+ if (read === "none") continue;+ if (read === "unreadable") return UNREADABLE_ADDRESS_REFUSAL;+ const { host } = read;+ if (isIP(host)) { if (!publicAddress(host)) return PRIVATE_ADDRESS_REFUSAL; continue; }+ if (!host.includes(".") || LOCAL_NAME.test(host) || METADATA_NAME.test(host)) return PRIVATE_ADDRESS_REFUSAL;+ names.add(host.replace(/\.$/, ""));+ }+ const answers = await Promise.all([...names].map(nameOpens));+ return answers.every(Boolean) ? null : PRIVATE_ADDRESS_REFUSAL;+ };+}diff --git a/server/cloud-browser/hardening.test.ts b/server/cloud-browser/hardening.test.tsnew file mode 100644index 0000000000..24c6b20e89--- /dev/null+++ b/server/cloud-browser/hardening.test.ts@@ -0,0 +1,631 @@+// What the home keeps from a browser sandbox it does not control: the sign-ins it writes back, the addresses a call opens,+// a deleted bot's profile in a sandbox that sleeps, a sandbox that can never resume, and files of a sandbox that takes no+// direct connections. Only the fake relay and provider+// (testing/fake-computer.ts) and temporary folders: never a real sandbox or provider.+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++import type { AppConfig } from "../config.ts";+import { signInsBackupFile } from "../browser-engine.ts";+import { backupSignIns, decryptBrowserState, readSignIns, restoreSignIns, signInBackups, signOutOfSites, writeSignIns } from "../browser-sites.ts";+import { createSignInBackupRoutes } from "../routes/browser-sign-in-backups.ts";+import { RuntimeRouter } from "../browser/engines.ts";+import type { BrowserRuntime } from "../browser-runtime.ts";+import type { ChromeEngine } from "../browser/engines.ts";+import { SIGN_IN_SYNC_MS, type SignInStore } from "./companion.ts";+import { INLINE_READ_MAX_BYTES, INLINE_WRITE_MAX_BYTES } from "../cloud-computer-files.ts";+import { addressGuard, PRIVATE_ADDRESS_REFUSAL, UNREADABLE_ADDRESS_REFUSAL } from "./guards.ts";+import { CLOUD_BROWSER_IDLE_MS, createCloudBrowser, REOPENED_NOTE, type CloudBrowserDeps } from "./index.ts";+import { createCloudBrowserRails } from "./rails.ts";+import { profileKey, providerOps } from "./remote.ts";+import type { SavedCookie } from "./sign-ins.ts";+import { agreed, MAX_COOKIE_BYTES, MAX_SIGN_IN_BYTES, mergeAtOpen, mergeInSession, openMerge, prints, writeBack } from "./sync.ts";+import { RELAY_KEY, startFakeComputer, type FakeComputer } from "./testing/fake-computer.ts";++let fake: FakeComputer;+let dir: string;+let clock: number;+let used: Array<[string, number]>;+let lines: string[];+let browsers: ReturnType<typeof createCloudBrowser>[];++beforeEach(async () => {+ fake = await startFakeComputer();+ vi.stubEnv("OMB_CLOUD_BOAT_URL", `${fake.base}/api/v1`);+ vi.stubEnv("OMB_CLOUD_BOAT_TOKEN", RELAY_KEY);+ vi.stubEnv("OMB_CLOUD_BROWSER", undefined);+ dir = mkdtempSync(join(tmpdir(), "cloud-browser-hardening-"));+ clock = Date.UTC(2026, 10, 27, 10, 0, 0);+ used = [];+ lines = [];+ browsers = [];+});++afterEach(async () => {+ for (const browser of browsers) browser.closeAll();+ vi.unstubAllEnvs();+ await fake.close();+ rmSync(dir, { recursive: true, force: true });+});++function browser(overrides: Partial<CloudBrowserDeps> & { budget?: number } = {}) {+ const now = () => clock;+ const { budget, ...rest } = overrides;+ const created = createCloudBrowser({+ dataDir: dir,+ ops: () => providerOps(() => ({}) as AppConfig),+ used: (owner, windowMs) => { used.push([owner, windowMs]); },+ closeEngine: async () => undefined,+ held: () => false,+ now,+ log: (line) => lines.push(line),+ pollMs: 5,+ rails: createCloudBrowserRails({ dataDir: dir, now, ...(budget ? { budget } : {}) }),+ disk: () => ({ free: 100 * 1024 ** 3, total: 200 * 1024 ** 3 }),+ ...rest,+ });+ browsers.push(created);+ return created;+}++const request = (botId = "scout") => ({ session: `bot-${botId}`, botId, refusal: null });+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");++/** The home's saved sign-ins in memory, as the restore file holds them; `writes` is what each save was given. */+function memorySignIns(initial: { cookies: unknown[]; origins: unknown[] } | null) {+ let saved = initial;+ let modified = initial ? 1_000 : 0;+ const writes: unknown[][] = [];+ const counts = { backups: 0 };+ const store: SignInStore = {+ load: () => (saved === null ? null : { state: saved, modified }),+ save: (_session, cookies) => { writes.push(cookies); saved = { cookies, origins: saved?.origins ?? [] }; modified += 1; return modified; },+ backup: () => { counts.backups += 1; },+ };+ return { store, writes, cookies: () => (saved?.cookies ?? []) as SavedCookie[], get backups() { return counts.backups; } };+}++const cookie = (name: string, domain: string, value = "v"): SavedCookie => ({ name, value, domain, path: "/", secure: true });+/** A home signed in on many sites, as a bot that browses daily is. */+const manySites = (count: number) => Array.from({ length: count }, (_, i) => cookie(`sid${i}`, `site${i}.example`, `value${i}`));+/** The sandbox Chrome's cookies for a profile, as a page (or whoever controls that Chrome) left them. */+const holds = (key: string, cookies: SavedCookie[]) => fake.cookies.set(key, cookies.map((one) => ({ ...one }) as Record<string, unknown>));+/** What Chrome hands back for a cookie it holds: its own shape, as the fake reports it. */+const asChrome = (one: SavedCookie) => ({ ...one, size: 1, session: true, expires: -1 });++/** Ends the session cleanly, so its sign-ins are written back. */+async function closeSession(cloud: ReturnType<typeof browser>) {+ clock += CLOUD_BROWSER_IDLE_MS;+ await cloud.closeIdle();+}++describe("what the sandbox writes back into the home's sign-ins", () => {+ it("a normal session's write-back is exactly what it was before these bounds", () => {+ const home = [cookie("sid", ".example.com", "s1"), cookie("keep", "keep.example", "home"), cookie("gone", "gone.example")];+ const baseline = home.map(asChrome);+ const current = [asChrome(cookie("sid", ".example.com", "s2")), asChrome(cookie("keep", "keep.example", "home")), asChrome(cookie("new", "new.example", "n"))];+ const last = { home: prints(home), sandbox: prints(baseline) };+ for (const state of [last, null]) {+ const back = writeBack(home, baseline, current, state);+ expect(JSON.stringify({ merged: back.merged, changed: back.changed })).toBe(JSON.stringify(mergeInSession(home, baseline, current, state)));+ expect(back.dropped).toEqual([]);+ const open = openMerge(home, current, state);+ expect(JSON.stringify({ merged: open.merged, fromSandbox: open.fromSandbox })).toBe(JSON.stringify(mergeAtOpen(home, current, state)));+ expect(open.dropped).toEqual([]);+ }+ });++ it("a normal session through the sandbox saves byte for byte what the old merge gives", async () => {+ const start = [cookie("sid", ".example.com", "s1"), cookie("keep", "keep.example", "home")];+ const home = memorySignIns({ cookies: start, origins: [] });+ const cloud = browser({ signIns: home.store });+ urlOf(await cloud.open(request()));+ const key = profileKey("scout");+ const baseline = (fake.cookies.get(key) ?? []).map((one) => asChrome(one as unknown as SavedCookie));+ const changed = [{ name: "sid", value: "s2", domain: ".example.com", path: "/", secure: true }, { name: "new", value: "n", domain: "new.example", path: "/" }];+ fake.cookies.set(key, changed);+ const expected = mergeInSession(start, baseline, changed.map((one) => asChrome(one as SavedCookie)), { home: prints(start), sandbox: prints(baseline) }).merged;+ await closeSession(cloud);+ expect(home.writes).toHaveLength(1);+ expect(JSON.stringify(home.writes[0])).toBe(JSON.stringify(expected));+ });++ it("honours a sign-out of a big site: its cookies are gone at home, never carried back in, and the session's new sign-ins come home", async () => {+ const big = Array.from({ length: 14 }, (_, i) => cookie(`s${i}`, ".bigsite.example", `b${i}`));+ const others = manySites(10);+ const home = memorySignIns({ cookies: [...big, ...others], origins: [] });+ const cloud = browser({ signIns: home.store });+ urlOf(await cloud.open(request()));+ const key = profileKey("scout");+ expect(fake.cookies.get(key)).toHaveLength(24);+ // The bot signs out of the big site (14 of the 24 cookies go) and signs in somewhere new.+ holds(key, [...others, cookie("fresh", "new.example", "n1")]);+ await closeSession(cloud);+ expect(home.cookies().map((one) => one.name).sort()).toEqual([...others.map((one) => one.name), "fresh"].sort());+ expect(lines.filter((line) => line.includes("left") && line.includes("out of the home's sign-ins"))).toEqual([]);+ // The next open carries nothing of the big site back into the sandbox.+ urlOf(await cloud.open(request()));+ expect((fake.cookies.get(key) ?? []).some((one) => one.domain === ".bigsite.example")).toBe(false);+ expect((fake.cookies.get(key) ?? []).map((one) => one.name)).toContain("fresh");+ });++ it("keeps one backup of the home's copy as each session opens, and none at a write-back", async () => {+ const home = memorySignIns({ cookies: manySites(3), origins: [] });+ const cloud = browser({ signIns: home.store, held: () => true });+ urlOf(await cloud.open(request()));+ expect(home.backups).toBe(1);+ holds(profileKey("scout"), manySites(2));+ clock += SIGN_IN_SYNC_MS;+ await cloud.closeIdle();+ expect(home.writes, "a periodic write-back went home").toHaveLength(1);+ expect(home.backups, "no backup at a write-back").toBe(1);+ await cloud.close("bot-scout");+ urlOf(await cloud.open(request()));+ expect(home.backups, "one per session").toBe(2);+ // A home with nothing saved yet has nothing to keep.+ const empty = memorySignIns(null);+ const other = browser({ signIns: empty.store });+ await cloud.close("bot-scout");+ urlOf(await other.open(request("writer")));+ expect(empty.backups).toBe(0);+ });++ it("keeps a week of backups, five at most, restores one, and removes them all at a sign-out", async () => {+ const root = mkdtempSync(join(tmpdir(), "omb-sign-ins-backup-"));+ try {+ const directory = join(root, ".agent-browser", "sessions");+ const key = "a".repeat(64);+ const day = 24 * 60 * 60_000;+ const start = Date.UTC(2026, 10, 1);+ writeSignIns(directory, "bot-scout", key, [cookie("first", "a.example")]);+ const firstId = backupSignIns(directory, "bot-scout", key, start)!;+ const backup = join(directory, signInsBackupFile("bot-scout", firstId));+ expect(readFileSync(backup).toString("utf8"), "encrypted").not.toContain("first");+ expect(JSON.parse(decryptBrowserState(readFileSync(backup), key)).cookies).toEqual([cookie("first", "a.example")]);+ // A session that wiped the sign-ins, then the owner puts them back.+ writeSignIns(directory, "bot-scout", key, []);+ expect(restoreSignIns(directory, "bot-scout", key, firstId, start + 1_000)).toBe(true);+ expect(readSignIns(directory, "bot-scout", key)).toMatchObject({ state: { cookies: [cookie("first", "a.example")] } });+ expect(signInBackups(directory, "bot-scout").map((one) => one.id), "the wiped copy was kept too, so the restore can be undone").toHaveLength(2);+ expect(restoreSignIns(directory, "bot-scout", key, "1234567890123")).toBe(false);+ // Older than a week, or past five: removed at the next backup.+ for (let i = 1; i <= 7; i++) backupSignIns(directory, "bot-scout", key, start + i * day);+ const kept = signInBackups(directory, "bot-scout");+ expect(kept).toHaveLength(5);+ expect(kept[0]!.takenAt).toBe(start + 7 * day);+ expect(kept.every((one) => one.takenAt >= start + 3 * day)).toBe(true);+ // Another session's backups are its own.+ writeSignIns(directory, "bot-scout-2", key, [cookie("x", "x.example")]);+ backupSignIns(directory, "bot-scout-2", key, start + 7 * day);+ await signOutOfSites({ binaryPath: "/fake/agent-browser", session: "bot-scout", env: { HOME: root, USERPROFILE: root }, encryptionKey: key }, null, { engine: async () => null });+ expect(signInBackups(directory, "bot-scout")).toEqual([]);+ expect(signInBackups(directory, "bot-scout-2")).toHaveLength(1);+ } finally {+ rmSync(root, { recursive: true, force: true });+ }+ });++ it("the owner's routes list a bot's backups and restore one; nobody else's do", async () => {+ const restored: Array<[string, string]> = [];+ const route = createSignInBackupRoutes({+ isOwner: (auth) => (auth as unknown as { owner: boolean }).owner,+ backups: (botId) => (botId === "scout" ? [{ id: "1764200000000", takenAt: 1764200000000, bytes: 512 }] : null),+ restore: async (botId, id) => { restored.push([botId, id]); return botId === "scout" ? (id === "1764200000000" ? "restored" : "no-backup") : "no-bot"; },+ });+ const call = async (method: string, path: string, owner: boolean, body?: unknown) => {+ const replies: Array<{ status: number; body: unknown }> = [];+ await route({ req: {} as never, res: {} as never, url: new URL(`http://x${path}`), path, method, auth: { owner } as never,+ json: ((_res: unknown, status: number, sent: unknown) => { replies.push({ status, body: sent }); }) as never, readBody: (async () => body) as never });+ return replies[0];+ };+ expect(await call("GET", "/api/bots/scout/browser-sign-ins/backups", true)).toEqual({ status: 200, body: { backups: [{ id: "1764200000000", takenAt: "2025-11-26T23:33:20.000Z", bytes: 512 }] } });+ expect((await call("GET", "/api/bots/scout/browser-sign-ins/backups", false))?.status).toBe(403);+ expect((await call("POST", "/api/bots/scout/browser-sign-ins/restore", false, { backup: "1764200000000" }))?.status).toBe(403);+ expect(await call("POST", "/api/bots/scout/browser-sign-ins/restore", true, { backup: "1764200000000" })).toEqual({ status: 200, body: { ok: true } });+ expect((await call("POST", "/api/bots/scout/browser-sign-ins/restore", true, { backup: "nope" }))?.status).toBe(400);+ expect((await call("GET", "/api/bots/ghost/browser-sign-ins/backups", true))?.status).toBe(404);+ expect(restored).toEqual([["scout", "1764200000000"]]);+ });++ it("never brings home a cookie no real Chrome holds, and keeps the home's value of one replaced by such a cookie", async () => {+ const home = memorySignIns({ cookies: [cookie("sid", ".example.com", "s1")], origins: [] });+ const cloud = browser({ signIns: home.store });+ urlOf(await cloud.open(request()));+ const huge = "x".repeat(MAX_COOKIE_BYTES);+ holds(profileKey("scout"), [cookie("sid", ".example.com", huge), cookie("new", "new.example", huge), cookie("fine", "fine.example", "ok")]);+ await closeSession(cloud);+ expect(home.cookies().map((one) => [one.name, one.value])).toEqual([["sid", "s1"], ["fine", "ok"]]);+ });++ /** Three hostile domains of 180 cookies of 4 KB each: past the cap together. */+ const flood = () => ["a", "b", "c"].flatMap((site) => Array.from({ length: 180 }, (_, i) => cookie(`f${i}`, `${site}.flood.example`, "y".repeat(4_000))));++ it("past the cap, leaves out the largest cookies of hosts the home never had, and still brings a real sign-in home", async () => {+ const start = [cookie("sid", ".example.com", "s1")];+ const home = memorySignIns({ cookies: start, origins: [] });+ const cloud = browser({ signIns: home.store });+ urlOf(await cloud.open(request()));+ const key = profileKey("scout");+ holds(key, [...start, cookie("session", "bank.example", "signed-in"), ...flood()]);+ await closeSession(cloud);+ const saved = home.cookies();+ expect(saved.map((one) => one.name)).toEqual(expect.arrayContaining(["sid", "session"]));+ const size = saved.reduce((sum, one) => sum + one.name.length + one.value.length, 0);+ expect(size).toBeLessThanOrEqual(MAX_SIGN_IN_BYTES);+ expect(saved.length, "only as many left out as the cap needs").toBeGreaterThan(500);+ expect(lines.filter((line) => line.includes("out of the home's sign-ins"))).toEqual([expect.stringMatching(/^browser bot-scout: left \d+ of the browser sandbox's cookies out of the home's sign-ins/)]);+ });++ it("never records a cookie it left out as agreed, so it is weighed again at the next open", () => {+ const home = [cookie("sid", ".example.com", "s1")];+ const sandbox = [...home, cookie("session", "bank.example", "signed-in"), ...flood()];+ const { merged, dropped } = openMerge(home, sandbox, null);+ expect(merged.map((one) => one.name)).toContain("session");+ expect(dropped.length).toBeGreaterThan(0);+ const recorded = agreed(sandbox, dropped);+ for (const id of dropped) expect(recorded[id]).toBeUndefined();+ expect(Object.keys(recorded).length).toBe(sandbox.length - dropped.length);+ // A home copy already past the cap is never made unwritable (a change that does not grow it goes through), and it is+ // never grown further.+ const bigHome = flood();+ const baseline = bigHome.map(asChrome);+ const shorter = [asChrome({ ...bigHome[0]!, value: "short" }), ...baseline.slice(1)];+ expect(writeBack(bigHome, baseline, shorter, null).merged[0]!.value).toBe("short");+ const grown = writeBack(bigHome, baseline, [...baseline, asChrome(cookie("new", "new.example", "n"))], null);+ expect(grown.merged.map((one) => one.name)).not.toContain("new");+ expect(grown.merged).toHaveLength(bigHome.length);+ });+});++describe("the addresses a call in the sandbox may open", () => {+ const open = (url: string) => ({ name: "agent_browser_open", arguments: { url } });+ const answers: Record<string, string[]> = { "public.example": ["93.184.215.14"], "rebind.example": ["93.184.215.14", "10.0.0.5"], "loop.example": ["127.0.0.1"] };+ const resolve = vi.fn(async (host: string) => answers[host] ?? Promise.reject(new Error("ENOTFOUND")));++ it("refuses loopback, link-local, private, metadata and reserved addresses however they are written", async () => {+ const guard = addressGuard(resolve);+ for (const url of ["http://127.0.0.1:9222/json/list", "127.1:9222", "http://2130706433/", "http://0x7f.1/", "http://[::1]:9222/", "http://[::ffff:127.0.0.1]/",+ "http://169.254.169.254/latest/meta-data/", "http://100.100.100.200/", "http://[fd00:ec2::254]/", "http://10.1.2.3/", "https://192.168.0.1/", "http://172.16.0.9/",+ "http://100.64.0.1/", "http://[fdaa::1]/", "http://[fe80::1]/", "http://0.0.0.0:8080/", "ws://127.0.0.1:39231/x", "http:127.0.0.1", "https:127.0.0.1/json", "localhost:9222"]) {+ expect(await guard(open(url)), url).toBe(PRIVATE_ADDRESS_REFUSAL);+ }+ });++ it("refuses names that are never a public site, and names the home resolves to such an address", async () => {+ const guard = addressGuard(resolve);+ for (const url of ["http://localhost:9222/", "https://LOCALHOST./", "http://app.localhost/", "http://metadata.google.internal/computeMetadata/v1/", "http://metadata/",+ "http://router/", "http://printer.local/", "http://db.internal/", "https://rebind.example/", "https://loop.example/", "http://metadata.goog/computeMetadata/v1/"]) {+ expect(await guard(open(url)), url).toBe(PRIVATE_ADDRESS_REFUSAL);+ }+ expect(await guard({ name: "agent_browser_tab_new", arguments: { options: { url: "http://127.0.0.1/" } } }), "however deep").toBe(PRIVATE_ADDRESS_REFUSAL);+ expect(await guard({ name: "agent_browser_batch", arguments: { steps: [{ a: { b: { c: { d: { e: { url: "http://169.254.169.254/" } } } } } }] } }), "deeper still").toBe(PRIVATE_ADDRESS_REFUSAL);+ });++ it("refuses a url it cannot read", async () => {+ const guard = addressGuard(resolve);+ for (const url of ["exa mple.com", "http://[::1", "https://"]) expect(await guard(open(url)), url).toBe(UNREADABLE_ADDRESS_REFUSAL);+ });++ it("opens public sites, and never refuses text a page is given", async () => {+ const guard = addressGuard(resolve);+ expect(await guard(open("https://public.example/path"))).toBeNull();+ expect(await guard(open("public.example"))).toBeNull();+ expect(await guard(open("https://93.184.215.14/"))).toBeNull();+ expect(await guard(open("http://[2606:4700:4700::1111]/")), "a public IPv6 address").toBeNull();+ expect(await guard(open("about:blank"))).toBeNull();+ expect(await guard({ name: "agent_browser_fill", arguments: { selector: "#q", text: "http://127.0.0.1:9222" } })).toBeNull();+ expect(await guard({ name: "agent_browser_snapshot", arguments: {} })).toBeNull();+ });++ it("goes ahead when the home cannot resolve a name, or not in time, and keeps every answer a minute, a late one too", async () => {+ let now = 0;+ let answerSlow: (addresses: string[]) => void = () => {};+ const slow = vi.fn((host: string) => (host === "slow.example" ? new Promise<string[]>((done) => { answerSlow = done; }) : resolve(host)));+ const guard = addressGuard(slow, () => now, 20);+ expect(await guard(open("https://unknown.example/"))).toBeNull();+ expect(await guard(open("https://unknown.example/again")), "a failed answer is kept").toBeNull();+ expect(slow.mock.calls.filter(([host]) => host === "unknown.example")).toHaveLength(1);+ expect(await guard(open("https://slow.example/")), "not answered in time: goes ahead").toBeNull();+ expect(await guard(open("https://slow.example/b")), "still unanswered: not waited for again").toBeNull();+ answerSlow(["10.0.0.7"]);+ await Promise.resolve();+ await Promise.resolve();+ expect(await guard(open("https://slow.example/c")), "the late answer counts for the rest of the minute").toBe(PRIVATE_ADDRESS_REFUSAL);+ expect(slow.mock.calls.filter(([host]) => host === "slow.example")).toHaveLength(1);+ await guard(open("https://rebind.example/a"));+ await guard(open("https://rebind.example/b"));+ expect(slow.mock.calls.filter(([host]) => host === "rebind.example")).toHaveLength(1);+ now += 60_000;+ await guard(open("https://rebind.example/c"));+ expect(slow.mock.calls.filter(([host]) => host === "rebind.example")).toHaveLength(2);+ });++ it("asks for every name of a call at once", async () => {+ let asking = 0;+ let most = 0;+ const counting: Parameters<typeof addressGuard>[0] = async (host) => {+ asking += 1;+ most = Math.max(most, asking);+ await new Promise((done) => setImmediate(done));+ asking -= 1;+ return host === "loop.example" ? ["127.0.0.1"] : ["93.184.215.14"];+ };+ const guard = addressGuard(counting);+ expect(await guard({ name: "agent_browser_batch", arguments: { steps: [{ url: "https://one.example/" }, { url: "https://two.example/" }, { url: "https://loop.example/" }] } })).toBe(PRIVATE_ADDRESS_REFUSAL);+ expect(most).toBe(3);+ });++ it("is asked only for a session it checks, before the call reaches the engine", async () => {+ const reached: unknown[] = [];+ const old = { agentRpc: vi.fn(async (_session: string, _spec: unknown, _method: string, params: unknown) => { reached.push(params); return "agent-browser"; }) };+ const guard = addressGuard(resolve);+ const runtime = new RuntimeRouter(old as unknown as BrowserRuntime, {} as ChromeEngine, { vet: (session, _spec, params) => (session === "sandbox" ? guard(params) : null) });+ const spec = { command: "/opt/agent-browser", args: [], env: {} };+ expect(await runtime.agentRpc("sandbox", spec, "tools/call", open("http://127.0.0.1:9222/json"))).toEqual({ isError: true, content: [{ type: "text", text: PRIVATE_ADDRESS_REFUSAL }] });+ expect(reached).toEqual([]);+ expect(await runtime.agentRpc("home", spec, "tools/call", open("http://127.0.0.1:3000/"))).toBe("agent-browser");+ expect(await runtime.agentRpc("sandbox", spec, "tools/call", open("https://public.example/"))).toBe("agent-browser");+ });+});++describe("a deleted bot's profile in a sandbox that sleeps", () => {+ /** Opens each bot's browser once (its profile and sign-ins in the sandbox), then lets the sandbox sleep. */+ async function profiles(cloud: ReturnType<typeof browser>, bots: string[]) {+ for (const bot of bots) urlOf(await cloud.open(request(bot)));+ await closeSession(cloud);+ fake.state = "archived";+ }++ it("deletes the whole sandbox when the last bot with a profile in it is deleted, without waking it", async () => {+ const cloud = browser({ signIns: memorySignIns(null).store });+ await profiles(cloud, ["scout"]);+ await cloud.erase("scout");+ await cloud.erased();+ expect(deletes()).toHaveLength(1);+ expect(fake.resumes(), "never woken for it").toBe(0);+ expect(lines).toContain("browser sandbox: deleted: no bot with a browser profile is left in it");+ // The next browser makes a fresh sandbox; nothing is left to erase.+ urlOf(await cloud.open(request("writer")));+ expect(fake.creates()).toBe(1);+ expect(fake.erased).toEqual([]);+ });++ it("wakes the sandbox once to erase it while other bots keep profiles there, and lets it sleep again", async () => {+ const cloud = browser({ signIns: memorySignIns(null).store });+ await profiles(cloud, ["scout", "writer"]);+ used = [];+ await cloud.erase("scout");+ await cloud.erased();+ expect(fake.erased).toEqual([profileKey("scout")]);+ expect(fake.resumes()).toBe(1);+ expect(deletes()).toEqual([]);+ expect(used.at(-1), "asked to sleep once the erase is done").toEqual(["browser", 1_000]);+ expect(cloud.busy("browser")).toBe(false);+ });++ it("when no start may be sent now, keeps the erase for the next wake", async () => {+ const cloud = browser({ signIns: memorySignIns(null).store, budget: 1 });+ fake.state = "archived";+ urlOf(await cloud.open(request("scout")));+ urlOf(await cloud.open(request("writer")));+ await closeSession(cloud);+ fake.state = "archived";+ await cloud.erase("scout");+ await cloud.erased();+ expect(fake.resumes(), "the day's one start was spent").toBe(1);+ expect(fake.erased).toEqual([]);+ clock += 24 * 60 * 60_000;+ urlOf(await cloud.open(request("writer")));+ expect(fake.erased).toEqual([profileKey("scout")]);+ });++ it("an open that comes while the sandbox is being deleted waits for it, then makes a fresh one: never resumes the one going", async () => {+ // The delete is held until the open has come: the open must wait for it.+ const real = providerOps(() => ({}) as AppConfig);+ let release: () => void = () => {};+ const gate = new Promise<void>((done) => { release = done; });+ let removing = false;+ const ops = { ...real, remove: async (id: string) => { removing = true; await gate; return real.remove(id); } };+ const cloud = browser({ signIns: memorySignIns(null).store, ops: () => ops });+ await profiles(cloud, ["scout"]);+ const first = fake.boxId;+ await cloud.erase("scout");+ await vi.waitFor(() => expect(removing).toBe(true));+ const opened = cloud.open(request("writer"));+ await new Promise((done) => setTimeout(done, 20));+ expect(fake.resumes(), "nothing sent while the delete is under way").toBe(0);+ release();+ urlOf(await opened);+ await cloud.erased();+ expect(deletes().map((one) => one.path)).toEqual([`/api/v1/sandboxes/${first}`]);+ expect(fake.resumes(), "the sandbox being deleted was never woken").toBe(0);+ expect(fake.creates()).toBe(1);+ expect(fake.boxId).not.toBe(first);+ expect(cloud.active("bot-writer")).not.toBeNull();+ });++ it("a bot that never had a profile there wakes nothing and deletes nothing", async () => {+ const cloud = browser({ signIns: memorySignIns(null).store });+ await profiles(cloud, ["scout"]);+ await cloud.erase("writer");+ await cloud.erased();+ expect(fake.resumes()).toBe(0);+ expect(deletes()).toEqual([]);+ });+});++describe("a sandbox that can never resume", () => {+ it("is replaced at once by a fresh one under one counted start, with no back-off and no word to the bot but the reopened note", async () => {+ const cloud = browser({ signIns: memorySignIns({ cookies: [cookie("sid", ".example.com", "s1")], origins: [] }).store });+ urlOf(await cloud.open(request()));+ const first = fake.boxId;+ // Stopped under the session (a plan's sandbox that keeps nothing): the session ends, and its next call opens again.+ fake.state = "archived";+ fake.resumeGone = true;+ await cloud.failed("bot-scout");+ expect(cloud.takeNotes("bot-scout")).toEqual([REOPENED_NOTE]);+ urlOf(await cloud.open(request()));+ expect(fake.boxId).not.toBe(first);+ expect(deletes().map((one) => one.path)).toEqual([`/api/v1/sandboxes/${first}`]);+ expect(fake.resumes()).toBe(1);+ expect(fake.creates()).toBe(1);+ expect(cloud.report()).toMatchObject({ resumes: 1, held: null, fallbacks: {} });+ // The fresh, empty profile gets the home's copy.+ expect(fake.cookies.get(profileKey("scout"))).toEqual([expect.objectContaining({ name: "sid", value: "s1" })]);+ expect(cloud.takeNotes("bot-scout")).toEqual([]);+ });++ it("goes the same way when it is found still stopping", async () => {+ fake.state = "archiving";+ fake.resumeGone = true;+ const cloud = browser();+ urlOf(await cloud.open(request()));+ expect(deletes()).toHaveLength(1);+ expect(fake.creates()).toBe(1);+ expect(cloud.report()).toMatchObject({ resumes: 1, held: null });+ });++ it("today's control plane answers a resume of an ended sandbox 503 no_ready_machine: that browser opens in the home with nothing held against it, and the next open makes a fresh one", async () => {+ const cloud = browser();+ fake.state = "archived";+ fake.startStatus = 503;+ fake.startBody = { ok: false, error: { code: "no_ready_machine", message: "No machine is ready." } };+ expect(await cloud.open(request())).toEqual({ home: "no-machine" });+ // The relay then leaves the ended sandbox out of the list.+ fake.exists = false;+ fake.startStatus = 200;+ fake.startBody = { ok: true };+ const first = fake.boxId;+ urlOf(await cloud.open(request()));+ expect(fake.creates()).toBe(1);+ expect(cloud.report()).toMatchObject({ held: null, fallbacks: { "no-machine": 1 } });+ expect(deletes(), "nothing to delete: the relay ended it").toEqual([]);+ expect(first).toBeTruthy();+ });++ it("every other refusal of a resume is what it was: a 410 without that code is a failed start", async () => {+ fake.state = "archived";+ fake.startStatus = 410;+ fake.startBody = { ok: false, error: { code: "gone", message: "Gone." } };+ const cloud = browser();+ expect(await cloud.open(request())).toEqual({ home: "start-failed" });+ expect(await cloud.open(request())).toEqual({ home: "start-failed" });+ expect(await cloud.open(request())).toEqual({ home: "backoff" });+ expect(deletes()).toEqual([]);+ expect(fake.creates()).toBe(0);+ });+});++describe("files of a sandbox that takes no direct connections", () => {+ let folder: string;+ beforeEach(() => { folder = mkdtempSync(join(tmpdir(), "bot-folder-")); fake.inbound = "boat-only"; });+ afterEach(() => { rmSync(folder, { recursive: true, force: true }); });++ const downloadPath = (guid: string) => `/home/user/.omb-browser/.downloads/${profileKey("scout")}/${guid}`;+ const finish = (guid: string, name: string, bytes: Buffer) => {+ fake.files.set(downloadPath(guid), bytes);+ fake.emit(profileKey("scout"), "Browser.downloadWillBegin", { guid, suggestedFilename: name, url: "https://files.example/x" });+ fake.emit(profileKey("scout"), "Browser.downloadProgress", { guid, totalBytes: bytes.length, receivedBytes: bytes.length, state: "completed" });+ };+ const fileCalls = () => fake.requests.filter((one) => one.path.endsWith("/files")).map((one) => one.method);+ const tooLarge = (name: string, size: string) => `${name} (${size}) is too large to copy: this browser's sandbox takes no direct connections, so a file moves to it in one piece of at most about 1.5 MiB.`;++ it("brings a download over through the provider's JSON file read, byte for byte, and removes it from the sandbox", async () => {+ const cloud = browser({ folder: () => folder });+ urlOf(await cloud.open(request()));+ const bytes = Buffer.from(Array.from({ length: 70_000 }, (_, i) => i % 256));+ finish("0f3e2a1b-guid", "report.pdf", bytes);+ await vi.waitFor(() => expect(existsSync(join(folder, "downloads", "report.pdf"))).toBe(true));+ expect(readFileSync(join(folder, "downloads", "report.pdf"))).toEqual(bytes);+ await vi.waitFor(() => expect(fake.files.has(downloadPath("0f3e2a1b-guid"))).toBe(false));+ expect(cloud.takeNotes("bot-scout")).toEqual([`Downloaded "report.pdf" into your working folder as ${join("downloads", "report.pdf")} (${bytes.length} bytes).`]);+ expect(fileCalls()).toEqual(["GET"]);+ });++ it("says plainly that a download over 5 MiB can't be brought over, and neither keeps it nor tries it again", async () => {+ const cloud = browser({ folder: () => folder });+ urlOf(await cloud.open(request()));+ finish("big-guid", "video.mp4", Buffer.alloc(INLINE_READ_MAX_BYTES + 1));+ await vi.waitFor(() => expect(cloud.takeNotes("bot-scout")).toEqual([`"video.mp4" was downloaded in the browser but could not be brought to your working folder: ${downloadPath("big-guid")} is too large to copy: this browser's sandbox takes no direct connections, so a file moves from it in one piece of at most 5 MiB.`]));+ await vi.waitFor(() => expect(fake.files.has(downloadPath("big-guid")), "removed from the sandbox").toBe(false));+ const before = fake.requests.length;+ await cloud.close("bot-scout");+ expect(fake.requests.slice(before).filter((one) => one.path.includes("/files")), "not tried again at close").toEqual([]);+ expect(existsSync(join(folder, "downloads", "video.mp4"))).toBe(false);+ expect(cloud.takeNotes("bot-scout"), "no line about it at close").toEqual([REOPENED_NOTE]);+ });++ it("a failure that may pass is kept and tried again at close, as before", async () => {+ let available = false;+ const cloud = browser({ folder: () => (available ? folder : null) });+ urlOf(await cloud.open(request()));+ finish("retry-guid", "data.csv", Buffer.from("a,b\n1,2\n"));+ await vi.waitFor(() => expect(cloud.takeNotes("bot-scout")).toEqual([expect.stringContaining("It is kept in the browser sandbox for a day and is tried again when this browser closes.")]));+ available = true;+ await cloud.close("bot-scout");+ expect(readFileSync(join(folder, "downloads", "data.csv"), "utf8")).toBe("a,b\n1,2\n");+ });++ it("gives a page a file through the provider's JSON file write, and refuses one over the cap in one line", async () => {+ const cloud = browser();+ urlOf(await cloud.open(request()));+ mkdirSync(join(folder, "in"), { recursive: true });+ const cv = Buffer.from("my cv \u0000\u00ff bytes");+ writeFileSync(join(folder, "in", "cv.pdf"), cv);+ const path = `/home/user/.omb-browser/.uploads/${profileKey("scout")}/cv.pdf`;+ expect(await cloud.upload("bot-scout", join(folder, "in", "cv.pdf"), null, cv.length)).toEqual({ path });+ expect(fake.files.get(path)).toEqual(cv);+ expect(fileCalls()).toEqual(["PUT"]);+ writeFileSync(join(folder, "in", "big.bin"), Buffer.alloc(INLINE_WRITE_MAX_BYTES + 1));+ expect(await cloud.upload("bot-scout", join(folder, "in", "big.bin"), null, INLINE_WRITE_MAX_BYTES + 1))+ .toEqual({ error: `big.bin could not be given to the browser: ${tooLarge("big.bin", "1.5 MiB")} Tell the person in one sentence and ask them to upload it themselves.` });+ expect(fileCalls(), "never sent").toEqual(["PUT"]);+ });++ it("the largest upload it sends fits the relay's 2 MiB request cap, and a 413 from the relay is the same plain line", async () => {+ fake.relayJsonMax = 2 * 1024 * 1024;+ const cloud = browser();+ urlOf(await cloud.open(request()));+ mkdirSync(join(folder, "in"), { recursive: true });+ writeFileSync(join(folder, "in", "fits.bin"), Buffer.alloc(INLINE_WRITE_MAX_BYTES, 7));+ expect(await cloud.upload("bot-scout", join(folder, "in", "fits.bin"), null, INLINE_WRITE_MAX_BYTES)).toEqual({ path: expect.stringContaining("fits.bin") });+ fake.relayJsonMax = 1024 * 1024;+ writeFileSync(join(folder, "in", "scan.pdf"), Buffer.alloc(1024 * 1024));+ expect(await cloud.upload("bot-scout", join(folder, "in", "scan.pdf"), null, 1024 * 1024))+ .toEqual({ error: `scan.pdf could not be given to the browser: ${tooLarge("scan.pdf", "1.0 MiB")} Tell the person in one sentence and ask them to upload it themselves.` });+ expect([...fake.files.keys()].some((key) => key.endsWith("scan.pdf"))).toBe(false);+ });++ it("while the relay does not open the JSON file calls to it, a download is refused plainly once and never tried again", async () => {+ fake.jsonFiles = false;+ const cloud = browser({ folder: () => folder });+ urlOf(await cloud.open(request()));+ finish("closed-guid", "report.pdf", Buffer.from("x"));+ await vi.waitFor(() => expect(cloud.takeNotes("bot-scout")).toEqual([`"report.pdf" was downloaded in the browser but could not be brought to your working folder: ${downloadPath("closed-guid")} could not be copied from this browser's sandbox (it answered 404): the sandbox takes no direct connections, and its files can't be copied another way here.`]));+ const before = fake.requests.length;+ await cloud.close("bot-scout");+ expect(fake.requests.slice(before).filter((one) => one.path.includes("/files")), "not tried again at close").toEqual([]);+ mkdirSync(join(folder, "in"), { recursive: true });+ writeFileSync(join(folder, "in", "a.txt"), "y");+ urlOf(await cloud.open(request()));+ expect(await cloud.upload("bot-scout", join(folder, "in", "a.txt"), null, 1)).toEqual({ error: expect.stringContaining("could not be copied to this browser's sandbox (it answered 404)") });+ });++ it("a sandbox that takes direct connections copies through its links only, as before", async () => {+ fake.inbound = "open";+ const cloud = browser({ folder: () => folder });+ urlOf(await cloud.open(request()));+ finish("link-guid", "a.txt", Buffer.from("x"));+ await vi.waitFor(() => expect(existsSync(join(folder, "downloads", "a.txt"))).toBe(true));+ mkdirSync(join(folder, "in"), { recursive: true });+ writeFileSync(join(folder, "in", "b.txt"), "y");+ await cloud.upload("bot-scout", join(folder, "in", "b.txt"), null, 1);+ expect(fileCalls()).toEqual([]);+ });+});diff --git a/server/cloud-browser/index.ts b/server/cloud-browser/index.tsindex a79b6c2a70..b0da0779ce 100644--- a/server/cloud-browser/index.ts+++ b/server/cloud-browser/index.ts@@ -102,6 +102,8 @@ export function createCloudBrowser(deps: CloudBrowserDeps) {const leftNotes = new Map<string, string[]>();/** One wake of the sandbox at a time, shared by every bot opening meanwhile. */let waking: Promise<{ id: string; started: boolean }> | null = null;+ /** Erasures of deleted bots' profiles in a sleeping sandbox, one after another. */+ let erasing: Promise<void> = Promise.resolve();let boxId: string | null = null;let sweep: ReturnType<typeof setInterval> | null = null;let leftAwakeArmed = false;@@ -191,15 +193,60 @@ export function createCloudBrowser(deps: CloudBrowserDeps) {}/** A deleted bot: its sessions end without their sign-ins going home, its sync stamps go, and its profile in the- * sandbox is erased now if the sandbox is awake, else at its next wake. */+ * sandbox is erased now if the sandbox is awake. A profile in a sleeping sandbox is not left for a wake that may never+ * come (eraseAsleep, after this returns). */async function erase(botId: string): Promise<void> {const key = profileKey(botId);+ const had = rails.hasProfile(key);rails.forgetProfile(key);sync.forget(key);const ops = deps.ops();// Erased while the sandbox is still awake for this session, before its close lets it sleep.if (awake && boxId && ops) await erasePending(ops, boxId);for (const [session, owner] of Array.from(sessions)) if (owner === botId) await close(session, { discard: true, why: "its bot was deleted" });+ // A bot that never had a profile there keeps today's way: its erase waits for the next wake.+ if (had && ops && rails.pendingErasures().includes(key)) {+ erasing = erasing.then(() => eraseAsleep(ops)).catch((error: unknown) => log(`browser sandbox: a deleted bot's profile is erased at its next wake (${error instanceof Error ? error.name : "error"})`));+ }+ }++ /** Deleted bots' profiles in a sleeping sandbox: with no other bot's profile left in it the whole sandbox is deleted (the+ * next browser makes a fresh one); else it is woken once for the erase and let sleep, when a start may be sent now. When+ * none may (the day's starts, a hold), the erase waits for the next wake. */+ async function eraseAsleep(ops: ComputerOps): Promise<void> {+ if (rails.pendingErasures().length === 0) return;+ // A browser open or opening: its wake erases them.+ if (bots().size > 0 || awake) return;+ const box = await ops.find();+ if (!box) {+ for (const key of rails.pendingErasures()) rails.erased(key);+ return;+ }+ boxId = box.id;+ // Awake without a browser of this run (one an earlier run left): erased now; its idle path lets it sleep.+ if (READY_STATES.has(box.state)) { await erasePending(ops, box.id); return; }+ const broken = box.state === "error" || box.state === "cancelled";+ if (broken || rails.profilesIn(box.id).length === 0) {+ if (bots().size > 0) return;+ const removed = await ops.remove(box.id);+ for (const key of rails.pendingErasures()) rails.erased(key);+ if (boxId === box.id) boxId = null;+ log(`browser sandbox: ${removed ? "deleted" : "deletion requested and journaled"}: no bot with a browser profile is left in it`);+ return;+ }+ if (rails.refusal(true) !== null) { log("browser sandbox: a deleted bot's profile is erased at its next wake: no start may be sent now"); return; }+ try {+ // wake() erases the pending profiles once the sandbox is ready.+ await wake(ops);+ log("browser sandbox: woken to erase a deleted bot's profile");+ } catch (error) {+ if (error instanceof StaysHome) return;+ if (error instanceof OldRelay) { rails.oldRelay(); return; }+ if (error instanceof Unavailable) { rails.unavailable(error.reason, error.resetsAt); return; }+ refused(error);+ } finally {+ letSleep();+ }}async function launch(request: OpenRequest, ops: ComputerOps, gaveUp: () => boolean): Promise<Opened> {@@ -208,6 +255,9 @@ export function createCloudBrowser(deps: CloudBrowserDeps) {const quit = async () => { if (box) await ops.quit(box.id, key).catch(() => undefined); };// Past the deadline this call already opened the home's browser: what follows only readies the sandbox for the next.const home = (_request: OpenRequest, reason: HomeReason): Opened => (gaveUp() ? { home: reason } : fallback(request, reason));+ // An erase of a deleted bot's profile under way (a sandbox being deleted, or woken for it) finishes first: this open then+ // finds the sandbox as that left it, never one half deleted.+ await erasing;try {box = await wake(ops);if (gaveUp()) return { home: "slow" };@@ -425,6 +475,8 @@ export function createCloudBrowser(deps: CloudBrowserDeps) {dialed: (session: string): number => doors.dialed(session),failed,erase,+ /** Settles once the erasures erase() started in the background are done (tests). */+ erased: (): Promise<void> => erasing,/** Lines for the session's next browser call (downloads that arrived, or could not). */takeNotes: (session: string): string[] => {const left = leftNotes.get(session) ?? [];diff --git a/server/cloud-browser/rails.ts b/server/cloud-browser/rails.tsindex d8128a5903..163835d5ae 100644--- a/server/cloud-browser/rails.ts+++ b/server/cloud-browser/rails.ts@@ -224,6 +224,10 @@ export function createCloudBrowserRails(options: CloudBrowserRailsOptions) {save();},pendingErasures: (): string[] => [...today().pendingErase],+ /** The bots' profile keys this sandbox has carried sign-ins for: the profiles it holds, as far as the home knows. */+ profilesIn: (boxId: string): string[] => Object.keys(today().carried).filter((stamp) => stamp.startsWith(`${boxId}:`)).map((stamp) => stamp.slice(boxId.length + 1)),+ /** Whether any sandbox ever carried this profile's sign-ins (so it has a profile to erase). */+ hasProfile: (key: string): boolean => Object.keys(today().carried).some((stamp) => stamp.endsWith(`:${key}`)),erased(key: string): void {const current = today();current.pendingErase = current.pendingErase.filter((one) => one !== key);diff --git a/server/cloud-browser/remote.ts b/server/cloud-browser/remote.tsindex 831d4a671c..5ff572f987 100644--- a/server/cloud-browser/remote.ts+++ b/server/cloud-browser/remote.ts@@ -9,7 +9,7 @@ import { createHash } from "node:crypto";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 { copyFromComputer, copyToComputer, type CopyOutcome } from "../cloud-computer-files.ts";+import { copyFromComputer, copyToComputer, readFromComputerInline, writeToComputerInline, type CopyOutcome } from "../cloud-computer-files.ts";import type { AppConfig } from "../config.ts";const READY = new Set(["idle", "ready", "running"]);@@ -42,15 +42,17 @@ export interface ComputerOps {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 relay's refusal (with its limit) on anything but a 2xx or a 409. */+ /** One resume. Throws SandboxGone when the relay says this sandbox can never resume, else 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>;/** One bot's Chrome started on its profile, with this open's door secret; `home` is the sandbox's home folder. *//** `policy`: the Chrome policy that blocks file:// and Chrome's own pages could be written in the sandbox. */launch(boxId: string, key: string, secret: string): Promise<{ chrome: boolean; home: string | null; policy: boolean }>;- /** A finished download (a sandbox path) brought into `folder` as `to`, with the cloud computers' copy checks and limits. */+ /** A finished download (a sandbox path) brought into `folder` as `to`, with the cloud computers' copy checks and limits.+ * A sandbox that takes no direct connections is copied from through the provider's JSON file read (at most 5 MiB). */fetchFile(boxId: string, path: string, folder: string, to: string): Promise<CopyOutcome>;- /** A file of the Cloud (`from`, inside `folder`) copied to a sandbox path for an upload. */+ /** A file of the Cloud (`from`, inside `folder`) copied to a sandbox path for an upload; likewise through the JSON file write. */sendFile(boxId: string, folder: string, from: string, path: string): Promise<CopyOutcome>;/** A deleted bot's profile, door secret and files in the sandbox, erased. */erase(boxId: string, key: string): Promise<void>;@@ -153,6 +155,7 @@ export function providerOps(cfg: () => AppConfig): ComputerOps {create,async resume(boxId) {const answer = await json(cfg(), `/sandboxes/${boxId}/resume`, { method: "POST" });+ if (sandboxGone(answer.status, answer.body)) throw new SandboxGone();// 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, true);},@@ -167,8 +170,18 @@ export function providerOps(cfg: () => AppConfig): ComputerOps {const home = typeof answer?.home === "string" && /^\/[^\0\n]*$/.test(answer.home) && !answer.home.split("/").includes("..") ? answer.home.replace(/\/+$/, "") : null;return { chrome: answer?.chrome === true, home, policy: answer?.policy === true };},- fetchFile: (boxId, path, folder, to) => copyFromComputer(cfg(), boxId, folder, { path, to }, AbortSignal.timeout(10 * 60_000)),- sendFile: (boxId, folder, from, path) => copyToComputer(cfg(), boxId, folder, { from, path }, AbortSignal.timeout(10 * 60_000)),+ // The link first, as on every sandbox before: on one that takes no direct connections the relay answers its 409+ // `inbound_closed` itself, without asking the provider, and the JSON file call goes instead.+ async fetchFile(boxId, path, folder, to) {+ const signal = AbortSignal.timeout(10 * 60_000);+ const linked = await copyFromComputer(cfg(), boxId, folder, { path, to }, signal);+ return "error" in linked && linked.inboundClosed ? readFromComputerInline(cfg(), boxId, folder, { path, to }, signal) : linked;+ },+ async sendFile(boxId, folder, from, path) {+ const signal = AbortSignal.timeout(10 * 60_000);+ const linked = await copyToComputer(cfg(), boxId, folder, { from, path }, signal);+ return "error" in linked && linked.inboundClosed ? writeToComputerInline(cfg(), boxId, folder, { from, path }, signal) : linked;+ },async erase(boxId, key) {if (!HEX16.test(key)) throw new Error("bad browser profile key");await action(boxId, { action: "erase", key });@@ -201,6 +214,15 @@ export function providerOps(cfg: () => AppConfig): ComputerOps {/** The provider silently takes a ttlSeconds that is not a number as an hour: only a whole number within the Admin's range goes. */export const ttlSecondsOf = (seconds: number): number => Math.min(1_800, Math.max(300, Math.round(Number.isFinite(seconds) ? seconds : 300)));+/** The relay's word that a sandbox can never be resumed (one that keeps nothing after a stop): `410` with the code+ * `browser_sandbox_gone`. Every other answer to a resume is what it was. */+export const SANDBOX_GONE_CODE = "browser_sandbox_gone";+export const sandboxGone = (status: number, body: any): boolean => status === 410 && (body?.code ?? body?.error?.code) === SANDBOX_GONE_CODE;++/** The sandbox can never resume: it is deleted and a fresh one made at once, under the start already counted for it. Not a+ * failure: nothing is held off for it. */+export class SandboxGone 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";@@ -231,12 +253,23 @@ export async function wakeSandbox(ops: ComputerOps, options: WakeOptions): Promiawait ops.remove(broken);found = null;}+ /** A sandbox the relay says can never resume goes the broken one's way: deleted, and a fresh one made. */+ const replaced = async (gone: string): Promise<{ id: string; state: string }> => {+ await ops.remove(gone);+ return ops.create();+ };const counted = async (box: { id: string; state: string } | null): Promise<{ id: string; state: string }> => {if (!options.mayStart()) throw new StaysHome("budget");await options.allowed();options.starting();if (!box) return ops.create();- await ops.resume(box.id);+ try {+ await ops.resume(box.id);+ } catch (error) {+ if (!(error instanceof SandboxGone)) throw error;+ // Its resume started nothing: the create is the one start counted above.+ return replaced(box.id);+ }return box;};let started = false;@@ -244,14 +277,21 @@ export async function wakeSandbox(ops: ComputerOps, options: WakeOptions): Promi* for a browser, so a stop the Admin made because the home was down is never undone by this; the newest request wins. */let takenBack = false;if (found?.state === "archiving") {- await ops.resume(found.id);- takenBack = true;+ try {+ await ops.resume(found.id);+ takenBack = true;+ } catch (error) {+ if (!(error instanceof SandboxGone)) throw error;+ // A take-back counts no start, but the create that replaces it is one.+ await ops.remove(found.id);+ found = await counted(null);+ }started = true;} else if (!found || SLEEPING_BOAT_STATES.has(found.state)) {found = await counted(found);started = true;}- const id = found!.id;+ let id = found!.id;const deadline = Date.now() + (options.budgetMs ?? 45_000);// Quick reads first: a resume after a short stop is ready in well under a second.for (let reads = 0; Date.now() < deadline; reads++) {@@ -260,7 +300,7 @@ export async function wakeSandbox(ops: ComputerOps, options: WakeOptions): Promiif (state && READY.has(state)) return { id, started };if (state && TERMINAL.has(state)) break;// The take-back came too late (the machine went with the stop): one real, counted resume instead.- if (takenBack && state === "archived") { takenBack = false; await counted({ id, state }); }+ if (takenBack && state === "archived") { takenBack = false; id = (await counted({ id, state })).id; }// Never a second start: a refused resume is billed as one too.}throw new Error("the browser sandbox did not become ready in time");diff --git a/server/cloud-browser/sync.ts b/server/cloud-browser/sync.tsindex 30f584074d..d0308100f9 100644--- a/server/cloud-browser/sync.ts+++ b/server/cloud-browser/sync.ts@@ -83,6 +83,80 @@ export function mergeInSession(homeCookies: readonly unknown[], baseline: readonreturn { merged: [...merged.values()].slice(0, MAX_COOKIES), changed };}+// What comes home from the sandbox is what its Chrome reports, so whoever controls that Chrome decides it. Removals are+// taken as they come (a sign-out is one; a count cannot tell it from a wipe): the home keeps a backup of its copy from each+// session's open instead (browser-sites.ts backupSignIns). What is bounded is what no real Chrome holds, and the size.++/** Chrome refuses a cookie whose name and value pass 4096 bytes, or an attribute past 1024: a larger one never comes home. */+export const MAX_COOKIE_BYTES = 4_096;+const MAX_ATTRIBUTE_BYTES = 1_024;+/** The home's copy is never grown past this many bytes of names and values by what the sandbox reports. */+export const MAX_SIGN_IN_BYTES = 2 * 1024 * 1024;++const bytes = (text: string) => Buffer.byteLength(text, "utf8");+const sizeOf = (cookie: SavedCookie) => bytes(cookie.name) + bytes(cookie.value);+/** A cookie a real Chrome could hold. */+export const plausibleCookie = (cookie: SavedCookie): boolean =>+ sizeOf(cookie) <= MAX_COOKIE_BYTES && bytes(cookie.domain) <= MAX_ATTRIBUTE_BYTES && bytes(cookie.path) <= MAX_ATTRIBUTE_BYTES;+const cookieBytes = (cookies: readonly unknown[]) => cookies.filter(isCookie).reduce((sum, cookie) => sum + sizeOf(cookie), 0);+const hostOf = (cookie: SavedCookie) => cookie.domain.replace(/^\./, "").toLowerCase();++/** The merge brought within MAX_SIGN_IN_BYTES (or the home's own size, if that is larger already): cookies the sandbox+ * set or changed are dropped, those of hosts the home's copy never had first, then the largest first, a dropped change+ * keeping the home's value. Never a cookie the sandbox did not bring. `dropped`: the ids not taken home. */+function fit(merged: readonly SavedCookie[], homeCookies: readonly unknown[]): { merged: SavedCookie[]; dropped: string[] } {+ const limit = Math.max(MAX_SIGN_IN_BYTES, cookieBytes(homeCookies));+ let size = cookieBytes(merged);+ if (size <= limit) return { merged: [...merged], dropped: [] };+ const home = byId(homeCookies);+ const homeHosts = new Set([...home.values()].map(hostOf));+ const brought = merged.filter((cookie) => { const was = home.get(cookieId(cookie)); return !was || fingerprint(was) !== fingerprint(cookie); });+ brought.sort((a, b) => Number(homeHosts.has(hostOf(a))) - Number(homeHosts.has(hostOf(b))) || sizeOf(b) - sizeOf(a));+ const out = new Map(merged.map((cookie) => [cookieId(cookie), cookie]));+ const dropped: string[] = [];+ for (const cookie of brought) {+ if (size <= limit) break;+ const id = cookieId(cookie);+ const was = home.get(id);+ size -= sizeOf(cookie) - (was ? sizeOf(was) : 0);+ if (was) out.set(id, was); else out.delete(id);+ dropped.push(id);+ }+ return { merged: [...out.values()], dropped };+}++/** The sandbox's fingerprints to record as agreed: never one of a cookie that was not taken home, so it is asked again. */+export function agreed(sandbox: readonly SavedCookie[], dropped: readonly string[]): Prints {+ const recorded = prints(sandbox);+ for (const id of dropped) delete recorded[id];+ return recorded;+}++/** mergeInSession with the bounds above: a cookie no real Chrome holds counts as unchanged, and the merge is brought within+ * its cap (fit). Removals are taken as mergeInSession takes them. */+export function writeBack(homeCookies: readonly unknown[], baseline: readonly SavedCookie[], current: readonly SavedCookie[], last: SyncState | null): { merged: SavedCookie[]; changed: number; dropped: string[] } {+ const before = byId(baseline);+ const implausible: string[] = [];+ const sane = current.flatMap((cookie) => {+ if (plausibleCookie(cookie)) return [cookie];+ const id = cookieId(cookie);+ implausible.push(id);+ const was = before.get(id);+ return was ? [was] : [];+ });+ const result = mergeInSession(homeCookies, baseline, sane, last);+ const { merged, dropped } = fit(result.merged, homeCookies);+ return { merged, changed: Math.max(0, result.changed - dropped.length), dropped: [...implausible, ...dropped] };+}++/** mergeAtOpen with the same bounds: a cookie no real Chrome holds never comes home, and what comes home fits the cap. */+export function openMerge(homeCookies: readonly unknown[], sandboxCookies: readonly SavedCookie[], last: SyncState | null): { merged: SavedCookie[]; fromSandbox: number; dropped: string[] } {+ const implausible = sandboxCookies.filter((cookie) => !plausibleCookie(cookie)).map(cookieId);+ const result = mergeAtOpen(homeCookies, sandboxCookies.filter(plausibleCookie), last);+ const { merged, dropped } = fit(result.merged, homeCookies);+ return { merged, fromSandbox: Math.max(0, result.fromSandbox - dropped.length), dropped: [...implausible, ...dropped] };+}+/** Whether the sandbox already holds what the merge asks of it: the same cookies, the same values. A cookie Chrome would* not keep before (in the home at the last sync, absent from the sandbox then and now, unchanged in the home) is not asked* again, so a per-site cap does not cost a carry at every open. */diff --git a/server/cloud-browser/testing/fake-computer.ts b/server/cloud-browser/testing/fake-computer.tsindex 57e3f68917..fe574b0565 100644--- a/server/cloud-browser/testing/fake-computer.ts+++ b/server/cloud-browser/testing/fake-computer.ts@@ -45,6 +45,16 @@ export interface FakeComputer {chromes: number;/** A resume during `archiving` finds the machine already gone. */takeBackFails: boolean;+ /** The relay says this sandbox can never resume (one that keeps nothing after a stop): its resumes answer 410+ * `browser_sandbox_gone`, and nothing else changes. */+ resumeGone: boolean;+ /** `boat-only`: the sandbox takes no direct connections, so the relay answers its transfer links 409 `inbound_closed`, and+ * files go through the provider's JSON file read and write (at most 5 MiB, under /home/user or /tmp). */+ inbound: "open" | "boat-only";+ /** The relay's cap on a request's JSON body (its 413 `request_too_large` past it), or null for none. */+ relayJsonMax: number | null;+ /** Whether the relay lets a browser sandbox use the JSON file calls (an Admin before that answers them 404). */+ jsonFiles: boolean;/** Whether the launch could write the Chrome policy (sudo in the sandbox). */policy: boolean;requests: Request[];@@ -81,7 +91,7 @@ export async function startFakeComputer(): Promise<FakeComputer> {let retired = true;const fake = {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, policy: true, takeBackFails: false, chromes: 2, caps: null, patchStatus: 200, oldRelayAnswer: 404, cookieCap: null, stall: new Map(), erased: [], requests: [], upgrades: [], frames: [], boxId: "bx_23456789",+ unavailableUntil: null, hostRoute: true, unprotected: false, chromeStarts: true, policy: true, takeBackFails: false, resumeGone: false, inbound: "open", relayJsonMax: null, jsonFiles: true, chromes: 2, caps: null, patchStatus: 200, oldRelayAnswer: 404, cookieCap: null, stall: new Map(), erased: [], requests: [], upgrades: [], frames: [], boxId: "bx_23456789",files: new Map(), cookies: new Map(), commands: [], failing: new Set(),} as unknown as FakeComputer;const watchers = new Map<string, Set<import("ws").WebSocket>>();@@ -112,6 +122,11 @@ export async function startFakeComputer(): Promise<FakeComputer> {return;}const raw = Buffer.concat(chunks).toString("utf8");+ if (fake.relayJsonMax !== null && chunks.reduce((sum, chunk) => sum + chunk.length, 0) > fake.relayJsonMax) {+ res.writeHead(413, { "content-type": "application/json", connection: "close" });+ res.end(JSON.stringify({ ok: false, error: { code: "request_too_large", message: "The request is too large." } }));+ return;+ }const body = raw && !url.pathname.startsWith("/put") ? JSON.parse(raw) as Record<string, unknown> : {};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)); };@@ -142,6 +157,7 @@ export async function startFakeComputer(): Promise<FakeComputer> {return send(200, { ok: true, operation: { id: `bdop_${"a".repeat(32)}`, status: "completed", kind: "sandbox", targetId: boxId } });}if (rest === `/sandboxes/${boxId}/resume`) {+ if (fake.resumeGone) return send(410, { ok: false, error: { code: "browser_sandbox_gone", message: "This browser sandbox keeps nothing after a stop and cannot be resumed." } });// Taken back while still stopping, unless the machine already went: then the stop finishes and the answer is 409.if (fake.state === "archiving" && fake.takeBackFails) { fake.state = "archived"; return send(409, { ok: false, code: "sandbox_stopping" }); }if (fake.startStatus < 300) fake.state = "ready";@@ -163,11 +179,32 @@ export async function startFakeComputer(): Promise<FakeComputer> {}if (rest === `/sandboxes/${boxId}/commands`) return send(404, { ok: false, code: "not_found" });if (rest === `/sandboxes/${boxId}/files/download-url` || rest === `/sandboxes/${boxId}/files/upload-url`) {+ if (fake.inbound === "boat-only") return send(409, { ok: false, error: { code: "inbound_closed", message: "Files can't be copied to or from this browser yet: its sandbox takes no direct connections." } });const path = String(body.path ?? "");const download = rest.endsWith("download-url");if (!new RegExp(`^${HOME}/\\.omb-browser/\\.${download ? "downloads" : "uploads"}/[a-f0-9]{16}/[^/.][^/]*$`).test(path)) return send(404, { ok: false, code: "not_found" });return send(200, { ok: true, url: `${fake.base}/${download ? "file" : "put"}?p=${encodeURIComponent(path)}`, method: download ? "GET" : "PUT", path });}+ // The provider's JSON file read and write, as the relay lets a browser sandbox use them: one file in a profile's+ // downloads (read) or uploads (write) folder, under /home/user or /tmp, at most 5 MiB after decoding.+ if (rest === `/sandboxes/${boxId}/files` && (req.method === "GET" || req.method === "PUT")) {+ if (!fake.jsonFiles) return send(404, { ok: false, error: { code: "not_found", message: "Not found." } });+ const read = req.method === "GET";+ const path = String(read ? url.searchParams.get("path") ?? "" : body.path ?? "");+ if (!new RegExp(`^${HOME}/\\.omb-browser/\\.${read ? "downloads" : "uploads"}/[a-f0-9]{16}/[^/.][^/]*$`).test(path)) return send(404, { ok: false, code: "not_found" });+ if (!/^\/(home\/user|tmp)\//.test(path)) return send(400, { ok: false, error: { code: "invalid_path", message: "The path must be under /home/user or /tmp." } });+ if (read) {+ const file = fake.files.get(path);+ if (!file) return send(404, { ok: false, error: { code: "not_found", message: "No such file." } });+ if (file.length > 5 * 1024 * 1024) return send(413, { ok: false, error: { code: "file_too_large", message: "Files up to 5 MiB." } });+ return send(200, { ok: true, type: "file.read", success: true, path, encoding: url.searchParams.get("encoding") ?? "utf8", size: file.length,+ content: url.searchParams.get("encoding") === "base64" ? file.toString("base64") : file.toString("utf8") });+ }+ const content = body.encoding === "base64" ? Buffer.from(String(body.content ?? ""), "base64") : Buffer.from(String(body.content ?? ""), "utf8");+ if (content.length > 5 * 1024 * 1024) return send(413, { ok: false, error: { code: "file_too_large", message: "Inline writes are limited to 5 MiB." } });+ fake.files.set(path, content);+ return send(200, { ok: true, type: "file.written", success: true, path, encoding: body.encoding ?? "utf8", size: content.length });+ }if (rest === `/sandboxes/${boxId}/stop`) { fake.state = "archived"; return send(200, { ok: true }); }send(404, { ok: false, code: "not_found" });}));diff --git a/server/cloud-computer-files.ts b/server/cloud-computer-files.tsindex 14989aa08c..66f8139806 100644--- a/server/cloud-computer-files.ts+++ b/server/cloud-computer-files.ts@@ -1,11 +1,15 @@// Boat (docs.boat.dev/openapi/boat-v1.yaml): POST /sandboxes/{id}/files/download-url and /files/upload-url answer a link// the sandbox serves itself, bound to one path, taking no Authorization header and no size limit; a PUT replaces a file// only once its upload completes.+// A sandbox made to take no direct connections (the Cloud's browser sandbox, by the relay's choice) gets no link: the relay+// answers `409 inbound_closed`, and the Cloud's browser copies through the provider's JSON file read and write instead+// (readFromComputerInline, writeToComputerInline): one call a file, with no range or append, so at most+// INLINE_READ_MAX_BYTES comes from it and INLINE_WRITE_MAX_BYTES goes to it.// Security: the link is a secret until it expires, so no result, error or log ever carries it. A copy reads or writes// only inside the bot's working folder, judged after every existing link is followed, and never under its secret folder.import { randomBytes } from "node:crypto";import { constants, lstatSync, mkdirSync, realpathSync, renameSync, rmSync, statfsSync } from "node:fs";-import { open } from "node:fs/promises";+import { open, type FileHandle } from "node:fs/promises";import { basename, dirname, isAbsolute, join, posix, relative, win32 } from "node:path";import { assertBoatNotDeleting, boatAccount, boatErrorMessage, boatFetch } from "./boat.ts";import type { AppConfig } from "./config.ts";@@ -22,7 +26,20 @@ const OLD_RELAY = "This Cloud's computer service can't hand out file transfer liconst UNUSABLE_LINK = "The cloud computer answered with a transfer link that can't be used. Try the copy again in a minute.";const noFollow = typeof constants.O_NOFOLLOW === "number" ? constants.O_NOFOLLOW : 0;-export type CopyOutcome = { path: string; bytes: number } | { error: string };+/** `inboundClosed`: the relay's 409 `inbound_closed` (no link on this sandbox). `final`: trying again can never copy it. */+export type CopyOutcome = { path: string; bytes: number } | { error: string; inboundClosed?: true; final?: true };++/** The relay's word that a sandbox takes no direct connections, so no transfer link works on it. */+export const INBOUND_CLOSED_CODE = "inbound_closed";+const INBOUND_CLOSED = "This cloud computer takes no direct connections, so its files can't be copied with transfer links.";+/** What the provider's JSON file read moves in one call, after decoding (docs: "Files up to 5 MiB"); the relay streams it. */+export const INLINE_READ_MAX_BYTES = 5 * MiB;+/** What one JSON file write can carry through the relay, whose request cap is 2 MiB of JSON: the file's base64 and its+ * path within it (the provider itself takes 5 MiB). */+export const INLINE_WRITE_MAX_BYTES = 1536 * 1024 - 3 * 1024;+/** The JSON around a read's base64 content: never buffered past this. */+const INLINE_MAX_JSON = Math.ceil(INLINE_READ_MAX_BYTES / 3) * 4 + 64 * 1024;+const BASE64 = /^[A-Za-z0-9+/]*={0,2}$/;export interface CopyOptions {/** Bytes free on the disk that holds `dir`. */freeBytes?(dir: string): number;@@ -87,12 +104,13 @@ function usableLink(cfg: AppConfig, link: unknown): URL | null {return loopback && url.protocol === "http:" && url.hostname === api.hostname ? url : null;}-async function transferLink(cfg: AppConfig, boxId: string, kind: "download-url" | "upload-url", path: string, signal: AbortSignal): Promise<{ url: URL; path: string } | { error: string }> {+async function transferLink(cfg: AppConfig, boxId: string, kind: "download-url" | "upload-url", path: string, signal: AbortSignal): Promise<{ url: URL; path: string } | { error: string; inboundClosed?: true }> {assertBoatNotDeleting(boxId);const response = await boatFetch(cfg, `/sandboxes/${boxId}/files/${kind}`, { method: "POST", body: JSON.stringify({ path, ttlSeconds: LINK_TTL_SECONDS }), signal });const body = await response.json().catch(() => null) as { ok?: unknown; code?: unknown; error?: { code?: unknown }; url?: unknown; method?: unknown; path?: unknown } | null;if (!response.ok || body?.ok === false) {if ((body?.error?.code ?? body?.code) === "not_available") return { error: OLD_RELAY };+ if (response.status === 409 && (body?.error?.code ?? body?.code) === INBOUND_CLOSED_CODE) return { error: INBOUND_CLOSED, inboundClosed: true };return { error: boatErrorMessage(response.status, `Copying ${path} ${kind === "download-url" ? "from" : "to"} the cloud computer`, body, boatAccount(cfg)?.included === true) };}const url = usableLink(cfg, body?.url);@@ -171,6 +189,18 @@ export async function copyFromComputer(return { path: relative(placed.root, target), bytes };}+/** The bot's file, opened without following a last link; or what to say. */+async function openLocal(placed: { file: string }, from: string): Promise<{ handle: FileHandle } | { error: string }> {+ try {+ return { handle: await open(placed.file, constants.O_RDONLY | noFollow) };+ } catch (error) {+ const code = (error as NodeJS.ErrnoException).code;+ if (code === "ENOENT") return { error: `${from} is not in your working folder.` };+ if (code === "ELOOP") return { error: `${from} leads outside your working folder.` };+ throw error;+ }+}+/** Streams the file from disk as the upload's body; the computer keeps its old file unless the whole upload lands. */export async function copyToComputer(cfg: AppConfig,@@ -181,15 +211,9 @@ export async function copyToComputer(): Promise<CopyOutcome> {const placed = placeInFolder(folder, args.from);if ("error" in placed) return placed;- let handle;- try {- handle = await open(placed.file, constants.O_RDONLY | noFollow);- } catch (error) {- const code = (error as NodeJS.ErrnoException).code;- if (code === "ENOENT") return { error: `${args.from} is not in your working folder.` };- if (code === "ELOOP") return { error: `${args.from} leads outside your working folder.` };- throw error;- }+ const opened = await openLocal(placed, args.from);+ if ("error" in opened) return opened;+ const { handle } = opened;try {const info = await handle.stat();if (!info.isFile()) return { error: `${args.from} is not a file.` };@@ -215,3 +239,136 @@ export async function copyToComputer(await handle.close().catch(() => {});}}++// Through the provider's JSON file calls, for a sandbox that takes no direct connections. Each moves the whole file in one+// call (the relay may take less than the provider: its 413 is the same answer), and neither takes a range, so a+// larger file can never move this way; that is said plainly, and never tried again.++const inlineTooBig = (path: string, bytes: number | null, way: "from" | "to") => ({+ error: `${path}${bytes === null ? "" : ` (${sized(bytes)})`} is too large to copy: this browser's sandbox takes no direct connections, so a file moves ${way} it in one piece of at most ${way === "from" ? "5 MiB" : "about 1.5 MiB"}.`,+ final: true as const,+});+const inlineBadPlace = (path: string) => ({ error: `${path} is in a place this browser's sandbox can't copy from or to while it takes no direct connections.`, final: true as const });+/** A refusal that will not change on a retry (the file is not there, or the Cloud's service does not copy such files). */+const inlineRefused = (path: string, way: "from" | "to", status: number) => ({+ error: `${path} could not be copied ${way} this browser's sandbox (it answered ${status}): the sandbox takes no direct connections, and its files can't be copied another way here.`,+ final: true as const,+});+const codeOf = (body: unknown): unknown => (body as { error?: { code?: unknown }; code?: unknown } | null)?.error?.code ?? (body as { code?: unknown } | null)?.code;++/** The response's text, never buffered past `max` bytes: null past it. */+async function boundedText(response: Response, max: number): Promise<string | null> {+ if (Number(response.headers.get("content-length") ?? 0) > max) { await response.body?.cancel().catch(() => {}); return null; }+ const reader = response.body?.getReader();+ const chunks: Uint8Array[] = [];+ let bytes = 0;+ try {+ for (;;) {+ const chunk = await reader?.read();+ if (!chunk || chunk.done) break;+ bytes += chunk.value.byteLength;+ if (bytes > max) return null;+ chunks.push(chunk.value);+ }+ } finally {+ await reader?.cancel().catch(() => {});+ }+ return Buffer.concat(chunks).toString("utf8");+}++/** copyFromComputer through the provider's JSON file read: the same folder and disk checks, written beside its place and renamed. */+export async function readFromComputerInline(+ cfg: AppConfig,+ boxId: string,+ folder: string,+ args: { path: string; to?: string },+ signal: AbortSignal,+ options: CopyOptions = {},+): Promise<CopyOutcome> {+ const wanted = args.to ?? posix.basename(args.path);+ if (!wanted) return { error: "Name the file to copy, or say where it goes with to." };+ const placed = placeInFolder(folder, wanted);+ if ("error" in placed) return placed;+ assertBoatNotDeleting(boxId);+ const response = await boatFetch(cfg, `/sandboxes/${boxId}/files?path=${encodeURIComponent(args.path)}&encoding=base64`, { signal });+ const text = await boundedText(response, INLINE_MAX_JSON);+ if (text === null) return inlineTooBig(args.path, null, "from");+ let body: { ok?: unknown; content?: unknown; encoding?: unknown; size?: unknown } | null = null;+ try { body = JSON.parse(text); } catch { /* judged below */ }+ if (response.status === 413 || codeOf(body) === "file_too_large") return inlineTooBig(args.path, typeof body?.size === "number" ? body.size : null, "from");+ if (response.status === 400 && codeOf(body) === "invalid_path") return inlineBadPlace(args.path);+ if (!response.ok || body?.ok === false) {+ if (response.status === 404 || response.status === 403 || response.status === 405) return inlineRefused(args.path, "from", response.status);+ return { error: boatErrorMessage(response.status, `Copying ${args.path} from the cloud computer`, body, boatAccount(cfg)?.included === true) };+ }+ const content = body?.content;+ const unusable = { error: `${args.path} came back from this browser's sandbox in a form that can't be used, so it was not brought over.`, final: true as const };+ if (typeof content !== "string" || content.length % 4 !== 0 || !BASE64.test(content) || (body?.encoding !== undefined && body.encoding !== "base64")) return unusable;+ const bytes = Buffer.from(content, "base64");+ if (typeof body?.size === "number" && body.size !== bytes.length) return unusable;+ if (bytes.length > INLINE_READ_MAX_BYTES) return inlineTooBig(args.path, bytes.length, "from");+ const free = (options.freeBytes ?? diskFree)(placed.root);+ if (bytes.length + DISK_RESERVE_BYTES > free) return { error: noSpace(args.path, bytes.length, free) };+ const landed = land(placed, wanted);+ if ("error" in landed) return landed;+ const { parent, target } = landed;+ const temporary = join(parent, `.${basename(target)}.${randomBytes(6).toString("hex")}.part`);+ const handle = await open(temporary, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | noFollow, 0o644);+ let written = false;+ try {+ try {+ await handle.writeFile(bytes);+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code === "ENOSPC") return { error: noSpace(args.path, bytes.length, free, true) };+ throw error;+ }+ await handle.close();+ signal.throwIfAborted();+ renameSync(temporary, target);+ written = true;+ } finally {+ await handle.close().catch(() => {});+ if (!written) rmSync(temporary, { force: true });+ }+ return { path: relative(placed.root, target), bytes: bytes.length };+}++/** copyToComputer through the provider's JSON file write: the whole file in one call, which lands whole or not at all. */+export async function writeToComputerInline(+ cfg: AppConfig,+ boxId: string,+ folder: string,+ args: { from: string; path: string },+ signal: AbortSignal,+): Promise<CopyOutcome> {+ const placed = placeInFolder(folder, args.from);+ if ("error" in placed) return placed;+ const opened = await openLocal(placed, args.from);+ if ("error" in opened) return opened;+ const { handle } = opened;+ let content: Buffer;+ try {+ const info = await handle.stat();+ if (!info.isFile()) return { error: `${args.from} is not a file.` };+ if (info.size > INLINE_WRITE_MAX_BYTES) return inlineTooBig(args.from, info.size, "to");+ content = Buffer.alloc(info.size);+ let read = 0;+ while (read < info.size) {+ const { bytesRead } = await handle.read(content, read, info.size - read, read);+ if (bytesRead === 0) return { error: `${args.from} changed while it was being read. Try again.` };+ read += bytesRead;+ }+ } finally {+ await handle.close().catch(() => {});+ }+ assertBoatNotDeleting(boxId);+ const response = await boatFetch(cfg, `/sandboxes/${boxId}/files`, {+ method: "PUT", signal, body: JSON.stringify({ path: args.path, content: content.toString("base64"), encoding: "base64" }),+ });+ const body = await boundedText(response, 64 * 1024).then((text) => { try { return JSON.parse(text ?? "") as { ok?: unknown; path?: unknown }; } catch { return null; } });+ if (response.status === 413 || codeOf(body) === "file_too_large" || codeOf(body) === "request_too_large") return inlineTooBig(args.from, content.length, "to");+ if (response.status === 400 && codeOf(body) === "invalid_path") return inlineBadPlace(args.path);+ if (response.status === 404 || response.status === 403 || response.status === 405) return inlineRefused(args.from, "to", response.status);+ if (!response.ok || body?.ok === false) return { error: boatErrorMessage(response.status, `Copying ${args.from} to the cloud computer`, body, boatAccount(cfg)?.included === true) };+ return { path: typeof body?.path === "string" ? body.path : args.path, bytes: content.length };+}diff --git a/server/host/browser-cloud-sandbox.test.ts b/server/host/browser-cloud-sandbox.test.tsindex 9a1f28d850..40ad2e4d36 100644--- a/server/host/browser-cloud-sandbox.test.ts+++ b/server/host/browser-cloud-sandbox.test.ts@@ -11,7 +11,7 @@ import { REDDIT_REFUSAL } from "../browser/egress/reddit.ts";import { DATA_DIR, type AppConfig } from "../config.ts";import type { Store } from "../store.ts";import { RELAY_KEY, startFakeComputer, type FakeComputer } from "../cloud-browser/testing/fake-computer.ts";-import { LOCAL_SCHEME_REFUSAL } from "../cloud-browser/guards.ts";+import { LOCAL_SCHEME_REFUSAL, PRIVATE_ADDRESS_REFUSAL } from "../cloud-browser/guards.ts";import { createBrowserHost, type BrowserHostDeps } from "./browser.ts";vi.mock("../browser-engine.ts", async (original) => {@@ -130,6 +130,23 @@ describe("a personal Cloud's bot browser opens in the Cloud's browser sandbox",expect(fake.requests).toEqual([]);});+ it("a call the sandbox's guards refuse never wakes it: it is refused, and nothing opens", async () => {+ const { host } = setup();+ for (const url of ["http://127.0.0.1:9222/json/list", "file:///home/user/.omb-browser/"]) {+ const call = { name: OPEN, arguments: { url } };+ const browser = (await host.browserIntegration(botId, undefined, undefined, "team", { opening: OPEN, params: call }))!;+ expect(browser.spec.env.AGENT_BROWSER_CDP, url).toBeUndefined();+ const answer = await host.browserRuntime.agentRpc(browser.session, browser.spec, "tools/call", call) as { isError?: boolean; content: Array<{ text: string }> };+ expect(answer.isError, url).toBe(true);+ expect([PRIVATE_ADDRESS_REFUSAL, LOCAL_SCHEME_REFUSAL]).toContain(answer.content[0]!.text);+ }+ expect(fake.requests, "no relay call: nothing woken").toEqual([]);+ expect(BrowserRuntime.prototype.agentRpc, "nothing reached the engine").not.toHaveBeenCalledWith(expect.anything(), expect.anything(), "tools/call", expect.anything(), expect.anything());+ // A public site opens the sandbox as before.+ const browser = (await host.browserIntegration(botId, undefined, undefined, "team", { opening: OPEN, params: { name: OPEN, arguments: { url: "https://93.184.215.14/" } } }))!;+ expect(browser.spec.env.AGENT_BROWSER_CDP).toMatch(/^ws:\/\/127\.0\.0\.1:/);+ });+it("a temporary or shared profile opens in the home: the sandbox keeps one profile per bot", async () => {const { host } = setup();const browser = await host.browserIntegration(botId, "guest", undefined, "team", { opening: OPEN });diff --git a/server/host/browser.ts b/server/host/browser.tsindex 7f5fce9c33..f0dd46d71c 100644--- a/server/host/browser.ts+++ b/server/host/browser.ts@@ -61,8 +61,9 @@ import { createBrowserReclaim, reclaimable } from "./browser-reclaim.ts";import { createCloudBrowser, type HomeReason } from "../cloud-browser/index.ts";import { providerOps } from "../cloud-browser/remote.ts";import { boatAccount, boatConfigured } from "../boat.ts";-import { localSchemeRefusal } from "../cloud-browser/guards.ts";-import { readSignIns, writeSignIns } from "../browser-sites.ts";+import { addressGuard, localSchemeRefusal } from "../cloud-browser/guards.ts";+import { backupSignIns, readSignIns, restoreSignIns, signInBackups, writeSignIns } from "../browser-sites.ts";+import { createSignInBackupRoutes } from "../routes/browser-sign-in-backups.ts";import { browserSessionsDirectory } from "../browser-engine.ts";import { BrowserUploadRefusal } from "../browser-upload.ts";import { BROWSER_TASKS, processBudget } from "../process-room.ts";@@ -241,11 +242,24 @@ export function createBrowserHost(deps: BrowserHostDeps) {const url = doorUrls.get(session);return url !== undefined && spec.env.AGENT_BROWSER_CDP === url;}+ const sandboxAddresses = addressGuard();+ /** A call the sandbox's guards refused before its browser opened (cloudBrowserUrl), so no wake was spent on it: answered+ * with that refusal when the same call reaches the router. */+ const refusedOpens = new Map<string, { call: string; refusal: string }>();+ const callKey = (params: unknown) => JSON.stringify([(params as { name?: unknown } | null)?.name ?? null, (params as { arguments?: unknown } | null)?.arguments ?? null]);// 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) => (cloudBrowser?.attached(session) ? localSchemeRefusal(params) ?? browserEgress.callRefusal(params): attachesToChrome(spec.env) ? null : browserEgress.callRefusal(params)),+ // A browser in the sandbox is kept from the addresses the home's own browsers are (the egress gate covers those).+ vet: (session, _spec, params) => {+ if (cloudBrowser?.attached(session)) return sandboxAddresses(params);+ const early = refusedOpens.get(session);+ if (!early) return null;+ refusedOpens.delete(session);+ return early.call === callKey(params) ? Promise.resolve(early.refusal) : null;+ },// 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"@@ -305,19 +319,41 @@ export function createBrowserHost(deps: BrowserHostDeps) {signIns: {load: (session) => readSignIns(sessionsDirectory(session), session, browserEngineEncryptionKey()),save: (session, cookies) => writeSignIns(sessionsDirectory(session), session, browserEngineEncryptionKey(), cookies),+ backup: (session) => { backupSignIns(sessionsDirectory(session), session, browserEngineEncryptionKey()); },},}) : null;+ /** The owner's way back to a bot's sign-ins from before one of its sessions in the browser sandbox. */+ const signInBackupRoutes = createSignInBackupRoutes({+ backups: (botId) => {+ if (!store.bot(botId)) return null;+ const session = currentBrowserSession(botId, undefined);+ return signInBackups(sessionsDirectory(session), session);+ },+ restore: async (botId, id) => {+ if (!store.bot(botId)) return "no-bot";+ const session = currentBrowserSession(botId, undefined);+ if (cloudBrowser?.active(session) || browserRunning(session, usedBrowserSessions.get(session))) return "open";+ return restoreSignIns(sessionsDirectory(session), session, browserEngineEncryptionKey(), id) ? "restored" : "no-backup";+ },+ });function sessionsDirectory(session: string): string {return browserSessionsDirectory(browserRuntimeEnv({ ...usedBrowserSessions.get(session)?.env, AGENT_BROWSER_SESSION: session }));}/** Where a session's browser opens, decided once when it opens: in the Cloud's browser sandbox (its address returned),* or in the home (undefined). A browser already running stays where it runs. */- async function cloudBrowserUrl(botId: string, profile: string | undefined, session: string, audience: Audience, opening: string | null | undefined): Promise<string | undefined> {+ async function cloudBrowserUrl(botId: string, profile: string | undefined, session: string, audience: Audience, opening: string | null | undefined, params?: unknown): Promise<string | undefined> {if (!cloudBrowser) return undefined;const live = cloudBrowser.active(session);if (live) return live;if (!opening || opening === "agent_browser_close" || browserRunning(session, usedBrowserSessions.get(session))) return undefined;- const opened = await cloudBrowser.open({ session, botId, refusal: cloudBrowserRefusal(profile, session, audience) });+ const refusal = cloudBrowserRefusal(profile, session, audience);+ // A call the sandbox's guards will refuse never wakes it: it is refused at the router, and nothing opens.+ const guarded = params === undefined || refusal !== null ? null : localSchemeRefusal(params) ?? await sandboxAddresses(params);+ if (guarded) {+ refusedOpens.set(session, { call: callKey(params), refusal: guarded });+ return undefined;+ }+ const opened = await cloudBrowser.open({ session, botId, refusal });return "cdpUrl" in opened ? opened.cdpUrl : undefined;}/** The sessions this slice keeps in the home: a shared, temporary or someone else's profile (the sandbox keeps one@@ -579,7 +615,7 @@ export function createBrowserHost(deps: BrowserHostDeps) {};}/** `opening`: the name of a browser tool call about to run, which may open the session's browser. */- async function browserIntegration(botId: string, profile: string | undefined, turn?: { threadId: string; generation: string }, audience = browserAudience(turn?.threadId), options: { opening?: string | null } = {}) {+ async function browserIntegration(botId: string, profile: string | undefined, turn?: { threadId: string; generation: string }, audience = browserAudience(turn?.threadId), options: { opening?: string | null; params?: unknown } = {}) {const profileTarget = profile && profile !== "guest" ? browserProfilePartitionTarget(cfg, profile) : null;const partitionId = profile === "guest" ? "guest" : (profileTarget?.partitionId ?? "");const browserProfileId = profileTarget?.profileId ?? profile;@@ -596,7 +632,7 @@ export function createBrowserHost(deps: BrowserHostDeps) {const session = currentBrowserSession(botId, profile, audience);const lent = lentChromeSession(browserProfileId);const cdpUrl = lent ? await lentChromeDoor(session) : undefined;- const cloudUrl = lent ? undefined : await cloudBrowserUrl(botId, profile, session, audience, options.opening);+ const cloudUrl = lent ? undefined : await cloudBrowserUrl(botId, profile, session, audience, options.opening, options.params);const spec = browserSessionSpec(status.binaryPath, session, browserProfileId, usesMyChrome(browserProfileId) || cloudUrl ? undefined : await browserEgress.open(session), cdpUrl, cloudUrl);// On a Cloud the place a session's browser runs can change between a turn's tools/list (which starts the engine's client)// and its first call, or after the sandbox's browser closed: an unused client of the other place goes, never a running browser.@@ -860,7 +896,7 @@ export function createBrowserHost(deps: BrowserHostDeps) {currentBrowserSession, forgetTemporaryBrowser, myChromeAvailable, lentChromeSummary, usesMyChrome, browserSessionSpec, browserIntegration,browserReady, currentBrowserSpec, loginInput, browserSystemPrompt, signedInSitesRefusal, closeBrowser, browserEngineSwitched,eraseDeletedBrowser, engineSummary, engineBrowsers, browserAudience, browserSessionsOf, signedInSitesTarget, uploadPaths,- eraseAudienceBrowsers, browserOwners, closeCapBrowsers,+ eraseAudienceBrowsers, browserOwners, closeCapBrowsers, signInBackupRoutes,cloudBrowserBusy: (owner: string) => cloudBrowser?.busy(owner) ?? false,cloudBrowserReport: () => cloudBrowser?.report() ?? null,/** The browser sandbox's idle sweep, run now (it runs on its own every 30 s while a session is open). */diff --git a/server/index.ts b/server/index.tsindex f632a04396..2d5930c9d1 100644--- a/server/index.ts+++ b/server/index.ts@@ -2353,7 +2353,7 @@ function cancelDirectTurnDispatch(botId: string, expectedThreadId?: string): Dirconst {browserRuntime, browserLive, usedBrowserSessions, browserSweep, temporaryBrowserSessions,currentBrowserSession, forgetTemporaryBrowser, myChromeAvailable, usesMyChrome, lentChromeSummary, browserSessionSpec, browserIntegration,- browserReady, currentBrowserSpec, loginInput, browserSystemPrompt, closeBrowser, browserEngineSwitched, eraseDeletedBrowser, engineSummary, browserSessionsOf, signedInSitesTarget, uploadPaths, eraseAudienceBrowsers, browserOwners, closeCapBrowsers, cloudBrowserBusy, cloudBrowserReport,+ browserReady, currentBrowserSpec, loginInput, browserSystemPrompt, closeBrowser, browserEngineSwitched, eraseDeletedBrowser, engineSummary, browserSessionsOf, signedInSitesTarget, uploadPaths, eraseAudienceBrowsers, browserOwners, closeCapBrowsers, cloudBrowserBusy, cloudBrowserReport, signInBackupRoutes,} = createBrowserHost({ cloudBrowser: CLOUD_PERSONAL ? { used: (owner, windowMs) => cloudComputerPower.used(owner, windowMs), folder: (botId) => { const bot = store.bot(botId); return bot ? bot.cwd || workspaceDir(bot.id) : null; } } : undefined, cfg, language: appLanguage, store: () => store, turnResources, activeInternalGenerationByThread, mintInternalCapability, DESKTOP_MANAGED, CLOUD_HOME, HOSTED_WORKSPACE, PORT, engineMemory, audienceOf: teamHost.browserAudience, ...(CLOUD_TEAM ? { browserBox: (fd: number, ro: readonly string[]) => botBox.browserBox(fd, ro) } : {}), lendRefusal: (turn) => cloudLendingRefusal({ botId: store.botByThread(turn.threadId)?.id ?? "", threadId: turn.threadId, generation: turn.generation }), device: () => deviceLinks.route(CLOUD_HOME_LENDER) ?? sharedComputers.internetAway(CLOUD_HOME_LENDER) ?? { unshared: true as const }, lentChrome: CLOUD_PERSONAL ? { route: () => deviceLinks.chromeRoute(CLOUD_HOME_LENDER), lender: () => sharedComputers.chromeLender(CLOUD_HOME_LENDER) } : undefined });const dataSheets = new DataSheetRegistry({@@ -12034,7 +12034,7 @@ ROUTES.push(createBotMemoryRoutes({}));const teamMoveIn = CLOUD_TEAM ? createTeamMoveIn({ team: CLOUD_TEAM, dataDir: DATA_DIR, sessions, store, routines: () => routines, library: () => readSkillLibraryIndex(), starters: threadStarters }) : null; const cloudSendOwner = (auth: RequestAuth) => teamMoveIn ? teamMoveIn.owner(auth) : (CLOUD_HOME && auth.kind === "session" && auth.scopes.includes("admin")) || ownHome.owner(auth) ? { person: actorKey(auth as RequestAuth & { kind: "session" }), name: cfg.profile?.name?.trim() || "User" } : desktopMainMover(auth, { desktopManaged: DESKTOP_MANAGED, managed: Boolean(CLOUD_HOME || HOSTED_WORKSPACE) }) ? thisComputerOwner(cfg.profile?.name) : null; const botMoves = CLOUD_PERSONAL || DESKTOP_MANAGED ? createBotMoves({ store, routines: () => routines, webhooks: () => webhooks, appEvents: () => appTriggers.manager, waits: () => botWaits, busy: (id) => botHasActiveTurn(id) || Boolean(routines?.activeRunForBot(id)), computer: !CLOUD_HOME, mcp: (id) => mcpServersHere(cfg, id), arrivals: arrivalsFile(DATA_DIR), stays: (id) => staysOnCloud(store.bot(id), { logins: logins.changes().length, secrets: logins.listSecrets(TEAM_READER).length, onePassword: logins.onePasswordConnectedAt() !== null, mcpServers: Object.keys(cfg.mcpServers ?? {}) }), lapseCheckMs: 15_000, log: (line) => console.error(line) }) : null; ROUTES.push(createBotMoveRoutes({ moves: botMoves, enabled: Boolean(botMoves) })); if (teamMoveIn) { ROUTES.unshift(teamMoveIn.guard); ROUTES.push(teamMoveIn.routes); teamOwners.backfill(teamMoveIn.list()); } ROUTES.push(createDeciderRoutes({ decider, extractor, config: () => cfg }), createImageSettingsRoutes({ config: () => cfg }), createTtsRoutes({ config: () => cfg }), createHelperSuggestionRoutes({ notNow: proactive.suggestionNotNow }), createSetupRequestRoutes({ store, language: personLanguages.forPlace, sendRefusal: cloudGuestSendRefusal, presser: (auth) => setupPresser(sharedMembership(), auth, messageSender(auth)), canSetUp: (botId, threadId) => registry.get(store.projectBotForTask(botId, threadId)?.modelSelection.instanceId ?? "")?.adapter.capabilities.agentsMcp === true, send: (auth, botId, threadId, text) => acceptDirectSend({ botId, threadId, text, sender: messageSender(auth), trigger: usageTriggerFor(auth), personPresent: auth.kind === "session" || DESKTOP_MANAGED }) }), createNotificationRoutes(undefined, notificationListed), createUpdateCheckRoutes(updateRouteDeps({ desktopManaged: DESKTOP_MANAGED, managed: Boolean(CLOUD_HOME || HOSTED_WORKSPACE), dataDir: DATA_DIR, activeTurns: () => liveTurnByThread.size, actor: adminActorFor })), createSeatsRoutes({ signInList: signInAllowList, sessions: () => sessions.list() }), createTimeZoneRoutes({ adopts: Boolean(CLOUD_HOME), dataDir: DATA_DIR, changed: () => routines?.rescheduleLocalTimes() }), createCloudSendRoutes({ appVersion: serverVersion(), ...(CLOUD_TEAM ? { refusal: personalMoveRefusal(CLOUD_TEAM), scope: (auth) => teamMoveIn?.scope(auth) ?? null } : {}), bots: () => store.bots, messagesTail: (threadId, limit) => store.messagesTail(threadId, limit), skills: (bot) => listSkills(bot.id), logins, config: () => cfg, lineLanguage: personLanguages.forLine, changes: { bots: () => store.bots, instances: () => cfg.instances ?? {}, mcpServers: () => cfg.mcpServers, skills: (bot) => listSkills(bot.id).map((skill) => ({ name: skill.name, enabled: skill.enabled, text: readSkillFile(bot.id, skill.name) })) }, chats: { store, dataDir: DATA_DIR, owner: cloudSendOwner, ...(CLOUD_OWNER_KEY ? { ownerKey: CLOUD_OWNER_KEY } : {}), stamped: (threadId) => ownerOnlyCache.delete(threadId), instanceExists: (id) => Boolean(registry.get(id)), approvalSupported: (selection, mode) => supportsApprovalMode(selection, mode) }, cloudHome: Boolean(CLOUD_HOME), ownHome: ownHome.owner, automations: { routines: () => routines, calls: () => calendarCalls, webhooks: () => webhooks, appEvents: () => appTriggers.manager, waits: () => botWaits }, connectionsMoved: (language) => cloudConnections.moved(language), connections: () => cloudConnections.connections(), connectionFingerprints: (nonce) => cloudConnections.fingerprints(nonce), move: { dataDir: DATA_DIR, store, routines: () => routines, calls: () => calendarCalls, webhooks: () => webhooks, appEvents: () => appTriggers.manager, claudeCodeSkills: () => (claudeUserSkillsEnabled(cfg) ? claudeCodeSkillInputs() : []), instanceExists: (id) => Boolean(registry.get(id)), owner: cloudSendOwner, ownRoutine: (routine, person) => { cloudRoutineAuthors?.record(routine.id, routine); cloudRoutineAuthors?.wrote(routine.id, person); }, arrived: () => ownerOnlyCache.clear(), teamMemory, aboutMe: () => cfg.profile?.aboutMe ?? "", saveAboutMe: (text) => { saveConfig({ profile: { ...cfg.profile, aboutMe: text } }); Object.assign(cfg, loadConfig()); broadcast({ kind: "config", ...configStatus() }); } } }), cloudConnections.routes, createTodayRoutes({ visibleFor: (auth) => visibleTo(viewerFor(auth)), ...(teamOwners.asks ? { asks: teamOwners.asks, messages: teamMessages.needsYou } : {}), sources: () => ({ bots: store.bots, groups: store.groups, routines, parked: coordinator.active(), engines: registry.instances().map((instance) => ({ instanceId: instance.instanceId, snapshot: registry.lastSnapshot(instance.instanceId) })) }) }), createInboxRoutes(teamMessages)); const conversationSharing = createConversationSharing({ team: CLOUD_TEAM, store: () => store, shares: conversationShares, saves: createTeamMemorySaves({ dataDir: DATA_DIR }), starter: (threadId) => threadStarters.get(threadId), audienceOf: teamHost.audienceOf, sees: (auth, threadId) => visibleTo(viewerFor(auth)).thread(threadId), levelOf, levelFor: (person, botId) => visibleTo(person.role === "member" ? { kind: "member", email: person.email } : { kind: "all", email: person.email }).level(botId), people: () => teamOwners.people?.list() ?? [], nameOf: (email) => teamHost.personName(personKey({ id: "", email })) ?? email, language: (person) => personLanguages.forLine(person), busy: threadBusy, routinesIn: (threadId) => (routines?.listRoutines() ?? []).filter((routine) => routine.sourceThreadId === threadId || routine.resultsThreadId === threadId).length, outside: cloudGuestDriven, audienceChanged: (botId, threadId) => { store.patchTask(botId, threadId, { rewound: true, resumeCursors: {} }); }, changed: (botId) => { const bot = store.bot(botId); if (bot) broadcast({ kind: "bot", bot: wireBot(bot) }); }, inbox: () => teamMessages.inbox, looking: (email, threadId) => teamPresence.looking(email, threadId), notify, botOf: (threadId) => store.botByThread(threadId)?.id, handTo: (threadId, person) => threadStarters.handTo(threadId, person) }); ROUTES.push(conversationSharing.routes);if (CLOUD_TEAM) teamHost.adoptServerProfile(sessions.list().flatMap((session) => session.email ? [session.email] : []));-const sidebarRoutes = createSidebarSectionRoutes({ store, teamComputers, maxBots: MAX_WORKSPACE_BOTS, assertTeamComputerChangeIdle, wireBot, visibleFor: (auth) => visibleTo(viewerFor(auth)), renamed: (from, to) => (to ? botHolds.rename(from, to) : botHolds.forget("department", from)) }); ROUTES.push(teamPresence.routes, sidebarRoutes, createPresenceRoutes({ isOwner: ownerOrAdmin, heard: (auth, language) => personLanguages.heard(auth.kind === "session" ? actorKey(auth) : THIS_COMPUTER, language), sawChat: (_auth, threadId, typing) => { if (!store.botByThread(threadId)) return; if (typing) enginePrestart.typedIn(threadId); sawThread(threadId); }, active: async (source, zone, language) => { const answer = await proactive.brief.active(source, zone, language); firstHourHooks.arrived(); return answer; }, ...(CLOUD_TEAM ? { member: (auth) => { noAiNotice.flush(); return teamMessages.arrived(auth); } } : {}) }), createMeRoutes({ team: CLOUD_TEAM, session: (auth) => (auth.kind === "session" ? auth.session : null), welcome: teamWelcome, profile: teamHost.memberProfile, save: teamHost.saveMemberProfile, seed: teamHost.seedMemberProfile, seeded: teamHost.seededFields, changed: () => broadcast({ kind: "config", ...configStatus() }), names: SELF_HOSTED ? { store: personNames, shownAs: sessionPersonName } : null }), teamAway.routes, createTeamPhoneRoutes({ team: CLOUD_TEAM, sessions, publicBase: (req, auth) => pairingLinkBase(publicUrl(), auth.kind === "session" ? requestOrigin(req) : null) }),+const sidebarRoutes = createSidebarSectionRoutes({ store, teamComputers, maxBots: MAX_WORKSPACE_BOTS, assertTeamComputerChangeIdle, wireBot, visibleFor: (auth) => visibleTo(viewerFor(auth)), renamed: (from, to) => (to ? botHolds.rename(from, to) : botHolds.forget("department", from)) }); ROUTES.push(teamPresence.routes, sidebarRoutes, signInBackupRoutes, createPresenceRoutes({ isOwner: ownerOrAdmin, heard: (auth, language) => personLanguages.heard(auth.kind === "session" ? actorKey(auth) : THIS_COMPUTER, language), sawChat: (_auth, threadId, typing) => { if (!store.botByThread(threadId)) return; if (typing) enginePrestart.typedIn(threadId); sawThread(threadId); }, active: async (source, zone, language) => { const answer = await proactive.brief.active(source, zone, language); firstHourHooks.arrived(); return answer; }, ...(CLOUD_TEAM ? { member: (auth) => { noAiNotice.flush(); return teamMessages.arrived(auth); } } : {}) }), createMeRoutes({ team: CLOUD_TEAM, session: (auth) => (auth.kind === "session" ? auth.session : null), welcome: teamWelcome, profile: teamHost.memberProfile, save: teamHost.saveMemberProfile, seed: teamHost.seedMemberProfile, seeded: teamHost.seededFields, changed: () => broadcast({ kind: "config", ...configStatus() }), names: SELF_HOSTED ? { store: personNames, shownAs: sessionPersonName } : null }), teamAway.routes, createTeamPhoneRoutes({ team: CLOUD_TEAM, sessions, publicBase: (req, auth) => pairingLinkBase(publicUrl(), auth.kind === "session" ? requestOrigin(req) : null) }),createTeamConnectionRoutes({ host: teamConnections, cfg: () => cfg, composio, policy: managedPolicy, publicOrigin: CLOUD_HOME?.publicOrigin ?? null, record: (auth, row) => appendAdminAction(DATA_DIR, { ...row, actor: decisionActorFor(auth) }) }), createSignInCardRoutes({ settle: signInSettle.settle, saveLogin: (botId, threadId, messageId, body, auth) => CLOUD_TEAM && !auth.scopes.includes("admin") ? Promise.resolve({ status: 403 as const, body: memberLoginRefusal(CLOUD_TEAM) }) : saveLoginFromCard(botId, threadId, messageId, body), saveTarget: signInSaveTarget, threadVisible: (auth, threadId) => visibleTo(viewerFor(auth)).thread(threadId), vault: createSignInVaultChoices({ logins, cardBots: (id) => botLogins.cardBots(id), settle: signInSettle.settle, openCard: (botId, threadId, messageId) => { const card = signInMessage(botId, threadId, messageId)?.signIn; return card && card.place === "browser" && !card.superseded && !card.answeredInChat && !card.stopped && !signInOutcome(card) ? card : null; } }) })); const appSuggestions = createAppSuggestions({ dataDir: DATA_DIR, store, configured: () => composio.configured(cfg), catalog: () => composio.listToolkits(cfg), services: async (live) => live ? composio.connectedServices(cfg) : (await composio.sharedConnectedInventory(cfg)).services, offerable: (slug) => !managedPolicy.appRefusal(slug) && !managedConnectorUnavailableReason(composio.connectionMode(cfg), slug) && !teamConnections.personApps().includes(slug), pickAvailable: () => appPickAvailable(cfg), decider }); ROUTES.push(createAppSuggestionRoutes(appSuggestions));ROUTES.push(createConnectorListingRoutes({ cfg: () => cfg, composio, managedHost: DESKTOP_MANAGED || CLOUD_HOME !== null })); composio.rememberCatalogIn(DATA_DIR); composio.onCatalogChange(() => broadcast({ kind: "apps-catalog" }, { adminOnly: true })); const githubSignIn = createGithubSignIn({ dataDir: DATA_DIR, team: Boolean(CLOUD_TEAM), vault: logins, tools: createGhTools({ dataDir: DATA_DIR, personalAllowed: () => !CLOUD_HOME && !HOSTED_WORKSPACE && !botBox.enabled() }), remember: (token) => heldSecrets.remember(token, "password") }); provideGithubSignIn(githubSignIn); ROUTES.push(createGithubSignInRoutes({ signIn: githubSignIn, team: Boolean(CLOUD_TEAM) })); const githubSignInCards = createGithubSignInCards({ store, signIn: githubSignIn, team: Boolean(CLOUD_TEAM), turnPerson: (threadId, generation) => teamConnections.turnPerson(threadId, generation), language: threadLanguage, threadVisible: (auth, threadId) => visibleTo(viewerFor(auth)).thread(threadId), resume: (threadId, resumeKey) => void maybeResumeConnectors(threadId, resumeKey), release: (threadId, messageId) => releaseCardNode(threadId, messageId, "The connection request was dismissed") }); provideGithubSignInCards(githubSignInCards); ROUTES.push(createGitCredentialRoutes({ port: PORT, enabled: () => !CLOUD_HOME && !HOSTED_WORKSPACE && !CLOUD_TEAM && !botBox.enabled() }));ROUTES.push(createRoomHoldRoutes({@@ -12905,7 +12905,7 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {if (body.method === "tools/call") {const abort = new AbortController(); res.once("close", () => { if (!res.writableEnded) abort.abort(); });const refused = await browserSeats.take(internalCapability, browser.session, abort.signal); requireActiveInternalCapability();- if (refused) return json(res, 200, { result: { isError: true, content: [{ type: "text", text: refused }] } }); if (!claimTurnResource(internalCapability, `browser:${browser.session}`)) throw Object.assign(new Error("another thread is using this browser — pause browser work until that thread finishes"), { status: 409 }); browser = (await browserIntegration(bot.id, bot.browserProfile, undefined, teamHost.browserAudience(internalCapability.threadId), { opening: String(body?.params?.name ?? "") || null })) ?? browser; // Only now, past the seat and the claim, may it open the Cloud's browser sandbox: a refused call never spends a start.+ if (refused) return json(res, 200, { result: { isError: true, content: [{ type: "text", text: refused }] } }); if (!claimTurnResource(internalCapability, `browser:${browser.session}`)) throw Object.assign(new Error("another thread is using this browser — pause browser work until that thread finishes"), { status: 409 }); browser = (await browserIntegration(bot.id, bot.browserProfile, undefined, teamHost.browserAudience(internalCapability.threadId), { opening: String(body?.params?.name ?? "") || null, params: body?.params })) ?? browser; // Only now, past the seat and the claim, may it open the Cloud's browser sandbox: a refused call never spends a start.}let params = body.params;if (body.method === "tools/call" && params?.name === BROWSER_UPLOAD_TOOL) {diff --git a/server/routes/browser-sign-in-backups.ts b/server/routes/browser-sign-in-backups.tsnew file mode 100644index 0000000000..bde3264477--- /dev/null+++ b/server/routes/browser-sign-in-backups.ts@@ -0,0 +1,45 @@+// A bot's saved sign-ins as they were when each of its sessions in the Cloud's browser sandbox opened (browser-sites.ts+// backupSignIns), for the owner to put back after a session that changed them wrongly:+// GET /api/bots/<id>/browser-sign-ins/backups the backups, newest first: id, when, size (never a cookie)+// POST /api/bots/<id>/browser-sign-ins/restore {backup} the sign-ins put back as that backup holds them+// The owner's (or an admin's) only. No screen uses it yet.+import type { SignInBackup } from "../browser-sites.ts";+import { ownerOrAdmin, type RequestAuth } from "../request-auth.ts";+import { PASS, type RouteHandler } from "./table.ts";++export type SignInRestore = "restored" | "no-bot" | "no-backup" | "open";++export interface SignInBackupDeps {+ /** The bot's backups, or null when there is no such bot. */+ backups(botId: string): SignInBackup[] | null;+ restore(botId: string, id: string): Promise<SignInRestore>;+ isOwner?(auth: RequestAuth): boolean;+}++const ROUTE = /^\/api\/bots\/([^/]{1,200})\/browser-sign-ins\/(backups|restore)$/;+const BACKUP_ID = /^\d{13}$/;++export function createSignInBackupRoutes(deps: SignInBackupDeps): RouteHandler {+ const isOwner = deps.isOwner ?? ownerOrAdmin;+ return async ({ req, res, path, method, auth, json, readBody }) => {+ const match = ROUTE.exec(path);+ if (!match) return PASS;+ let botId: string;+ try { botId = decodeURIComponent(match[1]!); } catch { return json(res, 404, { error: "No such bot." }); }+ if (!isOwner(auth)) return json(res, 403, { error: "Only the owner can see or restore a bot's saved sign-ins." });+ if (match[2] === "backups") {+ if (method !== "GET") return json(res, 405, { error: "Use GET." });+ const backups = deps.backups(botId);+ if (!backups) return json(res, 404, { error: "No such bot." });+ return json(res, 200, { backups: backups.map((backup) => ({ id: backup.id, takenAt: new Date(backup.takenAt).toISOString(), bytes: backup.bytes })) });+ }+ if (method !== "POST") return json(res, 405, { error: "Use POST." });+ const body: unknown = await readBody(req, 1024).catch(() => null);+ const id = (body as { backup?: unknown } | null)?.backup;+ if (typeof id !== "string" || !BACKUP_ID.test(id)) return json(res, 400, { error: "Send {backup: <id>}, an id from the backups list." });+ const outcome = await deps.restore(botId, id);+ if (outcome === "restored") return json(res, 200, { ok: true });+ if (outcome === "open") return json(res, 409, { error: "This bot's browser is open. Close it first, then restore its sign-ins." });+ return json(res, 404, { error: outcome === "no-bot" ? "No such bot." : "No such backup of this bot's sign-ins." });+ };+}