Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Bot box: the server's npm and git read no config from HOME (#5302)
Milind Soni4dc3f489a591
diff --git a/server/bot-box/hostile-home.test.ts b/server/bot-box/hostile-home.test.tsnew file mode 100644index 0000000000..be33f6f869--- /dev/null+++ b/server/bot-box/hostile-home.test.ts@@ -0,0 +1,101 @@+// While the bot box is on, a boxed bot can write the server's HOME. These run the real npm and git the server runs+// outside the box, against a HOME holding the config files a bot could leave there, and check that neither acts on them.+import { execFileSync } from "node:child_process";+import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { delimiter, dirname, join } from "node:path";+import { afterEach, beforeEach, describe, expect, it } from "vitest";++import { npmEnvironment, runNpm } from "../engine-install.ts";+import { gitInvocation } from "../lent-clone.ts";++const has = (command: string) => { try { execFileSync(command, ["--version"], { stdio: "ignore" }); return true; } catch { return false; } };+const posix = process.platform !== "win32";++describe.skipIf(!posix)("the server's own npm and git, with a HOME a bot wrote", () => {+ let dir: string, home: string, data: string, marker: string;++ beforeEach(() => {+ dir = realpathSync(mkdtempSync(join(tmpdir(), "omb-hostile-")));+ home = join(dir, "home");+ data = join(dir, "data");+ marker = join(dir, "escaped");+ mkdirSync(home, { recursive: true });+ mkdirSync(data, { recursive: true });+ });+ afterEach(() => rmSync(dir, { recursive: true, force: true }));++ /** A script that records that it ran, which is what a bot would put in a config file. */+ function hostileScript(): string {+ const script = join(home, ".local", "bin", "hostile");+ mkdirSync(dirname(script), { recursive: true });+ writeFileSync(script, `#!/bin/sh\necho "$0 $*" >> "${marker}"\nexec /bin/sh "$@"\n`);+ chmodSync(script, 0o755);+ return script;+ }++ it.skipIf(!has("npm"))("npm ignores a .npmrc in HOME, and the package's own install script still runs", async () => {+ writeFileSync(join(home, ".npmrc"), `script-shell=${hostileScript()}\n`);+ const pkg = join(dir, "pkg");+ mkdirSync(join(pkg, "bin"), { recursive: true });+ writeFileSync(join(pkg, "bin", "omb-hostile-check"), "#!/usr/bin/env node\nconsole.log('1.0.0');\n", { mode: 0o755 });+ writeFileSync(join(pkg, "package.json"), JSON.stringify({+ name: "omb-hostile-check", version: "1.0.0", bin: { "omb-hostile-check": "bin/omb-hostile-check" },+ scripts: { postinstall: "node -e \"require('fs').writeFileSync(process.env.OMB_TEST_POSTINSTALL, 'ran')\"" },+ }));+ const env = { PATH: [dirname(process.execPath), "/usr/bin", "/bin"].join(delimiter), HOME: home };+ const tarball = join(dir, execFileSync("npm", ["pack", "--silent", "--pack-destination", dir, pkg], { cwd: dir, env: { ...env, npm_config_cache: join(dir, "pack-cache") }, encoding: "utf8" }).trim().split("\n").at(-1)!);+ const install = async (boxed: boolean, prefix: string) => {+ mkdirSync(prefix, { recursive: true });+ const npmEnv = { ...npmEnvironment(env, env.PATH, boxed, data), OMB_TEST_POSTINSTALL: join(prefix, "postinstall-ran"), npm_config_offline: "true" };+ return runNpm(["install", "-g", "--prefix", prefix, "--loglevel=error", "--allow-scripts=omb-hostile-check", tarball], npmEnv, prefix, 120_000);+ };++ // The same install with the box off reads HOME's .npmrc: the stand-in for a bot's script runs the install script.+ const open = await install(false, join(dir, "open"));+ expect(open.code, open.output).toBe(0);+ expect(existsSync(marker)).toBe(true);+ rmSync(marker);+ rmSync(join(home, ".npm"), { recursive: true, force: true });++ const boxed = await install(true, join(dir, "boxed"));+ expect(boxed.code, boxed.output).toBe(0);+ expect(existsSync(marker)).toBe(false);+ expect(readFileSync(join(dir, "boxed", "postinstall-ran"), "utf8")).toBe("ran");+ expect(existsSync(join(data, "tools", "npm-home", "cache"))).toBe(true);+ expect(existsSync(join(home, ".npm"))).toBe(false);+ }, 180_000);++ it.skipIf(!has("git"))("git ignores a .gitconfig in HOME: no insteadOf, no ext:: transport, no helper, no fsmonitor", () => {+ const hostile = hostileScript();+ const work = join(dir, "work");+ mkdirSync(work);+ const sh = (...args: string[]) => execFileSync("git", ["-C", work, "-c", "user.name=t", "-c", "[email protected]", ...args], { env: { PATH: "/usr/bin:/bin", HOME: dir }, encoding: "utf8" });+ sh("init", "--quiet", "--initial-branch", "main");+ writeFileSync(join(work, "plan.md"), "v1");+ sh("add", "plan.md");+ sh("commit", "--quiet", "-m", "one");+ const origin = join(dir, "origin.git");+ execFileSync("git", ["clone", "--quiet", "--bare", work, origin], { env: { PATH: "/usr/bin:/bin", HOME: dir } });+ writeFileSync(join(home, ".gitconfig"), [+ `[url "ext::${hostile} -c true"]`, `\tinsteadOf = file://`,+ `[protocol "ext"]`, `\tallow = always`,+ `[core]`, `\tfsmonitor = ${hostile}`,+ `[credential]`, `\thelper = !${hostile}`,+ ].join("\n") + "\n");+ const clone = (boxed: boolean, into: string) => {+ const run = gitInvocation(["clone", "--quiet", "--", `file://${origin}`, into], { PATH: "/usr/bin:/bin", HOME: home }, boxed, home);+ try { execFileSync("git", [...run.args], { env: run.env, stdio: ["ignore", "ignore", "pipe"] }); return true; } catch { return false; }+ };++ clone(false, join(dir, "open"));+ expect(existsSync(marker)).toBe(true);+ rmSync(marker);++ expect(clone(true, join(dir, "boxed"))).toBe(true);+ const run = gitInvocation(["-C", join(dir, "boxed"), "status", "--porcelain"], { PATH: "/usr/bin:/bin", HOME: home }, true, home);+ execFileSync("git", run.args, { env: run.env });+ expect(readFileSync(join(dir, "boxed", "plan.md"), "utf8")).toBe("v1");+ expect(existsSync(marker)).toBe(false);+ });+});diff --git a/server/engine-install.ts b/server/engine-install.tsindex 5ed729f91a..2d4b249416 100644--- a/server/engine-install.ts+++ b/server/engine-install.ts@@ -9,6 +9,7 @@ import { npmEnginesPrefix } from "./engine-roots.ts";import { registerStandaloneBinDirs, standaloneAssetFor, standaloneRunEnv } from "./engine-standalone.ts";import { STANDALONE_RELEASES } from "./standalone-releases.ts";import { augmentedPath, findCliCandidates, registerPathDir, resetPathCache } from "./env-path.ts";+import { botBox } from "./bot-box/box.ts";import { execCli, killCliTree, spawnCli } from "./procs.ts";const MAX_OUTPUT = 64 * 1024;@@ -128,7 +129,16 @@ export function npmRunning(pkg: string, baseDir = DATA_DIR): boolean {return running.has(`${baseDir} ${pkg}`);}-export function npmEnvironment(base: NodeJS.ProcessEnv = process.env, path: string = augmentedPath()): NodeJS.ProcessEnv {+/** npm's own HOME, config files and cache in the data folder, which no boxed bot can write. */+export function npmServerHome(baseDir = DATA_DIR): { home: string; userconfig: string; globalconfig: string; cache: string } {+ const home = join(baseDir, "tools", "npm-home");+ return { home, userconfig: join(home, ".npmrc"), globalconfig: join(home, "npmrc-global"), cache: join(home, "cache") };+}++/** Security: while the bot box is on (`boxed`), a boxed bot can write the server's HOME, so npm, the install scripts it+ * runs and the CLI checked after it never read a config, a cache or anything else from there: `script-shell`, a+ * registry or a cached package a bot left would otherwise run, or be installed, outside the box. */+export function npmEnvironment(base: NodeJS.ProcessEnv = process.env, path: string = augmentedPath(), boxed = botBox.enabled(), baseDir = DATA_DIR): NodeJS.ProcessEnv {const env: NodeJS.ProcessEnv = {...base,PATH: path,@@ -139,6 +149,12 @@ export function npmEnvironment(base: NodeJS.ProcessEnv = process.env, path: stri};// Workspace credentials (xai/box/voice keys) are not npm's to see.stripWorkspaceCredentialEnv(env as Record<string, string | undefined>);+ if (boxed) {+ const own = npmServerHome(baseDir);+ mkdirSync(own.cache, { recursive: true, mode: 0o700 });+ for (const name of Object.keys(env)) if (/^npm_config_(?:userconfig|globalconfig|cache|script_shell)$/i.test(name)) delete env[name];+ Object.assign(env, { HOME: own.home, npm_config_userconfig: own.userconfig, npm_config_globalconfig: own.globalconfig, npm_config_cache: own.cache });+ }return env;}@@ -152,7 +168,7 @@ export function npmInstallArgs(prefix: string, pkg: string, version = "latest"):export async function npmLatestVersion(pkg: string, baseDir = DATA_DIR): Promise<string> {const prefix = enginesPrefix(baseDir);mkdirSync(prefix, { recursive: true });- const result = await runNpm(["view", `${pkg}@latest`, "version", "--loglevel=error"], npmEnvironment(), prefix, PROBE_TIMEOUT_MS * 2);+ const result = await runNpm(["view", `${pkg}@latest`, "version", "--loglevel=error"], npmEnvironment(process.env, augmentedPath(), botBox.enabled(), baseDir), prefix, PROBE_TIMEOUT_MS * 2);const version = stripVTControlCharacters(result.output).split(/\r?\n/).map((line) => line.trim()).filter(Boolean).at(-1);if (result.code !== 0 || !version || !/^\d+\.\d+\.\d+(?:[-+][\w.-]+)?$/.test(version)) {throw new Error(`npm could not look up the newest ${pkg}.${tail(result.output)}`);@@ -163,7 +179,7 @@ export async function npmLatestVersion(pkg: string, baseDir = DATA_DIR): Promiseasync function installOnce(pkg: string, options: InstallOptions): Promise<void> {const prefix = enginesPrefix(options.baseDir);mkdirSync(prefix, { recursive: true });- const env = npmEnvironment(options.env, options.path);+ const env = npmEnvironment(options.env, options.path, botBox.enabled(), options.baseDir);const args = npmInstallArgs(prefix, pkg, options.version);const timeoutMs = options.timeoutMs ?? NPM_INSTALL_TIMEOUT_MS;await runInstall(pkg, args, env, prefix, timeoutMs);diff --git a/server/engine-npm-update.ts b/server/engine-npm-update.tsindex f6e6cf7ca6..4911a8cd95 100644--- a/server/engine-npm-update.ts+++ b/server/engine-npm-update.ts@@ -160,7 +160,7 @@ export function updateNpmEngineStaged(options: StagedNpmUpdate): Promise<void> {async function stagedOnce(options: StagedNpmUpdate, baseDir: string): Promise<void> {const { pkg, version } = options;- const env = npmEnvironment(options.env);+ const env = npmEnvironment(options.env, undefined, undefined, baseDir);const staging = join(toolsDir(baseDir), `${STAGING_PREFIX}${randomUUID()}`);try {await mkdir(staging, { recursive: true, mode: 0o700 });diff --git a/server/lent-clone.ts b/server/lent-clone.tsindex f9370d2886..816e42a970 100644--- a/server/lent-clone.ts+++ b/server/lent-clone.ts@@ -5,9 +5,11 @@// the copy to Files, as for any other folder. The person chooses nothing.import { spawn } from "node:child_process";import { mkdirSync, readdirSync, readFileSync, renameSync, rmSync } from "node:fs";+import { homedir } from "node:os";import { join } from "node:path";import { z } from "zod";import { writeFileAtomic } from "./atomic.ts";+import { botBox } from "./bot-box/box.ts";export const lentGit = z.object({repo: z.string().regex(/^[A-Za-z0-9_.-]{1,100}\/[A-Za-z0-9_.-]{1,100}$/).refine((repo) => !repo.split("/").some((part) => part === "." || part === "..")),@@ -21,14 +23,27 @@ type CloneRecord = { state: "cloning" | "cloned" | "failed"; at: number; repo: sconst CLONE_MS = 10 * 60_000;const RETRY_MS = 24 * 60 * 60_000;+/** Security: while the bot box is on (`boxed`), a boxed bot can write HOME, so git reads no config from there: a+ * helper, an `insteadOf`, an fsmonitor or an `ext::` address a bot left would otherwise run outside the box. Its sign-in+ * is then only what `~/.git-credentials` holds, read by git's own store helper, which runs nothing. */+export function gitInvocation(args: string[], env: NodeJS.ProcessEnv = process.env, boxed = botBox.enabled(), home = homedir()): { args: string[]; env: NodeJS.ProcessEnv } {+ const base = ["-c", "credential.interactive=never", "-c", "core.hooksPath=/dev/null"];+ const quiet = { GIT_TERMINAL_PROMPT: "0", GIT_ASKPASS: "/bin/false", SSH_ASKPASS: "/bin/false", GCM_INTERACTIVE: "never", GIT_SSH_COMMAND: "ssh -o BatchMode=yes" };+ if (!boxed) return { args: [...base, ...args], env: { ...env, ...quiet } };+ const kept = Object.fromEntries(Object.entries(env).filter(([name]) => !name.startsWith("GIT_")));+ return {+ args: [...base, "-c", "protocol.ext.allow=never", "-c", "core.fsmonitor=false",+ "-c", "credential.helper=", "-c", `credential.helper=store --file=${join(home, ".git-credentials")}`, ...args],+ env: { ...kept, ...quiet, GIT_CONFIG_GLOBAL: "/dev/null", GIT_CONFIG_NOSYSTEM: "1" },+ };+}+/** git without a prompt: no terminal, no askpass, no credential dialog; only the sign-in My Cloud already has. */export function runGit(args: string[], timeoutMs = CLONE_MS): Promise<void> {return new Promise((resolve, reject) => {// The address is always https://github.com/<owner>/<name>.git (lentGit's repo), never one a computer sent.- const child = spawn("git", ["-c", "credential.interactive=never", "-c", "core.hooksPath=/dev/null", ...args], {- stdio: ["ignore", "ignore", "pipe"],- env: { ...process.env, GIT_TERMINAL_PROMPT: "0", GIT_ASKPASS: "/bin/false", SSH_ASKPASS: "/bin/false", GCM_INTERACTIVE: "never", GIT_SSH_COMMAND: "ssh -o BatchMode=yes" },- });+ const run = gitInvocation(args);+ const child = spawn("git", run.args, { stdio: ["ignore", "ignore", "pipe"], env: run.env });let error = "";child.stderr.on("data", (chunk) => { if (error.length < 4_000) error += chunk; });const timer = setTimeout(() => child.kill("SIGKILL"), timeoutMs);