Skip to content

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

Cloud browser: the home's sign-ins are the truth at open, write-back merges only the session's own changes; downloads capped against the Cloud's disk

milind-sonif3783c55cd04
diff --git a/server/cloud-browser/cloud-browser.test.ts b/server/cloud-browser/cloud-browser.test.ts
index cc61d03c9a..598b77fd92 100644
--- a/server/cloud-browser/cloud-browser.test.ts
+++ b/server/cloud-browser/cloud-browser.test.ts
@@ -9,7 +9,8 @@ import WebSocket from "ws";
import type { AppConfig } from "../config.ts";
import { ComputerIdleTimer } from "../computer-idle.ts";
import { LOCAL_SCHEME_REFUSAL, localSchemeRefusal } from "./guards.ts";
-import { UPLOAD_MAX_BYTES, type SignInStore } from "./companion.ts";
+import { SESSION_DOWNLOAD_BYTES, SIGN_IN_SYNC_MS, UPLOAD_MAX_BYTES, type SignInStore } from "./companion.ts";
+import { cookieParam } from "./sign-ins.ts";
import { CLOUD_BROWSER_IDLE_MS, createCloudBrowser, type CloudBrowserDeps } from "./index.ts";
import { CLOUD_BROWSER_BACKOFF_MS, createCloudBrowserRails } from "./rails.ts";
import { BROWSER_SANDBOX_CHROMES, BROWSER_SANDBOX_OWNER, browserSandboxCreateBody, profileKey, providerOps } from "./remote.ts";
@@ -57,6 +58,8 @@ function browser(overrides: Partial<CloudBrowserDeps> & { budget?: number; awake
log: () => {},
pollMs: 5,
rails: createCloudBrowserRails({ dataDir: dir, now, ...(budget ? { budget } : {}), ...(awakeMinutes ? { awakeMinutes } : {}) }),
+ // A roomy disk, whatever this machine's own is.
+ disk: () => ({ free: 100 * 1024 ** 3, total: 200 * 1024 ** 3 }),
...rest,
});
browsers.push(created);
@@ -507,6 +510,110 @@ describe("a bot's sign-ins between the home and its sandbox profile", () => {
expect(fake.cookies.get(profileKey("scout"))?.map((cookie) => cookie.name)).toContain("fallback");
});
+ it("a sign-out in the home stays a sign-out: the home's newer copy replaces the sandbox's cookies, and nothing old is written back", async () => {
+ const home = memorySignIns({ cookies: [SIGNED_IN], origins: [] });
+ const cloud = browser({ signIns: home.store });
+ urlOf(await cloud.open(request()));
+ clock += CLOUD_BROWSER_IDLE_MS;
+ await cloud.closeIdle();
+ // The person uses "Sign out of all sites" in Settings: the home's copy is now empty, and newer.
+ home.change({ cookies: [], origins: [] });
+ urlOf(await cloud.open(request()));
+ expect(fake.cookies.get(profileKey("scout")), "the sandbox's old cookie is gone").toEqual([]);
+ const writes = home.writes.length;
+ clock += CLOUD_BROWSER_IDLE_MS;
+ await cloud.closeIdle();
+ expect(home.writes.length, "nothing changed in the session, so nothing is written back").toBe(writes);
+ expect(home.store.load("bot-scout")).toMatchObject({ state: { cookies: [] } });
+ });
+
+ it("a replaced sandbox gets the home's copy carried in, and a profile that lost its cookies never empties the home", async () => {
+ const home = memorySignIns({ cookies: [SIGNED_IN], origins: [] });
+ const cloud = browser({ signIns: home.store });
+ urlOf(await cloud.open(request()));
+ clock += CLOUD_BROWSER_IDLE_MS;
+ await cloud.closeIdle();
+ // The same sandbox, its profile emptied (Chrome lost its cookies): the home's copy is not newer, so nothing is carried,
+ // and the close writes back only what the session itself changed.
+ fake.cookies.set(profileKey("scout"), []);
+ urlOf(await cloud.open(request()));
+ clock += CLOUD_BROWSER_IDLE_MS;
+ await cloud.closeIdle();
+ expect(home.store.load("bot-scout")).toMatchObject({ state: { cookies: [expect.objectContaining({ name: "sid" })] } });
+ // A new sandbox (the provider broke the old one): its empty profile gets the home's copy.
+ fake.state = "error";
+ urlOf(await cloud.open(request()));
+ expect(fake.boxId).not.toBe("bx_23456789");
+ expect(fake.cookies.get(profileKey("scout"))).toEqual([expect.objectContaining({ name: "sid", value: "s1" })]);
+ });
+
+ it("writes back only the cookies the session changed: one the session never touched stays as the home has it", async () => {
+ const home = memorySignIns({ cookies: [SIGNED_IN, { ...SIGNED_IN, name: "keep", domain: "keep.example", value: "home" }], origins: [] });
+ const cloud = browser({ signIns: home.store });
+ urlOf(await cloud.open(request()));
+ const key = profileKey("scout");
+ // In the session: one cookie changed, one signed out of, one new.
+ fake.cookies.set(key, [{ name: "sid", value: "s2", domain: ".example.com", path: "/", secure: true, httpOnly: true, sameSite: "Lax" },
+ { name: "new", value: "n", domain: "new.example", path: "/" }]);
+ clock += CLOUD_BROWSER_IDLE_MS;
+ await cloud.closeIdle();
+ const saved = (home.store.load("bot-scout") as { state: { cookies: Array<{ name: string; value: string }> } }).state.cookies;
+ expect(saved.map((cookie) => [cookie.name, cookie.value]).sort()).toEqual([["new", "n"], ["sid", "s2"]]);
+ });
+
+ it("skips a cookie Chrome refuses instead of failing the carry, never counts it against the sandbox, and does not carry the same copy again", async () => {
+ const broken = { ...SIGNED_IN, name: "bad", domain: "bad.example", sameSite: "None", secure: false };
+ const lines: string[] = [];
+ const home = memorySignIns({ cookies: [SIGNED_IN, broken], origins: [] });
+ const cloud = browser({ signIns: home.store, log: (line) => lines.push(line) });
+ urlOf(await cloud.open(request()));
+ expect(fake.cookies.get(profileKey("scout"))?.map((cookie) => cookie.name)).toEqual(["sid"]);
+ expect(lines.join("\n")).toContain("1 refused by Chrome");
+ expect(cloud.report().held).toBeNull();
+ clock += CLOUD_BROWSER_IDLE_MS;
+ await cloud.closeIdle();
+ const sets = fake.commands.filter((one) => one.method === "Storage.setCookies").length;
+ urlOf(await cloud.open(request()));
+ expect(fake.commands.filter((one) => one.method === "Storage.setCookies").length).toBe(sets);
+ });
+
+ it("when Chrome takes nothing of the home's copy, opens in the home, never as a sandbox failure, and wakes the sandbox for it again only once the copy changes", async () => {
+ fake.failing.add("Storage.clearCookies");
+ const home = memorySignIns({ cookies: [SIGNED_IN], origins: [] });
+ const cloud = browser({ signIns: home.store });
+ expect(await cloud.open(request())).toEqual({ home: "sign-ins" });
+ expect(cloud.report().held, "no back-off for anyone").toBeNull();
+ fake.state = "archived";
+ const asked = fake.requests.length;
+ expect(await cloud.open(request())).toEqual({ home: "sign-ins" });
+ expect(fake.requests.length, "no wake for the same refused copy").toBe(asked);
+ fake.failing.clear();
+ home.change({ cookies: [SIGNED_IN], origins: [] });
+ urlOf(await cloud.open(request()));
+ });
+
+ it("writes a long session's changed sign-ins home every 10 minutes, so an unclean end loses minutes at most", async () => {
+ const home = memorySignIns(null);
+ const cloud = browser({ signIns: home.store });
+ const cdpUrl = urlOf(await cloud.open(request()));
+ clock += SIGN_IN_SYNC_MS;
+ await act(cdpUrl, 1);
+ await cloud.closeIdle();
+ expect(home.writes, "nothing changed yet").toEqual([]);
+ fake.cookies.set(profileKey("scout"), [{ name: "auth", value: "a", domain: "mail.example", path: "/" }]);
+ clock += SIGN_IN_SYNC_MS;
+ await act(cdpUrl, 1);
+ await cloud.closeIdle();
+ expect(home.writes).toEqual([[expect.objectContaining({ name: "auth" })]]);
+ expect(cloud.active("bot-scout"), "the session goes on").toBe(cdpUrl);
+ });
+
+ it("keeps a cookie's partition, saved as an object or as a site's text", () => {
+ expect(cookieParam({ ...SIGNED_IN, partitionKey: "https://top.example" })).toMatchObject({ partitionKey: "https://top.example" });
+ expect(cookieParam({ ...SIGNED_IN, partitionKey: { topLevelSite: "https://top.example", hasCrossSiteAncestor: false } }))
+ .toMatchObject({ partitionKey: { topLevelSite: "https://top.example", hasCrossSiteAncestor: false } });
+ });
+
it("never puts a cookie value in the log", async () => {
const lines: string[] = [];
const cloud = browser({ signIns: memorySignIns({ cookies: [SIGNED_IN], origins: [] }).store, log: (line) => lines.push(line) });
@@ -568,6 +675,37 @@ describe("downloads and uploads of a browser in the sandbox", () => {
expect(fake.files.has(downloadPath("retry-guid"))).toBe(false);
});
+ it("keeps a download in the sandbox when the Cloud's disk would be left with less than 1 GiB or 10% free", async () => {
+ const cloud = browser({ folder: () => folder, disk: () => ({ free: 1.5 * 1024 ** 3, total: 10 * 1024 ** 3 }) });
+ urlOf(await cloud.open(request()));
+ fake.files.set(downloadPath("full-guid"), Buffer.alloc(16));
+ fake.emit(profileKey("scout"), "Browser.downloadWillBegin", { guid: "full-guid", suggestedFilename: "movie.mp4" });
+ fake.emit(profileKey("scout"), "Browser.downloadProgress", { guid: "full-guid", totalBytes: 600 * 1024 ** 2, receivedBytes: 600 * 1024 ** 2, state: "completed" });
+ await vi.waitFor(() => expect(cloud.takeNotes("bot-scout").join("\n")).toContain("the Cloud's disk is too full for it"));
+ expect(fake.files.has(downloadPath("full-guid"))).toBe(true);
+ });
+
+ it("brings at most 2 GiB of downloads into the Cloud per session", async () => {
+ const cloud = browser({ folder: () => folder, disk: () => ({ free: 100 * 1024 ** 3, total: 200 * 1024 ** 3 }) });
+ urlOf(await cloud.open(request()));
+ fake.files.set(downloadPath("huge-guid"), Buffer.alloc(8));
+ fake.emit(profileKey("scout"), "Browser.downloadWillBegin", { guid: "huge-guid", suggestedFilename: "a.bin" });
+ fake.emit(profileKey("scout"), "Browser.downloadProgress", { guid: "huge-guid", totalBytes: SESSION_DOWNLOAD_BYTES + 1, receivedBytes: 10, state: "inProgress" });
+ await vi.waitFor(() => expect(fake.commands.some((one) => one.method === "Browser.cancelDownload")).toBe(true));
+ });
+
+ it("a last retry's line at close reaches the session's next call", async () => {
+ let available = false;
+ const cloud = browser({ folder: () => (available ? folder : null) });
+ urlOf(await cloud.open(request()));
+ await finish("late-guid", "late.txt", Buffer.from("x"));
+ await vi.waitFor(() => expect(cloud.takeNotes("bot-scout")).toHaveLength(1));
+ await cloud.close("bot-scout");
+ expect(cloud.takeNotes("bot-scout")).toEqual([expect.stringContaining(`"late.txt" was downloaded in the browser but could not be brought`)]);
+ expect(cloud.takeNotes("bot-scout")).toEqual([]);
+ available = true;
+ });
+
it("gives a page a file from the Cloud by copying it into the sandbox first, and refuses a large one in one line", async () => {
const cloud = browser();
urlOf(await cloud.open(request()));
diff --git a/server/cloud-browser/companion.ts b/server/cloud-browser/companion.ts
index 3e79be0b21..f4b95335c8 100644
--- a/server/cloud-browser/companion.ts
+++ b/server/cloud-browser/companion.ts
@@ -1,19 +1,25 @@
// What rides beside a bot's browser session in the Cloud's browser sandbox, on one more connection through the same door:
// its sign-ins carried in from the home when they changed there, carried back to the home on a clean close, and its
// downloads brought to the bot's working folder as they finish. Uploads go the other way, one file at a time.
-import { existsSync } from "node:fs";
+import { existsSync, statfsSync } from "node:fs";
import { basename, dirname, join } from "node:path";
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 } from "./sign-ins.ts";
+import { carryIn, carryOut, cookieChanges, mergeCookies, type SavedCookie } from "./sign-ins.ts";
/** Where a download lands in the bot's working folder. */
export const DOWNLOADS_SUBFOLDER = "downloads";
/** The largest file an upload copies into the sandbox; a larger one fails that one action with a line. */
export const UPLOAD_MAX_BYTES = 50 * 1024 * 1024;
+/** Downloads one session may bring into the Cloud in all. */
+export const SESSION_DOWNLOAD_BYTES = 2 * 1024 ** 3;
+/** A download is brought over only if the Cloud's disk keeps at least this much free afterwards, and 10% of it. */
+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;
export interface SignInStore {
/** The home's saved sign-ins for a session, when they last changed; null when none; "unreadable" when not readable now. */
@@ -36,12 +42,25 @@ export interface CompanionDeps {
folder(botId: string): string | null;
connect(url: string, listeners: { event(message: CdpEvent): void }): Promise<Cdp>;
log(line: string): void;
+ now?: () => number;
+ /** Bytes free and in all on the disk of a folder; tests pass their own. */
+ disk?(folder: string): { free: number; total: number };
}
/** The home's sign-ins could not be read now: the session opens in the home this time, and the carry is tried next time. */
export class SignInsUnreadable extends Error {}
-interface Pending { guid: string; name: string }
+/** Chrome would not take the home's copy at all (not one cookie's refusal: those are skipped): the session opens in the
+ * home, and this copy is not tried again, nor the sandbox woken for it, until the home's copy changes. */
+export class CarryFailed extends Error {
+ readonly modified: number;
+ constructor(modified: number) {
+ super("carry failed");
+ this.modified = modified;
+ }
+}
+
+interface Pending { guid: string; name: string; bytes: number }
export class SandboxCompanion {
readonly #deps: CompanionDeps;
@@ -51,7 +70,15 @@ export class SandboxCompanion {
readonly #pending = new Map<string, Pending>();
readonly #notes: string[] = [];
#started = 0;
+ #delivered = 0;
+ readonly #sizes = new Map<string, number>();
#delivering: Promise<void> = Promise.resolve();
+ /** The profile's cookies as of the last carry or write-back: what the session changed is measured against them. */
+ #baseline: SavedCookie[] | null = null;
+ /** The home's copy was carried into this sandbox in this session, so a removal since then is the person's own. */
+ #carried = false;
+ #syncedAt = 0;
+ #syncing = false;
constructor(deps: CompanionDeps) { this.#deps = deps; }
@@ -59,19 +86,60 @@ export class SandboxCompanion {
/** Opens its connection, carries the home's sign-ins in when they changed since the last carry, and takes the session's
* downloads. Throws SignInsUnreadable, or any failure, before the session is used: it then opens in the home. */
+ /** The sync stamp is this sandbox's: a replaced sandbox (a fresh, empty profile) gets the home's copy carried in again. */
+ get #stamp(): string { return `${this.#deps.boxId}:${this.#deps.key}`; }
+ #now(): number { return this.#deps.now?.() ?? Date.now(); }
+
async start(cdpUrl: string): Promise<void> {
- const { session, key, rails, signIns } = this.#deps;
+ const { session, rails, signIns } = this.#deps;
const loaded = signIns ? signIns.load(session) : null;
if (loaded === "unreadable") throw new SignInsUnreadable();
this.#cdp = await this.#deps.connect(cdpUrl, { event: (message) => this.#event(message) });
- if (loaded && loaded.modified > rails.carried(key)) {
- const carried = await carryIn(this.#cdp, loaded.state);
- rails.setCarried(key, loaded.modified);
- this.#deps.log(`browser ${session}: carried ${carried.cookies} saved cookies and ${carried.origins} sites' storage into the browser sandbox`);
+ if (signIns && loaded && loaded.modified > rails.carried(this.#stamp)) {
+ // The home's copy is newer than this sandbox's last sync: it is the truth at open, sign-outs included.
+ const carried = await carryIn(this.#cdp, loaded.state).catch(() => { throw new CarryFailed(loaded.modified); });
+ rails.setCarried(this.#stamp, loaded.modified);
+ this.#carried = true;
+ this.#baseline = carried.set;
+ this.#deps.log(`browser ${session}: carried ${carried.cookies} saved cookies${carried.refused ? ` (${carried.refused} refused by Chrome and left out)` : ""} and ${carried.origins} sites' storage into the browser sandbox`);
+ } else if (signIns) {
+ this.#baseline = await carryOut(this.#cdp);
}
+ this.#syncedAt = this.#now();
await this.#cdp.send("Browser.setDownloadBehavior", { behavior: "allowAndName", downloadPath: this.downloadDir, eventsEnabled: true });
}
+ /** Writes the session's own cookie changes into the home's copy: a cookie the session never touched stays as the home
+ * has it, and an empty profile that was never carried into never empties the home. */
+ async syncSignIns(): Promise<void> {
+ const { session, rails, signIns } = this.#deps;
+ if (!this.#cdp || !signIns || this.#baseline === null || this.#syncing) return;
+ this.#syncing = true;
+ try {
+ const current = await carryOut(this.#cdp);
+ const changes = cookieChanges(this.#baseline, current);
+ this.#syncedAt = this.#now();
+ if (!changes.set.length && !changes.removed.length) return;
+ const home = signIns.load(session);
+ if (home === "unreadable") return;
+ const before = home?.state.cookies ?? [];
+ const merged = mergeCookies(before, changes);
+ if (!this.#carried && before.length > 0 && merged.length < before.length / 2) {
+ this.#deps.log(`browser ${session}: kept the home's saved sign-ins: the browser sandbox's profile had far fewer and was never carried into this session`);
+ return;
+ }
+ rails.setCarried(this.#stamp, signIns.save(session, merged));
+ this.#baseline = current;
+ } finally {
+ this.#syncing = false;
+ }
+ }
+
+ /** From the controller's sweep: a long session's changed sign-ins go home every SIGN_IN_SYNC_MS. */
+ async periodic(): Promise<void> {
+ if (this.#now() - this.#syncedAt >= SIGN_IN_SYNC_MS) await this.syncSignIns().catch(() => undefined);
+ }
+
/** Lines for the bot's next browser call: downloads that arrived, or could not. */
takeNotes(): string[] { return this.#notes.splice(0); }
@@ -90,8 +158,7 @@ export class SandboxCompanion {
for (const pending of this.#pending.values()) await this.#deliver(pending);
if (this.#cdp && this.#deps.signIns) {
try {
- const cookies = await carryOut(this.#cdp);
- this.#deps.rails.setCarried(this.#deps.key, this.#deps.signIns.save(this.#deps.session, cookies));
+ await this.syncSignIns();
} catch (error) {
this.#deps.log(`browser ${this.#deps.session}: could not save the browser sandbox's sign-ins in the home (${error instanceof Error ? error.name : "error"}); they stay in the sandbox`);
}
@@ -118,6 +185,8 @@ export class SandboxCompanion {
this.#names.set(guid, safeFileName(String(params.suggestedFilename ?? "")) || "download");
return;
}
+ const seen = Math.max(Number(params.totalBytes) || 0, Number(params.receivedBytes) || 0);
+ if (seen) this.#sizes.set(guid, seen);
if (message.method !== "Browser.downloadProgress") return;
const name = this.#names.get(guid) ?? "download";
const bytes = Math.max(Number(params.totalBytes) || 0, Number(params.receivedBytes) || 0);
@@ -130,7 +199,8 @@ export class SandboxCompanion {
if (params.state === "canceled") { this.#names.delete(guid); return; }
if (params.state !== "completed") return;
this.#names.delete(guid);
- const pending = { guid, name };
+ const pending = { guid, name, bytes: this.#sizes.get(guid) ?? 0 };
+ this.#sizes.delete(guid);
this.#delivering = this.#delivering.then(() => this.#deliver(pending));
}
@@ -142,15 +212,24 @@ export class SandboxCompanion {
this.#notes.push(`"${pending.name}" was downloaded in the browser but could not be brought to your working folder (${why}). It is kept in the browser sandbox for a day and is tried again when this browser closes.`);
};
if (!folder) return failed("your working folder is not available right now");
+ if (this.#delivered + pending.bytes > SESSION_DOWNLOAD_BYTES) return failed(`this browser session already brought ${SESSION_DOWNLOAD_BYTES / 1024 ** 3} GiB of downloads into the Cloud`);
+ const disk = (this.#deps.disk ?? diskOf)(folder);
+ 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) return failed(fetched.error);
this.#pending.delete(pending.guid);
+ this.#delivered += fetched.bytes;
await ops.removeDownload(boxId, key, pending.guid).catch(() => undefined);
this.#notes.push(`Downloaded "${pending.name}" into your working folder as ${fetched.path} (${fetched.bytes} bytes).`);
}
}
+function diskOf(folder: string): { free: number; total: number } {
+ const disk = statfsSync(folder);
+ return { free: Number(disk.bavail) * Number(disk.bsize), total: Number(disk.blocks) * Number(disk.bsize) };
+}
+
/** `downloads/<name>`, or `downloads/<name> (2)` and so on when that is taken, as a browser names a second copy. */
function unusedName(folder: string, name: string): string {
const dot = name.lastIndexOf(".");
diff --git a/server/cloud-browser/index.ts b/server/cloud-browser/index.ts
index 1dd501deb5..1ea7701640 100644
--- a/server/cloud-browser/index.ts
+++ b/server/cloud-browser/index.ts
@@ -8,7 +8,7 @@ import { randomBytes } from "node:crypto";
import { cloudFailureOf } from "../boat-limit.ts";
import { CloudBrowserDoors, dialable, probeDoor, type DoorTarget } from "./door.ts";
import { connectCdp } from "../browser-sites.ts";
-import { SandboxCompanion, SignInsUnreadable, type CompanionDeps, type SignInStore } from "./companion.ts";
+import { CarryFailed, SandboxCompanion, SignInsUnreadable, type CompanionDeps, type SignInStore } from "./companion.ts";
import { createCloudBrowserRails, type CloudBrowserRails, type HomeReason } from "./rails.ts";
import { BROWSER_SANDBOX_CHROMES, BROWSER_SANDBOX_OWNER, COMPUTER_DOOR_PORT, OldRelay, profileKey, StaysHome, wakeSandbox, type ComputerOps } from "./remote.ts";
@@ -36,6 +36,8 @@ export interface CloudBrowserDeps {
folder?(botId: string): string | null;
/** Tests: the companion's own connection through the door. */
connect?: CompanionDeps["connect"];
+ /** Tests: the Cloud disk's free and total bytes. */
+ disk?: CompanionDeps["disk"];
env?: NodeJS.ProcessEnv;
now?: () => number;
log?: (line: string) => void;
@@ -78,6 +80,8 @@ export function createCloudBrowser(deps: CloudBrowserDeps) {
const pendingSessions = new Map<string, Promise<Opened>>();
const closing = new Set<string>();
const companions = new Map<string, SandboxCompanion>();
+ /** What a closed session's companion still had to say (a last download retry), for that session's next call. */
+ 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;
let boxId: string | null = null;
@@ -168,7 +172,7 @@ export function createCloudBrowser(deps: CloudBrowserDeps) {
const cdpUrl = await doors.open(request.session, target);
const companion = new SandboxCompanion({
session: request.session, botId: request.botId, key, boxId: box.id, home: answer.home, ops, rails, signIns: deps.signIns ?? null,
- folder: (botId) => deps.folder?.(botId) ?? null, log,
+ folder: (botId) => deps.folder?.(botId) ?? null, log, now, ...(deps.disk ? { disk: deps.disk } : {}),
connect: deps.connect ?? ((url, listeners) => connectCdp(url, 10_000, listeners)),
});
try {
@@ -178,9 +182,11 @@ export function createCloudBrowser(deps: CloudBrowserDeps) {
doors.close(request.session);
await quit();
if (error instanceof SignInsUnreadable) return home(request, "sign-ins");
+ if (error instanceof CarryFailed) { rails.setCarryBad(key, error.modified); return home(request, "sign-ins"); }
rails.failed();
return home(request, "unreachable");
}
+ rails.setCarryBad(key, null);
companions.set(request.session, companion);
sessions.set(request.session, request.botId);
rails.opened();
@@ -233,6 +239,10 @@ export function createCloudBrowser(deps: CloudBrowserDeps) {
// One Chrome per bot's profile: a second session of the same bot (another audience's) stays in the home.
if (bots().has(request.botId)) return home(request, "busy");
if (bots().size >= BROWSER_SANDBOX_CHROMES) return home(request, "sandbox-full");
+ // The home's copy Chrome refused before, unchanged since: not worth a wake.
+ const known = deps.signIns?.load(request.session);
+ const bad = rails.carryBad(profileKey(request.botId));
+ if (bad !== null && known && known !== "unreadable" && known.modified === bad) return home(request, "sign-ins");
opening.add(request.botId);
try {
return await launch(request, ops);
@@ -248,7 +258,10 @@ export function createCloudBrowser(deps: CloudBrowserDeps) {
if (!botId || closing.has(session)) return;
closing.add(session);
try {
- await companions.get(session)?.stop().catch(() => undefined);
+ const companion = companions.get(session);
+ await companion?.stop().catch(() => undefined);
+ const notes = companion?.takeNotes() ?? [];
+ if (notes.length) leftNotes.set(session, notes);
companions.delete(session);
await deps.closeEngine(session).catch(() => undefined);
doors.close(session);
@@ -264,6 +277,7 @@ export function createCloudBrowser(deps: CloudBrowserDeps) {
async function closeIdle(): Promise<void> {
const at = now();
+ await Promise.all([...companions.values()].map((companion) => companion.periodic()));
await Promise.all(doors.sessions().map(async (session) => {
const last = doors.lastActivity(session);
if (last !== null && at - last >= CLOUD_BROWSER_IDLE_MS && !deps.held(session)) await close(session);
@@ -288,7 +302,11 @@ export function createCloudBrowser(deps: CloudBrowserDeps) {
closeIdle,
dialed: (session: string): number => doors.dialed(session),
/** Lines for the session's next browser call (downloads that arrived, or could not). */
- takeNotes: (session: string): string[] => companions.get(session)?.takeNotes() ?? [],
+ takeNotes: (session: string): string[] => {
+ const left = leftNotes.get(session) ?? [];
+ leftNotes.delete(session);
+ return [...left, ...(companions.get(session)?.takeNotes() ?? [])];
+ },
/** A file of the Cloud given to the session's browser for a page's file input: its path in the sandbox, or the line to say. */
upload: (session: string, file: string, name: string | null, size: number) =>
companions.get(session)?.upload(file, name, size) ?? Promise.resolve({ error: "This browser closed; try the upload again." }),
diff --git a/server/cloud-browser/rails.ts b/server/cloud-browser/rails.ts
index ae7651d65c..d6bd605453 100644
--- a/server/cloud-browser/rails.ts
+++ b/server/cloud-browser/rails.ts
@@ -44,8 +44,11 @@ interface State extends Day {
oldRelayUntil: number;
/** The relay said no browser sandbox may start (the fleet's day spent, switched off): nothing is started before this. */
unavailableUntil: number;
- /** Per bot's profile key: when the home's saved sign-ins last carried in (or were last written back), by file time. */
+ /** Per sandbox and bot's profile key (`<box id>:<key>`): when the home's saved sign-ins last carried in, or were last
+ * written back, by the home file's time. A replaced sandbox has none, so the home's copy is carried into it. */
carried: Record<string, number>;
+ /** Per bot's profile key: the home copy (by file time) Chrome would not take, not tried again until it changes. */
+ carryBad: Record<string, number>;
/** Since when the operator lever has kept every browser in the home; 0 when it does not. */
leverSince: number;
}
@@ -75,7 +78,7 @@ export function createCloudBrowserRails(options: CloudBrowserRailsOptions) {
const awakeCapMs = (options.awakeMinutes ?? CLOUD_BROWSER_DAILY_AWAKE_MINUTES) * 60_000;
const file = join(options.dataDir, "cloud-browser", "rails.json");
const fresh = (day: string): Day => ({ day, resumes: 0, awakeMs: 0, computer: 0, home: 0, fallbacks: {} });
- let state: State = { ...fresh(utcDay(now())), failuresInRow: 0, backoffUntil: 0, accountUntil: 0, hoursUntil: 0, noRouteDay: null, awakeSince: 0, leverSince: 0, oldRelayUntil: 0, unavailableUntil: 0, carried: {} };
+ let state: State = { ...fresh(utcDay(now())), failuresInRow: 0, backoffUntil: 0, accountUntil: 0, hoursUntil: 0, noRouteDay: null, awakeSince: 0, leverSince: 0, oldRelayUntil: 0, unavailableUntil: 0, carried: {}, carryBad: {} };
try {
const saved = JSON.parse(readFileSync(file, "utf8")) as Partial<State>;
const number = (value: unknown) => (typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : 0);
@@ -89,6 +92,8 @@ export function createCloudBrowserRails(options: CloudBrowserRailsOptions) {
awakeSince: number(saved.awakeSince), leverSince: number(saved.leverSince),
oldRelayUntil: number(saved.oldRelayUntil), unavailableUntil: number(saved.unavailableUntil),
carried: Object.fromEntries(Object.entries(saved.carried && typeof saved.carried === "object" ? saved.carried : {})
+ .filter(([key, at]) => /^bx_[a-z0-9]{8}:[a-f0-9]{16}$/.test(key) && typeof at === "number" && Number.isFinite(at))),
+ carryBad: Object.fromEntries(Object.entries(saved.carryBad && typeof saved.carryBad === "object" ? saved.carryBad : {})
.filter(([key, at]) => /^[a-f0-9]{16}$/.test(key) && typeof at === "number" && Number.isFinite(at))),
};
} catch {
@@ -200,6 +205,12 @@ export function createCloudBrowserRails(options: CloudBrowserRailsOptions) {
save();
},
carried: (key: string): number => today().carried[key] ?? 0,
+ carryBad: (key: string): number | null => today().carryBad[key] ?? null,
+ setCarryBad(key: string, at: number | null): void {
+ const current = today();
+ if (at === null) delete current.carryBad[key]; else current.carryBad[key] = at;
+ save();
+ },
setCarried(key: string, at: number): void {
today().carried[key] = at;
save();
diff --git a/server/cloud-browser/remote.ts b/server/cloud-browser/remote.ts
index de3561a0be..698cbe28d9 100644
--- a/server/cloud-browser/remote.ts
+++ b/server/cloud-browser/remote.ts
@@ -87,6 +87,12 @@ export function providerOps(cfg: () => AppConfig): ComputerOps {
const body = JSON.stringify(browserSandboxCreateBody());
let request = beginBoatCreate(BROWSER_SANDBOX_OWNER, body).request;
let answer = request.boxId ? await json(config, `/sandboxes/${request.boxId}`) : null;
+ // A remembered sandbox proven gone frees its key: never create again under it, which could return the gone one.
+ if (request.boxId && (answer?.status === 404 || answer?.status === 410)) {
+ discardBoatCreate(request);
+ request = beginBoatCreate(BROWSER_SANDBOX_OWNER, body).request;
+ answer = null;
+ }
let posted = false;
if (!answer?.ok) {
posted = true;
diff --git a/server/cloud-browser/sign-ins.ts b/server/cloud-browser/sign-ins.ts
index 860bc6885b..0f436123e7 100644
--- a/server/cloud-browser/sign-ins.ts
+++ b/server/cloud-browser/sign-ins.ts
@@ -10,7 +10,7 @@ export const MAX_STORAGE_ORIGINS = 200;
const MAX_STORAGE_BYTES = 5 * 1024 * 1024;
/** A cookie as agent-browser saves it: Chrome's own (`Network.getAllCookies`), so `session` marks one with no expiry. */
-interface SavedCookie {
+export interface SavedCookie {
name: string; value: string; domain: string; path: string; expires?: number; httpOnly?: boolean; secure?: boolean;
session?: boolean; sameSite?: string; partitionKey?: unknown; sourceScheme?: string; sourcePort?: number; priority?: string;
}
@@ -28,10 +28,36 @@ export function cookieParam(cookie: SavedCookie): Record<string, unknown> {
name: cookie.name, value: cookie.value, domain: cookie.domain, path: cookie.path,
...(cookie.secure === true ? { secure: true } : {}), ...(cookie.httpOnly === true ? { httpOnly: true } : {}),
...(sameSite ? { sameSite } : {}), ...(expires !== undefined ? { expires } : {}),
- ...(cookie.partitionKey && typeof cookie.partitionKey === "object" ? { partitionKey: cookie.partitionKey } : {}),
+ // A partitioned cookie stays partitioned, in either of the shapes Chrome has saved it in (an object, or a site's text).
+ ...((cookie.partitionKey && typeof cookie.partitionKey === "object") || (typeof cookie.partitionKey === "string" && cookie.partitionKey)
+ ? { partitionKey: cookie.partitionKey } : {}),
};
}
+/** A cookie's identity: Chrome keeps one per name, domain, path and partition. */
+export const cookieId = (cookie: SavedCookie): string =>
+ JSON.stringify([cookie.name, cookie.domain, cookie.path, cookie.partitionKey ?? null]);
+
+/** The cookies a session changed: those it set or changed since `baseline`, and the ids of those it removed. */
+export function cookieChanges(baseline: readonly SavedCookie[], current: readonly SavedCookie[]) {
+ const before = new Map(baseline.map((cookie) => [cookieId(cookie), cookie]));
+ const now = new Map(current.map((cookie) => [cookieId(cookie), cookie]));
+ const set = [...now.values()].filter((cookie) => {
+ const old = before.get(cookieId(cookie));
+ return !old || old.value !== cookie.value || old.expires !== cookie.expires;
+ });
+ const removed = [...before.keys()].filter((id) => !now.has(id));
+ return { set, removed };
+}
+
+/** The home's cookies with only a session's own changes applied: a cookie the session never touched stays as the home has it. */
+export function mergeCookies(home: readonly unknown[], changes: ReturnType<typeof cookieChanges>): SavedCookie[] {
+ const merged = new Map(home.filter(isSavedCookie).map((cookie) => [cookieId(cookie), cookie]));
+ for (const id of changes.removed) merged.delete(id);
+ for (const cookie of changes.set) merged.set(cookieId(cookie), cookie);
+ return [...merged.values()].slice(0, MAX_COOKIES);
+}
+
interface Storage { origin: string; items: Array<{ name: string; value: string }> }
function storageOf(origins: readonly unknown[]): Storage[] {
@@ -49,17 +75,30 @@ function storageOf(origins: readonly unknown[]): Storage[] {
return kept;
}
-/** The home's saved sign-ins set in the sandbox's Chrome: every cookie, then, as best it can, each site's local storage
- * through one blank page of its own (Chrome may want a page of that site first; a site it refuses keeps its cookies). A
- * cookie Chrome refuses fails the carry, so the session opens in the home instead of signed out. */
-export async function carryIn(cdp: Cdp, state: { cookies: readonly unknown[]; origins: readonly unknown[] }): Promise<{ cookies: number; origins: number }> {
- const cookies = state.cookies.filter(isSavedCookie).slice(0, MAX_COOKIES).map(cookieParam);
- if (cookies.length) await cdp.send("Storage.setCookies", { cookies });
+/** The home's saved sign-ins made the sandbox profile's, the home being the newer: the profile's cookies are cleared first
+ * (so a site signed out of in the home stays signed out), then each cookie is set on its own, so one Chrome refuses (a
+ * SameSite=None one without Secure, say) is skipped and counted instead of failing the rest. Then, as best it can, each
+ * site's local storage through one blank page of its own (Chrome may want a page of that site first; a site it refuses
+ * keeps its cookies). Returns the cookies now in the profile from the home's copy. */
+export async function carryIn(cdp: Cdp, state: { cookies: readonly unknown[]; origins: readonly unknown[] }): Promise<{ cookies: number; refused: number; origins: number; set: SavedCookie[] }> {
+ const saved = state.cookies.filter(isSavedCookie).slice(0, MAX_COOKIES);
+ await cdp.send("Storage.clearCookies", {});
+ const set: SavedCookie[] = [];
+ let refused = 0;
+ for (const cookie of saved) {
+ try {
+ await cdp.send("Storage.setCookies", { cookies: [cookieParam(cookie)] });
+ set.push(cookie);
+ } catch {
+ refused += 1;
+ }
+ }
+ const cookies = set;
const storage = storageOf(state.origins);
let carried = 0;
if (storage.length) {
const { targetId } = await cdp.send("Target.createTarget", { url: "about:blank", background: true }).catch(() => ({})) as { targetId?: string };
- if (typeof targetId !== "string") return { cookies: cookies.length, origins: 0 };
+ if (typeof targetId !== "string") return { cookies: cookies.length, refused, origins: 0, set };
try {
const { sessionId } = await cdp.send("Target.attachToTarget", { targetId, flatten: true }) as { sessionId?: string };
if (typeof sessionId !== "string") throw new Error("no page for the storage carry");
@@ -80,11 +119,11 @@ export async function carryIn(cdp: Cdp, state: { cookies: readonly unknown[]; or
await cdp.send("Target.closeTarget", { targetId }).catch(() => undefined);
}
}
- return { cookies: cookies.length, origins: carried };
+ return { cookies: cookies.length, refused, origins: carried, set };
}
/** The sandbox's cookies as the home saves them (Chrome's own shape, as agent-browser writes it), at most MAX_COOKIES. */
-export async function carryOut(cdp: Cdp): Promise<unknown[]> {
+export async function carryOut(cdp: Cdp): Promise<SavedCookie[]> {
const { cookies } = await cdp.send("Storage.getCookies", {}) as { cookies?: unknown[] };
return (cookies ?? []).filter(isSavedCookie).slice(0, MAX_COOKIES);
}
diff --git a/server/cloud-browser/testing/fake-computer.ts b/server/cloud-browser/testing/fake-computer.ts
index caadeeafc3..2aa8b25747 100644
--- a/server/cloud-browser/testing/fake-computer.ts
+++ b/server/cloud-browser/testing/fake-computer.ts
@@ -39,6 +39,9 @@ export interface FakeComputer {
cookies: Map<string, Array<Record<string, unknown>>>;
/** Every DevTools command the sandbox's Chromes got, with its profile key. */
commands: Array<{ key: string; method: string; params: Record<string, unknown> }>;
+ /** DevTools commands the sandbox's Chrome answers with an error, by method; `Storage.setCookies` also refuses a
+ * SameSite=None cookie without Secure, as Chrome does. */
+ failing: Set<string>;
/** Sends a DevTools event to the connections of a profile that asked for download events. */
emit(key: string, method: string, params: Record<string, unknown>): void;
resumes(): number;
@@ -57,10 +60,11 @@ export async function startFakeComputer(): Promise<FakeComputer> {
const secrets = new Map<string, string>();
const wss = new WebSocketServer({ noServer: true });
let made = 0;
+ 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, requests: [], upgrades: [], frames: [], boxId: "bx_23456789",
- files: new Map(), cookies: new Map(), commands: [],
+ files: new Map(), cookies: new Map(), commands: [], failing: new Set(),
} as unknown as FakeComputer;
const watchers = new Map<string, Set<import("ws").WebSocket>>();
const HOME = "/home/user";
@@ -98,8 +102,8 @@ export async function startFakeComputer(): Promise<FakeComputer> {
if (rest === "/sandboxes" && req.method === "GET") return send(200, { ok: true, sandboxes: fake.exists ? [row] : [], pageInfo: { nextCursor: null } });
if (rest === "/sandboxes" && req.method === "POST") {
if (fake.startStatus >= 300) return send(fake.startStatus, fake.startBody);
- made += 1;
- fake.boxId = made === 1 ? fake.boxId : `bx_2345678${"abcdefgh"[made % 8]}`;
+ // A sandbox made after one was deleted is a new one, with an id of its own.
+ if (retired) { made += 1; fake.boxId = `bx_2345678${"abcdefgh"[made % 8]}`; retired = false; }
fake.exists = true;
fake.state = "ready";
return send(202, { ok: true, sandbox: { id: fake.boxId, state: "provisioning", ...(!fake.oldRelay && body.purpose ? { purpose: body.purpose } : {}) } });
@@ -108,6 +112,7 @@ export async function startFakeComputer(): Promise<FakeComputer> {
if (rest === `/sandboxes/${boxId}` && req.method === "GET") return fake.exists ? send(200, { ok: true, sandbox: row }) : send(404, { ok: false });
if (rest === `/sandboxes/${boxId}` && req.method === "DELETE") {
fake.exists = false;
+ retired = true;
fake.state = "ready";
return send(200, { ok: true, operation: { id: `bdop_${"a".repeat(32)}`, status: "completed", kind: "sandbox", targetId: boxId } });
}
@@ -157,6 +162,12 @@ export async function startFakeComputer(): Promise<FakeComputer> {
const params = message.params ?? {};
fake.commands.push({ key, method: message.method, params });
let result: Record<string, unknown> = {};
+ const refusedCookie = message.method === "Storage.setCookies" && (params.cookies as Array<Record<string, unknown>>).some((cookie) => cookie.sameSite === "None" && cookie.secure !== true);
+ if (fake.failing.has(message.method) || refusedCookie) {
+ ws.send(JSON.stringify({ id: message.id, error: { code: -32000, message: "Sanitizing cookie failed" } }));
+ return;
+ }
+ if (message.method === "Storage.clearCookies") fake.cookies.set(key, []);
if (message.method === "Storage.setCookies") fake.cookies.set(key, [...(fake.cookies.get(key) ?? []), ...(params.cookies as Array<Record<string, unknown>>)]);
if (message.method === "Storage.getCookies") result = { cookies: (fake.cookies.get(key) ?? []).map((cookie) => ({ ...cookie, size: 1, session: cookie.expires === undefined, expires: cookie.expires ?? -1 })) };
if (message.method === "Browser.setDownloadBehavior") { const set = watchers.get(key) ?? new Set(); set.add(ws); watchers.set(key, set); }