Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Windows: hide preinstalled Caddy and strengthen spawn checks
vincent2ee1897ef456
diff --git a/server/caddy.test.ts b/server/caddy.test.tsindex 0cf163fcbc..4aea405c77 100644--- a/server/caddy.test.ts+++ b/server/caddy.test.ts@@ -1,13 +1,18 @@-import { spawnSync } from "node:child_process";+import { ChildProcess, spawn, spawnSync } from "node:child_process";import { createHash } from "node:crypto";import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, statSync, writeFileSync } from "node:fs";import { tmpdir } from "node:os";import { join } from "node:path";-import { afterEach, beforeEach, describe, expect, it } from "vitest";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import { CADDY_ASSETS, CADDY_VERSION, caddyfileFor, ensureCaddy, normalizeDomainOption, pinnedCaddyPath, portPermissionRefused, resolveCaddyBinary, startCaddy } from "./caddy.ts";import { removeTempDir } from "./testing/cleanup.ts";+vi.mock("node:child_process", async (importOriginal) => {+ const actual = await importOriginal<typeof import("node:child_process")>();+ return { ...actual, spawn: vi.fn(actual.spawn) };+});+const posix = process.platform !== "win32";describe("the managed Caddy", () => {@@ -46,6 +51,23 @@ describe("the managed Caddy", () => {expect(resolveCaddyBinary({ dataDir: join(dir, "elsewhere"), env: { PATH: "" }, platform: "linux", arch: "x64", exists })).toBeNull();});+ it("hides a preinstalled Windows Caddy while preserving missing-binary rejection", async () => {+ const binary = join(dir, "caddy.exe");+ writeFileSync(binary, "");+ const fetchImpl = vi.fn<typeof fetch>();+ expect(await ensureCaddy({ dataDir: dir, env: { PATH: dir }, platform: "win32", fetchImpl })).toBe(binary);+ await expect(ensureCaddy({ dataDir: dir, env: { PATH: "" }, platform: "win32", fetchImpl })).rejects.toThrow("--domain is not available on Windows yet");+ expect(fetchImpl).not.toHaveBeenCalled();++ const child = new ChildProcess();+ vi.mocked(spawn).mockClear().mockImplementationOnce(() => {+ queueMicrotask(() => child.emit("error", new Error("fixture exit")));+ return child;+ });+ await expect(startCaddy({ binary, dataDir: dir, domain: "maus.example.com", appPort: 18799, webhookPort: 18800, env: { PATH: dir } })).rejects.toThrow("exit 1");+ expect(spawn).toHaveBeenCalledWith(binary, ["run", "--config", join(dir, "caddy", "Caddyfile"), "--adapter", "caddyfile"], expect.objectContaining({ windowsHide: true, stdio: ["ignore", "pipe", "pipe"] }));+ });+it("takes a bare public hostname for --domain", () => {expect(normalizeDomainOption(" HTTPS://Maus.Example.com/ ")).toBe("maus.example.com");expect(normalizeDomainOption("maus.example.com:443")).toEqual({ error: expect.stringContaining("bare hostname") });diff --git a/server/caddy.ts b/server/caddy.tsindex a30aa3407a..ea6712c86f 100644--- a/server/caddy.ts+++ b/server/caddy.ts@@ -160,6 +160,7 @@ export async function startCaddy(options: {const child: ChildProcess = spawn(options.binary, ["run", "--config", configFile, "--adapter", "caddyfile"], {env: { ...(options.env ?? process.env), XDG_DATA_HOME: join(home, "data"), XDG_CONFIG_HOME: join(home, "config") },stdio: ["ignore", "pipe", "pipe"],+ windowsHide: true,});let output = "";const receive = (chunk: Buffer) => {diff --git a/server/vps-ssh-windows-hide.test.ts b/server/vps-ssh-windows-hide.test.tsindex b75b1fc78c..ea04b080d6 100644--- a/server/vps-ssh-windows-hide.test.ts+++ b/server/vps-ssh-windows-hide.test.ts@@ -1,23 +1,42 @@-// The wake script is a console child: without windowsHide Windows gives it a visible console window. These tests-// stub the platform because the POSIX wake fixtures cannot run on the Windows CI shards that exercise this path.import { EventEmitter } from "node:events";-import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";+import { mkdtempSync, rmSync, writeFileSync } from "node:fs";import { tmpdir } from "node:os";-import { join } from "node:path";+import { dirname, join } from "node:path";import { afterEach, describe, expect, it, vi } from "vitest";-import { ensureVpsSshMaster, prepareVpsSsh, VPS_SSH_DIR, VPS_WAKE_SCRIPT } from "./vps-ssh.ts";+import { ensureVpsSshMaster, VPS_WAKE_SCRIPT } from "./vps-ssh.ts";-const spawns = vi.hoisted(() => [] as Array<{ file: string; args: string[]; options: Record<string, unknown> }>);+const fixture = vi.hoisted(() => ({+ spawns: [] as Array<{ file: string; args: string[]; options: Record<string, unknown> }>,+ commands: [] as string[][],+ wakePaths: new Set<string>(),+}));++vi.mock("node:fs", async (importOriginal) => {+ const actual = await importOriginal<typeof import("node:fs")>();+ return {+ ...actual,+ statSync(path: Parameters<typeof actual.statSync>[0]) {+ const stat = actual.statSync(path);+ if (typeof path === "string" && fixture.wakePaths.has(path)) stat.mode |= 0o100;+ return stat;+ },+ };+});vi.mock("node:child_process", async (importOriginal) => {const actual = await importOriginal<typeof import("node:child_process")>();return {...actual,+ execFile(_file: string, args: string[], _options: unknown, callback: (error: Error, stdout: string, stderr: string) => void) {+ fixture.commands.push(args);+ queueMicrotask(() => callback(new Error("SSH failed"), "", "Connection refused"));+ return { stdin: { end() {} } };+ },spawn(file: string, args: string[], options: Record<string, unknown>) {- spawns.push({ file, args, options });+ fixture.spawns.push({ file, args, options });const child = Object.assign(new EventEmitter(), { pid: 60_000, stderr: new EventEmitter() });- setImmediate(() => child.emit("close", 0, null));+ queueMicrotask(() => child.emit("close", 0, null));return child;},};@@ -26,40 +45,35 @@ vi.mock("node:child_process", async (importOriginal) => {const roots: string[] = [];afterEach(() => {vi.unstubAllGlobals();+ fixture.spawns.length = 0;+ fixture.commands.length = 0;+ fixture.wakePaths.clear();for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true });});-/** A host that refuses SSH, with an executable wake script, so ensureVpsSshMaster runs the script as a child. */function refusingHost() {const root = mkdtempSync(join(tmpdir(), "omb-vps-hide-"));roots.push(root);- const bin = join(root, "bin");- const data = join(root, "data");- mkdirSync(bin);- mkdirSync(data);- writeFileSync(join(bin, "ssh"), [- "#!/bin/sh",- `echo 'ssh: connect to host refused.example port 22: Connection refused' >&2`,- "exit 255",- "",- ].join("\n"), { mode: 0o700 });- const ssh = prepareVpsSsh(data, bin, "linux");- writeFileSync(join(data, VPS_SSH_DIR, VPS_WAKE_SCRIPT), "#!/bin/sh\nexit 0\n", { mode: 0o700 });- return ssh;+ const wake = join(root, VPS_WAKE_SCRIPT);+ writeFileSync(wake, "", { mode: 0o700 });+ fixture.wakePaths.add(wake);+ return { configPath: join(root, "config"), path: root };}describe("VPS wake script spawn options", () => {- it("hides the wake script's console on Windows, without a process group there", async () => {- vi.stubGlobal("process", { ...process, platform: "win32" });- const ssh = refusingHost();- await expect(ensureVpsSshMaster(ssh, "hidden-vps")).rejects.toThrow("Connection refused");- expect(spawns.at(-1)?.options).toMatchObject({ windowsHide: true, detached: false });- });-- it("keeps the POSIX process group while hiding the console", async () => {- vi.stubGlobal("process", { ...process, platform: "linux" });+ it.each([+ { platform: "win32", detached: false },+ { platform: "linux", detached: true },+ ] as const)("hides the wake child and sets its process group on $platform", async ({ platform, detached }) => {+ vi.stubGlobal("process", { ...process, platform, getuid: undefined });const ssh = refusingHost();- await expect(ensureVpsSshMaster(ssh, "grouped-vps")).rejects.toThrow("Connection refused");- expect(spawns.at(-1)?.options).toMatchObject({ windowsHide: true, detached: true });+ await expect(ensureVpsSshMaster(ssh, "fixture-vps")).rejects.toThrow("Connection refused");+ expect(fixture.commands).toEqual([+ ["-O", "check", "--", "fixture-vps"],+ ["-o", "BatchMode=yes", "-o", "PermitLocalCommand=no", "-T", "--", "fixture-vps", "true"],+ ["-o", "BatchMode=yes", "-o", "PermitLocalCommand=no", "-T", "--", "fixture-vps", "true"],+ ]);+ expect(fixture.spawns).toHaveLength(1);+ expect(fixture.spawns[0]).toMatchObject({ file: join(dirname(ssh.configPath), VPS_WAKE_SCRIPT), args: ["fixture-vps"], options: { windowsHide: true, detached } });});});diff --git a/server/windows-hide.test.ts b/server/windows-hide.test.tsindex a8bc9bcb42..bcb67c1e1b 100644--- a/server/windows-hide.test.ts+++ b/server/windows-hide.test.ts@@ -2,11 +2,13 @@// Windows. Every spawn/exec site in server/ and electron/ must set windowsHide (a no-op elsewhere), spread// OWN_GROUP, or be allowlisted here with the reason it may stay as it is.import { readFileSync, readdirSync, statSync } from "node:fs";-import { join } from "node:path";+import { join, relative, win32 } from "node:path";import { fileURLToPath } from "node:url";+import ts from "@typescript/typescript6";import { describe, expect, it } from "vitest";-const ROOT = fileURLToPath(new URL("..", import.meta.url)).replace(/\/+$/, "");+const ROOT = fileURLToPath(new URL("..", import.meta.url));+const repoRelative = (root: string, file: string, getRelative = relative): string => getRelative(root, file).replace(/\\/g, "/");const APIS = ["spawn", "spawnSync", "execFile", "execFileSync", "exec", "execSync"];const isTestFile = (name: string): boolean =>@@ -35,6 +37,15 @@ const withoutCommentLines = (src: string): string =>/** child_process entry points plus the local names bound to them (`promisify(execFile)`, `run = options.run ?? execFileAsync`, `run = execFile`). */function trackedNames(src: string): Set<string> {const names = new Set(APIS);+ for (const match of src.matchAll(/import\s*\{([^}]+)\}\s*from\s*["']node:child_process["']/g)) {+ for (const binding of (match[1] ?? "").split(",")) {+ const parts = binding.trim().split(/\s+as\s+/);+ if (APIS.includes(parts[0] ?? "") && parts[1]) names.add(parts[1]);+ }+ }+ for (const match of src.matchAll(/import\s+\*\s+as\s+(\w+)\s+from\s*["']node:child_process["']/g)) {+ for (const api of APIS) names.add(`${match[1]}.${api}`);+ }for (let round = 0; round < 3; round++) {const bare = (identifier: string | undefined): boolean =>identifier !== undefined && new RegExp(`^(${[...names].join("|")})$`).test(identifier);@@ -62,8 +73,8 @@ const ALLOWED: Array<{ file: string; match?: string; why: string }> = [{ file: "server/bot-box/self-check.ts", match: "spawn(wrapped.command", why: "Linux box self-check" },{ file: "server/browser/desktop/policy.ts", match: "execFileSync(candidate", why: "bwrap sandbox policy probe, Linux" },{ file: "server/browser/desktop/displays.ts", match: "spawn(xvnc", why: "Xvnc per-display server, Linux desktops only" },+ { file: "server/browser/desktop/displays.ts", match: "spawnProcess(file, args", why: "Xvnc per-display server, Linux desktops only" },{ file: "server/caddy.ts", match: 'spawnSync("tar"', why: "ensureCaddy refuses win32 before any download; the tar extraction is POSIX-only" },- { file: "server/caddy.ts", match: "spawn(options.binary", why: "startCaddy is reachable only through ensureCaddy, so never on Windows" },{ file: "server/cloud-clock-keeper.ts", match: "spawnSync(DATE", why: "/bin/date clock step, Linux cloud home" },{ file: "server/cloud-home-start.ts", match: 'spawnSync("/usr/bin/flock"', why: "Linux cloud home" },{ file: "server/cloud-home-start.ts", match: "spawnSync(command, args", why: "Linux cloud home" },@@ -113,6 +124,10 @@ const ALLOWED: Array<{ file: string; match?: string; why: string }> = [{ file: "server/headless/prompt.ts", match: 'spawn(command, args, { stdio: "ignore", detached: true }', why: "deliberately detached + unref'd browser opener; Windows' opener rundll32 is GUI-subsystem" },{ file: "server/env-path.ts", match: 'spawn(shell, ["-l", "-i", "-c"', why: "POSIX login-shell PATH probe ($SHELL), deliberately detached: an interactive shell takes the terminal's foreground" },{ file: "server/vps-ssh.ts", match: 'execFile("ssh"', why: "needs a ControlMaster config, and prepareVpsSsh returns configPath null on win32, so ensureVpsSshMaster returns before this" },+ { file: "server/mcp-bridge.ts", match: "shell: false, windowsHide, env, stdio", why: "consoleChild selects windowsHide at the bridge caller" },+ { file: "server/mcp-gate.ts", match: '...(process.platform === "win32" ? { windowsHide: true } : {})', why: "windowsHide is true on win32" },+ { file: "server/procs.ts", match: '...(process.platform === "win32" ? { windowsHide: true } : { detached: true })', why: "windowsHide is true on win32" },+ { file: "server/memory-store.ts", match: 'stdio: "ignore", windowsHide: false, detached: true', why: "GUI openers must remain visible on Windows" },{ file: "electron/elevated-install.mjs", match: "pkexec", why: "Linux package install (pkexec + .deb)" },{ file: "electron/terminal-launch.mjs", match: "run(executable, args, options", why: "options come from the callers; the win32 caller passes windowsHide: true" },@@ -124,7 +139,7 @@ interface Site { line: number; api: string; text: string }function callSites(src: string, names: Set<string>): Site[] {const sites: Site[] = [];- const alt = [...names].sort((a, b) => b.length - a.length).join("|");+ const alt = [...names].sort((a, b) => b.length - a.length).map((name) => name.replace(/\./g, "\\.")).join("|");const collect = (re: RegExp): void => {let m: RegExpExecArray | null;while ((m = re.exec(src))) {@@ -144,15 +159,68 @@ function callSites(src: string, names: Set<string>): Site[] {return sites;}+function hidesConsole(text: string): boolean {+ const source = ts.createSourceFile("call.ts", `f(${text})`, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS);+ const statement = source.statements[0];+ if (!statement || !ts.isExpressionStatement(statement) || !ts.isCallExpression(statement.expression)) return false;+ return statement.expression.arguments.slice(1, 3).some((argument) => {+ if (!ts.isObjectLiteralExpression(argument)) return false;+ let hidden = false;+ for (const property of argument.properties) {+ if (ts.isSpreadAssignment(property)) hidden = ts.isIdentifier(property.expression) && property.expression.text === "OWN_GROUP";+ else if (ts.isPropertyAssignment(property) && property.name.getText(source).replace(/^["']|["']$/g, "") === "windowsHide") {+ hidden = property.initializer.kind === ts.SyntaxKind.TrueKeyword;+ }+ }+ return hidden;+ });+}+describe("windows console hiding", () => {+ it.each([+ ['import { spawn as start } from "node:child_process"; start("cmd.exe");', "start"],+ ['import * as cp from "node:child_process"; cp.spawn("cmd.exe");', "cp.spawn"],+ ['import { execFile } from "node:child_process"; const run = promisify(execFile); run("cmd.exe");', "run"],+ ])("detects an unhidden child process through imported bindings", (src, api) => {+ expect(callSites(src, trackedNames(src)).map((site) => site.api)).toContain(api);+ });++ it.each([+ 'spawn("cmd.exe", [], { windowsHide: false })',+ 'spawn("windowsHide")',+ 'spawn("cmd.exe", ["windowsHide: true"])',+ 'spawn("cmd.exe", [], { env: { windowsHide: true } })',+ 'spawn("cmd.exe", [], { windowsHide: true, windowsHide: false })',+ 'spawn("cmd.exe", [], { windowsHide: true, ...other })',+ 'spawn("cmd.exe", [], { ...OWN_GROUP, windowsHide: false })',+ 'spawn("cmd.exe", [], { note: "windowsHide: true" })',+ 'spawn({ windowsHide: true }, [])',+ 'spawn("cmd.exe", [], { /* windowsHide: true */ })',+ ])("rejects an unrelated or disabled hiding option", (src) => {+ const site = callSites(src, trackedNames(src))[0];+ expect(site && hidesConsole(site.text)).toBe(false);+ });++ it.each([+ 'spawn("cmd.exe", [], { windowsHide: true })',+ 'spawn("cmd.exe", [], { ...OWN_GROUP })',+ ])("accepts an enabled hiding option", (src) => {+ const site = callSites(src, trackedNames(src))[0];+ expect(site && hidesConsole(site.text)).toBe(true);+ });++ it("normalizes Windows paths for the allowlist", () => {+ expect(repoRelative("C:\\repo\\", "C:\\repo\\server\\testing\\fixture.ts", win32.relative)).toBe("server/testing/fixture.ts");+ });+it("every child_process spawn in server/ and electron/ hides its console on Windows or is allowlisted", () => {const unhidden: string[] = [];for (const file of childProcessFiles()) {- const rel = file.slice(ROOT.length + 1);+ const rel = repoRelative(ROOT, file);const src = withoutCommentLines(readFileSync(file, "utf8"));const lines = src.split("\n");for (const site of callSites(src, trackedNames(src))) {- if (/windowsHide|OWN_GROUP/.test(site.text)) continue;+ if (hidesConsole(site.text)) continue;const line = (lines[site.line - 1] ?? "").trim();const why = ALLOWED.find((entry) =>(entry.file.endsWith("/") ? rel.startsWith(entry.file) : rel === entry.file)