Skip to content

an open-source alternative to the dots, bots and muses of the world, run an office of claude code/codex like agents on your laptop, sandboxes or anywhere, uses your existing subscriptions

harden(spawn): only resolve plain command names against the shell PATH

chaitanyagiriea7e0d2f3535
diff --git a/src/main/index.ts b/src/main/index.ts
index f0147e3c..79342b50 100644
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@ -6,11 +6,11 @@ import {
readlinkSync, symlinkSync
} from 'node:fs';
import { randomBytes, createHash, timingSafeEqual } from 'node:crypto';
-import { join, resolve, sep, basename, dirname } from 'node:path';
+import { join, resolve, sep, basename, dirname, isAbsolute } from 'node:path';
import { homedir } from 'node:os';
import { request as httpsRequest } from 'node:https';
import { PtyManager, type SpawnOptions } from './pty';
-import { resolveCommand as resolveCliCommand } from './shellEnv';
+import { resolveCommand as resolveCliCommand, isSafeCommandName } from './shellEnv';
import { initAutoUpdater, abortPendingRestart } from './updater';
import { RealtimeFloorWatcher } from './realtimeFloorWatcher';
import {
@@ -4575,6 +4575,16 @@ async function processSpawnRequest(filePath: string): Promise<void> {
autoMode: !!cfgSpawn.autoMode
});
const bin = launch.bin;
+ // Validate the executable name on the spawn path. A spawn-request file is
+ // untrusted input (authored by the orchestrator, reachable by anything that can
+ // write HIVE_ROOT/spawn-requests), so the bin must be a plain command token or
+ // an absolute path — never a string a downstream shell `which`/`where` could
+ // reinterpret. Rejected here, before any resolution; the resolver guards behind
+ // it validate the same thing in depth.
+ if (!isSafeCommandName(bin) && !isAbsolute(bin)) {
+ fail(`refusing spawn: engine command "${bin}" is not a plain command name or an absolute path`);
+ return;
+ }
// Missing-CLI → FAIL FAST. A headless worker has no human to watch an installer,
// so we never run the cc49e1e install banner here — we reject and tell god.
if (!ptyManager.isCommandAvailable(bin)) { fail(`engine CLI "${bin}" is not installed`); return; }
diff --git a/src/main/pty.ts b/src/main/pty.ts
index 35d557d6..9e038c54 100644
--- a/src/main/pty.ts
+++ b/src/main/pty.ts
@@ -6,7 +6,7 @@ import { spawnSync } from 'node:child_process';
import { ensureKilled, hardKillTree } from './procKill';
import { expandTilde } from './fs';
import { buildPtyEnv } from './ptyEnv';
-import { captureFromLoginShell, userShellPath } from './shellEnv';
+import { captureFromLoginShell, isSafeCommandName, userShellPath } from './shellEnv';
/** APPEND the hive's bundled-node dir (`<HIVE_ROOT>/bin/runtime`, which holds a
* shim literally named `node`) to a child's PATH.
@@ -409,8 +409,12 @@ export class PtyManager {
// Already an absolute/relative path (Unix `/` or Windows `\`) — pass through;
// `found` reflects whether that path actually exists on disk.
if (command.includes('/') || command.includes('\\')) return { path: command, found: existsSync(command) };
+ // Only a plain command name is resolved against PATH. Anything else is
+ // refused here so it never reaches `which`/`where`; `found:false` makes the
+ // caller treat it as missing.
+ if (!isSafeCommandName(command)) return { path: command, found: false };
if (process.platform === 'win32') {
- // `where` is the Windows equivalent of `which`; runs via cmd.exe (shell:true).
+ // `where` is the Windows equivalent of `which`.
// It can return MULTIPLE matches in PATH order; the first is often an
// EXTENSIONLESS shim (bare `claude`). Skip extensionless hits and take
// the first PATHEXT-eligible one (.CMD/.BAT/.EXE/…). NOTE: even .CMD/.BAT
@@ -418,7 +422,9 @@ export class PtyManager {
// spawn() either decodes the shim to its real interpreter or, failing that,
// routes it through `cmd.exe /c` (see resolveWindowsShimSpawn below).
try {
- const res = spawnSync('where', [command], { encoding: 'utf8', timeout: 3000, shell: true });
+ // No `shell:true`: `command` is proven metacharacter-free above, and
+ // running `where` directly keeps cmd.exe from re-parsing the argument.
+ const res = spawnSync('where', [command], { encoding: 'utf8', timeout: 3000 });
const lines = (res.stdout ?? '').trim().split(/\r?\n/).map((l) => l.trim()).filter(Boolean);
const pathExts = (process.env.PATHEXT ?? '.COM;.EXE;.BAT;.CMD')
.split(';').map((e) => e.trim().toUpperCase()).filter(Boolean);
diff --git a/src/main/shellEnv.ts b/src/main/shellEnv.ts
index 4542560a..64c29d7c 100644
--- a/src/main/shellEnv.ts
+++ b/src/main/shellEnv.ts
@@ -72,13 +72,29 @@ export function userShellPath(): string {
/** Resolve a bare command (e.g. 'claude') against the user's PATH + common
* install locations. Returns the input unchanged if it already looks like a path. */
+/** A plain executable name — the only shape we resolve against the user's PATH.
+ * A resolver may interpolate this token into a shell (`$SHELL -ilc "… which
+ * <it> …"`), so it is constrained to characters that are unambiguously part of
+ * a binary name (`[A-Za-z0-9._+-]`); anything else is not a command name and is
+ * refused rather than resolved. Callers early-return real paths (containing `/`
+ * or `\`) before this, so the only input that reaches a resolver is meant to be
+ * a bare binary name. */
+export function isSafeCommandName(command: string): boolean {
+ return /^[A-Za-z0-9._+-]+$/.test(command);
+}
+
export function resolveCommand(command: string): string {
// Already an absolute/relative path (Unix `/` or Windows `\`) — pass through.
if (command.includes('/') || command.includes('\\')) return command;
+ // Not a plain command name → nothing to resolve. Returned unchanged so the
+ // caller's spawn ENOENTs it, and no shell ever sees it.
+ if (!isSafeCommandName(command)) return command;
if (process.platform === 'win32') {
- // `where` is the Windows equivalent of `which`; runs via cmd.exe (shell:true).
+ // `where` is the Windows equivalent of `which`. No `shell:true`: the command
+ // is already proven metacharacter-free above, and running `where` directly
+ // (libuv resolves it to where.exe via PATHEXT) keeps cmd.exe out of the loop.
try {
- const res = spawnSync('where', [command], { encoding: 'utf8', timeout: 3000, shell: true });
+ const res = spawnSync('where', [command], { encoding: 'utf8', timeout: 3000 });
const path = (res.stdout ?? '').trim().split(/\r?\n/)[0];
if (path && existsSync(path)) return path;
} catch { /* fall through */ }
diff --git a/test/command-name-validation.test.cjs b/test/command-name-validation.test.cjs
new file mode 100644
index 00000000..6564536d
--- /dev/null
+++ b/test/command-name-validation.test.cjs
@@ -0,0 +1,126 @@
+'use strict';
+
+/**
+ * Engine command-name validation.
+ *
+ * The engine `command` on a spawn request is untrusted input (orchestrator LLM
+ * output, or anything that can write HIVE_ROOT/spawn-requests). Its first token
+ * becomes the executable NAME, and a resolver may interpolate that name into a
+ * shell PATH lookup (`$SHELL -ilc "… which <it> …"` on POSIX, `where <it>` on
+ * Windows). So only a PLAIN command name is resolved; anything else is refused.
+ *
+ * The predicate is `isSafeCommandName`, applied at three sites:
+ * 1. resolveCommand (shellEnv.ts) — refuses to hand a non-plain name to which;
+ * 2. resolveCommandUncached (pty.ts) — the same, and drops shell:true on `where`;
+ * 3. the spawn-request intake (index.ts) — refuses a bin that is neither a plain
+ * name nor an absolute path, before any resolution.
+ *
+ * These tests pin the predicate AND that each of the three sites actually calls
+ * it — a predicate that is correct but never invoked would leave the boundary
+ * open while every unit test stayed green.
+ */
+
+const test = require('node:test');
+const assert = require('node:assert/strict');
+const loadTs = require('./load-ts.cjs');
+
+const { isSafeCommandName } = loadTs('src/main/shellEnv.ts');
+const { buildWorkerLaunch } = loadTs('src/main/workerLaunch.ts');
+
+test('legit engine binary names are accepted', () => {
+ for (const name of ['claude', 'codex', 'grok', 'kimi', 'agy', 'qwen', 'opencode',
+ 'crush', 'pi', 'copilot', 'cursor-agent', 'node', 'npm', 'node.js', 'a_b+c']) {
+ assert.equal(isSafeCommandName(name), true, `${name} should be safe`);
+ }
+});
+
+test('a name carrying any character outside a plain command name is rejected', () => {
+ // Only [A-Za-z0-9._+-] is a command name. Every one of these carries something
+ // a shell would treat as more than a name (a separator, a pipe, a redirect,
+ // substitution, or whitespace introducing a second word), so none resolves.
+ for (const bad of [
+ 'claude;rest',
+ 'claude&&rest',
+ 'claude|rest',
+ 'x`rest`',
+ '$(rest)',
+ 'claude>rest',
+ 'claude rest',
+ 'claude\trest',
+ 'claude$IFS',
+ 'a&b',
+ '',
+ ]) {
+ assert.equal(isSafeCommandName(bad), false, `${JSON.stringify(bad)} must be rejected`);
+ }
+});
+
+test('a path is NOT a plain command name (the resolver early-returns paths before this)', () => {
+ assert.equal(isSafeCommandName('/usr/bin/claude'), false);
+ assert.equal(isSafeCommandName('./claude'), false);
+ assert.equal(isSafeCommandName('a\\b'), false);
+});
+
+test('the tokenizer still yields a non-plain bin, so the allowlist is load-bearing', () => {
+ // buildWorkerLaunch is pure tokenization; it does NOT validate. The guard at the
+ // spawn-request call site (index.ts) is what rejects a non-plain bin. If this
+ // ever changes so bin comes back constrained, revisit whether the call-site
+ // guard is still needed — but do not remove it on the strength of the tokenizer.
+ const l = buildWorkerLaunch({ requestCommand: 'claude;rest', autoMode: false });
+ assert.equal(l.bin, 'claude;rest');
+ assert.equal(isSafeCommandName(l.bin), false);
+});
+
+// ── each of the three sites actually calls the predicate ─────────────────────
+// A predicate that passes every unit test still leaves the boundary open if a
+// site forgets to call it. The three sites are the two resolvers (shellEnv.ts and
+// pty.ts) and the spawn-request intake (index.ts). Two of those import electron
+// and cannot load under plain node, so their wiring is asserted against source
+// text — the pattern the rest of this suite uses for main-process wiring. The
+// resolver that CAN load is checked behaviourally.
+
+const fs = require('node:fs');
+const path = require('node:path');
+const { resolveCommand } = loadTs('src/main/shellEnv.ts');
+const readSrc = (rel) => fs.readFileSync(path.resolve(__dirname, '..', rel), 'utf8');
+
+test('resolveCommand returns a non-plain name unchanged — it never reaches the shell lookup', () => {
+ // A bare name (no `/` or `\`) that is not a plain command name must come straight
+ // back, BEFORE any `captureFromLoginShell(\`which …\`)`. Equality means the shell
+ // interpolation was never reached — a resolved binary would be an absolute path.
+ // Proven behaviourally too: the name below, were it ever interpolated into the
+ // login-shell lookup, would create a marker file; a plain path (with a `/`) is
+ // avoided so resolveCommand does not early-return before the guard. Clean before
+ // and after so the check is hermetic and cannot leave a file in the repo.
+ const probe = path.resolve(process.cwd(), 'md_wiring_probe');
+ try { fs.rmSync(probe, { force: true }); } catch { /* nothing to clean */ }
+ const nonPlain = 'claude;touch md_wiring_probe';
+ try {
+ assert.equal(resolveCommand(nonPlain), nonPlain);
+ assert.equal(fs.existsSync(probe), false, 'the name reached a shell — the guard did not hold');
+ } finally {
+ try { fs.rmSync(probe, { force: true }); } catch { /* best effort */ }
+ }
+});
+
+test('pty.ts resolver validates before which/where', () => {
+ const src = readSrc('src/main/pty.ts');
+ // The guard must sit in resolveCommandUncached and precede the spawnSync('where')
+ // and the captureFromLoginShell(`which …`) calls, and `where` must not run under
+ // a shell (which would re-parse the argument).
+ assert.match(src, /if \(!isSafeCommandName\(command\)\) return \{ path: command, found: false \};/);
+ assert.doesNotMatch(src, /spawnSync\('where', \[command\], \{ encoding: 'utf8', timeout: 3000, shell: true \}\)/);
+ const guardAt = src.indexOf('if (!isSafeCommandName(command)) return { path: command, found: false };');
+ const whichAt = src.indexOf('captureFromLoginShell(`which ${command}`)');
+ assert.ok(guardAt > 0 && whichAt > guardAt, 'the guard must precede the `which` interpolation');
+});
+
+test('index.ts validates the bin at the spawn-request intake', () => {
+ const src = readSrc('src/main/index.ts');
+ // The spawn path rejects a bin that is neither a plain name nor an absolute path,
+ // and it does so BEFORE isCommandAvailable(bin) (which itself calls the resolver).
+ assert.match(src, /if \(!isSafeCommandName\(bin\) && !isAbsolute\(bin\)\) \{/);
+ const guardAt = src.indexOf('if (!isSafeCommandName(bin) && !isAbsolute(bin)) {');
+ const availAt = src.indexOf('if (!ptyManager.isCommandAvailable(bin))');
+ assert.ok(guardAt > 0 && availAt > guardAt, 'the guard must precede isCommandAvailable(bin)');
+});