Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Local VM: configurable limits, host-uid workspaces, package installs
aivsomkar17fd69283770
diff --git a/server/config.ts b/server/config.tsindex 18feef8615..956cdeac53 100644--- a/server/config.ts+++ b/server/config.ts@@ -30,6 +30,7 @@ import { liveConfigSchema, liveConfigWithEnv, liveSettingEnv, type LiveConfig }import { browserEngineConfigSchema, isValidCdpTarget, type BrowserEngineConfig } from "./browser/config.ts";import { roomContextSettings } from "./room-context-settings.ts";import { MAX_LOCAL_VM_IDLE_TIMEOUT_MINUTES, MAX_LOCAL_VM_MAX_INSTANCES, MIN_LOCAL_VM_IDLE_TIMEOUT_MINUTES, MIN_LOCAL_VM_MAX_INSTANCES } from "./local-vm-settings.ts";+import { MAX_DESKTOP_CPUS, MAX_DESKTOP_MEMORY_GB, MIN_DESKTOP_CPUS, MIN_DESKTOP_MEMORY_GB } from "./container-limits.ts";export * from "./local-vm-settings.ts";const optionalText = z.string().optional();@@ -103,6 +104,10 @@ const localVmConfigSchema = z.object({.max(MAX_LOCAL_VM_IDLE_TIMEOUT_MINUTES).optional(),preserveInstalledApps: z.boolean().optional(),+ /** Each desktop's memory limit in GiB, with swap capped to the same; 4 when unset. New desktops take a change; on Docker and Podman a stopped one takes it when it next starts. */+ memoryGb: z.number().int().min(MIN_DESKTOP_MEMORY_GB).max(MAX_DESKTOP_MEMORY_GB).optional(),+ /** Each desktop's CPU limit; 2 when unset. */+ cpus: z.number().int().min(MIN_DESKTOP_CPUS).max(MAX_DESKTOP_CPUS).optional(),});/** A named browser session; its id names a durable Electron partition. */const browserProfileSchema = z.object({@@ -497,7 +502,7 @@ export interface AppConfig extends HelperConfig {threads?: { maxConcurrentPerBot: number; eventLogMaxBytes?: number; eventLogRetentionDays?: number };context?: { rebuildBytes?: number; compactAt?: number; autoCompact?: boolean; roomCompactAt?: number; roomSessions?: boolean; replayToolHistory?: boolean };memory?: { captureQuietMs?: number; tidyHour?: number };- localVm?: { mode?: "shared" | "per-bot" | "pool"; maxInstances?: number; idleTimeoutMinutes?: number; preserveInstalledApps?: boolean };+ localVm?: { mode?: "shared" | "per-bot" | "pool"; maxInstances?: number; idleTimeoutMinutes?: number; preserveInstalledApps?: boolean; memoryGb?: number; cpus?: number };features?: { skillAuthoring?: boolean; skillReview?: boolean; skillReviewSteps?: number; showToolCalls?: boolean; browser?: boolean; sharedComputers?: boolean; claudeUserMcp?: boolean; claudeUserSkills?: boolean; llmThreadTitles?: boolean; smartSetupChoices?: boolean; autoRecall?: boolean; skillsLibrary?: boolean; shareLearnedSkills?: "off" | "ask" | "auto"; roomMemoryCapture?: boolean; parallelRoomJobs?: boolean; acpPlanLines?: boolean; agentsToolBridge?: boolean; savedSteps?: boolean };onboarding?: { completedAt?: string; version?: number; reelSeen?: boolean; hintsSeen?: string[]; firstTurnAt?: string };browserProfiles?: BrowserProfile[];diff --git a/server/container-computer.test.ts b/server/container-computer.test.tsindex 2fe7a0fc90..7739c9f66e 100644--- a/server/container-computer.test.ts+++ b/server/container-computer.test.ts@@ -11,6 +11,8 @@ import {CUA_DRIVER_VERSION,CUA_EXECUTABLE,CUA_SOCKET,+ DESKTOP_FLAGS_LABEL,+ DESKTOP_FLAGS_VERSION,DRIVER_LABEL,IMAGE,IMAGE_LAYER_LABEL,@@ -246,6 +248,8 @@ describe("managed image preparation", () => {});});+const PACKAGE_INSTALL_CAPS = ["CAP_CHOWN", "CAP_DAC_OVERRIDE", "CAP_FOWNER", "CAP_FSETID", "CAP_SETGID", "CAP_SETUID"];+function readyInspect(overrides: Record<string, unknown> = {}) {return JSON.stringify([{@@ -257,6 +261,7 @@ function readyInspect(overrides: Record<string, unknown> = {}) {[BASE_IMAGE_LABEL]: BASE_IMAGE_DIGEST,[IMAGE_LAYER_LABEL]: IMAGE_LAYER_VERSION,[WORKSPACE_LABEL]: "1",+ [DESKTOP_FLAGS_LABEL]: DESKTOP_FLAGS_VERSION,},Env: ["VNC_PW=secret123"],},@@ -269,7 +274,8 @@ function readyInspect(overrides: Record<string, unknown> = {}) {NanoCpus: 2_000_000_000,PidsLimit: 512,CapDrop: ["ALL"],- CapAdd: ["CAP_SETUID", "CAP_SETGID"],+ CapAdd: [...PACKAGE_INSTALL_CAPS],+ SecurityOpt: ["no-new-privileges"],Privileged: false,IpcMode: "private",CgroupnsMode: "private",@@ -432,6 +438,92 @@ describe("containerComputerStatus", () => {expect(dockerSecurityIsHardened(config, { restartPolicy: "any" })).toBe(false);});+ it("accepts exactly the supervisor caps or the package-install caps, and nothing between or beyond", () => {+ const config = JSON.parse(readyInspect())[0].HostConfig;+ for (const [caps, hardened] of [+ [["CAP_SETUID", "CAP_SETGID"], true],+ [PACKAGE_INSTALL_CAPS, true],+ [["CAP_SETUID", "CAP_SETGID", "CAP_CHOWN"], false],+ [[...PACKAGE_INSTALL_CAPS, "CAP_SYS_ADMIN"], false],+ [[...PACKAGE_INSTALL_CAPS, "CAP_SETFCAP"], false],+ [["CAP_SETUID"], false],+ ] as const) {+ expect(dockerSecurityIsHardened({ ...config, CapAdd: [...caps] }), caps.join(",")).toBe(hardened);+ }+ expect(podmanSecurityIsHardened(config, [...PACKAGE_INSTALL_CAPS, "CAP_SYS_CHROOT"], [...PACKAGE_INSTALL_CAPS, "CAP_SYS_CHROOT"])).toBe(true);+ expect(podmanSecurityIsHardened(config, [...PACKAGE_INSTALL_CAPS, "CAP_SYS_CHROOT"], ["CAP_SETGID", "CAP_SETUID", "CAP_SYS_CHROOT"])).toBe(false);+ });++ it("requires no-new-privileges where the desktop's root is the host's root", () => {+ const config = JSON.parse(readyInspect())[0].HostConfig;+ expect(dockerSecurityIsHardened(config, { requireNoNewPrivileges: true })).toBe(true);+ expect(dockerSecurityIsHardened({ ...config, SecurityOpt: ["no-new-privileges:true"] }, { requireNoNewPrivileges: true })).toBe(true);+ for (const caps of [PACKAGE_INSTALL_CAPS, ["CAP_SETUID", "CAP_SETGID"]]) {+ expect(dockerSecurityIsHardened({ ...config, CapAdd: [...caps], SecurityOpt: [] }, { requireNoNewPrivileges: true })).toBe(false);+ expect(dockerSecurityIsHardened({ ...config, CapAdd: [...caps], SecurityOpt: [] })).toBe(true);+ }+ });++ it.each([+ ["linux", "unsafe"],+ ["darwin", "hardened"],+ ] as const)("judges a Docker desktop without no-new-privileges on %s as %s", async (platform, security) => {+ const base = JSON.parse(readyInspect())[0].HostConfig;+ const fake = runner({+ "/usr/bin/which docker": "docker\n",+ "/usr/bin/which podman": new Error("missing"),+ "docker info --format {{.ServerVersion}}": "29\n",+ [`docker image inspect ${IMAGE}`]: preparedImageInspect(),+ [`docker inspect ${CONTAINER}`]: readyInspect({ HostConfig: { ...base, SecurityOpt: [] } }),+ });+ const status = await containerComputerStatus(fake.run, platform, SHARED_LOCAL_VM_TARGET, { probeDesktop: false });+ expect(status.security).toBe(security);+ });++ it("updates a desktop made under older run flags like one on an older image", async () => {+ const detail = JSON.parse(readyInspect())[0];+ delete detail.Config.Labels[DESKTOP_FLAGS_LABEL];+ const fake = runner({+ "/usr/bin/which docker": "docker\n",+ "/usr/bin/which podman": new Error("missing"),+ "docker info --format {{.ServerVersion}}": "29\n",+ [`docker image inspect ${IMAGE}`]: preparedImageInspect(),+ [`docker inspect ${CONTAINER}`]: JSON.stringify([detail]),+ });+ const status = await containerComputerStatus(fake.run, "linux");+ expect(status).toMatchObject({ managed: true, imageMatches: false, ready: false });+ expect(status.problem).toContain("older desktop");+ expect(fake.calls.some((call) => call.startsWith("docker exec "))).toBe(false);+ });++ it.each([+ [{ cpus: 4, memoryInBytes: 8 * 1024 ** 3 }, "hardened"],+ [{ cpus: 1, memoryInBytes: 2 * 1024 ** 3 }, "hardened"],+ [{ cpus: 4, memoryInBytes: 1024 ** 3 }, "unsafe"],+ [{ cpus: 0, memoryInBytes: 4 * 1024 ** 3 }, "unsafe"],+ [undefined, "unsafe"],+ ] as const)("judges Apple container resources %j as %s", async (resources, security) => {+ const fake = runner({+ "/usr/bin/which docker": new Error("missing"),+ "/usr/bin/which podman": new Error("missing"),+ "/usr/bin/which container": "container\n",+ "container system status": "running\n",+ [`container image inspect ${IMAGE}`]: appleImageInspect([appleImageVariant(preparedLabels)]),+ [`container inspect ${CONTAINER}`]: JSON.stringify([{+ configuration: {+ image: { reference: IMAGE, descriptor: { digest: "sha256:managed-image-id" } },+ resources,+ publishedPorts: [{ hostAddress: "127.0.0.1", containerPort: 6901 }],+ labels: { ...preparedLabels, [WORKSPACE_LABEL]: "1", [DESKTOP_FLAGS_LABEL]: DESKTOP_FLAGS_VERSION },+ mounts: [{ source: VM_WORKSPACE_DIR, destination: VM_WORKSPACE_GUEST, options: [] }],+ },+ status: { state: "stopped" },+ }]),+ });+ const status = await containerComputerStatus(fake.run, "darwin");+ expect(status.security).toBe(security);+ });+it.each([{ Memory: 1024 ** 3, MemorySwap: 2 * 1024 ** 3, NanoCpus: 4_000_000_000, PidsLimit: 1024, ShmSize: 1024 ** 3, OomKillDisable: true },{ Memory: 0, MemorySwap: -1, NanoCpus: 0, PidsLimit: -1, ShmSize: 64 * 1024 ** 2, OomKillDisable: null },@@ -545,6 +637,7 @@ describe("containerComputerStatus", () => {[BASE_IMAGE_LABEL]: BASE_IMAGE_DIGEST,[IMAGE_LAYER_LABEL]: IMAGE_LAYER_VERSION,[WORKSPACE_LABEL]: "1",+ [DESKTOP_FLAGS_LABEL]: DESKTOP_FLAGS_VERSION,},mounts: [{ source: VM_WORKSPACE_DIR, destination: VM_WORKSPACE_GUEST, options: [] }],},@@ -1033,6 +1126,7 @@ describe("containerComputerAction", () => {"docker info --format {{.ServerVersion}}": "29\n",[`docker image inspect ${IMAGE}`]: preparedImageInspect(),[`docker inspect ${CONTAINER}`]: readyInspect({ State: { Running: false, FinishedAt: "2026-10-01T12:00:00Z" } }),+ [`docker update --memory 8g --memory-swap 8g --cpus 4 ${CONTAINER}`]: CONTAINER,[`docker start ${CONTAINER}`]: CONTAINER,});@@ -1040,8 +1134,10 @@ describe("containerComputerAction", () => {expect(localVmResumable(stopped)).toBe(true);expect(stopped.resumable).toBe(true);expect(stopped.stopped_at).toBe("2026-10-01T12:00:00Z");- await containerComputerAction("start", fake.run, "linux");- expect(fake.calls).toContain(`docker start ${CONTAINER}`);+ await containerComputerAction("start", fake.run, "linux", SHARED_LOCAL_VM_TARGET, { memoryGb: 8, cpus: 4 });+ const update = fake.calls.indexOf(`docker update --memory 8g --memory-swap 8g --cpus 4 ${CONTAINER}`);+ expect(update).toBeGreaterThan(-1);+ expect(update).toBeLessThan(fake.calls.indexOf(`docker start ${CONTAINER}`));expect(fake.calls.some(call => call.includes(" rm ") || call.includes(" run "))).toBe(false);});});@@ -1095,12 +1191,15 @@ describe("setupCommands", () => {expect(setupCommands("docker", "linux").start).toBe(`docker start ${CONTAINER}`);});- it("limits resources and retains only the sandbox supervisor's identity-switch caps", () => {+ it("limits resources and grants only the supervisor and package-install caps", () => {const command = setupCommands("docker", "linux").run!;expect(command).toContain("--memory 4g --memory-swap 4g");expect(command).toContain("--cpus 2 --pids-limit 4096");expect(command).toContain("--ipc private --cgroupns private");- expect(command).toContain("--cap-drop ALL --cap-add SETUID --cap-add SETGID");+ expect(command).toContain(+ "--cap-drop ALL --cap-add CHOWN --cap-add DAC_OVERRIDE --cap-add FOWNER --cap-add FSETID --cap-add SETGID --cap-add SETUID",+ );+ expect(command).toContain(`--label ${DESKTOP_FLAGS_LABEL}=${DESKTOP_FLAGS_VERSION}`);expect(command).toContain(`--label ${MANAGED_LABEL}=1`);expect(command).toContain(`--label ${DRIVER_LABEL}=${CUA_DRIVER_VERSION}`);expect(command).toContain(`--label ${WORKSPACE_LABEL}=1`);@@ -1110,6 +1209,48 @@ describe("setupCommands", () => {);});+ it("bars every route to root only where the desktop's root is the host's root", () => {+ expect(setupCommands("docker", "linux").run).toContain("--security-opt no-new-privileges");+ for (const [runtime, platform] of [["docker", "darwin"], ["docker", "win32"], ["podman", "linux"], ["container", "darwin"]] as const) {+ expect(setupCommands(runtime, platform).run, `${runtime} on ${platform}`).not.toContain("no-new-privileges");+ }+ });++ it("takes the configured memory and CPU limits", () => {+ const resources = { memoryGb: 8, cpus: 4 };+ for (const runtime of ["docker", "podman"] as const) {+ const command = containerRunArgs(runtime, "secret", SHARED_LOCAL_VM_TARGET, { platform: "linux", resources, hostUser: null }).join(" ");+ expect(command).toContain("--memory 8g --memory-swap 8g --cpus 4");+ }+ const apple = containerRunArgs("container", "secret", SHARED_LOCAL_VM_TARGET, { platform: "darwin", resources, hostUser: null }).join(" ");+ expect(apple).toContain("--memory 8g --cpus 4 --cap-drop ALL");+ expect(apple).not.toContain("--memory-swap");+ });++ it.each([+ ["docker", "linux", { uid: 1001, gid: 1002 }, ["1001", "1002"]],+ ["docker", "linux", { uid: 1000, gid: 1000 }, null],+ ["docker", "linux", { uid: 1000, gid: 100 }, null],+ ["docker", "linux", { uid: 0, gid: 0 }, null],+ ["docker", "darwin", { uid: 501, gid: 20 }, null],+ ["podman", "linux", { uid: 1001, gid: 1001 }, null],+ ] as const)("on %s/%s with host user %j gives cua the host ids: %j", (runtime, platform, hostUser, ids) => {+ const args = containerRunArgs(runtime, "secret", SHARED_LOCAL_VM_TARGET, {+ platform,+ resources: { memoryGb: 4, cpus: 2 },+ hostUser,+ });+ const tail = args.slice(args.indexOf(IMAGE) + 1);+ if (!ids) {+ expect(tail).toEqual([]);+ return;+ }+ expect(tail.slice(0, 2)).toEqual(["sh", "-c"]);+ expect(tail.slice(3)).toEqual(["openmausbot-desktop", ...ids]);+ expect(tail[2]).toContain("exec /usr/bin/supervisord -c /etc/supervisor/supervisord.conf");+ expect(tail[2]).toMatch(/\|\| \{ echo "cua did not take uid \$uid gid \$gid" >&2; exit 1; \}\n find /);+ });+it("asks rootless Podman to map and privately relabel the durable workspace", () => {const command = setupCommands("podman", "linux").run!;expect(command).toContain("--cap-add SYS_CHROOT");diff --git a/server/container-computer.ts b/server/container-computer.tsindex b91418f593..f45ed1a075 100644--- a/server/container-computer.ts+++ b/server/container-computer.ts@@ -2,7 +2,7 @@import { execFile } from "node:child_process";import { createHash, randomBytes } from "node:crypto";import { lstatSync } from "node:fs";-import { chmod, mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";+import { chmod, chown, mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";import { tmpdir } from "node:os";import { join, resolve } from "node:path";import { promisify } from "node:util";@@ -10,7 +10,17 @@ import { promisify } from "node:util";import { augmentedPath, resolveCliSpawn } from "./env-path.ts";import { workspacePreparationDockerfile } from "./container-workspace.ts";import { DATA_DIR } from "./config.ts";-import { PIDS_LIMIT, raisePidsLimit } from "./container-limits.ts";+import {+ applyResourcesBeforeStart,+ DEFAULT_DESKTOP_RESOURCES,+ MAX_DESKTOP_CPUS,+ MIN_DESKTOP_CPUS,+ MIN_DESKTOP_MEMORY_GB,+ PIDS_LIMIT,+ raisePidsLimit,+ resourceArgs,+ type DesktopResources,+} from "./container-limits.ts";import { SPAWNED_PROXIES } from "./proxy-paths.ts";const run = promisify(execFile);@@ -39,6 +49,9 @@ export const DRIVER_LABEL = "com.openmausbot.cua-driver";export const BASE_IMAGE_LABEL = "com.openmausbot.cua-base";export const WORKSPACE_LABEL = "com.openmausbot.workspace";export const TARGET_LABEL = "com.openmausbot.local-vm-target";+/** The run flags a desktop was made with. A desktop made under other flags is updated like one on an older image. */+export const DESKTOP_FLAGS_LABEL = "com.openmausbot.desktop-flags";+export const DESKTOP_FLAGS_VERSION = "2";export const VM_WORKSPACE_DIR = join(DATA_DIR, "vm-home");export const VM_WORKSPACE_GUEST = "/home/cua/workspace";export const DISPLAY = ":1";@@ -51,7 +64,57 @@ export type LifecycleAction = "pull" | "run" | "start" | "stop" | "remove";const INTERNAL_VIEWER_PORT = 6901;const HOST_VIEWER_PORT = 6080;-const MEMORY_BYTES = 4 * 1024 * 1024 * 1024;+const GIB = 1024 * 1024 * 1024;+const GUEST_UID = 1000;+/** What supervisord needs to start each program as cua. */+const SUPERVISOR_CAPS = ["SETGID", "SETUID"];+/** apt and dpkg also need these to install a package as root (measured on Debian 12: without DAC_OVERRIDE every download fails). */+const PACKAGE_INSTALL_CAPS = ["CHOWN", "DAC_OVERRIDE", "FOWNER", "FSETID", ...SUPERVISOR_CAPS];+/** The only capability sets a hardened desktop may hold; one made with just SUPERVISOR_CAPS is sealed but cannot install packages. */+const HARDENED_CAP_SETS = [SUPERVISOR_CAPS, PACKAGE_INSTALL_CAPS];+/** The pinned base image's own CMD (trycua/xfce-cua 0.1.0). */+const SUPERVISORD = "/usr/bin/supervisord -c /etc/supervisor/supervisord.conf";+/** Runs as PID 1 before supervisord: gives cua the host workspace owner's ids, then fails closed if /etc/passwd did not take them. */+const GUEST_IDS_SCRIPT = [+ "set -eu",+ 'uid="$1"; gid="$2"; old_uid="$(id -u cua)"; old_gid="$(id -g cua)"',+ 'if [ "$old_uid:$old_gid" != "$uid:$gid" ]; then',+ ' sed -i "s/^cua:x:$old_uid:$old_gid:/cua:x:$uid:$gid:/" /etc/passwd',+ ' sed -i "s/^cua:x:$old_gid:/cua:x:$gid:/" /etc/group',+ ' [ "$(id -u cua):$(id -g cua)" = "$uid:$gid" ] || { echo "cua did not take uid $uid gid $gid" >&2; exit 1; }',+ ' find / -xdev -uid "$old_uid" -exec chown -h "$uid" {} +',+ ' find / -xdev -gid "$old_gid" -exec chgrp -h "$gid" {} +',+ "fi",+ `exec ${SUPERVISORD}`,+].join("\n");++/** Rootful Docker on Linux runs the desktop's root as the host's root, so nothing in the desktop may gain root+ * (no-new-privileges), and the guest account must take the host workspace owner's ids itself. */+function desktopRootIsHostRoot(runtime: Runtime | null, platform: NodeJS.Platform): boolean {+ return runtime === "docker" && platform === "linux";+}++export interface HostUser {+ uid: number;+ gid: number;+}++function currentHostUser(platform: NodeJS.Platform): HostUser | null {+ return platform === "win32" || !process.getuid || !process.getgid ? null : { uid: process.getuid(), gid: process.getgid() };+}++/** Root's workspace is handed to cua instead (see ensureVmWorkspace), so cua is never given uid 0. */+function guestIdsFor(runtime: Runtime, platform: NodeJS.Platform, host: HostUser | null): HostUser | null {+ if (!desktopRootIsHostRoot(runtime, platform) || !host || host.uid === 0 || host.uid === GUEST_UID) return null;+ return host;+}++export interface DesktopRunOptions {+ platform: NodeJS.Platform;+ resources: DesktopResources;+ /** The account that owns the workspace on the host. */+ hostUser: HostUser | null;+}export interface LocalVmTarget {key: string;@@ -516,14 +579,13 @@ export async function containerComputerStatus(? normalizeImageId(detail.configuration.image.descriptor?.digest): null;status.imageMatches =- appleImage === IMAGE && status.image_id !== null && appleImageId === status.image_id;+ appleImage === IMAGE && status.image_id !== null && appleImageId === status.image_id &&+ detail?.configuration?.labels?.[DESKTOP_FLAGS_LABEL] === DESKTOP_FLAGS_VERSION;status.managed = containerOwnershipLabelsMatch(detail?.configuration?.labels, target);status.persistence = appleWorkspaceMountIsSafe(detail?.configuration?.mounts, platform, target.workspaceDir)? "durable": "unsafe";- const resources = detail?.configuration?.resources;- status.security =- (resources?.memoryInBytes ?? 0) >= MEMORY_BYTES && resources?.cpus === 2 ? "hardened" : "unsafe";+ status.security = appleResourcesAreLimited(detail?.configuration?.resources) ? "hardened" : "unsafe";status.viewer_url = viewerUrl(viewerPassword(detail?.configuration?.environment), status.viewer_port);} else {const inspected = JSON.parse(stdout) as Array<{@@ -553,6 +615,7 @@ export async function containerComputerStatus(status.imageMatches =detail?.Config?.Image === IMAGE &&imageLabelsMatch(detail?.Config?.Labels) &&+ detail?.Config?.Labels?.[DESKTOP_FLAGS_LABEL] === DESKTOP_FLAGS_VERSION &&status.image_id !== null &&normalizeImageId(detail?.Image) === status.image_id;status.managed = containerOwnershipLabelsMatch(detail?.Config?.Labels, target);@@ -566,7 +629,9 @@ export async function containerComputerStatus(status.security = (status.runtime === "podman"? podmanSecurityIsHardened(detail?.HostConfig, detail?.EffectiveCaps, detail?.BoundingCaps)- : dockerSecurityIsHardened(detail?.HostConfig)+ : dockerSecurityIsHardened(detail?.HostConfig, {+ requireNoNewPrivileges: desktopRootIsHostRoot(status.runtime, platform),+ })) ? "hardened" : "unsafe";status.viewer_url = viewerUrl(viewerPassword(detail?.Config?.Env), status.viewer_port);}@@ -727,6 +792,13 @@ function dockerWorkspaceMountIsSafe();}+/** Apple container defaults to 1 GiB, below any limit this server sets, so a desktop made without our flags fails here. */+function appleResourcesAreLimited(resources: { cpus?: number; memoryInBytes?: number } | undefined): boolean {+ const cpus = resources?.cpus ?? 0;+ return (resources?.memoryInBytes ?? 0) >= MIN_DESKTOP_MEMORY_GB * GIB &&+ Number.isInteger(cpus) && cpus >= MIN_DESKTOP_CPUS && cpus <= MAX_DESKTOP_CPUS;+}+function appleWorkspaceMountIsSafe(mounts: Array<{ source?: string; destination?: string; options?: string[] }> | undefined,platform: NodeJS.Platform,@@ -763,16 +835,33 @@ export interface DockerHardeningConfig {RestartPolicy?: { Name?: string; MaximumRetryCount?: number };}+function capSetKey(caps: string[] | null | undefined): string {+ return (caps ?? []).map((cap) => cap.toLowerCase().replace(/^cap_/, "")).sort().join(",");+}++function isHardenedCapSet(caps: string[] | null | undefined, podmanBrowserSandbox: boolean): boolean {+ const key = capSetKey(caps);+ return HARDENED_CAP_SETS.some((set) => capSetKey(podmanBrowserSandbox ? [...set, "SYS_CHROOT"] : set) === key);+}++export function desktopCapArgs(runtime: Runtime): string[] {+ // Podman's default seccomp profile gates chroot on this capability, and Firefox chroots to build its sandbox.+ const caps = runtime === "podman" ? [...PACKAGE_INSTALL_CAPS, "SYS_CHROOT"] : PACKAGE_INSTALL_CAPS;+ return ["--cap-drop", "ALL", ...caps.flatMap((cap) => ["--cap-add", cap])];+}+/** Shared isolation contract for Local VM and VPS containers; Podman alone needs chroot for Firefox's sandbox. */export function dockerSecurityIsHardened(config: DockerHardeningConfig | undefined,- options: { restartPolicy?: "no" | "unless-stopped" | "any"; podmanBrowserSandbox?: boolean } = {},+ options: {+ restartPolicy?: "no" | "unless-stopped" | "any";+ podmanBrowserSandbox?: boolean;+ requireNoNewPrivileges?: boolean;+ } = {},): boolean {if (!config) return false;const capDrop = (config.CapDrop ?? []).map((cap) => cap.toLowerCase());- const capAdd = (config.CapAdd ?? [])- .map((cap) => cap.toLowerCase().replace(/^cap_/, ""))- .sort();+ const noNewPrivileges = (config.SecurityOpt ?? []).some((option) => /^no-new-privileges(?:[:=]true)?$/i.test(option));const unsafeSecurityOption = (config.SecurityOpt ?? []).some((option) => /(?:^|=)(?:unconfined|disable)$/i.test(option));const restartPolicy = config.RestartPolicy?.Name;const restartPolicyOk =@@ -781,7 +870,8 @@ export function dockerSecurityIsHardened(: restartPolicy === undefined || restartPolicy === "" || restartPolicy === "no");return (capDrop.includes("all") &&- capAdd.join(",") === (options.podmanBrowserSandbox ? "setgid,setuid,sys_chroot" : "setgid,setuid") &&+ isHardenedCapSet(config.CapAdd, options.podmanBrowserSandbox === true) &&+ (options.requireNoNewPrivileges !== true || noNewPrivileges) &&config.Privileged === false &&!config.PidMode &&config.IpcMode === "private" &&@@ -803,12 +893,7 @@ export function podmanSecurityIsHardened(boundingCaps: string[] | undefined,): boolean {if (!config) return false;- const normalizeCaps = (caps: string[] | undefined) => (caps ?? [])- .map((cap) => cap.toLowerCase().replace(/^cap_/, ""))- .sort();- const exactCaps = "setgid,setuid,sys_chroot";- if (normalizeCaps(effectiveCaps).join(",") !== exactCaps) return false;- if (normalizeCaps(boundingCaps).join(",") !== exactCaps) return false;+ if (!isHardenedCapSet(effectiveCaps, true) || capSetKey(boundingCaps) !== capSetKey(effectiveCaps)) return false;return dockerSecurityIsHardened({...config,CapDrop: ["all"],@@ -826,6 +911,7 @@ export function containerRunArgs(runtime: Runtime,password = "CHANGE_ME",target: LocalVmTarget = SHARED_LOCAL_VM_TARGET,+ desktop: DesktopRunOptions = { platform: process.platform, resources: DEFAULT_DESKTOP_RESOURCES, hostUser: null },): string[] {if (runtime === "container" && target.key !== SHARED_LOCAL_VM_TARGET.key) {throw new Error("Per-bot Local VMs require Docker or Podman because Apple container requires a fixed host port");@@ -848,51 +934,30 @@ export function containerRunArgs(`${WORKSPACE_LABEL}=1`,"--label",`${TARGET_LABEL}=${target.label}`,+ "--label",+ `${DESKTOP_FLAGS_LABEL}=${DESKTOP_FLAGS_VERSION}`,);if (runtime === "container") {// Apple container already places each Linux container in a lightweight VM.- common.push(- "--memory",- "4g",- "--cpus",- "2",- "--cap-drop",- "ALL",- "--cap-add",- "SETUID",- "--cap-add",- "SETGID",- "--shm-size",- "512m",- );+ common.push(...resourceArgs(desktop.resources, { swap: false }), ...desktopCapArgs(runtime), "--shm-size", "512m");} else {common.push("--hostname",target.containerName,- "--memory",- "4g",- "--memory-swap",- "4g",- "--cpus",- "2",+ ...resourceArgs(desktop.resources, { swap: true }),"--pids-limit", String(PIDS_LIMIT),// Pinned: a daemon with host-mode IPC/cgroup defaults would create a container the hardening check then rejects."--ipc","private","--cgroupns","private",- "--cap-drop",- "ALL",- "--cap-add",- "SETUID",- "--cap-add",- "SETGID",+ ...desktopCapArgs(runtime),"--shm-size","512m",);}- // Podman's default seccomp profile gates chroot on this capability, and Firefox chroots to build its sandbox.- if (runtime === "podman") common.push("--cap-add", "SYS_CHROOT");+ if (desktopRootIsHostRoot(runtime, desktop.platform)) common.push("--security-opt", "no-new-privileges");+ const guestIds = guestIdsFor(runtime, desktop.platform, desktop.hostUser);common.push("--mount",runtime === "podman"@@ -906,12 +971,17 @@ export function containerRunArgs(: `127.0.0.1::${INTERNAL_VIEWER_PORT}`,IMAGE,);+ if (guestIds) common.push("sh", "-c", GUEST_IDS_SCRIPT, "openmausbot-desktop", String(guestIds.uid), String(guestIds.gid));return common;}-async function ensureVmWorkspace(platform: NodeJS.Platform, target: LocalVmTarget): Promise<void> {+async function ensureVmWorkspace(platform: NodeJS.Platform, target: LocalVmTarget, runtime: Runtime): Promise<void> {await mkdir(target.workspaceDir, { recursive: true, mode: 0o700 });- if (platform !== "win32") await chmod(target.workspaceDir, 0o700);+ if (platform === "win32") return;+ await chmod(target.workspaceDir, 0o700);+ if (desktopRootIsHostRoot(runtime, platform) && currentHostUser(platform)?.uid === 0) {+ await chown(target.workspaceDir, GUEST_UID, GUEST_UID);+ }}function baseImagePullArgs(runtime: Runtime): string[] {@@ -934,6 +1004,7 @@ export async function containerComputerAction(runner: CommandRunner = sh,platform: NodeJS.Platform = process.platform,target: LocalVmTarget = SHARED_LOCAL_VM_TARGET,+ resources: DesktopResources = DEFAULT_DESKTOP_RESOURCES,): Promise<ContainerComputerStatus> {if (runner === sh && platform === process.platform) screenshotStatusCache.delete(target.key);const before = await containerComputerStatus(runner, platform, target);@@ -969,10 +1040,17 @@ export async function containerComputerAction(if (action === "pull") {await prepareManagedImage(runtime, runner);} else {- if (action === "run") await ensureVmWorkspace(platform, target);+ if (action === "run") await ensureVmWorkspace(platform, target, runtime);+ if (action === "start" && runtime !== "container") {+ await applyResourcesBeforeStart(target.containerName, resources, (args, timeoutMs) => runner(runtime, args, timeoutMs));+ }const args =action === "run"- ? containerRunArgs(runtime, randomBytes(6).toString("base64url"), target)+ ? containerRunArgs(runtime, randomBytes(6).toString("base64url"), target, {+ platform,+ resources,+ hostUser: currentHostUser(platform),+ }): action === "remove"? ["rm", runtime === "container" ? "--force" : "-f", target.containerName]: [action, target.containerName];@@ -1216,7 +1294,11 @@ export function setupCommands(run:runtime === "container" && target.key !== SHARED_LOCAL_VM_TARGET.key? null- : command(containerRunArgs(runtime, "CHANGE_ME", target)),+ : command(containerRunArgs(runtime, "CHANGE_ME", target, {+ platform,+ resources: DEFAULT_DESKTOP_RESOURCES,+ hostUser: null,+ })),start: command(["start", target.containerName]),stop: command(["stop", target.containerName]),remove: command(["rm", runtime === "container" ? "--force" : "-f", target.containerName]),diff --git a/server/container-limits.ts b/server/container-limits.tsindex 8de614fe34..60d52983b8 100644--- a/server/container-limits.ts+++ b/server/container-limits.ts@@ -4,6 +4,23 @@ export const PIDS_LIMIT = 4096;/** The cap desktops were made with before. Any other value is someone's choice and stays. */const PREVIOUS_PIDS_LIMIT = 512;+export interface DesktopResources {+ memoryGb: number;+ cpus: number;+}++export const DEFAULT_DESKTOP_RESOURCES: DesktopResources = { memoryGb: 4, cpus: 2 };+export const MIN_DESKTOP_MEMORY_GB = 2;+export const MAX_DESKTOP_MEMORY_GB = 128;+export const MIN_DESKTOP_CPUS = 1;+export const MAX_DESKTOP_CPUS = 64;++/** Swap is capped at the memory limit, so a desktop over its budget is stopped rather than left thrashing the host. */+export function resourceArgs(resources: DesktopResources, options: { swap: boolean }): string[] {+ const memory = `${resources.memoryGb}g`;+ return ["--memory", memory, ...(options.swap ? ["--memory-swap", memory] : []), "--cpus", String(resources.cpus)];+}+const raised = new Set<string>();/** Docker and Podman change an existing container's cap in place, running or stopped, so a desktop made under the old cap@@ -17,3 +34,12 @@ export function raisePidsLimit(raised.add(container);void Promise.resolve().then(() => docker(["update", "--pids-limit", String(PIDS_LIMIT), container], 15_000)).catch(() => {});}++/** A stopped desktop takes the configured limits before it starts. An engine without `update --memory` keeps the old ones. */+export async function applyResourcesBeforeStart(+ container: string,+ resources: DesktopResources,+ docker: (args: string[], timeoutMs?: number) => Promise<unknown>,+): Promise<void> {+ await docker(["update", ...resourceArgs(resources, { swap: true }), container], 15_000).catch(() => {});+}diff --git a/server/index.ts b/server/index.tsindex 9c1be57efc..1c4fea851b 100644--- a/server/index.ts+++ b/server/index.ts@@ -157,6 +157,7 @@ import {localVmMaxInstances,localVmMode,localVmPreservesInstalledApps,+ localVmResources,roomTurnTimeoutMinutes,mcpCallTimeoutMinutes,cacheKeepWarmSettings,@@ -5609,7 +5610,7 @@ let localVmProvisionBusy = false;let localVmModeChangeBusy = false;const localVmUpdates = createLocalVmUpdater({status: (target) => containerComputerStatus(undefined, undefined, target),- act: (action, target) => containerComputerAction(action, undefined, undefined, target),+ act: (action, target) => containerComputerAction(action, undefined, undefined, target, localVmResources(cfg)),imageBusy: { get: () => localVmImageBusy, set: (busy) => { localVmImageBusy = busy; } },provisionBusy: { get: () => localVmProvisionBusy, set: (busy) => { localVmProvisionBusy = busy; } },lifecycleBusy: localVmLifecycleBusy,@@ -11682,7 +11683,7 @@ async function readyLocalVmForTurn(botId: string, target: LocalVmTarget, isCurrebroadcast({ kind: "computer", botId, state: "provisioning" });try {- status = await containerComputerAction(action, undefined, undefined, target);+ status = await containerComputerAction(action, undefined, undefined, target, localVmResources(cfg));} catch {// `run` can throw after the container exists, so arm the idle backstop anyway.localVmIdleFor(target).touch();diff --git a/server/local-vm-settings.ts b/server/local-vm-settings.tsindex 5909142d01..f9ec8ef3f1 100644--- a/server/local-vm-settings.ts+++ b/server/local-vm-settings.ts@@ -1,5 +1,6 @@// The Local VM's settings, read from the config the server loaded.import type { AppConfig } from "./config.ts";+import { DEFAULT_DESKTOP_RESOURCES, type DesktopResources } from "./container-limits.ts";export const DEFAULT_LOCAL_VM_MODE = "shared" as const;export const DEFAULT_LOCAL_VM_MAX_INSTANCES = 2;@@ -25,3 +26,10 @@ export function localVmIdleTimeoutMinutes(cfg: AppConfig): number {export function localVmPreservesInstalledApps(cfg: AppConfig): boolean {return cfg.localVm?.preserveInstalledApps === true;}++export function localVmResources(cfg: AppConfig): DesktopResources {+ return {+ memoryGb: cfg.localVm?.memoryGb ?? DEFAULT_DESKTOP_RESOURCES.memoryGb,+ cpus: cfg.localVm?.cpus ?? DEFAULT_DESKTOP_RESOURCES.cpus,+ };+}diff --git a/server/routes/computers.ts b/server/routes/computers.tsindex 7a68f45089..6d9a172e16 100644--- a/server/routes/computers.ts+++ b/server/routes/computers.ts@@ -1,7 +1,7 @@import { z, type ZodString } from "zod";import * as boat from "../boat.ts";import type { ComputerControl } from "../computer-control.ts";-import { isValidSshAlias, localVmMaxInstances, localVmMode, type AppConfig } from "../config.ts";+import { isValidSshAlias, localVmMaxInstances, localVmMode, localVmResources, type AppConfig } from "../config.ts";import {containerComputerAction,containerComputerExists,@@ -312,7 +312,7 @@ export function createComputerRoutes(deps: ComputerRouteDeps): RouteHandler {else localVmLifecycleBusy.add(SHARED_LOCAL_VM_TARGET.key);try {if (action === "remove") await keepSignInsBeforeRemove(SHARED_LOCAL_VM_TARGET);- const status = await containerComputerAction(action, undefined, undefined, SHARED_LOCAL_VM_TARGET);+ const status = await containerComputerAction(action, undefined, undefined, SHARED_LOCAL_VM_TARGET, localVmResources(cfg));if (action === "run" || action === "start") {localVmSeen.add(SHARED_LOCAL_VM_TARGET.key);localVmIdleFor(SHARED_LOCAL_VM_TARGET).touch();@@ -387,7 +387,7 @@ export function createComputerRoutes(deps: ComputerRouteDeps): RouteHandler {}}if (action === "remove") await keepSignInsBeforeRemove(target);- const status = await containerComputerAction(action, undefined, undefined, target);+ const status = await containerComputerAction(action, undefined, undefined, target, localVmResources(cfg));if (action === "run" || action === "start") {localVmSeen.add(target.key);localVmIdleFor(target).touch();diff --git a/server/vps-computer.test.ts b/server/vps-computer.test.tsindex f52fa3dc1a..5e5c9a3445 100644--- a/server/vps-computer.test.ts+++ b/server/vps-computer.test.ts@@ -463,6 +463,9 @@ describe("VPS computer", () => {expect(status.ready).toBe(true);const run = provision.calls.find(({ args }) => args[2] === "run")?.args ?? [];expect(run).toContain("--memory");+ expect(run.join(" "), "a VPS desktop has no host mounts, so root may install packages there")+ .toContain("--cap-drop ALL --cap-add CHOWN --cap-add DAC_OVERRIDE --cap-add FOWNER --cap-add FSETID --cap-add SETGID --cap-add SETUID");+ expect(run).not.toContain("no-new-privileges");expect(run[run.indexOf("--pids-limit") + 1], "Firefox needs room for its threads").toBe(String(PIDS_LIMIT));expect(run).toContain("--ipc");expect(run[run.indexOf("--ipc") + 1]).toBe("private");diff --git a/server/vps-computer.ts b/server/vps-computer.tsindex 8c47c284b9..8ed0e36de9 100644--- a/server/vps-computer.ts+++ b/server/vps-computer.ts@@ -9,6 +9,7 @@ import {CUA_SOCKET,IMAGE as CUA_IMAGE,cuaExecArgs,+ desktopCapArgs,dockerSecurityIsHardened,imageLabelsMatch,managedImageDockerfile,@@ -762,12 +763,8 @@ export function vpsContainerRunArgs("private","--cgroupns","private",- "--cap-drop",- "ALL",- "--cap-add",- "SETUID",- "--cap-add",- "SETGID",+ // No host mounts, so root in this desktop can install packages without reaching the host's files.+ ...desktopCapArgs("docker"),"--shm-size","512m",// Without a restart policy Docker leaves the container down after a VPS reboot; unless-stopped still honors Stop.