import { execFile } from "node:child_process"; import { constants, accessSync, statSync } from "node:fs"; import { access, realpath } from "node:fs/promises"; import { join } from "node:path"; import { promisify } from "node:util"; const execFileAsync = promisify(execFile); /** * A command as an executable plus its already-separated arguments. * * The alternative — a single string handed to `/bin/sh` — has cost this * codebase twice, in two different ways, and both were shipped rather than * hypothetical: * * 1. **A word the shell could not resolve.** `pip install ` died with * `/bin/sh: pip: command not found` on machines where `pip` is only an * interactive-zsh alias. `services/toolchain.ts` fixed *which word* gets * emitted; it could not fix that the words are re-parsed at spawn time. * 2. **Package names are re-parsed as shell syntax.** The builders are fed * `bin.package` / `bin.formula` / `bin.module`, which come from * `.claude/profiles.json` and from plugin `requires.bin` — hand-authored, * committed by teammates, fetched from marketplaces. Under `shell: true` * those go through word-splitting and `$(…)` expansion. Today's catalogue is * benign; the surface is not, and nothing checks it. * * As argv there is no shell, so a package name is one token no matter what * characters it contains, and `cmd` must name a real executable rather than * anything PATH-plus-a-profile might have meant. * * `services/plugin-setup.ts` arrived at this same shape independently for the * MCP dependency installer. This is the codebase agreeing with itself. */ export interface Command { readonly cmd: string; readonly args: readonly string[]; } /** * Characters that need no quoting in any POSIX shell. * * Deliberately conservative, and the reason {@link formatCommand} is display- * neutral: every token claudeup actually builds — `@anthropic-ai/claude-code`, * `claudish@1.2.0`, `aider==0.1`, `github.com/x/t@latest`, `--upgrade` — is * made only of these, so quoting never fires for real input and the rendered * string is byte-identical to the one this codebase printed before commands * became argv. `doctor-bins.test.ts` is the gate on that claim. */ const SHELL_SAFE = /^[A-Za-z0-9_@%+=:,./-]+$/; /** * Render a {@link Command} as the shell line a human would type. * * FOR DISPLAY ONLY. Nothing may feed this back to a shell — that would undo the * whole point of carrying argv. It exists so `doctor` can print "run: brew * install tmux" and the updater can show what it is about to do. * * A token outside {@link SHELL_SAFE} is single-quoted, with `'` closed, * escaped and reopened (`'\''`) — the only POSIX-portable escape, since single * quotes have no escape character inside them. An empty token quotes too: * unquoted it would vanish, which would misrepresent the argv it came from. */ export function formatCommand(c: Command): string { return [c.cmd, ...c.args].map(quoteToken).join(" "); } function quoteToken(token: string): string { if (SHELL_SAFE.test(token)) return token; return `'${token.replaceAll("'", `'\\''`)}'`; } /** * Check if a command exists in PATH * Uses execFile (not exec) to avoid shell injection vulnerabilities * @param command - Command name to check * @returns Path to command if found, null otherwise */ export async function which(command: string): Promise { try { // Use execFile with argument array to prevent command injection const { stdout } = await execFileAsync("which", [command]); return stdout.trim() || null; } catch { return null; } } /** * Synchronous PATH lookup — walks `$PATH` rather than spawning `which(1)`. * * Synchronous on purpose. The installer-command builders in * `services/toolchain.ts` are sync and used by printers; making them async just * to answer "does this machine have uv?" would ripple through every caller. * * Node's `fs` is used rather than `Bun.which` so this needs no `@types/bun`, * whose globals collide with `@types/node` in this project. * * Unlike {@link resolveExecutable} this does NOT follow symlinks to prove the * target still exists — use it to pick between candidates, not to prove a * binary works. */ export function whichSync(command: string): string | null { // An explicit path is not a PATH lookup; honour it as given. if (command.includes("/")) { return isExecutableFile(command) ? command : null; } for (const dir of (process.env.PATH ?? "").split(":")) { if (!dir) continue; const candidate = join(dir, command); if (isExecutableFile(candidate)) return candidate; } return null; } function isExecutableFile(p: string): boolean { try { if (!statSync(p).isFile()) return false; accessSync(p, constants.X_OK); return true; } catch { return false; } } /** * Like {@link which}, but verifies the command actually RESOLVES and is * executable — a dangling symlink (e.g. a stale npx-cache link) returns null. * `which` alone reports the symlink's own path even when its target is gone, * which is exactly how a plugin's binary can look "present" yet fail at runtime. * @returns The real (symlink-resolved) executable path, or null. */ export async function resolveExecutable( command: string, ): Promise { const p = await which(command); if (!p) return null; try { const real = await realpath(p); // follows symlinks; throws if dangling await access(real, constants.X_OK); // must be executable return real; } catch { return null; // dangling link or not executable } }