Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
browser: private displays for the bots' browser windows, behind an input gate
milind-soni893634b41140
diff --git a/NOTICE b/NOTICEindex 11a9d37c13..9102af1f56 100644--- a/NOTICE+++ b/NOTICE@@ -100,6 +100,11 @@ viewers and screencast pacing, tool definitions and snapshot bound(apps/server/src/preview and apps/server/src/mcp), Copyright 2026 T3 ToolsInc., used under the MIT License (third_party/t3-code/LICENSE).+The input gate of the bots' browser desktop view+(server/browser/desktop/rfb-filter.ts) adapts the RFB client-message filter of+Hermes Agent, https://github.com/NousResearch/hermes-agent, Copyright (c) 2025+Nous Research, used under the MIT License (third_party/hermes-agent/LICENSE).+The social post previews template (skills/social-posts/posts.html) adapts thepost card markup and platform styling of MiniMock,https://github.com/minianon/MiniMock, Copyright (c) 2026 Tushar Bhardwaj, useddiff --git a/server/browser/desktop/displays.test.ts b/server/browser/desktop/displays.test.tsnew file mode 100644index 0000000000..72a5871af6--- /dev/null+++ b/server/browser/desktop/displays.test.ts@@ -0,0 +1,201 @@+import type { ChildProcess } from "node:child_process";+import { EventEmitter } from "node:events";+import { existsSync, mkdtempSync, readFileSync, rmSync, statSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { PassThrough } from "node:stream";++import { afterEach, beforeEach, describe, expect, it } from "vitest";++import { DESKTOP_SIZE, DISPLAY_RANGE, DisplaySupervisor, findXvnc, xauthority, xvncArgs } from "./displays.ts";++class FakeXvnc extends EventEmitter {+ readonly stderr = new PassThrough();+ readonly signals: string[] = [];+ exited = false;+ /** Whether it ignores a polite stop. */+ stubborn = false;+ readonly args: string[];+ constructor(args: string[]) {+ super();+ this.args = args;+ }+ kill(signal: NodeJS.Signals = "SIGTERM"): boolean {+ this.signals.push(signal);+ if (this.stubborn && signal === "SIGTERM") return true;+ this.exit();+ return true;+ }+ exit(): void {+ if (this.exited) return;+ this.exited = true;+ setImmediate(() => {+ this.stderr.end();+ this.emit("exit", null, "SIGTERM");+ this.emit("close", null, "SIGTERM");+ });+ }+}++let root: string;+beforeEach(() => { root = mkdtempSync(join(tmpdir(), "displays-")); });+afterEach(() => { rmSync(root, { recursive: true, force: true }); });++function supervisor(overrides: { taken?: (n: number) => boolean; failOn?: Set<number>; orphans?: number[] } = {}) {+ const spawned: FakeXvnc[] = [];+ const killed: Array<[number, string]> = [];+ const displays = new DisplaySupervisor({+ root,+ xvnc: "/usr/bin/Xvnc",+ bwrap: "/usr/bin/bwrap",+ spawn: (_file, args) => {+ const child = new FakeXvnc(args);+ spawned.push(child);+ if (overrides.failOn?.has(Number(args[0]!.slice(1)))) {+ child.stderr.write("Fatal server error: Server is already active for display\n");+ child.exit();+ }+ return child as unknown as ChildProcess;+ },+ taken: overrides.taken ?? (() => false),+ orphans: () => overrides.orphans ?? [],+ kill: (pid, signal) => { killed.push([pid, signal]); },+ ready: (_socket, _timeoutMs, exited) => new Promise((resolve, reject) => {+ setTimeout(resolve, 5);+ void exited.then(() => reject(new Error("The display server exited while starting.")));+ }),+ });+ return { displays, spawned, killed };+}++describe("display supervisor", () => {+ it("starts one display per browser on the first free number, with its own cookie and private socket", async () => {+ const { displays, spawned } = supervisor({ taken: (n) => n === DISPLAY_RANGE.first });+ const first = await displays.acquire("bot:a");+ const second = await displays.acquire("bot:b");+ expect(first.number).toBe(DISPLAY_RANGE.first + 1);+ expect(second.number).toBe(DISPLAY_RANGE.first + 2);+ expect(first.env.DISPLAY).toBe(`:${first.number}`);+ expect(first.size).toEqual(DESKTOP_SIZE);+ expect(spawned[0]!.args).toEqual(xvncArgs(first.number, DESKTOP_SIZE, first.socket, first.env.XAUTHORITY));+ if (process.platform !== "win32") {+ expect(statSync(first.env.XAUTHORITY).mode & 0o777).toBe(0o600);+ expect(statSync(join(first.socket, "..")).mode & 0o777).toBe(0o700);+ }+ expect(readFileSync(first.env.XAUTHORITY).includes(Buffer.from("MIT-MAGIC-COOKIE-1"))).toBe(true);+ expect(readFileSync(first.env.XAUTHORITY).equals(readFileSync(second.env.XAUTHORITY))).toBe(false);+ const policy = join(first.socket, "..", "policy");+ expect(first.wrap.command).toBe("/usr/bin/bwrap");+ expect(first.wrap.args).toEqual(expect.arrayContaining(["--ro-bind", policy, "/etc/opt/chrome_for_testing/policies/managed"]));+ expect(JSON.parse(readFileSync(join(policy, "openmausbot.json"), "utf8")).URLBlocklist).toContain("file://*");+ });++ it("gives browsers that start together different displays, each with its own folder", async () => {+ const { displays, spawned } = supervisor();+ const [a, b, again] = await Promise.all([displays.acquire("bot:a"), displays.acquire("bot:b"), displays.acquire("bot:a")]);+ expect(a.number).not.toBe(b.number);+ expect(again.number).toBe(a.number);+ expect(spawned).toHaveLength(2);+ expect(existsSync(a.env.XAUTHORITY) && existsSync(b.env.XAUTHORITY)).toBe(true);+ });++ it("gives a second holder of the same browser the running display and stops it after the last release", async () => {+ const { displays, spawned } = supervisor();+ const one = await displays.acquire("bot:a");+ const two = await displays.acquire("bot:a");+ expect(two.number).toBe(one.number);+ expect(spawned).toHaveLength(1);+ await one.release();+ await one.release();+ expect(spawned[0]!.exited).toBe(false);+ await two.release();+ expect(spawned[0]!.signals).toEqual(["SIGTERM"]);+ expect(existsSync(join(one.socket, ".."))).toBe(false);+ expect(displays.numbers()).toEqual([]);+ });++ it("kills a display server that ignores the polite stop", async () => {+ const { displays, spawned } = supervisor();+ const display = await displays.acquire("bot:a");+ spawned[0]!.stubborn = true;+ await display.release();+ expect(spawned[0]!.signals).toEqual(["SIGTERM", "SIGKILL"]);+ });++ it("moves on to the next number when a display server cannot start", async () => {+ const { displays, spawned } = supervisor({ failOn: new Set([DISPLAY_RANGE.first]) });+ const display = await displays.acquire("bot:a");+ expect(display.number).toBe(DISPLAY_RANGE.first + 1);+ expect(spawned).toHaveLength(2);+ expect(existsSync(join(root, `d${DISPLAY_RANGE.first}`))).toBe(false);+ });++ it("says why when no display can start", async () => {+ const { displays } = supervisor({ failOn: new Set(Array.from({ length: 70 }, (_, i) => DISPLAY_RANGE.first + i)) });+ await expect(displays.acquire("bot:a")).rejects.toThrow(/exited while starting.*already active/);+ });++ it("forgets a display whose server died, and starts a fresh one next time", async () => {+ const { displays, spawned } = supervisor();+ const display = await displays.acquire("bot:a");+ spawned[0]!.exit();+ await display.exited;+ await new Promise((resolve) => setTimeout(resolve, 0));+ expect(displays.numbers()).toEqual([]);+ const again = await displays.acquire("bot:a");+ expect(spawned).toHaveLength(2);+ expect(again.number).toBe(display.number);+ });++ it("stops display servers an earlier run left, once, before starting its own", async () => {+ const { displays, killed } = supervisor({ orphans: [4242, 4343] });+ await displays.acquire("bot:a");+ await displays.acquire("bot:b");+ expect(killed).toEqual([[4242, "SIGKILL"], [4343, "SIGKILL"]]);+ });++ it("stops everything on close", async () => {+ const { displays, spawned } = supervisor();+ await displays.acquire("bot:a");+ await displays.acquire("bot:b");+ await displays.closeAll();+ expect(spawned.every((child) => child.exited)).toBe(true);+ expect(displays.numbers()).toEqual([]);+ });++ it("refuses without Xvnc", async () => {+ const displays = new DisplaySupervisor({ root, xvnc: null, bwrap: "/usr/bin/bwrap" });+ expect(displays.available).toBe(false);+ await expect(displays.acquire("bot:a")).rejects.toThrow(/Xvnc is not installed/);+ let probes = 0;+ const lazy = new DisplaySupervisor({ root, xvnc: "/usr/bin/Xvnc", bwrap: () => { probes++; return null; } });+ expect(probes).toBe(0);+ expect(lazy.available).toBe(false);+ expect(lazy.available).toBe(false);+ expect(probes).toBe(1);+ const unwrapped = new DisplaySupervisor({ root, xvnc: "/usr/bin/Xvnc", bwrap: null });+ expect(unwrapped.available).toBe(false);+ await expect(unwrapped.acquire("bot:a")).rejects.toThrow(/locked down/);+ expect(findXvnc({ PATH: "/usr/bin" }, "darwin")).toBeNull();+ });+});++describe("display launch details", () => {+ it("never opens a TCP port and never sends the desktop's clipboard", () => {+ const args = xvncArgs(21, DESKTOP_SIZE, "/s/rfb", "/s/auth");+ expect(args.slice(args.indexOf("-rfbport"), args.indexOf("-rfbport") + 2)).toEqual(["-rfbport", "-1"]);+ expect(args).toContain("-SendCutText=0");+ expect(args).toContain("-AcceptSetDesktopSize=1");+ expect(args.slice(args.indexOf("-nolisten"), args.indexOf("-nolisten") + 2)).toEqual(["-nolisten", "tcp"]);+ });++ it("writes an authority entry for any host", () => {+ const cookie = Buffer.alloc(16, 7);+ const file = xauthority(21, cookie);+ expect(file.readUInt16BE(0)).toBe(0xffff);+ expect(file.readUInt16BE(2)).toBe(0);+ expect(file.subarray(4, 6).readUInt16BE(0)).toBe(2);+ expect(file.subarray(6, 8).toString()).toBe("21");+ expect(file.subarray(-16).equals(cookie)).toBe(true);+ });+});diff --git a/server/browser/desktop/displays.ts b/server/browser/desktop/displays.tsnew file mode 100644index 0000000000..6e92d85946--- /dev/null+++ b/server/browser/desktop/displays.ts@@ -0,0 +1,383 @@+// The private displays the bots' browsers show their windows on when browserEngine.cloudDisplay is on: one Xvnc per+// running browser, started with it and stopped when it exits, so a server with no browser open runs none.+//+// Security: a display has no TCP port. Its RFB socket is a 0600 unix socket in a 0700 folder that only the server's own+// desktop route reads, and X clients need the display's cookie, which only the browser launched on it is given.+import { spawn as spawnProcess, type ChildProcess } from "node:child_process";+import { randomBytes } from "node:crypto";+import { accessSync, constants, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";+import { connect } from "node:net";+import { delimiter, join } from "node:path";++import { spawnBotWork } from "../../oom-score.ts";+import { policyWrap, type PolicyWrap } from "./policy.ts";+import { MAX_CUT_TEXT } from "./rfb-filter.ts";++export interface DisplaySize {+ width: number;+ height: number;+}++/** A laptop-sized desktop: the panel scales it down, and a page laid out for it reads well there. */+export const DESKTOP_SIZE: DisplaySize = { width: 1280, height: 800 };++/** X display numbers this server picks from, clear of :0 and of the low numbers other tools take. */+export const DISPLAY_RANGE = { first: 20, last: 89 } as const;+const START_ATTEMPTS = 5;+const READY_MS = 10_000;+const STOP_GRACE_MS = 2_000;+const OUTPUT_LIMIT = 8 * 1024;++export interface DesktopDisplay {+ readonly number: number;+ /** The display server's RFB socket. */+ readonly socket: string;+ /** What a program needs to open windows on it. */+ readonly env: { DISPLAY: string; XAUTHORITY: string };+ /** What a Chrome shown on it starts under: the lock-down policy in force for that Chrome alone (policy.ts). */+ readonly wrap: PolicyWrap;+ readonly size: DisplaySize;+ /** Settles when the display server has exited, whichever way. */+ readonly exited: Promise<void>;+ /** Gives the display back; the last holder's release stops it. */+ release(): Promise<void>;+}++type Spawn = (file: string, args: string[], options: { env: NodeJS.ProcessEnv }) => ChildProcess;++export interface DisplaySupervisorOptions {+ /** Where each display keeps its socket and cookie; a short path, as a unix socket's may not pass about 100 bytes. */+ root: string;+ /** The Xvnc binary, or null where there is none. */+ xvnc: string | null;+ /** bubblewrap, which puts the lock-down policy in force for a display's Chrome alone; null where it cannot run. A+ * function is asked once, the first time a display is wanted, so a server that never wants one never probes. */+ bwrap: string | null | (() => string | null);+ spawn?: Spawn;+ /** Whether something other than this server holds display `n`. */+ taken?: (n: number) => boolean;+ /** Display servers an earlier run of this server left behind. */+ orphans?: (root: string) => number[];+ kill?: (pid: number, signal: NodeJS.Signals) => void;+ /** Settles once the RFB socket answers. */+ ready?: (socket: string, timeoutMs: number, exited: Promise<void>) => Promise<void>;+ log?: (line: string) => void;+}++/** The Xvnc on PATH, on Linux only. */+export function findXvnc(env: NodeJS.ProcessEnv = process.env, platform: NodeJS.Platform = process.platform): string | null {+ if (platform !== "linux") return null;+ for (const dir of (env.PATH ?? "").split(delimiter)) {+ if (!dir) continue;+ const candidate = join(dir, "Xvnc");+ try {+ accessSync(candidate, constants.X_OK);+ return candidate;+ } catch {}+ }+ return null;+}++/** An X authority file holding one cookie for any host and the given display, as `xauth add` writes it. */+export function xauthority(display: number, cookie: Buffer): Buffer {+ const field = (value: Buffer) => {+ const length = Buffer.alloc(2);+ length.writeUInt16BE(value.length);+ return Buffer.concat([length, value]);+ };+ const family = Buffer.alloc(2);+ family.writeUInt16BE(0xffff);+ return Buffer.concat([family, field(Buffer.alloc(0)), field(Buffer.from(String(display))), field(Buffer.from("MIT-MAGIC-COOKIE-1")), field(cookie)]);+}++export function xvncArgs(display: number, size: DisplaySize, socket: string, auth: string): string[] {+ return [+ `:${display}`,+ "-geometry", `${size.width}x${size.height}`,+ "-depth", "24",+ "-dpi", "96",+ "-rfbport", "-1",+ "-rfbunixpath", socket,+ "-rfbunixmode", "0600",+ // Safe only because the socket is the server's alone: whoever reaches it is the desktop route.+ "-SecurityTypes", "None",+ "-AlwaysShared",+ // Resized only by the person holding the browser, within limits (rfb-filter.ts); its window follows (views.ts).+ "-AcceptSetDesktopSize=1",+ // The desktop's clipboard never goes to viewers: a page or the bot may have put a secret there.+ "-SendCutText=0",+ "-SendPrimary=0",+ "-MaxCutText", String(MAX_CUT_TEXT),+ "-FrameRate", "30",+ "-nolisten", "tcp",+ "-auth", auth,+ "-desktop", "OpenMausBot",+ ];+}++const alive = (pid: number) => {+ try {+ process.kill(pid, 0);+ return true;+ } catch (error) {+ return (error as NodeJS.ErrnoException).code === "EPERM";+ }+};++/** An X server's lock file names a running process. */+function displayTaken(n: number): boolean {+ try {+ const pid = Number(readFileSync(`/tmp/.X${n}-lock`, "utf8").trim());+ return !Number.isInteger(pid) || pid <= 0 || alive(pid);+ } catch {+ return false;+ }+}++/** Xvnc processes whose RFB socket lies under `root`. */+function leftBehind(root: string): number[] {+ const pids: number[] = [];+ let entries: string[];+ try {+ entries = readdirSync("/proc");+ } catch {+ return pids;+ }+ for (const entry of entries) {+ if (!/^\d+$/.test(entry) || Number(entry) === process.pid) continue;+ try {+ const argv = readFileSync(`/proc/${entry}/cmdline`, "utf8").split("\0");+ const at = argv.indexOf("-rfbunixpath");+ if (/(^|\/)Xvnc$/.test(argv[0] ?? "") && at > 0 && argv[at + 1]?.startsWith(`${root}/`)) pids.push(Number(entry));+ } catch {}+ }+ return pids;+}++function socketAnswers(socket: string, timeoutMs: number, exited: Promise<void>): Promise<void> {+ return new Promise((resolve, reject) => {+ let done = false;+ const deadline = setTimeout(() => finish(new Error(`The display did not start within ${timeoutMs} ms.`)), timeoutMs);+ const finish = (error: Error | null) => {+ if (done) return;+ done = true;+ clearTimeout(deadline);+ if (error) reject(error);+ else resolve();+ };+ void exited.then(() => finish(new Error("The display server exited while starting.")));+ const attempt = () => {+ if (done) return;+ const probe = connect(socket);+ probe.once("connect", () => {+ probe.destroy();+ finish(null);+ });+ probe.once("error", () => {+ probe.destroy();+ setTimeout(attempt, 50).unref();+ });+ };+ attempt();+ });+}++interface Running {+ readonly display: DesktopDisplay;+ readonly child: ChildProcess;+ readonly dir: string;+ holders: number;+ stopping: Promise<void> | null;+}++const children = new Set<ChildProcess>();+let exitHook = false;++/** Starts and stops the displays; nothing it started outlives the server. */+export class DisplaySupervisor {+ readonly #options: DisplaySupervisorOptions;+ readonly #running = new Map<string, Running>();+ readonly #starting = new Map<string, Promise<Running>>();+ /** Display numbers a start of this server holds, from the moment it picks one until that display is gone. */+ readonly #claimed = new Set<number>();+ #swept = false;+ #probed: { bwrap: string | null } | null = null;++ constructor(options: DisplaySupervisorOptions) {+ this.#options = options;+ }++ /** Security: with no way to put the policy in force for its Chrome alone, no browser gets a display. */+ get available(): boolean {+ return this.#options.xvnc !== null && this.#bwrap() !== null;+ }++ #bwrap(): string | null {+ const bwrap = this.#options.bwrap;+ if (typeof bwrap !== "function") return bwrap;+ this.#probed ??= { bwrap: bwrap() };+ return this.#probed.bwrap;+ }++ /** The numbers of the displays running now. */+ numbers(): number[] {+ return [...this.#running.values()].map((running) => running.display.number);+ }++ /** A display for the browser of profile `key`: its running one, else a new one. */+ async acquire(key: string, size: DisplaySize = DESKTOP_SIZE, fileRoots: readonly string[] = []): Promise<DesktopDisplay> {+ for (;;) {+ const running = this.#running.get(key);+ if (running?.stopping) {+ await running.stopping;+ continue;+ }+ if (running) {+ running.holders++;+ return this.#handle(key, running);+ }+ const starting = this.#starting.get(key) ?? this.#start(key, size, fileRoots).finally(() => this.#starting.delete(key));+ this.#starting.set(key, starting);+ const started = await starting;+ if (this.#running.get(key) === started && !started.stopping) {+ started.holders++;+ return this.#handle(key, started);+ }+ }+ }++ /** Stops every display; the server is shutting down. */+ async closeAll(): Promise<void> {+ await Promise.all([...this.#running.keys()].map((key) => this.#stop(key)));+ }++ #handle(key: string, running: Running): DesktopDisplay {+ let released = false;+ return {+ ...running.display,+ release: async () => {+ if (released) return;+ released = true;+ running.holders--;+ if (running.holders <= 0 && this.#running.get(key) === running) await this.#stop(key);+ },+ };+ }++ #sweep(): void {+ if (this.#swept) return;+ this.#swept = true;+ const kill = this.#options.kill ?? ((pid, signal) => process.kill(pid, signal));+ for (const pid of (this.#options.orphans ?? leftBehind)(this.#options.root)) {+ try {+ kill(pid, "SIGKILL");+ this.#options.log?.(`browser display: stopped a display server an earlier run left (pid ${pid})`);+ } catch {}+ }+ }++ /** The first number neither this server nor anything else holds, claimed before anything awaits. */+ #claim(skip: ReadonlySet<number>): number | null {+ const taken = this.#options.taken ?? displayTaken;+ for (let n = DISPLAY_RANGE.first; n <= DISPLAY_RANGE.last; n++) {+ if (this.#claimed.has(n) || skip.has(n) || taken(n)) continue;+ this.#claimed.add(n);+ return n;+ }+ return null;+ }++ async #start(key: string, size: DisplaySize, fileRoots: readonly string[]): Promise<Running> {+ const xvnc = this.#options.xvnc;+ if (!xvnc) throw new Error("This server has no display for a browser window: Xvnc is not installed.");+ const bwrap = this.#bwrap();+ if (!bwrap) throw new Error("This server cannot keep a browser window's Chrome locked down: bubblewrap cannot run here.");+ this.#sweep();+ mkdirSync(this.#options.root, { recursive: true, mode: 0o700 });+ let lastError: Error | null = null;+ const tried = new Set<number>();+ for (let attempt = 0; attempt < START_ATTEMPTS; attempt++) {+ const number = this.#claim(tried);+ if (number === null) break;+ tried.add(number);+ try {+ const running = await this.#launch(xvnc, bwrap, number, size, fileRoots);+ this.#running.set(key, running);+ void running.display.exited.then(() => {+ if (this.#running.get(key) === running) this.#running.delete(key);+ rmSync(running.dir, { recursive: true, force: true });+ this.#claimed.delete(number);+ });+ return running;+ } catch (error) {+ this.#claimed.delete(number);+ lastError = error instanceof Error ? error : new Error(String(error));+ }+ }+ throw lastError ?? new Error("No display number is free for a browser window.");+ }++ async #launch(xvnc: string, bwrap: string, number: number, size: DisplaySize, fileRoots: readonly string[]): Promise<Running> {+ const dir = join(this.#options.root, `d${number}`);+ rmSync(dir, { recursive: true, force: true });+ mkdirSync(dir, { recursive: true, mode: 0o700 });+ const socket = join(dir, "rfb");+ const auth = join(dir, "Xauthority");+ writeFileSync(auth, xauthority(number, randomBytes(16)), { mode: 0o600 });+ const spawn = this.#options.spawn ?? ((file, args, options) => spawnProcess(file, args, { ...options, stdio: ["ignore", "ignore", "pipe"] }));+ const child = spawnBotWork(() => spawn(xvnc, xvncArgs(number, size, socket, auth), { env: process.env }));+ let output = "";+ child.stderr?.on("data", (chunk: Buffer) => { output = (output + chunk.toString("utf8")).slice(-OUTPUT_LIMIT); });+ const exited = new Promise<void>((resolve) => {+ // "close" comes after the error output was read.+ child.once("close", () => resolve());+ child.once("error", (error) => {+ output += `${error.message}\n`;+ resolve();+ });+ });+ children.add(child);+ void exited.then(() => children.delete(child));+ if (!exitHook) {+ exitHook = true;+ process.once("exit", () => { for (const running of children) try { running.kill("SIGKILL"); } catch {} });+ }+ try {+ await (this.#options.ready ?? socketAnswers)(socket, READY_MS, exited);+ } catch (error) {+ try { child.kill("SIGKILL"); } catch {}+ await exited;+ rmSync(dir, { recursive: true, force: true });+ const reason = output.trim().split("\n").slice(-3).join(" ");+ throw new Error(`${error instanceof Error ? error.message : String(error)}${reason ? ` ${reason}` : ""}`);+ }+ const display: DesktopDisplay = {+ number,+ socket,+ env: { DISPLAY: `:${number}`, XAUTHORITY: auth },+ wrap: policyWrap(bwrap, join(dir, "policy"), fileRoots),+ size,+ exited,+ release: async () => {},+ };+ return { display, child, dir, holders: 0, stopping: null };+ }++ #stop(key: string): Promise<void> {+ const running = this.#running.get(key);+ if (!running) return Promise.resolve();+ running.stopping ??= (async () => {+ const { child } = running;+ try { child.kill("SIGTERM"); } catch {}+ const late = await Promise.race([running.display.exited.then(() => false), new Promise<boolean>((resolve) => setTimeout(() => resolve(true), STOP_GRACE_MS).unref())]);+ if (late) {+ try { child.kill("SIGKILL"); } catch {}+ await running.display.exited;+ }+ if (this.#running.get(key) === running) this.#running.delete(key);+ rmSync(running.dir, { recursive: true, force: true });+ this.#claimed.delete(running.display.number);+ })();+ return running.stopping;+ }+}diff --git a/server/browser/desktop/policy.test.ts b/server/browser/desktop/policy.test.tsnew file mode 100644index 0000000000..7a36a73d7e--- /dev/null+++ b/server/browser/desktop/policy.test.ts@@ -0,0 +1,43 @@+import { mkdtempSync, readFileSync, rmSync, statSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import { afterEach, describe, expect, it } from "vitest";++import { desktopPolicy, policyWrap } from "./policy.ts";++const folders: string[] = [];+afterEach(() => { for (const folder of folders.splice(0)) rmSync(folder, { recursive: true, force: true }); });++describe("the lock-down policy of a Chrome on a private display", () => {+ it("blocks files, Chrome's pages, DevTools and page source, but keeps the new tab page and the DevTools Protocol", () => {+ const policy = desktopPolicy();+ expect(policy.URLBlocklist).toEqual(["file://*", "chrome://*", "devtools://*", "view-source:*"]);+ expect(policy.URLAllowlist).toEqual(["chrome://newtab", "chrome://new-tab-page", "chrome://new-tab-page-third-party"]);+ expect(policy.IncognitoModeAvailability).toBe(1);+ expect(policy.AllowFileSelectionDialogs).toBe(false);+ expect(policy).not.toHaveProperty("DeveloperToolsAvailability");+ });++ it("lets through only the folders named, and nothing beside them", () => {+ expect(desktopPolicy(["/data/.openmausbot/workspaces/scout/", "/srv/files"]).URLAllowlist).toEqual(expect.arrayContaining(["file:///data/.openmausbot/workspaces/scout/", "file:///srv/files/"]));+ });++ it("is put in force for that Chrome alone, in every installed brand's folder of a private mount namespace", () => {+ const dir = join(mkdtempSync(join(tmpdir(), "omb-policy-")), "policy");+ folders.push(join(dir, ".."));+ const installed = new Set(["/etc/chromium"]);+ const wrap = policyWrap("/usr/bin/bwrap", dir, [], (path) => installed.has(path));+ expect(wrap.command).toBe("/usr/bin/bwrap");+ expect(wrap.args).toEqual([+ "--dev-bind", "/", "/", "--die-with-parent",+ "--tmpfs", "/etc/opt", "--ro-bind", dir, "/etc/opt/chrome/policies/managed",+ "--ro-bind", dir, "/etc/opt/chrome_for_testing/policies/managed",+ "--tmpfs", "/etc/chromium/policies", "--ro-bind", dir, "/etc/chromium/policies/managed",+ "--",+ ]);+ expect(JSON.parse(readFileSync(join(dir, "openmausbot.json"), "utf8"))).toEqual(desktopPolicy());+ if (process.platform !== "win32") expect(statSync(join(dir, "openmausbot.json")).mode & 0o777).toBe(0o600);+ expect(policyWrap("/usr/bin/bwrap", dir, [], () => false).args).not.toContain("/etc/chromium/policies/managed");+ });+});diff --git a/server/browser/desktop/policy.ts b/server/browser/desktop/policy.tsnew file mode 100644index 0000000000..3ace7c878d--- /dev/null+++ b/server/browser/desktop/policy.ts@@ -0,0 +1,83 @@+// The Chrome policy that keeps a person on the browser desktop away from this computer's files, Chrome's own pages and+// DevTools. It applies only to a Chrome launched on a private display: that Chrome starts inside its own mount namespace+// (bubblewrap) where each brand's managed-policy folder holds this policy, so every other Chrome on the computer, the+// bots' headless ones included, reads its folders as they are. Chrome reads policy from a folder per brand: Chromium's+// chrome_paths.cc, and Chrome for Testing 158's binary names /etc/opt/chrome_for_testing/policies.+import { execFileSync } from "node:child_process";+import { accessSync, constants, existsSync, mkdirSync, writeFileSync } from "node:fs";+import { delimiter, join } from "node:path";++/** Pages a person may still open from Chrome's own address bar: the new tab page. */+const ALLOWED_CHROME_PAGES = ["chrome://newtab", "chrome://new-tab-page", "chrome://new-tab-page-third-party"];++/** The policy, with `fileRoots` (absolute folders) the one exception to the block on files. */+export function desktopPolicy(fileRoots: readonly string[] = []): Record<string, unknown> {+ return {+ URLBlocklist: ["file://*", "chrome://*", "devtools://*", "view-source:*"],+ URLAllowlist: [...ALLOWED_CHROME_PAGES, ...fileRoots.map((root) => `file://${root.replace(/\/+$/u, "")}/`)],+ // DeveloperToolsAvailability 2 would also stop DevTools Protocol clients attaching to pages (Chromium 156), and the+ // bots drive Chrome through that protocol: DevTools is kept out by its address and its keys (rfb-filter.ts).+ BrowserGuestModeEnabled: false,+ BrowserAddPersonEnabled: false,+ IncognitoModeAvailability: 1,+ BrowserSignin: 0,+ SyncDisabled: true,+ AllowFileSelectionDialogs: false,+ PromptForDownloadLocation: false,+ TaskManagerEndProcessEnabled: false,+ DefaultBrowserSettingEnabled: false,+ };+}++/** Each brand's managed-policy folder, and the folder above it that a private tmpfs replaces to put the policy there. */+const BRANDS = [+ { managed: "/etc/opt/chrome/policies/managed", covered: "/etc/opt" },+ { managed: "/etc/opt/chrome_for_testing/policies/managed", covered: "/etc/opt" },+ { managed: "/etc/chromium/policies/managed", covered: "/etc/chromium/policies" },+] as const;++export interface PolicyWrap {+ command: string;+ /** bubblewrap's own arguments; Chrome's command line follows. */+ args: string[];+}++/** Writes the policy into `dir` and answers the command that starts Chrome with only that policy in force. */+export function policyWrap(bwrap: string, dir: string, fileRoots: readonly string[] = [], exists: (path: string) => boolean = existsSync): PolicyWrap {+ mkdirSync(dir, { recursive: true, mode: 0o700 });+ writeFileSync(join(dir, "openmausbot.json"), `${JSON.stringify(desktopPolicy(fileRoots), null, 2)}\n`, { mode: 0o600 });+ const args = ["--dev-bind", "/", "/", "--die-with-parent"];+ const covered = new Set<string>();+ for (const brand of BRANDS) {+ // A brand whose own folder is absent is not installed here. Security: any other folder that cannot be covered makes+ // bubblewrap fail, so that Chrome does not start at all rather than start without the policy.+ if (brand.covered !== "/etc/opt" && !exists(brand.managed.slice(0, brand.managed.indexOf("/policies")))) continue;+ if (!covered.has(brand.covered)) {+ args.push("--tmpfs", brand.covered);+ covered.add(brand.covered);+ }+ args.push("--ro-bind", dir, brand.managed);+ }+ return { command: bwrap, args: [...args, "--"] };+}++/** bubblewrap on PATH, if it can make the private mount namespace here (a container may refuse user namespaces). */+export function findBwrap(env: NodeJS.ProcessEnv = process.env, platform: NodeJS.Platform = process.platform): string | null {+ if (platform !== "linux") return null;+ for (const folder of (env.PATH ?? "").split(delimiter)) {+ if (!folder) continue;+ const candidate = join(folder, "bwrap");+ try {+ accessSync(candidate, constants.X_OK);+ } catch {+ continue;+ }+ try {+ execFileSync(candidate, ["--dev-bind", "/", "/", "--tmpfs", "/etc/opt", "--", "/bin/true"], { stdio: "ignore", timeout: 10_000 });+ return candidate;+ } catch {+ return null;+ }+ }+ return null;+}diff --git a/server/browser/desktop/rfb-filter.test.ts b/server/browser/desktop/rfb-filter.test.tsnew file mode 100644index 0000000000..7de910c9a0--- /dev/null+++ b/server/browser/desktop/rfb-filter.test.ts@@ -0,0 +1,143 @@+import { describe, expect, it } from "vitest";++import { MAX_CUT_TEXT, RfbClientFilter, RfbProtocolError } from "./rfb-filter.ts";++const HANDSHAKE = Buffer.concat([Buffer.from("RFB 003.008\n", "latin1"), Buffer.from([1, 0])]);+const key = (down: boolean, keysym: number) => { const message = Buffer.alloc(8); message[0] = 4; message[1] = down ? 1 : 0; message.writeUInt32BE(keysym, 4); return message; };+const qemuKey = (down: boolean, keysym: number, keycode: number) => { const message = Buffer.alloc(12); message[0] = 255; message.writeUInt16BE(down ? 1 : 0, 2); message.writeUInt32BE(keysym, 4); message.writeUInt32BE(keycode, 8); return message; };+const pointer = (mask: number, x: number, y: number) => { const message = Buffer.alloc(6); message[0] = 5; message[1] = mask; message.writeUInt16BE(x, 2); message.writeUInt16BE(y, 4); return message; };+const cutText = (text: string) => { const bytes = Buffer.from(text, "latin1"); const head = Buffer.alloc(8); head[0] = 6; head.writeInt32BE(bytes.length, 4); return Buffer.concat([head, bytes]); };+const updateRequest = () => Buffer.from([3, 1, 0, 0, 0, 0, 5, 0, 3, 32]);+const setEncodings = (encodings: number[]) => { const message = Buffer.alloc(4 + 4 * encodings.length); message[0] = 2; message.writeUInt16BE(encodings.length, 2); encodings.forEach((encoding, index) => message.writeInt32BE(encoding, 4 + 4 * index)); return message; };+const desktopSize = () => { const message = Buffer.alloc(8 + 16); message[0] = 251; message.writeUInt16BE(800, 2); message.writeUInt16BE(600, 4); message[6] = 1; return message; };++function filter(allowed: { value: boolean }) {+ let inputs = 0;+ const gate = new RfbClientFilter({ allowInput: () => allowed.value, onInput: () => { inputs++; } });+ return { gate, inputs: () => inputs };+}++describe("RFB client filter", () => {+ it("passes the handshake, forcing a shared session", () => {+ const { gate } = filter({ value: false });+ const exclusive = Buffer.from(HANDSHAKE);+ exclusive[13] = 0;+ expect([...gate.feed(exclusive)]).toEqual([...HANDSHAKE.subarray(0, 13), 1]);+ });++ it("passes each step of the handshake as soon as it is whole, since the server answers each before the next", () => {+ const { gate } = filter({ value: false });+ expect(gate.feed(HANDSHAKE.subarray(0, 5)).length).toBe(0);+ expect(gate.feed(HANDSHAKE.subarray(5, 12)).toString("latin1")).toBe("RFB 003.008\n");+ expect([...gate.feed(HANDSHAKE.subarray(12, 13))]).toEqual([1]);+ expect([...gate.feed(Buffer.from([0]))]).toEqual([1]);+ });++ it("refuses a version or security type it cannot frame", () => {+ expect(() => filter({ value: true }).gate.feed(Buffer.from("RFB 003.003\n", "latin1"))).toThrow(RfbProtocolError);+ const vncAuth = Buffer.from(HANDSHAKE);+ vncAuth[12] = 2;+ expect(() => filter({ value: true }).gate.feed(vncAuth)).toThrow(RfbProtocolError);+ });++ it("drops pointer, key, clipboard and resize messages from a viewer without control, and keeps the picture flowing", () => {+ const { gate, inputs } = filter({ value: false });+ gate.feed(HANDSHAKE);+ const picture = Buffer.concat([setEncodings([7, 16, 0, -223]), updateRequest()]);+ const out = gate.feed(Buffer.concat([pointer(1, 10, 20), key(true, 0x61), picture, qemuKey(true, 0x62, 48), cutText("secret"), desktopSize()]));+ expect(out.equals(picture)).toBe(true);+ expect(inputs()).toBe(0);+ });++ it("passes the same input once its viewer holds control", () => {+ const { gate, inputs } = filter({ value: true });+ gate.feed(HANDSHAKE);+ const input = Buffer.concat([pointer(1, 10, 20), pointer(0, 10, 20), key(true, 0x61), key(false, 0x61), cutText("hello")]);+ expect(gate.feed(input).equals(input)).toBe(true);+ expect(inputs()).toBe(5);+ });++ it("frames messages split across chunks at any byte", () => {+ const allowed = { value: true };+ const { gate } = filter(allowed);+ const stream = Buffer.concat([HANDSHAKE, setEncodings([7, 0]), key(true, 0x61), key(false, 0x61), cutText("abc"), updateRequest()]);+ const out: Buffer[] = [];+ for (let at = 0; at < stream.length; at++) out.push(gate.feed(stream.subarray(at, at + 1)));+ const joined = Buffer.concat(out);+ const expected = Buffer.from(stream);+ expected[13] = 1;+ expect(joined.equals(expected)).toBe(true);+ });++ it("applies a change of control to the very next message", () => {+ const allowed = { value: true };+ const { gate } = filter(allowed);+ gate.feed(HANDSHAKE);+ expect(gate.feed(key(true, 0x61)).length).toBe(8);+ allowed.value = false;+ // The held key is let go once, then nothing more gets through.+ expect([...gate.feed(key(true, 0x62))]).toEqual([...key(false, 0x61)]);+ expect(gate.feed(key(true, 0x63)).length).toBe(0);+ });++ it("lets go of held keys and buttons when asked", () => {+ const { gate } = filter({ value: true });+ gate.feed(HANDSHAKE);+ gate.feed(Buffer.concat([key(true, 0x61), qemuKey(true, 0x62, 48), pointer(1, 30, 40)]));+ expect(gate.holding).toBe(true);+ expect([...gate.release()]).toEqual([...key(false, 0x61), ...qemuKey(false, 0x62, 48), ...pointer(0, 30, 40)]);+ expect(gate.holding).toBe(false);+ expect(gate.release().length).toBe(0);+ });++ it("sizes the display as the picture view sizes the page, the screens in it too, within limits, and reports the size", () => {+ const sizes: Array<[number, number]> = [];+ const gate = new RfbClientFilter({ allowInput: () => true, onResize: (width, height) => { sizes.push([width, height]); } });+ gate.feed(HANDSHAKE);+ const out = gate.feed(desktopSize());+ expect(sizes).toEqual([[1280, 960]]);+ const phone = Buffer.from(desktopSize());+ phone.writeUInt16BE(400, 2);+ phone.writeUInt16BE(750, 4);+ const fitted = gate.feed(phone);+ expect([fitted.readUInt16BE(2), fitted.readUInt16BE(4), fitted.readUInt16BE(16), fitted.readUInt16BE(18)]).toEqual([1280, 2400, 1280, 2400]);+ const huge = Buffer.from(desktopSize());+ huge.writeUInt16BE(9000, 2);+ huge.writeUInt16BE(3000, 4);+ gate.feed(huge);+ expect(sizes.at(-1)).toEqual([2560, 2560]);+ expect(out.length).toBe(24);+ });++ it("swallows the keyboard's ways into DevTools and printing, presses and releases alike, and keeps the page's own shortcuts", () => {+ const { gate } = filter({ value: true });+ gate.feed(HANDSHAKE);+ const CONTROL = 0xffe3, SHIFT = 0xffe1;+ const chord = (modifiers: number[], keysym: number) => Buffer.concat([...modifiers.map((m) => key(true, m)), key(true, keysym), key(false, keysym), ...[...modifiers].reverse().map((m) => key(false, m))]);+ const modifiersOnly = (modifiers: number[]) => Buffer.concat([...modifiers.map((m) => key(true, m)), ...[...modifiers].reverse().map((m) => key(false, m))]);+ expect(gate.feed(Buffer.concat([key(true, 0xffc9), key(false, 0xffc9)])).length).toBe(0);+ for (const letter of [0x49, 0x69, 0x4a, 0x6a]) expect(gate.feed(chord([CONTROL, SHIFT], letter)).equals(modifiersOnly([CONTROL, SHIFT])), letter.toString(16)).toBe(true);+ for (const letter of [0x70, 0x50]) expect(gate.feed(chord([CONTROL], letter)).equals(modifiersOnly([CONTROL]))).toBe(true);+ expect(gate.feed(qemuKey(true, 0xffc9, 88)).length).toBe(0);+ expect(gate.feed(qemuKey(false, 0xffc9, 88)).length).toBe(0);+ // Ctrl+U underlines and Ctrl+Shift+C copies in editors and terminals; the policy already blocks page source and DevTools.+ const ordinary = Buffer.concat([chord([CONTROL], 0x63), chord([SHIFT], 0x49), chord([CONTROL], 0x75), chord([CONTROL, SHIFT], 0x43), key(true, 0x75), key(false, 0x75)]);+ expect(gate.feed(ordinary).equals(ordinary)).toBe(true);+ expect(gate.holding).toBe(false);+ });++ it("ends the stream on a message it cannot frame or an oversized clipboard", () => {+ const unknown = filter({ value: true }).gate;+ unknown.feed(HANDSHAKE);+ expect(() => unknown.feed(Buffer.from([99, 0, 0, 0]))).toThrow(RfbProtocolError);+ const huge = filter({ value: false }).gate;+ huge.feed(HANDSHAKE);+ const head = Buffer.alloc(8);+ head[0] = 6;+ head.writeInt32BE(-(MAX_CUT_TEXT + 1), 4);+ expect(() => huge.feed(head)).toThrow(RfbProtocolError);+ const qemuAudio = filter({ value: true }).gate;+ qemuAudio.feed(HANDSHAKE);+ expect(() => qemuAudio.feed(Buffer.from([255, 1]))).toThrow(RfbProtocolError);+ });+});diff --git a/server/browser/desktop/rfb-filter.ts b/server/browser/desktop/rfb-filter.tsnew file mode 100644index 0000000000..89fc0573e1--- /dev/null+++ b/server/browser/desktop/rfb-filter.ts@@ -0,0 +1,230 @@+// Adapted from NousResearch/hermes-agent@a3b993b9 tools/bot_desktop/rfb_filter.py, MIT License, Copyright (c) 2025 Nous+// Research (full text in third_party/hermes-agent/LICENSE); modified: written in TypeScript, the handshake is checked+// rather than assumed, and what a viewer pressed is let go when its input stops being allowed.+//+// Security: noVNC's viewOnly is only a hint to the page; anyone holding the socket could still send input. So the+// client's byte stream is parsed (RFC 6143 section 7.5, plus TigerVNC's EnableContinuousUpdates 150, Fence 248 and+// SetDesktopSize 251, and the QEMU Extended KeyEvent 255 noVNC switches to) and an input message reaches the display+// only while its viewer may give input. RFB messages do not align with WebSocket frames, so this is a stateful parser+// fed arbitrary chunks. A message it cannot frame ends the stream: forwarding it blind would let input hide behind it.++import { fillPage } from "../viewers/viewport.ts";++const KEY_EVENT = 4;+const POINTER_EVENT = 5;+const CLIENT_CUT_TEXT = 6;+const SET_ENCODINGS = 2;+const FENCE = 248;+const SET_DESKTOP_SIZE = 251;+const QEMU = 255;+const XK = { f12: 0xffc9, controlLeft: 0xffe3, controlRight: 0xffe4, shiftLeft: 0xffe1, shiftRight: 0xffe2 } as const;++/** A key message's keysym and whether it presses or releases; null for any other message. */+function keyOf(message: Buffer): { keysym: number; down: boolean } | null {+ if (message[0] === KEY_EVENT) return { keysym: message.readUInt32BE(4), down: message[1] !== 0 };+ if (message[0] === QEMU) return { keysym: message.readUInt32BE(4), down: message.readUInt16BE(2) !== 0 };+ return null;+}++const INPUT_TYPES = new Set([KEY_EVENT, POINTER_EVENT, CLIENT_CUT_TEXT, SET_DESKTOP_SIZE, QEMU]);++/** Fixed-length client messages: type to total length, type byte included. */+const FIXED: ReadonlyMap<number, number> = new Map([+ [0, 20], // SetPixelFormat+ [3, 10], // FramebufferUpdateRequest+ [KEY_EVENT, 8],+ [POINTER_EVENT, 6],+ [150, 10], // EnableContinuousUpdates+ [QEMU, 12], // sub-type 0, Extended KeyEvent, the only one noVNC sends+]);++/** The largest display a person's view may ask for. */+export const DESKTOP_SIZE_LIMITS = { maxWidth: 2560, maxHeight: 2560 } as const;++/** The display server is started with the same -MaxCutText: the length is the client's to declare, so without a cap a+ * viewer could make the proxy buffer up to 2 GiB waiting for a payload. */+export const MAX_CUT_TEXT = 256 * 1024;++/** RFB 3.7 and 3.8 clients answer the server's security types with one byte; 3.3 lets the server choose. */+const VERSIONS = new Set(["RFB 003.008\n", "RFB 003.007\n"]);+const SECURITY_NONE = 1;+const HANDSHAKE_BYTES = 12 + 1 + 1;++export class RfbProtocolError extends Error {}++const clamp = (value: number, min: number, max: number) => Math.min(max, Math.max(min, value));++/** Turns a SetDesktopSize message, each screen in it too, into the size the page takes for a panel of that size, as the+ * picture view's does (viewers/viewport.ts: a narrow panel gets a desktop-width page of its shape), within the limits;+ * answers that size. */+function clampDesktopSize(message: Buffer): [number, number] {+ const limits = DESKTOP_SIZE_LIMITS;+ const panel = { width: Math.max(1, message.readUInt16BE(2)), height: Math.max(1, message.readUInt16BE(4)) };+ const page = fillPage(panel);+ const width = clamp(page.width, 1, limits.maxWidth);+ const height = clamp(page.height, 1, limits.maxHeight);+ message.writeUInt16BE(width, 2);+ message.writeUInt16BE(height, 4);+ for (let screen = 0; screen < message[6]!; screen++) {+ const at = 8 + 16 * screen;+ message.writeUInt16BE(0, at + 4);+ message.writeUInt16BE(0, at + 6);+ message.writeUInt16BE(width, at + 8);+ message.writeUInt16BE(height, at + 10);+ }+ return [width, height];+}++export interface RfbFilterOptions {+ /** Asked for every input message, so a change of hold applies to the very next key or pointer event. */+ allowInput(): boolean;+ /** An input message was let through. */+ onInput?(): void;+ /** A resize of the display was let through, at this size. */+ onResize?(width: number, height: number): void;+}++export class RfbClientFilter {+ readonly #options: RfbFilterOptions;+ #buffer: Buffer = Buffer.alloc(0);+ #handshake: Buffer = Buffer.alloc(0);+ /** Handshake bytes already passed on. */+ #forwarded = 0;+ /** The release message of each key held down, by keysym or QEMU keycode. */+ readonly #keys = new Map<string, Buffer>();+ /** Keys whose press was swallowed, so their release is too. */+ readonly #swallowed = new Set<number>();+ #buttons = 0;+ #pointer: Buffer = Buffer.from([POINTER_EVENT, 0, 0, 0, 0, 0]);++ constructor(options: RfbFilterOptions) {+ this.#options = options;+ }++ /** The bytes of `chunk` (and of earlier partial messages) that may reach the display. */+ feed(chunk: Buffer): Buffer {+ this.#buffer = this.#buffer.length ? Buffer.concat([this.#buffer, chunk]) : chunk;+ const out: Buffer[] = [];+ if (this.#handshake.length < HANDSHAKE_BYTES) {+ const take = Math.min(HANDSHAKE_BYTES - this.#handshake.length, this.#buffer.length);+ this.#handshake = Buffer.concat([this.#handshake, this.#buffer.subarray(0, take)]);+ this.#buffer = this.#buffer.subarray(take);+ // Each step goes on as soon as it is whole and checked: the server answers it before the client sends the next.+ let checked = 0;+ if (this.#handshake.length >= 12) {+ if (!VERSIONS.has(this.#handshake.subarray(0, 12).toString("latin1"))) throw new RfbProtocolError("unsupported RFB version");+ checked = 12;+ }+ if (this.#handshake.length >= 13) {+ if (this.#handshake[12] !== SECURITY_NONE) throw new RfbProtocolError("unexpected security type");+ checked = 13;+ }+ // ClientInit's shared flag: a viewer never disconnects the others.+ if (this.#handshake.length === HANDSHAKE_BYTES) {+ this.#handshake[HANDSHAKE_BYTES - 1] = 1;+ checked = HANDSHAKE_BYTES;+ }+ out.push(this.#handshake.subarray(this.#forwarded, checked));+ this.#forwarded = Math.max(this.#forwarded, checked);+ if (this.#handshake.length < HANDSHAKE_BYTES) return Buffer.concat(out);+ }+ while (this.#buffer.length) {+ const length = this.#messageLength();+ if (length === null || this.#buffer.length < length) break;+ const message = Buffer.from(this.#buffer.subarray(0, length));+ this.#buffer = this.#buffer.subarray(length);+ if (!INPUT_TYPES.has(message[0]!)) {+ out.push(message);+ continue;+ }+ if (!this.#options.allowInput()) {+ out.push(this.release());+ continue;+ }+ if (this.#swallow(message)) continue;+ this.#track(message);+ if (message[0] === SET_DESKTOP_SIZE) this.#options.onResize?.(...clampDesktopSize(message));+ this.#options.onInput?.();+ out.push(message);+ }+ if (this.#buffer.length) this.#buffer = Buffer.from(this.#buffer);+ return Buffer.concat(out);+ }++ /** Messages that let go of every key and button this viewer holds down; empty when it holds none. */+ release(): Buffer {+ const out = [...this.#keys.values()];+ this.#keys.clear();+ if (this.#buttons !== 0) {+ const up = Buffer.from(this.#pointer);+ up[1] = 0;+ out.push(up);+ this.#buttons = 0;+ }+ return Buffer.concat(out);+ }++ /** Whether a key or button of this viewer is down. */+ get holding(): boolean {+ return this.#keys.size > 0 || this.#buttons !== 0;+ }++ /** A key of one of the keyboard's ways into DevTools or printing (F12, Ctrl+Shift+I or J, Ctrl+P), its release too:+ * without a window manager their windows would sit over the page, and the policy blanks what they would show. */+ #swallow(message: Buffer): boolean {+ const key = keyOf(message);+ if (!key) return false;+ if (!key.down) return this.#swallowed.delete(key.keysym);+ const held = [...this.#keys.values()].map((sent) => keyOf(sent)?.keysym);+ const control = held.some((keysym) => keysym === XK.controlLeft || keysym === XK.controlRight);+ const shift = held.some((keysym) => keysym === XK.shiftLeft || keysym === XK.shiftRight);+ const letter = String.fromCharCode(key.keysym).toLowerCase();+ const blocked = key.keysym === XK.f12 || (control && shift && "ij".includes(letter) && key.keysym < 0x100) || (control && !shift && letter === "p" && key.keysym < 0x100);+ if (blocked) this.#swallowed.add(key.keysym);+ return blocked;+ }++ #track(message: Buffer): void {+ if (message[0] === KEY_EVENT) {+ const key = `k${message.readUInt32BE(4)}`;+ if (message[1]) {+ const up = Buffer.from(message);+ up[1] = 0;+ this.#keys.set(key, up);+ } else {+ this.#keys.delete(key);+ }+ } else if (message[0] === QEMU) {+ const key = `q${message.readUInt32BE(8)}`;+ if (message.readUInt16BE(2)) {+ const up = Buffer.from(message);+ up.writeUInt16BE(0, 2);+ this.#keys.set(key, up);+ } else {+ this.#keys.delete(key);+ }+ } else if (message[0] === POINTER_EVENT) {+ this.#buttons = message[1]!;+ this.#pointer = Buffer.from(message);+ }+ }++ #messageLength(): number | null {+ const buffer = this.#buffer;+ const type = buffer[0]!;+ if (type === QEMU && buffer.length >= 2 && buffer[1] !== 0) throw new RfbProtocolError(`unknown QEMU message ${buffer[1]}`);+ const fixed = FIXED.get(type);+ if (fixed !== undefined) return fixed;+ if (type === SET_ENCODINGS) return buffer.length < 4 ? null : 4 + 4 * buffer.readUInt16BE(2);+ if (type === CLIENT_CUT_TEXT) {+ if (buffer.length < 8) return null;+ // Extended clipboard (TigerVNC): a negative length, its absolute value in bytes follows.+ const length = Math.abs(buffer.readInt32BE(4));+ if (length > MAX_CUT_TEXT) throw new RfbProtocolError("clipboard message too large");+ return 8 + length;+ }+ if (type === FENCE) return buffer.length < 9 ? null : 9 + buffer[8]!;+ if (type === SET_DESKTOP_SIZE) return buffer.length < 8 ? null : 8 + 16 * buffer[6]!;+ throw new RfbProtocolError(`unknown RFB client message ${type}`);+ }+}diff --git a/server/browser/desktop/views.test.ts b/server/browser/desktop/views.test.tsnew file mode 100644index 0000000000..9310504606--- /dev/null+++ b/server/browser/desktop/views.test.ts@@ -0,0 +1,218 @@+import { createServer, type Server } from "node:http";+import type { AddressInfo, Socket } from "node:net";+import { Duplex } from "node:stream";++import { afterEach, describe, expect, it } from "vitest";+import { WebSocket } from "ws";++import { DESKTOP_CLOSE, DesktopViews, type DesktopRequest, type DesktopTarget } from "./views.ts";++const HANDSHAKE = Buffer.concat([Buffer.from("RFB 003.008\n", "latin1"), Buffer.from([1, 1])]);+const key = (down: boolean, keysym: number) => { const message = Buffer.alloc(8); message[0] = 4; message[1] = down ? 1 : 0; message.writeUInt32BE(keysym, 4); return message; };+const pointer = (mask: number, x: number, y: number) => { const message = Buffer.alloc(6); message[0] = 5; message[1] = mask; message.writeUInt16BE(x, 2); message.writeUInt16BE(y, 4); return message; };+const updateRequest = () => Buffer.from([3, 1, 0, 0, 0, 0, 5, 0, 3, 32]);+const desktopSize = (width: number, height: number) => { const message = Buffer.alloc(8 + 16); message[0] = 251; message.writeUInt16BE(width, 2); message.writeUInt16BE(height, 4); message[6] = 1; message.writeUInt16BE(width, 16); message.writeUInt16BE(height, 18); return message; };++class Display extends Duplex {+ readonly received: Buffer[] = [];+ _read(): void {}+ _write(chunk: Buffer, _encoding: BufferEncoding, done: () => void): void {+ this.received.push(chunk);+ done();+ }+ bytes(): Buffer {+ return Buffer.concat(this.received);+ }+}++class Control {+ owner: string | null = null;+ ready = false;+ readonly #listeners = new Set<() => void>();+ canControl(owner: string): boolean { return this.owner === owner && this.ready; }+ onChange(listener: () => void): () => void { this.#listeners.add(listener); return () => this.#listeners.delete(listener); }+ set(owner: string | null, ready = owner !== null): void {+ this.owner = owner;+ this.ready = ready;+ for (const listener of this.#listeners) listener();+ }+}++const servers: Server[] = [];+afterEach(async () => {+ for (const server of servers.splice(0)) {+ server.closeAllConnections();+ await new Promise((resolve) => server.close(resolve));+ }+});++async function harness(options: { desktop?: boolean; stopped?: boolean; person?: string; canOperate?: boolean } = {}) {+ const display = new Display();+ const control = new Control();+ let used = 0;+ let current = true;+ const resizes: Array<[number, number]> = [];+ const target: DesktopTarget = { socket: "/unused", control, used: () => { used++; }, resized: (width, height) => { resizes.push([width, height]); } };+ const views = new DesktopViews({ desktop: async () => (options.desktop === false ? "pictures" : options.stopped ? "stopped" : target), connectSocket: () => display });+ const server = createServer();+ servers.push(server);+ server.on("upgrade", (req, socket, head) => {+ const request: DesktopRequest = {+ target: { session: "s", key: "bot:a" }, botId: "a", owner: "session-1", person: options.person ?? "alice",+ canOperate: options.canOperate ?? true, req, socket: socket as Socket, head, isCurrent: () => current,+ };+ views.open(request);+ });+ await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));+ const { port } = server.address() as AddressInfo;+ const ws = new WebSocket(`ws://127.0.0.1:${port}/`);+ const fromDisplay: Buffer[] = [];+ const closed = new Promise<number>((resolve) => ws.once("close", (code) => resolve(code)));+ ws.on("message", (data) => fromDisplay.push(Buffer.from(data as Buffer)));+ await new Promise((resolve, reject) => { ws.once("open", resolve); ws.once("error", reject); });+ return { ws, display, control, views, closed, fromDisplay, resizes, used: () => used, setCurrent: (value: boolean) => { current = value; } };+}++/** Waits until `check` holds; what must not happen is checked behind a message the display does receive. */+async function until(check: () => boolean, timeoutMs = 5_000): Promise<void> {+ for (const deadline = Date.now() + timeoutMs; !check(); await new Promise((resolve) => setTimeout(resolve, 10))) {+ if (Date.now() > deadline) throw new Error("timed out");+ }+}+const endsWith = (display: Display, bytes: Buffer) => {+ const all = display.bytes();+ return all.length >= bytes.length && all.subarray(all.length - bytes.length).equals(bytes);+};++describe("desktop views", () => {+ it("shows the display to a watcher and drops its pointer and keys", async () => {+ const { ws, display, fromDisplay, used } = await harness();+ ws.send(Buffer.concat([HANDSHAKE, pointer(1, 5, 5), key(true, 0x61), updateRequest()]));+ await until(() => endsWith(display, updateRequest()));+ expect(display.bytes().equals(Buffer.concat([HANDSHAKE, updateRequest()]))).toBe(true);+ display.push(Buffer.from("RFB 003.008\n"));+ await until(() => Buffer.concat(fromDisplay).length === 12);+ expect(Buffer.concat(fromDisplay).toString()).toBe("RFB 003.008\n");+ expect(used()).toBe(0);+ ws.close();+ });++ it("passes the person's input once they hold the browser, and counts it as use", async () => {+ const { ws, display, control, used } = await harness();+ control.set("alice");+ const input = Buffer.concat([HANDSHAKE, pointer(1, 5, 5), pointer(0, 5, 5), key(true, 0x61), key(false, 0x61)]);+ ws.send(input);+ await until(() => display.bytes().length === input.length);+ expect(display.bytes().equals(input)).toBe(true);+ expect(used()).toBe(1);+ ws.close();+ });++ it("waits for the takeover to drain the bot's work before passing input", async () => {+ const { ws, display, control } = await harness();+ control.set("alice", false);+ ws.send(Buffer.concat([HANDSHAKE, key(true, 0x61), updateRequest()]));+ await until(() => endsWith(display, updateRequest()));+ expect(display.bytes().equals(Buffer.concat([HANDSHAKE, updateRequest()]))).toBe(true);+ ws.close();+ });++ it("lets go of what the person held when they hand the browser back", async () => {+ const { ws, display, control } = await harness();+ control.set("alice");+ const held = Buffer.concat([HANDSHAKE, key(true, 0x61), pointer(1, 9, 9)]);+ ws.send(held);+ await until(() => display.bytes().length === held.length);+ display.received.length = 0;+ control.set(null);+ const release = Buffer.concat([key(false, 0x61), pointer(0, 9, 9)]);+ await until(() => display.bytes().length >= release.length);+ expect(display.bytes().equals(release)).toBe(true);+ ws.send(Buffer.concat([key(true, 0x62), updateRequest()]));+ await until(() => endsWith(display, updateRequest()));+ expect(display.bytes().equals(Buffer.concat([release, updateRequest()]))).toBe(true);+ ws.close();+ });++ it("lets only the person holding the browser resize the display, within limits, and fits the window to it", async () => {+ const { ws, display, control, resizes } = await harness();+ ws.send(Buffer.concat([HANDSHAKE, desktopSize(900, 700), updateRequest()]));+ await until(() => endsWith(display, updateRequest()));+ expect(resizes).toEqual([]);+ control.set("alice");+ ws.send(Buffer.concat([desktopSize(400, 750), updateRequest()]));+ await until(() => resizes.length === 1);+ expect(resizes).toEqual([[1280, 2400]]);+ const sent = display.bytes().subarray(HANDSHAKE.length + 10, HANDSHAKE.length + 10 + 24);+ expect([sent.readUInt16BE(2), sent.readUInt16BE(4), sent.readUInt16BE(16), sent.readUInt16BE(18)]).toEqual([1280, 2400, 1280, 2400]);+ ws.close();+ });++ it("never drives from a passive view", async () => {+ const { ws, display, control } = await harness({ canOperate: false });+ control.set("alice");+ ws.send(Buffer.concat([HANDSHAKE, key(true, 0x61), updateRequest()]));+ await until(() => endsWith(display, updateRequest()));+ expect(display.bytes().equals(Buffer.concat([HANDSHAKE, updateRequest()]))).toBe(true);+ ws.close();+ });++ it("closes, showing nothing more, when another person takes the browser", async () => {+ const { ws, display, control, closed, fromDisplay } = await harness();+ ws.send(HANDSHAKE);+ await until(() => display.bytes().length === HANDSHAKE.length);+ control.set("bob");+ display.push(Buffer.from("pixels"));+ expect(await closed).toBe(DESKTOP_CLOSE.heldElsewhere);+ expect(fromDisplay).toHaveLength(0);+ });++ it("refuses to open while another person holds the browser", async () => {+ const first = await harness();+ first.ws.close();+ const second = await harness();+ second.control.set("bob");+ second.ws.send(HANDSHAKE);+ expect(await second.closed).toBe(DESKTOP_CLOSE.heldElsewhere);+ });++ it("closes a view whose person may no longer see the browser", async () => {+ const { ws, display, closed, setCurrent } = await harness();+ setCurrent(false);+ ws.send(Buffer.concat([HANDSHAKE, key(true, 0x61)]));+ expect(await closed).toBe(DESKTOP_CLOSE.gone);+ expect(display.bytes().length).toBe(0);+ });++ it("closes on a browser that runs without a display, so the panel shows pictures", async () => {+ const { closed } = await harness({ desktop: false });+ expect(await closed).toBe(DESKTOP_CLOSE.pictures);+ });++ it("closes, without starting anything, on a browser that is not running", async () => {+ const { closed, display } = await harness({ stopped: true });+ expect(await closed).toBe(DESKTOP_CLOSE.gone);+ expect(display.bytes().length).toBe(0);+ });++ it("closes on anything that is not RFB", async () => {+ const text = await harness();+ text.ws.send("hello");+ expect(await text.closed).toBe(DESKTOP_CLOSE.protocol);+ const garbage = await harness();+ garbage.ws.send(Buffer.concat([HANDSHAKE, Buffer.from([99])]));+ expect(await garbage.closed).toBe(DESKTOP_CLOSE.protocol);+ });++ it("closes when the display goes", async () => {+ const { display, closed } = await harness();+ display.destroy();+ expect(await closed).toBe(DESKTOP_CLOSE.gone);+ });++ it("closes a bot's views on request", async () => {+ const { views, closed } = await harness();+ views.closeForBot("a");+ expect(await closed).toBe(DESKTOP_CLOSE.gone);+ });+});diff --git a/server/browser/desktop/views.ts b/server/browser/desktop/views.tsnew file mode 100644index 0000000000..4b1cbfb152--- /dev/null+++ b/server/browser/desktop/views.ts@@ -0,0 +1,259 @@+// People's remote-desktop views of a bot's browser window on its private display: the display's RFB stream spliced into+// a WebSocket that noVNC reads. The v2 stream stays open beside it and carries the hold, the tabs and the prompts; this+// view only carries pixels one way and, from the person holding the browser, input the other.+//+// Security: the hold is enforced here, at the byte level. A viewer whose person does not hold the browser sends no input+// to the display, and while another person holds it, sees nothing: that person may be typing a password.+import type { IncomingMessage } from "node:http";+import { connect, type Socket } from "node:net";+import type { Duplex } from "node:stream";++import { WebSocketServer, type RawData, type WebSocket } from "ws";++import type { ProfileControl } from "../control.ts";+import type { BrowserTarget } from "../service.ts";+import { RfbClientFilter, RfbProtocolError } from "./rfb-filter.ts";++/** Close codes the desktop view acts on. */+export const DESKTOP_CLOSE = {+ /** The view is no longer the person's to see, or the browser is not running: the panel reconnects once the v2 view+ * shows it running again. */+ gone: 4404,+ /** This browser runs without a display: the panel shows the picture view. */+ pictures: 4415,+ /** Another person holds the browser. */+ heldElsewhere: 4409,+ /** Too many views are open. */+ busy: 1013,+ /** The display or the browser could not start. */+ failed: 1011,+ /** The client sent something that is not RFB. */+ protocol: 1003,+} as const;++const RECHECK_MS = 5_000;+const PING_MS = 15_000;+const INPUT_NOTICE_MS = 1_000;+const HIGH_WATER_BYTES = 4 * 1024 * 1024;+const LOW_WATER_BYTES = 1024 * 1024;+const MAX_MESSAGE_BYTES = 512 * 1024;+const VIEWS_PER_PROFILE = 4;+const VIEWS_TOTAL = 16;+const CLOSE_GRACE_MS = 2_000;++/** What a view needs of the browser it shows. */+export interface DesktopTarget {+ /** The display's RFB socket. */+ readonly socket: string;+ readonly control: Pick<ProfileControl, "owner" | "canControl" | "onChange">;+ /** A person sent input: the browser's idle time and their hold's start again. */+ used(): void;+ /** The person resized the display: the browser's window fills it again. */+ resized(width: number, height: number): void;+}++export interface DesktopLink {+ /** "gone" once the viewer may no longer see this browser, "held" while another person holds it. */+ watch(): "ok" | "gone" | "held";+ allowInput(): boolean;+ onInput(): void;+ onResize?(width: number, height: number): void;+}++export interface Splice {+ /** Applies a change of who may see or drive the browser now. */+ recheck(): void;+ close(code: number, reason: string): void;+ readonly closed: Promise<void>;+}++const bytesOf = (data: RawData): Buffer => (Buffer.isBuffer(data) ? data : Array.isArray(data) ? Buffer.concat(data) : Buffer.from(data));++/** Carries one viewer's RFB stream between its WebSocket and the display, through the input gate. */+export function spliceDesktop(ws: WebSocket, upstream: Duplex, link: DesktopLink): Splice {+ const filter = new RfbClientFilter({ allowInput: () => link.allowInput(), onInput: () => link.onInput(), onResize: (width, height) => link.onResize?.(width, height) });+ let ended = false;+ let finished!: () => void;+ const closed = new Promise<void>((resolve) => { finished = resolve; });+ const end = () => {+ if (ended) return;+ ended = true;+ const release = filter.release();+ if (release.length && !upstream.destroyed) upstream.end(release);+ else upstream.end();+ setTimeout(() => upstream.destroy(), CLOSE_GRACE_MS).unref();+ finished();+ };+ const close = (code: number, reason: string) => {+ if (ended) return;+ end();+ try { ws.close(code, reason.slice(0, 120)); } catch {}+ setTimeout(() => ws.terminate(), CLOSE_GRACE_MS).unref();+ };+ const allowedToWatch = (): boolean => {+ const state = link.watch();+ if (state === "ok") return true;+ close(state === "held" ? DESKTOP_CLOSE.heldElsewhere : DESKTOP_CLOSE.gone, state === "held" ? "Another person controls this browser." : "This browser view is no longer available.");+ return false;+ };+ ws.on("message", (data, binary) => {+ if (ended) return;+ if (!binary) return close(DESKTOP_CLOSE.protocol, "The desktop view speaks RFB only.");+ if (!allowedToWatch()) return;+ let forward: Buffer;+ try {+ forward = filter.feed(bytesOf(data));+ } catch (error) {+ return close(DESKTOP_CLOSE.protocol, error instanceof RfbProtocolError ? error.message : "The desktop view sent something it cannot.");+ }+ if (forward.length && !upstream.write(forward)) {+ ws.pause();+ upstream.once("drain", () => ws.resume());+ }+ });+ upstream.on("data", (chunk: Buffer) => {+ if (ended || !allowedToWatch()) return;+ ws.send(chunk, { binary: true }, () => {+ if (upstream.isPaused() && ws.bufferedAmount < LOW_WATER_BYTES) upstream.resume();+ });+ if (ws.bufferedAmount > HIGH_WATER_BYTES) upstream.pause();+ });+ upstream.once("close", () => close(DESKTOP_CLOSE.gone, "The browser closed."));+ upstream.on("error", () => close(DESKTOP_CLOSE.gone, "The browser closed."));+ ws.once("close", end);+ ws.on("error", end);+ return {+ recheck() {+ if (ended || !allowedToWatch()) return;+ if (!link.allowInput() && filter.holding) upstream.write(filter.release());+ },+ close,+ closed,+ };+}++export interface DesktopRequest {+ target: BrowserTarget;+ botId: string;+ owner: string;+ /** Whose hold this view shares. */+ person: string;+ /** False for a passive view: it never sends input. */+ canOperate: boolean;+ req: IncomingMessage;+ socket: Socket;+ head: Buffer;+ /** False once this view no longer shows the bot's current browser to a live sign-in. */+ isCurrent(): boolean;+}++interface View {+ readonly request: DesktopRequest;+ readonly ws: WebSocket;+ splice: Splice | null;+ closed: boolean;+}++/** Every remote-desktop view of the bots' browsers on this server. */+export class DesktopViews {+ readonly #desktop: (target: BrowserTarget) => Promise<DesktopTarget | "pictures" | "stopped">;+ readonly #connect: (socket: string) => Duplex;+ readonly #views = new Set<View>();+ readonly #server = new WebSocketServer({ noServer: true, perMessageDeflate: false, maxPayload: MAX_MESSAGE_BYTES });++ constructor({ desktop, connectSocket = (path) => connect(path) }: { desktop: (target: BrowserTarget) => Promise<DesktopTarget | "pictures" | "stopped">; connectSocket?: (socket: string) => Duplex }) {+ this.#desktop = desktop;+ this.#connect = connectSocket;+ }++ open(request: DesktopRequest): void {+ const perProfile = [...this.#views].filter((view) => view.request.target.key === request.target.key).length;+ const busy = this.#views.size >= VIEWS_TOTAL || perProfile >= VIEWS_PER_PROFILE;+ this.#server.handleUpgrade(request.req, request.socket, request.head, (ws) => {+ if (busy) {+ ws.close(DESKTOP_CLOSE.busy, "Too many browser views are open. Close another browser panel first.");+ return;+ }+ const view: View = { request, ws, splice: null, closed: false };+ this.#views.add(view);+ ws.once("close", () => {+ view.closed = true;+ this.#views.delete(view);+ });+ void this.#serve(view, ws);+ });+ }++ async #serve(view: View, ws: WebSocket): Promise<void> {+ const { request } = view;+ let target: DesktopTarget | "pictures" | "stopped";+ try {+ target = await this.#desktop(request.target);+ } catch {+ ws.close(DESKTOP_CLOSE.failed, "The browser could not start.");+ return;+ }+ if (view.closed) return;+ if (target === "pictures") {+ ws.close(DESKTOP_CLOSE.pictures, "This browser has no desktop view.");+ return;+ }+ if (target === "stopped") {+ ws.close(DESKTOP_CLOSE.gone, "The browser is not running.");+ return;+ }+ const { control } = target;+ let noticed = 0;+ const link: DesktopLink = {+ watch: () => (!request.isCurrent() ? "gone" : control.owner !== null && control.owner !== request.person ? "held" : "ok"),+ allowInput: () => request.canOperate && control.canControl(request.person),+ onInput: () => {+ const now = Date.now();+ if (now - noticed < INPUT_NOTICE_MS) return;+ noticed = now;+ target.used();+ },+ onResize: (width, height) => target.resized(width, height),+ };+ if (link.watch() !== "ok") {+ ws.close(link.watch() === "held" ? DESKTOP_CLOSE.heldElsewhere : DESKTOP_CLOSE.gone, "This browser view is not available now.");+ return;+ }+ const splice = spliceDesktop(ws, this.#connect(target.socket), link);+ view.splice = splice;+ const off = control.onChange(() => splice.recheck());+ let alive = true;+ ws.on("pong", () => { alive = true; });+ const ping = setInterval(() => {+ if (!alive) { ws.terminate(); return; }+ alive = false;+ try { ws.ping(); } catch {}+ }, PING_MS);+ ping.unref();+ const recheck = setInterval(() => splice.recheck(), RECHECK_MS);+ recheck.unref();+ await splice.closed;+ off();+ clearInterval(ping);+ clearInterval(recheck);+ }++ get size(): number {+ return this.#views.size;+ }++ closeForSession(session: string): void { this.#closeWhere((request) => request.target.session === session); }+ closeForOwner(owner: string): void { this.#closeWhere((request) => request.owner === owner); }+ closeForBot(botId: string): void { this.#closeWhere((request) => request.botId === botId); }+ closeAll(): void { this.#closeWhere(() => true); }+ /** Closes now every view the recheck would close. */+ recheck(): void { for (const view of this.#views) view.splice?.recheck(); }++ #closeWhere(match: (request: DesktopRequest) => boolean): void {+ for (const view of this.#views) {+ if (!match(view.request)) continue;+ if (view.splice) view.splice.close(DESKTOP_CLOSE.gone, "This browser view closed.");+ else view.ws.close(DESKTOP_CLOSE.gone, "This browser view closed.");+ }+ }+}diff --git a/server/browser/desktop/window.test.ts b/server/browser/desktop/window.test.tsnew file mode 100644index 0000000000..a48ed121d9--- /dev/null+++ b/server/browser/desktop/window.test.ts@@ -0,0 +1,64 @@+import { mkdtempSync, rmSync } from "node:fs";+import { createServer } from "node:net";+import { tmpdir } from "node:os";+import { join } from "node:path";++import { describe, expect, it } from "vitest";++import { fillDisplay, resizeDisplay } from "./window.ts";++describe("windows on a private display", () => {+ it("brings each window to its normal state and makes it fill the display from the corner", async () => {+ const sent: Array<{ method: string; params: unknown }> = [];+ const root = {+ send: async (method: string, params: { targetId?: string }) => {+ sent.push({ method, params });+ return method === "Browser.getWindowForTarget" ? { windowId: params.targetId === "c" ? 2 : 1 } : {};+ },+ };+ const browser = { connection: { root }, pages: () => [{ targetId: "a" }, { targetId: "b" }, { targetId: "c" }] } as unknown as Parameters<typeof fillDisplay>[0];+ await fillDisplay(browser, { width: 1600, height: 900 });+ expect(sent.filter((call) => call.method === "Browser.setWindowBounds").map((call) => call.params)).toEqual([+ { windowId: 1, bounds: { windowState: "normal" } },+ { windowId: 1, bounds: { left: 0, top: 0, width: 1600, height: 900 } },+ { windowId: 2, bounds: { windowState: "normal" } },+ { windowId: 2, bounds: { left: 0, top: 0, width: 1600, height: 900 } },+ ]);+ });+});++describe("giving the display its usual size back", () => {+ it.skipIf(process.platform === "win32")("asks the display server for it over the RFB socket, as a viewer would", async () => {+ const dir = mkdtempSync(join(tmpdir(), "omb-rfb-"));+ const socket = join(dir, "rfb");+ const received: Buffer[] = [];+ const ended = new Promise<void>((resolve) => {+ const server = createServer((client) => {+ client.write("RFB 003.008\n");+ client.on("data", (chunk: Buffer) => {+ received.push(chunk);+ const sent = Buffer.concat(received);+ if (sent.length === 12) client.write(Buffer.from([1, 1]));+ if (sent.length === 13) client.write(Buffer.alloc(4));+ if (sent.length === 14) {+ const init = Buffer.alloc(24);+ init.writeUInt16BE(1600, 0);+ init.writeUInt16BE(900, 2);+ client.write(init);+ }+ });+ client.on("end", () => { server.close(); resolve(); });+ }).listen(socket);+ });+ try {+ await resizeDisplay(socket, { width: 1280, height: 800 });+ await ended;+ const sent = Buffer.concat(received);+ expect(sent.subarray(0, 12).toString("latin1")).toBe("RFB 003.008\n");+ const resize = sent.subarray(sent.length - 24);+ expect([resize[0], resize.readUInt16BE(2), resize.readUInt16BE(4), resize[6], resize.readUInt16BE(16), resize.readUInt16BE(18)]).toEqual([251, 1280, 800, 1, 1280, 800]);+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+ });+});diff --git a/server/browser/desktop/window.ts b/server/browser/desktop/window.tsnew file mode 100644index 0000000000..a2016dae35--- /dev/null+++ b/server/browser/desktop/window.ts@@ -0,0 +1,66 @@+// The browser's windows on a private display follow the display's size: with no window manager, nothing else moves or+// resizes them when a person's view resizes the display.+import { connect } from "node:net";++import type { CdpBrowser } from "../cdp/browser.ts";++/** Each window of `browser` fills the display from its top left corner. */+export async function fillDisplay(browser: Pick<CdpBrowser, "connection" | "pages">, size: { width: number; height: number }): Promise<void> {+ const root = browser.connection.root;+ const windows = new Set<number>();+ for (const page of browser.pages()) {+ const found = await root.send<{ windowId: number }>("Browser.getWindowForTarget", { targetId: page.targetId }).catch(() => null);+ if (found) windows.add(found.windowId);+ }+ for (const windowId of windows) {+ // Chrome sets a size only on a window in its normal state.+ await root.send("Browser.setWindowBounds", { windowId, bounds: { windowState: "normal" } }).catch(() => undefined);+ await root.send("Browser.setWindowBounds", { windowId, bounds: { left: 0, top: 0, width: size.width, height: size.height } }).catch(() => undefined);+ }+}++/** Asks the display server for a new size over its own RFB socket, as a viewer would: used to give the bot back the+ * display's usual size once the person who resized it hands the browser back. */+export async function resizeDisplay(socket: string, size: { width: number; height: number }, timeoutMs = 5_000): Promise<void> {+ const connection = connect(socket);+ let buffer = Buffer.alloc(0);+ let wake: (() => void) | null = null;+ connection.on("data", (chunk: Buffer) => { buffer = Buffer.concat([buffer, chunk]); wake?.(); });+ const closed = new Promise<void>((resolve) => connection.once("close", () => resolve()));+ connection.on("error", () => wake?.());+ const deadline = Date.now() + timeoutMs;+ const read = async (bytes: number): Promise<Buffer> => {+ while (buffer.length < bytes) {+ if (connection.destroyed || Date.now() > deadline) throw new Error("The display did not answer.");+ await new Promise<void>((resolve) => { wake = resolve; setTimeout(resolve, 50).unref(); });+ }+ const out = buffer.subarray(0, bytes);+ buffer = buffer.subarray(bytes);+ return out;+ };+ try {+ await read(12);+ connection.write("RFB 003.008\n");+ await read((await read(1))[0]!);+ connection.write(Buffer.from([1]));+ await read(4);+ connection.write(Buffer.from([1]));+ const init = await read(24);+ await read(init.readUInt32BE(20));+ const encodings = Buffer.alloc(8);+ encodings[0] = 2;+ encodings.writeUInt16BE(1, 2);+ encodings.writeInt32BE(-308, 4);+ const resize = Buffer.alloc(8 + 16);+ resize[0] = 251;+ resize.writeUInt16BE(size.width, 2);+ resize.writeUInt16BE(size.height, 4);+ resize[6] = 1;+ resize.writeUInt16BE(size.width, 16);+ resize.writeUInt16BE(size.height, 18);+ connection.end(Buffer.concat([encodings, resize]));+ await Promise.race([closed, new Promise((resolve) => setTimeout(resolve, 1_000).unref())]);+ } finally {+ connection.destroy();+ }+}diff --git a/third_party/hermes-agent/LICENSE b/third_party/hermes-agent/LICENSEnew file mode 100644index 0000000000..75410e7331--- /dev/null+++ b/third_party/hermes-agent/LICENSE@@ -0,0 +1,21 @@+MIT License++Copyright (c) 2025 Nous Research++Permission is hereby granted, free of charge, to any person obtaining a copy+of this software and associated documentation files (the "Software"), to deal+in the Software without restriction, including without limitation the rights+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+copies of the Software, and to permit persons to whom the Software is+furnished to do so, subject to the following conditions:++The above copyright notice and this permission notice shall be included in all+copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE+SOFTWARE.diff --git a/third_party/hermes-agent/README.md b/third_party/hermes-agent/README.mdnew file mode 100644index 0000000000..5636a22400--- /dev/null+++ b/third_party/hermes-agent/README.md@@ -0,0 +1,6 @@+# Hermes Agent++`server/browser/desktop/rfb-filter.ts` adapts the RFB client-message framing and input gate of Hermes Agent's+`tools/bot_desktop/rfb_filter.py` at commit `a3b993b98a1c679193bd8d4ea99b89ce7614bfde`,+https://github.com/NousResearch/hermes-agent, MIT License, Copyright (c) 2025 Nous Research. The full license text is+in [LICENSE](LICENSE).