Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
fix(browser): stage Chrome uploads before any wait; refuse workspace uploads on Windows (#3716)
zicochaos6656b9e240ce
diff --git a/server/attachments.ts b/server/attachments.tsindex 581dc17f7c..3e52b45730 100644--- a/server/attachments.ts+++ b/server/attachments.ts@@ -11,15 +11,14 @@ import {} from "node:fs";import { link, open, unlink } from "node:fs/promises";import { join, extname } from "node:path";+import { FILE_MAX_BYTES } from "../shared/upload-limits.ts";import { DATA_DIR } from "./config.ts";+export { FILE_MAX_BYTES } from "../shared/upload-limits.ts";export const ATTACHMENTS_DIR = join(DATA_DIR, "attachments");export const IMAGE_MAX_BYTES = 10 * 1024 * 1024;-/** Below Cloudflare's transport ceiling; a local inbox, not unbounded storage. */-export const FILE_MAX_BYTES = 25 * 1024 * 1024;-export const DEFAULT_ATTACHMENTS_MAX_BYTES = 512 * 1024 * 1024;/** A person's own Cloud is the only home of everything their computers held, on a volume a move grows to fit. */export const CLOUD_HOME_ATTACHMENTS_MAX_BYTES = 8 * 1024 * 1024 * 1024;diff --git a/server/browser-upload-security.test.ts b/server/browser-upload-security.test.tsnew file mode 100644index 0000000000..32f5c4a701--- /dev/null+++ b/server/browser-upload-security.test.ts@@ -0,0 +1,172 @@+import * as fs from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { afterEach, expect, it, vi } from "vitest";++const hooks = vi.hoisted(() => ({+ beforeRead: null as ((input: number) => void) | null,+ afterOpen: null as ((path: fs.PathLike) => void) | null,+ openFlags: null as ((path: fs.PathLike, flags: fs.OpenMode) => fs.OpenMode) | null,+ readlink: null as ((path: fs.PathLike) => string) | null,+}));+vi.mock("node:fs", async (importOriginal) => {+ const original = await importOriginal<typeof import("node:fs")>();+ return {+ ...original,+ openSync: (...args: Parameters<typeof original.openSync>) => {+ const input = original.openSync(args[0], hooks.openFlags?.(args[0], args[1]) ?? args[1], args[2]);+ hooks.afterOpen?.(args[0]);+ return input;+ },+ readlinkSync: (...args: Parameters<typeof original.readlinkSync>) => hooks.readlink?.(args[0]) ?? original.readlinkSync(...args),+ readSync: (...args: Parameters<typeof original.readSync>) => {+ hooks.beforeRead?.(args[0]);+ return original.readSync(...args);+ },+ read: Object.defineProperties((...args: Parameters<typeof original.read>) => {+ hooks.beforeRead?.(args[0]);+ return original.read(...args);+ }, Object.getOwnPropertyDescriptors(original.read)),+ };+});++const { namedUploadPaths, uploadableFiles } = await import("./browser-upload.ts");+const dirs: string[] = [];+afterEach(() => {+ hooks.beforeRead = null;+ hooks.afterOpen = null;+ hooks.openFlags = null;+ hooks.readlink = null;+ vi.unstubAllGlobals();+ for (const dir of dirs.splice(0)) fs.rmSync(dir, { recursive: true, force: true });+});++it.each(["darwin", "linux"])("stages a regular file with valid %s open flags", async (platform) => {+ const base = fs.realpathSync(fs.mkdtempSync(join(tmpdir(), "omb-upload-flags-")));+ dirs.push(base);+ const source = join(base, "report.txt");+ fs.writeFileSync(source, "report");+ vi.stubGlobal("process", { ...process, platform });+ const flags: fs.OpenMode[] = [];+ if (platform === "linux") hooks.readlink = () => source;+ hooks.openFlags = (path, mode) => {+ if (path !== source) return mode;+ flags.push(mode);+ if (platform === "darwin" && typeof mode === "number") {+ if ((mode & 0x20000000) && (mode & fs.constants.O_NOFOLLOW)) throw Object.assign(new Error("EINVAL"), { code: "EINVAL" });+ return (mode & ~0x20000000) | fs.constants.O_NOFOLLOW;+ }+ return mode;+ };+ const [staged] = await namedUploadPaths([{ file: source, name: "Report.txt" }], join(base, "uploads"));+ expect(flags).toEqual([platform === "darwin" ? fs.constants.O_RDONLY | fs.constants.O_NONBLOCK | 0x20000000+ : fs.constants.O_RDONLY | fs.constants.O_NONBLOCK | fs.constants.O_NOFOLLOW]);+ expect(fs.readFileSync(staged!, "utf8")).toBe("report");+});++it.each([false, true])("stages workspace files on Windows from the checked path (everyFile: %s)", async (everyFile) => {+ const base = fs.realpathSync(fs.mkdtempSync(join(tmpdir(), "omb-upload-windows-")));+ dirs.push(base);+ const source = join(base, "report.txt"), folder = join(base, "uploads");+ fs.writeFileSync(source, "report");+ vi.stubGlobal("process", { ...process, platform: "win32" });+ const flags: fs.OpenMode[] = [];+ hooks.openFlags = (path, mode) => {+ if (path === source) flags.push(mode);+ return mode;+ };+ const [staged] = await namedUploadPaths([{ file: source, name: everyFile ? null : "Report.txt" }], folder, Date.now(), { everyFile });+ expect(flags).toEqual([fs.constants.O_RDONLY]);+ expect(staged).not.toBe(source);+ expect(fs.readFileSync(staged!, "utf8")).toBe("report");+});++it.skipIf(process.platform === "win32")("pins both sources before a directory is swapped while the first file copies", async () => {+ const base = fs.realpathSync(fs.mkdtempSync(join(tmpdir(), "omb-upload-race-")));+ dirs.push(base);+ const workspace = join(base, "workspace"), sub = join(workspace, "sub"), outside = join(base, "outside");+ fs.mkdirSync(sub, { recursive: true });+ fs.mkdirSync(outside);+ fs.writeFileSync(join(workspace, "large.bin"), Buffer.alloc(1024 * 1024 + 1));+ fs.writeFileSync(join(sub, "report.txt"), "report");+ fs.writeFileSync(join(outside, "report.txt"), "outside secret");+ const checked = uploadableFiles([join(workspace, "large.bin"), join(sub, "report.txt")], [workspace]);+ if ("error" in checked) throw new Error(checked.error);+ hooks.beforeRead = () => {+ hooks.beforeRead = null;+ fs.rmSync(sub, { recursive: true });+ fs.symlinkSync(outside, sub, "dir");+ };+ const staged = await namedUploadPaths(checked.files.map((file) => ({ file, name: null })), join(base, "uploads"), Date.now(), { everyFile: true });+ expect(fs.readFileSync(staged[1]!, "utf8")).toBe("report");+});++it.skipIf(process.platform === "win32")("removes every directory from a batch when its second file fails", async () => {+ const base = fs.realpathSync(fs.mkdtempSync(join(tmpdir(), "omb-upload-cleanup-")));+ dirs.push(base);+ const first = join(base, "first.txt"), second = join(base, "second.txt"), folder = join(base, "uploads");+ fs.writeFileSync(first, "first");+ fs.writeFileSync(second, "second");+ const secondInode = fs.statSync(second, { bigint: true }).ino;+ hooks.beforeRead = (input) => {+ if (fs.fstatSync(input, { bigint: true }).ino === secondInode) fs.truncateSync(second, 0);+ };+ await expect(async () => namedUploadPaths([+ { file: first, name: "First.txt" }, { file: second, name: "Second.txt" },+ ], folder)).rejects.toThrow(/changed/);+ expect(fs.readdirSync(folder)).toEqual([]);+});++it.skipIf(process.platform === "win32")("rejects an oversized sparse file before reading it", async () => {+ const base = fs.realpathSync(fs.mkdtempSync(join(tmpdir(), "omb-upload-size-")));+ dirs.push(base);+ const source = join(base, "large.bin");+ fs.writeFileSync(source, "");+ fs.truncateSync(source, 25 * 1024 * 1024 + 1);+ let read = false;+ hooks.beforeRead = () => { read = true; };+ await expect(async () => namedUploadPaths([{ file: source, name: "Large.bin" }], join(base, "uploads"))).rejects.toThrow(/limit/i);+ expect(read).toBe(false);+});++it.skipIf(process.platform === "win32")("rejects a batch over 100 MiB before reading any file", async () => {+ const base = fs.realpathSync(fs.mkdtempSync(join(tmpdir(), "omb-upload-batch-")));+ dirs.push(base);+ const files = Array.from({ length: 5 }, (_, i) => {+ const file = join(base, `${i}.bin`);+ fs.writeFileSync(file, "");+ fs.truncateSync(file, 21 * 1024 * 1024);+ return { file, name: `Upload-${i}.bin` };+ });+ let read = false;+ hooks.beforeRead = () => { read = true; };+ await expect(async () => namedUploadPaths(files, join(base, "uploads"))).rejects.toThrow(/limit/i);+ expect(read).toBe(false);+});++it.skipIf(process.platform === "win32")("lets the event loop run while an accepted upload copies", async () => {+ const base = fs.realpathSync(fs.mkdtempSync(join(tmpdir(), "omb-upload-async-")));+ dirs.push(base);+ const source = join(base, "large.bin");+ fs.writeFileSync(source, Buffer.alloc(2 * 1024 * 1024, 0x61));+ let yielded = false;+ setImmediate(() => { yielded = true; });+ const [staged] = await namedUploadPaths([{ file: source, name: "Large.bin" }], join(base, "uploads"));+ expect(yielded).toBe(true);+ expect(fs.readFileSync(staged!)).toEqual(Buffer.alloc(2 * 1024 * 1024, 0x61));+});++it.skipIf(process.platform === "win32")("rejects a directory symlink inserted after the allowlist check before staging", async () => {+ const base = fs.realpathSync(fs.mkdtempSync(join(tmpdir(), "omb-upload-parent-")));+ dirs.push(base);+ const workspace = join(base, "workspace"), sub = join(workspace, "sub"), outside = join(base, "outside");+ fs.mkdirSync(sub, { recursive: true });+ fs.mkdirSync(outside);+ fs.writeFileSync(join(sub, "report.txt"), "report");+ fs.writeFileSync(join(outside, "report.txt"), "outside secret");+ const checked = uploadableFiles([join(sub, "report.txt")], [workspace]);+ if ("error" in checked) throw new Error(checked.error);+ fs.rmSync(sub, { recursive: true });+ fs.symlinkSync(outside, sub, "dir");+ await expect(async () => namedUploadPaths(checked.files.map((file) => ({ file, name: "Report.txt" })), join(base, "uploads"))).rejects.toThrow();+});diff --git a/server/browser-upload.test.ts b/server/browser-upload.test.tsindex a5347cb6f4..0b9e2301d8 100644--- a/server/browser-upload.test.ts+++ b/server/browser-upload.test.ts@@ -10,7 +10,7 @@ const dirs: string[] = [];afterEach(() => { for (const dir of dirs.splice(0)) removeTempDir(dir); });function folders() {- const base = realpathSync(mkdtempSync(join(tmpdir(), "omb-upload-")));+ const base = realpathSync.native(mkdtempSync(join(tmpdir(), "omb-upload-")));dirs.push(base);const attachments = join(base, "attachments"), workspace = join(base, "workspace"), outside = join(base, "outside");for (const dir of [attachments, workspace, outside]) mkdirSync(dir);@@ -48,10 +48,10 @@ describe("files a page may receive", () => {});describe("the name a page sees", () => {- it("gives an attachment the person's own name, and leaves every other file as it is", () => {+ it("gives an attachment the person's own name, and leaves every other file as it is", async () => {const { base, attachments, workspace } = folders();const stored = join(attachments, "cv.pdf"), report = join(workspace, "report.csv");- const [named, same, unnamed, unsafe] = namedUploadPaths([+ const [named, same, unnamed, unsafe] = await namedUploadPaths([{ file: stored, name: "Jane Doe CV.pdf" }, { file: report, name: "report.csv" }, { file: report, name: null }, { file: stored, name: "../escape.pdf" },], join(base, "uploads"));expect(basename(named!)).toBe("Jane Doe CV.pdf");@@ -60,33 +60,53 @@ describe("the name a page sees", () => {expect([same, unnamed, unsafe]).toEqual([report, report, stored]);});- it("removes named copies a day old", () => {+ it("removes named copies a day old", async () => {const { base, attachments } = folders();const folder = join(base, "uploads");- const [old] = namedUploadPaths([{ file: join(attachments, "cv.pdf"), name: "old.pdf" }], folder);+ const [old] = await namedUploadPaths([{ file: join(attachments, "cv.pdf"), name: "old.pdf" }], folder);const day = 24 * 60 * 60 * 1000;utimesSync(dirname(old!), new Date(Date.now() - day - 1000), new Date(Date.now() - day - 1000));- const [fresh] = namedUploadPaths([{ file: join(attachments, "cv.pdf"), name: "new.pdf" }], folder);+ const [fresh] = await namedUploadPaths([{ file: join(attachments, "cv.pdf"), name: "new.pdf" }], folder);expect(existsSync(old!)).toBe(false);expect(existsSync(fresh!)).toBe(true);});++ it.each([0, 3, 1024 * 1024 + 7])("keeps %i copied bytes independent of later writes to the source", async (size) => {+ const { base, workspace } = folders();+ const file = join(workspace, "report.csv");+ writeFileSync(file, Buffer.alloc(size, 0x61));+ const [staged] = await namedUploadPaths([{ file, name: "Report.csv" }], join(base, "uploads"));+ writeFileSync(file, "changed");+ expect(readFileSync(staged!).equals(Buffer.alloc(size, 0x61))).toBe(true);+ });++ it.skipIf(process.platform === "win32")("refuses a file replaced by a symlink after the allowlist check", async () => {+ const { base, workspace, outside, roots } = folders();+ const file = join(workspace, "report.csv");+ const checked = uploadableFiles([file], roots);+ expect(checked).toEqual({ files: [file] });+ if ("error" in checked) throw new Error(checked.error);+ rmSync(file);+ symlinkSync(join(outside, "secret.txt"), file);+ await expect(namedUploadPaths(checked.files.map((file) => ({ file, name: null })), join(base, "uploads"), Date.now(), { everyFile: true })).rejects.toThrow();+ });});describe("the files a boxed browser is given", () => {- it("links every file into the one folder the box shows Chrome, under the person's name or its own", () => {- const root = mkdtempSync(join(tmpdir(), "omb-boxed-upload-"));+ it("copies every file into the one folder the box shows Chrome, under the person's name or its own", async () => {+ const root = realpathSync.native(mkdtempSync(join(tmpdir(), "omb-boxed-upload-")));const source = join(root, "work", "report.txt"), stored = join(root, "attachments", "a1b2.pdf");mkdirSync(dirname(source), { recursive: true });mkdirSync(dirname(stored), { recursive: true });writeFileSync(source, "report");writeFileSync(stored, "pdf");const folder = join(root, "profile", "omb-uploads");- const linked = namedUploadPaths([{ file: source, name: null }, { file: stored, name: "Invoice.pdf" }], folder, Date.now(), { everyFile: true });+ const linked = await namedUploadPaths([{ file: source, name: null }, { file: stored, name: "Invoice.pdf" }], folder, Date.now(), { everyFile: true });expect(linked.every((path) => path.startsWith(folder + sep))).toBe(true);expect(linked.map((path) => basename(path))).toEqual(["report.txt", "Invoice.pdf"]);expect(readFileSync(linked[0]!, "utf8")).toBe("report");// Unboxed, a file already under its own name is given as it is.- expect(namedUploadPaths([{ file: source, name: null }], folder)).toEqual([source]);+ expect(await namedUploadPaths([{ file: source, name: null }], folder)).toEqual([source]);rmSync(root, { recursive: true, force: true });});});diff --git a/server/browser-upload.ts b/server/browser-upload.tsindex 00155b3f17..ab34d6e59b 100644--- a/server/browser-upload.ts+++ b/server/browser-upload.ts@@ -1,15 +1,22 @@import { randomUUID } from "node:crypto";-import { copyFileSync, linkSync, mkdirSync, readdirSync, realpathSync, rmSync, statSync, writeFileSync } from "node:fs";+import { closeSync, constants, fstatSync, mkdirSync, openSync, read, readdirSync, readlinkSync, realpathSync, rmSync, statSync, write, writeFileSync } from "node:fs";import { homedir } from "node:os";import { basename, isAbsolute, join, relative } from "node:path";+import { promisify } from "node:util";+import { BROWSER_UPLOAD_MAX_BYTES, FILE_MAX_BYTES } from "../shared/upload-limits.ts";import { safeFileName } from "./browser/cdp/downloads.ts";const MAX_FILES = 10;+const readChunk = promisify(read), writeChunk = promisify(write);+// Node 24 omits Darwin's O_NOFOLLOW_ANY, which rejects symlinks in every path component.+const O_NOFOLLOW_ANY = 0x20000000;const NAMED_COPY_MAX_AGE_MS = 24 * 60 * 60 * 1000;+export class BrowserUploadRefusal extends Error {}+function realRoot(root: string): string | null {- try { return realpathSync(root); } catch { return null; }+ try { return realpathSync.native(root); } catch { return null; }}function inside(root: string, file: string): boolean {@@ -28,7 +35,7 @@ export function uploadableFiles(files: unknown, roots: readonly string[]): { filconst path = file.startsWith("~/") ? join(homedir(), file.slice(2)) : file;if (!isAbsolute(path)) return { error: `${file} is not an absolute path.` };let real: string;- try { real = realpathSync(path); } catch { return { error: `${file} does not exist.` }; }+ try { real = realpathSync.native(path); } catch { return { error: `${file} does not exist.` }; }if (!allowed.some((root) => inside(root, real))) {return { error: `${file} is not one of this conversation's attachments or in your working folder, so it cannot be uploaded. Ask the person to attach the file.` };}@@ -39,19 +46,77 @@ export function uploadableFiles(files: unknown, roots: readonly string[]): { fil}/** Chrome names an uploaded file after its file on disk and reads it only when the form is sent, so an attachment stored- * under a random id gets a link with the person's own name that outlives the call. `everyFile`: a boxed Chrome sees only- * `folder`, so each file gets a link there. */-export function namedUploadPaths(files: ReadonlyArray<{ file: string; name: string | null }>, folder: string, now = Date.now(), { everyFile = false } = {}): string[] {+ * under a random id gets a copy with the person's own name that outlives the call. `everyFile`: stage every file in+ * `folder`, outside the bot's writable workspace. */+export async function namedUploadPaths(files: ReadonlyArray<{ file: string; name: string | null }>, folder: string, now = Date.now(), { everyFile = false } = {}): Promise<string[]> {sweepNamedCopies(folder, now);- return files.map(({ file, name: given }) => {- const name = given && basename(given) === given ? given : everyFile ? basename(file) : null;- if (!name || (name === basename(file) && !everyFile)) return file;- const dir = join(folder, randomUUID());- mkdirSync(dir, { recursive: true, mode: 0o700 });- const named = join(dir, name);- try { linkSync(file, named); } catch { copyFileSync(file, named); }- return named;- });+ const created: string[] = [];+ const opened: Array<{ input: number; size: number }> = [];+ try {+ let total = 0;+ const prepared = files.map(({ file, name: given }) => {+ const name = given && basename(given) === given ? given : everyFile ? basename(file) : null;+ if (!name || (name === basename(file) && !everyFile)) return { file };+ const source = openUpload(file);+ opened.push(source);+ total += source.size;+ if (total > BROWSER_UPLOAD_MAX_BYTES) throw new BrowserUploadRefusal("Uploads are limited to 100 MiB per batch.");+ return { file, name, source };+ });+ const paths: string[] = [];+ for (const entry of prepared) {+ if (!entry.source) { paths.push(entry.file); continue; }+ const dir = join(folder, randomUUID());+ mkdirSync(dir, { recursive: true, mode: 0o700 });+ created.push(dir);+ const named = join(dir, entry.name);+ await copyUpload(entry.source, named, entry.file);+ paths.push(named);+ }+ return paths;+ } catch (error) {+ for (const dir of created) rmSync(dir, { recursive: true, force: true });+ throw error;+ } finally {+ for (const { input } of opened) closeSync(input);+ }+}++function openUpload(source: string): { input: number; size: number } {+ // Windows has no O_NOFOLLOW: there the copy is read from the path the allowlist just checked, before any wait.+ const flags = process.platform === "win32" ? constants.O_RDONLY+ : constants.O_RDONLY | constants.O_NONBLOCK | (process.platform === "darwin" ? O_NOFOLLOW_ANY : constants.O_NOFOLLOW);+ const input = openSync(source, flags);+ try {+ if (process.platform === "linux" && readlinkSync(`/proc/self/fd/${input}`) !== source) throw new BrowserUploadRefusal(`${source} changed while staging the upload.`);+ const file = fstatSync(input, { bigint: true });+ if (!file.isFile()) throw new BrowserUploadRefusal(`${source} is not a file.`);+ if (file.size > BigInt(FILE_MAX_BYTES)) throw new BrowserUploadRefusal("Uploads are limited to 25 MiB per file.");+ return { input, size: Number(file.size) };+ } catch (error) {+ closeSync(input);+ throw error;+ }+}++async function copyUpload({ input, size }: { input: number; size: number }, destination: string, source: string): Promise<void> {+ const output = openSync(destination, "wx", 0o600);+ try {+ const chunk = Buffer.allocUnsafe(1024 * 1024);+ for (let remaining = size; remaining > 0;) {+ const { bytesRead: count } = await readChunk(input, chunk, 0, Math.min(chunk.length, remaining), null);+ if (!count) throw new BrowserUploadRefusal(`${source} changed while staging the upload.`);+ let offset = 0;+ while (offset < count) {+ const { bytesWritten } = await writeChunk(output, chunk, offset, count - offset, null);+ if (!bytesWritten) throw new Error(`Could not stage ${source}.`);+ offset += bytesWritten;+ }+ remaining -= count;+ }+ } finally {+ closeSync(output);+ }}/** Files a person picked on their own device for a page's file picker, kept under their own names for a day. */diff --git a/server/host/browser.test.ts b/server/host/browser.test.tsindex 4ebd19b801..9059333085 100644--- a/server/host/browser.test.ts+++ b/server/host/browser.test.ts@@ -1,4 +1,4 @@-import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";+import { existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, symlinkSync, writeFileSync } from "node:fs";import { connect } from "node:net";import { tmpdir } from "node:os";import { join } from "node:path";@@ -17,6 +17,9 @@ import { BrowserRuntime } from "../browser-runtime.ts";import { LentChromeDoors, type ChromeLender } from "../browser/lent-chrome.ts";import { audienceBrowserSuffix } from "../browser/audience.ts";import { chromeLauncher } from "../browser/chrome/launcher.ts";+import type { CdpSession, Params } from "../browser/cdp/connection.ts";+import { FileChoosers } from "../browser/cdp/files.ts";+import { uploadableFiles } from "../browser-upload.ts";import { createBrowserHost, type BrowserHostDeps } from "./browser.ts";vi.mock("../browser-engine.ts", async (original) => {@@ -615,18 +618,70 @@ describe("a Team Cloud's browsers, one per audience", () => {describe("a Team Cloud's boxed browsers and the files a turn uploads", () => {afterEach(() => chromeLauncher.boxWith(() => null));- it("are linked into that browser's own profile, the one folder of the disk its box shows Chrome", () => {- const work = mkdtempSync(join(tmpdir(), "omb-host-upload-"));+ it.each([null, "report.txt", "Report.txt"])("gives Chrome on Windows a private copy of a workspace file (name: %s)", async (name) => {+ const work = realpathSync(mkdtempSync(join(tmpdir(), "omb-host-upload-windows-")));+ try {+ const file = join(work, "report.txt");+ writeFileSync(file, "report");+ const { host } = setup("chrome");+ vi.stubGlobal("process", { ...process, platform: "win32" });+ const [staged] = await host.uploadPaths([{ file, name }], "bot-scout", { command: "omb-cdp", args: ["bot:scout"], env: {} });+ vi.unstubAllGlobals();+ expect(staged!.startsWith(join(DATA_DIR, "browser-uploads"))).toBe(true);+ expect(readFileSync(staged!, "utf8")).toBe("report");+ } finally {+ vi.unstubAllGlobals();+ rmSync(work, { recursive: true, force: true });+ }+ });++ it.skipIf(process.platform === "win32").each([false, true])("keeps workspace bytes through a symlink swap while Chrome waits for a picker (boxed: %s)", async (boxed) => {+ const work = realpathSync(mkdtempSync(join(tmpdir(), "omb-host-upload-")));+ try {+ const secret = join(work, "secret.txt");+ const workspace = join(work, "workspace");+ mkdirSync(workspace);+ const source = join(workspace, "report.txt");+ writeFileSync(source, "report");+ writeFileSync(secret, "outside secret");+ const checked = uploadableFiles([source], [workspace]);+ if ("error" in checked) throw new Error(checked.error);+ const box = { bwrap: "/usr/bin/bwrap", options: ["--unshare-pid"], seccomp: null };+ const { host } = setup("chrome", { cloudHome: true, ...(boxed ? { browserBox: () => box } : {}) });+ const paths = await host.uploadPaths(checked.files.map((file) => ({ file, name: null })), "bot-scout", { command: "omb-cdp", args: ["bot:scout"], env: {} });+ const choosers = new FileChoosers();+ let opened!: (params: Params) => void;+ const uploaded: Array<{ method: string; files: unknown; bytes: string[] }> = [];+ const session = {+ on: (_method: string, listener: (params: Params) => void) => { opened = listener; return () => {}; },+ send: async (method: string, params: Params) => { uploaded.push({ method, files: params.files, bytes: (params.files as string[]).map((path) => readFileSync(path, "utf8")) }); return {}; },+ } as unknown as CdpSession;+ choosers.watch(session);+ const answering = choosers.answer(paths);+ rmSync(source);+ symlinkSync(secret, source);+ opened({ frameId: "F", backendNodeId: 7, mode: "selectSingle" });+ await answering;+ expect(uploaded).toEqual([{ method: "DOM.setFileInputFiles", files: [expect.stringMatching(/browser-uploads/)], bytes: ["report"] }]);+ expect(paths[0]).not.toBe(source);+ expect(readFileSync(paths[0]!, "utf8")).toBe("report");+ } finally {+ rmSync(work, { recursive: true, force: true });+ }+ });++ it("are copied into that browser's own profile, the one folder of the disk its box shows Chrome", async () => {+ const work = realpathSync(mkdtempSync(join(tmpdir(), "omb-host-upload-")));const file = join(work, "report.txt");writeFileSync(file, "report");const box = { bwrap: "/usr/bin/bwrap", options: ["--unshare-pid"], seccomp: null };const boxed = setup(undefined, { cloudHome: true, browserBox: () => box }).host;const session = `bot-scout${ADA}`;- const [linked] = boxed.uploadPaths([{ file, name: null }], session, { command: "agent-browser", env: {} });+ const [linked] = await boxed.uploadPaths([{ file, name: null }], session, { command: "agent-browser", env: {} });expect(linked!.startsWith(join(DATA_DIR, "agent-browser-profiles"))).toBe(true);expect(readFileSync(linked!, "utf8")).toBe("report");const plain = setup(undefined, { cloudHome: true }).host;- expect(plain.uploadPaths([{ file, name: null }], session, { command: "agent-browser", env: {} }), "unboxed, the file is given as it is").toEqual([file]);+ expect(await plain.uploadPaths([{ file, name: null }], session, { command: "agent-browser", env: {} }), "unboxed, the file is given as it is").toEqual([file]);rmSync(work, { recursive: true, force: true });});});diff --git a/server/host/browser.ts b/server/host/browser.tsindex 3fe755c3b0..be07f041ec 100644--- a/server/host/browser.ts+++ b/server/host/browser.ts@@ -498,10 +498,11 @@ export function createBrowserHost(deps: BrowserHostDeps) {];return (await Promise.all(requests.map((request) => eraseOneBrowser(request)))).every(Boolean);}- /** Where a page's file input finds the files a turn uploads: a boxed Chrome sees only its own profile's folder. */- function uploadPaths(files: ReadonlyArray<{ file: string; name: string | null }>, session: string, spec: Spec): string[] {- if (!boxed || chromeTarget(session, spec)) return namedUploadPaths(files, join(DATA_DIR, "browser-uploads"));- return namedUploadPaths(files, join(browserProfileDirectory(session), "omb-uploads"), Date.now(), { everyFile: true });+ /** Chrome receives private copies; a boxed agent-browser reads them from its own profile's folder. */+ function uploadPaths(files: ReadonlyArray<{ file: string; name: string | null }>, session: string, spec: Spec): Promise<string[]> {+ const chrome = chromeTarget(session, spec);+ const folder = boxed && !chrome ? join(browserProfileDirectory(session), "omb-uploads") : join(DATA_DIR, "browser-uploads");+ return namedUploadPaths(files, folder, Date.now(), { everyFile: boxed || Boolean(chrome) });}/** The saved sign-ins of a bot's or a shared profile's browser, for one audience. */async function signedInSitesTarget(which: BrowserSitesRef, audience: Audience = "team"): Promise<BrowserSitesTarget | { status: number; error: string }> {diff --git a/server/index.test.ts b/server/index.test.tsindex 4990a37999..7b0399c871 100644--- a/server/index.test.ts+++ b/server/index.test.ts@@ -5,7 +5,7 @@ import { createHash, randomUUID } from "node:crypto";import { once } from "node:events";import { createServer, request, type Server } from "node:http";import { connect, type Socket } from "node:net";-import { chmodSync, existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, renameSync, rmSync, statSync, symlinkSync, utimesSync, writeFileSync } from "node:fs";+import { chmodSync, existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, renameSync, rmSync, statSync, symlinkSync, truncateSync, utimesSync, writeFileSync } from "node:fs";import { tmpdir } from "node:os";import { dirname, join } from "node:path";import { fileURLToPath, pathToFileURL } from "node:url";@@ -1189,6 +1189,8 @@ beforeAll(async () => {// Emulates only our temporary browser executable (also on Windows, where the marker is not executable).const browserPrelude = `data:text/javascript,${encodeURIComponent(`import childProcess from "node:child_process";+ import fs from "node:fs";+ import path from "node:path";import { syncBuiltinESMExports } from "node:module";const spawn = childProcess.spawn;const base = ${JSON.stringify(home)};@@ -1201,6 +1203,20 @@ beforeAll(async () => {+ 'process.exit(fs.existsSync(path.join(base, "browser-clear-fails")) ? 1 : 0);';return spawn(process.execPath, ["-e", program, ...args], options);};+ const read = fs.read;+ fs.read = Object.defineProperties(function(input, ...args) {+ const gate = path.join(base, "browser-upload-read-gate");+ if (!fs.existsSync(gate) || fs.fstatSync(input).ino !== fs.statSync(fs.readFileSync(gate, "utf8")).ino) {+ return read(input, ...args);+ }+ fs.rmSync(gate);+ fs.writeFileSync(gate + ".entered", "");+ const timer = setInterval(() => {+ if (!fs.existsSync(gate + ".release")) return;+ clearInterval(timer);+ read(input, ...args);+ }, 10);+ }, Object.getOwnPropertyDescriptors(read));syncBuiltinESMExports();`)}`;child = spawn(process.execPath, ["--import", browserPrelude, join(SERVER_DIR, "index.ts")], {@@ -9792,6 +9808,77 @@ describe("harness HTTP API", () => {}});+ it.skipIf(process.platform === "win32").each([+ { mode: "size", sizes: [25 * 1024 * 1024 + 1], message: "Uploads are limited to 25 MiB per file.", status: 200 },+ { mode: "batch", sizes: Array(5).fill(21 * 1024 * 1024) as number[], message: "Uploads are limited to 100 MiB per batch.", status: 200 },+ { mode: "changed", sizes: [1024], message: expect.stringContaining("changed while staging"), status: 200 },+ { mode: "stop", sizes: [1024], message: "the internal turn capability has expired", status: 401 },+ { mode: "disk", sizes: [1024], message: expect.stringMatching(/ENOTDIR|EEXIST/), status: 500 },+ ])("returns the correct browser upload result for $mode", async ({ mode, sizes, message, status }) => {+ const bot = (await api("POST", "/api/bots")).body.bot;+ const gate = join(home, "browser-upload-read-gate");+ const folder = join(home, ".openmausbot", "browser-uploads");+ const backup = folder + ".backup";+ let blockedFolder = false;+ let pending: Promise<Response> | undefined;+ try {+ expect((await api("PATCH", "/api/config", {+ features: { browser: true }, browserEngine: { engine: "chrome" },+ })).status).toBe(200);+ expect((await api("PATCH", `/api/bots/${bot.id}`, {+ approvalMode: "auto", modelSelection: { instanceId: "claude", model: "claude-sonnet-5" },+ })).status).toBe(200);+ const workspace = join(home, ".openmausbot", "workspaces", bot.id);+ mkdirSync(workspace, { recursive: true });+ const files = sizes.map((size, i) => {+ const file = join(workspace, `upload-${i}.bin`);+ writeFileSync(file, "");+ truncateSync(file, size);+ return file;+ });+ rmSync(fakeClaudeDump, { force: true });+ expect((await api("POST", `/api/bots/${bot.id}/messages`, { text: "Upload the synthetic files." })).status).toBe(202);+ const dump = await readJsonFileWhenReady(fakeClaudeDump) as {+ mcpConfig: { mcpServers: { browser: { env: Record<string, string> } } };+ };+ if (mode === "disk") {+ if (existsSync(folder)) renameSync(folder, backup);+ writeFileSync(folder, "not a directory");+ blockedFolder = true;+ }+ if (mode === "changed" || mode === "stop") writeFileSync(gate, files[0]!);+ pending = fetch(`${BASE}/api/internal/browser/mcp`, {+ method: "POST", headers: {+ "content-type": "application/json",+ authorization: `Bearer ${dump.mcpConfig.mcpServers.browser.env.OMB_MCP_TOKEN_BROWSER}`,+ },+ body: JSON.stringify({ method: "tools/call", params: { name: "agent_browser_upload", arguments: { files } } }),+ });+ if (mode === "changed" || mode === "stop") {+ await expect.poll(() => existsSync(gate + ".entered")).toBe(true);+ truncateSync(files[0]!, 0);+ if (mode === "stop") expect((await api("POST", `/api/bots/${bot.id}/interrupt`, {})).status).toBe(200);+ writeFileSync(gate + ".release", "");+ }+ const response = await pending;+ const body = await response.json();+ expect({ status: response.status, body }).toEqual({+ status, body: status === 200 ? { result: { isError: true, content: [{ type: "text", text: message }] } } : { error: message },+ });+ } finally {+ writeFileSync(gate + ".release", "");+ await api("POST", `/api/bots/${bot.id}/interrupt`, {}).catch(() => undefined);+ await pending?.catch(() => undefined);+ for (const file of [gate, gate + ".entered", gate + ".release"]) rmSync(file, { force: true });+ if (blockedFolder) {+ rmSync(folder, { force: true });+ if (existsSync(backup)) renameSync(backup, folder);+ }+ await api("PATCH", "/api/config", { features: { browser: false }, browserEngine: { engine: "agent-browser" } }).catch(() => undefined);+ await api("DELETE", `/api/bots/${bot.id}`).catch(() => undefined);+ }+ });+it.each(["direct", "room"] as const)("mounts the browser engine's MCP server and the sign-in policy in %s turns and preview", async (target) => {const bot = (await api("POST", "/api/bots")).body.bot;let room: any;diff --git a/server/index.ts b/server/index.tsindex 192f75ac7b..1127cde9f1 100644--- a/server/index.ts+++ b/server/index.ts@@ -436,7 +436,7 @@ import { vpsConfigForBot, vpsSshAliasForBot } from "./vps-hosts.ts";import { ROUTINE_RESTARTED, RoutineManager, type RoutineRun, type RoutineRunOn, type RoutineRunTrigger } from "./routines.ts";import { CalendarCallManager, type CalendarCall } from "./calendar-calls.ts";import { BROWSER_UPLOAD_TOOL, browserRuntimeEnv } from "./browser-runtime.ts";-import { uploadableFiles } from "./browser-upload.ts";+import { BrowserUploadRefusal, uploadableFiles } from "./browser-upload.ts";import { listSignedInSites, signOutOfSites } from "./browser-sites.ts";import { HeldSecrets, LoginStore } from "./login-store.ts";import { OnePasswordLogins, onePasswordUnavailable, sdkOnePasswordClient, type OnePasswordSdk } from "./onepassword.ts";@@ -13526,9 +13526,9 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {if (body.method === "tools/call" && params?.name === BROWSER_UPLOAD_TOOL) {const upload = uploadableFiles(params.arguments?.files, messageFileRootsForThread(bot.id, internalCapability.threadId));if ("error" in upload) return json(res, 200, { result: { isError: true, content: [{ type: "text", text: upload.error }] } });- const requested = params.arguments.files as string[];- const files = uploadPaths(upload.files.map((file, i) => ({ file, name: attachmentNameInThread(internalCapability.threadId, requested[i]!) })), browser.session, browser.spec);- params = { ...params, arguments: { ...params.arguments, files } };+ try {+ params = { ...params, arguments: { ...params.arguments, files: await uploadPaths(upload.files.map((file, i) => ({ file, name: attachmentNameInThread(internalCapability.threadId, params.arguments.files[i]) })), browser.session, browser.spec) } };+ } catch (error) { requireActiveInternalCapability(); if (!(error instanceof BrowserUploadRefusal)) throw error; return json(res, 200, { result: { isError: true, content: [{ type: "text", text: error.message }] } }); }}const result = await browserRuntime.agentRpc(browser.session, browser.spec, body.method, params, () => {requireActiveInternalCapability();diff --git a/server/routes/browser-viewers.test.ts b/server/routes/browser-viewers.test.tsindex 6a6afcbd3b..596a4d830e 100644--- a/server/routes/browser-viewers.test.ts+++ b/server/routes/browser-viewers.test.ts@@ -6,7 +6,7 @@ import { createServer, request, type IncomingMessage, type Server, type ServerReimport type { AddressInfo, Socket } from "node:net";import { tmpdir } from "node:os";import { basename, join } from "node:path";-import { afterEach, describe, expect, it } from "vitest";+import { afterEach, describe, expect, it, vi } from "vitest";import { BrowserHostError, SETUP_COMMAND } from "../browser/chrome/host-setup.ts";import type { Audience } from "../audience.ts";@@ -65,6 +65,7 @@ interface Fixture {const servers: Server[] = [];const folders: string[] = [];afterEach(async () => {+ vi.unstubAllGlobals();for (const server of servers.splice(0)) await new Promise<void>((resolve) => { server.close(() => resolve()); server.closeAllConnections(); });for (const folder of folders.splice(0)) await removeTempDir(folder);});@@ -313,8 +314,9 @@ describe("the v1 live view", () => {});describe("the page's file picker and downloads", () => {- it("passes uploaded files to the page's open picker, which only its current id answers", async () => {+ it.each(["linux", "darwin", "win32"])("passes uploaded bytes to the page's open picker on %s, which only its current id answers", async (platform) => {const fixture = await serve();+ vi.stubGlobal("process", { ...process, platform });const upload = (chooser: string) => {const body = new FormData();body.append("file", new File(["hello"], "notes.txt", { type: "text/plain" }));diff --git a/server/routes/browser-viewers.ts b/server/routes/browser-viewers.tsindex f7db2b468e..3657b448f0 100644--- a/server/routes/browser-viewers.ts+++ b/server/routes/browser-viewers.ts@@ -8,6 +8,7 @@ import type { IncomingMessage } from "node:http";import { dirname, join } from "node:path";import { Readable, Transform } from "node:stream";+import { BROWSER_UPLOAD_MAX_BYTES as UPLOAD_MAX_BYTES } from "../../shared/upload-limits.ts";import type { Audience } from "../audience.ts";import { storeUploads } from "../browser-upload.ts";import type { BrowserLive } from "../browser-live.ts";@@ -24,7 +25,6 @@ const UPLOAD = /^\/api\/bots\/([\w-]+)\/browser\/upload$/;const DOWNLOAD = /^\/api\/bots\/([\w-]+)\/browser\/download\/([\w-]{1,64})$/;const CHOOSER = /^[\w-]{1,64}$/;const UPLOAD_MAX_FILES = 20;-const UPLOAD_MAX_BYTES = 100 * 1024 * 1024;const PICKER_CLOSED = "The page's file picker is no longer open.";type Spec = Parameters<BrowserLive["open"]>[0]["spec"];diff --git a/shared/upload-limits.ts b/shared/upload-limits.tsnew file mode 100644index 0000000000..d44f218c8f--- /dev/null+++ b/shared/upload-limits.ts@@ -0,0 +1,3 @@+/** Below Cloudflare's transport ceiling; a local inbox, not unbounded storage. */+export const FILE_MAX_BYTES = 25 * 1024 * 1024;+export const BROWSER_UPLOAD_MAX_BYTES = 100 * 1024 * 1024;