diff --git a/app/electron/cli.test.ts b/app/electron/cli.test.ts index 77d0ac0e..2759b087 100644 --- a/app/electron/cli.test.ts +++ b/app/electron/cli.test.ts @@ -3,9 +3,9 @@ import { describe, it, expect, beforeEach, afterEach } from 'vitest' import { spawn } from 'node:child_process' import { mkdtempSync, mkdirSync, writeFileSync, readFileSync, rmSync, chmodSync } from 'node:fs' import { tmpdir } from 'node:os' -import { dirname, join, isAbsolute, relative, win32, posix } from 'node:path' +import { delimiter, dirname, join, isAbsolute, relative, win32, posix } from 'node:path' -import { spawnCli, spawnCliAction, spawnEnvFor, spawnSpecFor, startServe, killAll, shutdownAll, CliError, nodeManagerDirs, notFoundStage, reapOrphanServe, resolveCodeburnPath, resolveTarget } from './cli' +import { spawnCli, spawnCliAction, spawnEnvFor, spawnSpecFor, startServe, killAll, shutdownAll, CliError, cmdShimArgs, escapeForCmd, nodeManagerDirs, notFoundStage, reapOrphanServe, resolveCodeburnPath, resolveTarget } from './cli' let dir: string const originalBin = process.env.CODEBURN_BIN @@ -15,6 +15,15 @@ const originalViteUrl = process.env.VITE_DEV_SERVER_URL const originalBundled = process.env.CODEBURN_BUNDLED_CLI const originalDevRepoRoot = process.env.CODEBURN_DEV_REPO_ROOT +/** + * Windows has no catchable SIGTERM: child.kill() is TerminateProcess, which ends the child + * outright, so a grace window, a cleanup handler and a child that ignores the first signal + * are all things the platform cannot do rather than things this code gets wrong. The same + * goes for a resident that closes its own stdin. These stay exactly as they are and simply + * do not run there. + */ +const posixOnly = it.skipIf(process.platform === 'win32') + /** Writes an executable node script and points CODEBURN_BIN at it. */ function fakeBin(name: string, body: string): string { const p = join(dir, name) @@ -316,7 +325,7 @@ describe('spawnSpecFor (bundled CLI runs via Electron-as-node)', () => { expect(spec.env.ELECTRON_RUN_AS_NODE).toBe('1') // PATH is still augmented (the bundle's own dir leads), harmless for a CLI // that itself shells out during pairing/sync. - expect((spec.env.PATH ?? '').split(':')[0]).toBe('/res/cli/dist') + expect((spec.env.PATH ?? '').split(delimiter)[0]).toBe('/res/cli/dist') }) it('spawns an external CLI directly, with no run-as-node flag', () => { @@ -324,7 +333,84 @@ describe('spawnSpecFor (bundled CLI runs via Electron-as-node)', () => { expect(spec.bin).toBe('/some/bin/codeburn') expect(spec.args).toEqual(['status']) expect(spec.env.ELECTRON_RUN_AS_NODE).toBeUndefined() - expect((spec.env.PATH ?? '').split(':')[0]).toBe('/some/bin') + expect((spec.env.PATH ?? '').split(delimiter)[0]).toBe('/some/bin') + }) + + // Windows cannot start a script. Both shapes a `codeburn` install takes there get a runner + // that can; a POSIX `codeburn` is a shebang script with an exec bit and still runs directly. + const windowsOnly = it.skipIf(process.platform !== 'win32') + + windowsOnly('runs a .js CLI through Node rather than failing with EFTYPE', () => { + const spec = spawnSpecFor({ kind: 'external', bin: 'C:\\repo\\dist\\cli.js' }, ['status']) + expect(spec.bin).toBe(process.execPath) + expect(spec.args).toEqual(['C:\\repo\\dist\\cli.js', 'status']) + expect(spec.env.ELECTRON_RUN_AS_NODE).toBe('1') + }) + + windowsOnly('runs a .cmd shim through cmd.exe, as one verbatim command line', () => { + const spec = spawnSpecFor({ kind: 'external', bin: 'C:\\npm\\codeburn.cmd' }, ['status', '--period', 'today']) + expect(spec.bin.toLowerCase()).toMatch(/\\system32\\cmd\.exe$/) + expect(spec.args.slice(0, 3)).toEqual(['/d', '/s', '/c']) + expect(spec.verbatim).toBe(true) + expect(spec.env.ELECTRON_RUN_AS_NODE).toBeUndefined() + }) + + windowsOnly('leaves an .exe alone', () => { + const spec = spawnSpecFor({ kind: 'external', bin: 'C:\\tools\\codeburn.exe' }, ['status']) + expect(spec.bin).toBe('C:\\tools\\codeburn.exe') + expect(spec.args).toEqual(['status']) + expect(spec.verbatim).toBeUndefined() + }) +}) + +// Two parsers read this string: cmd itself, then the runtime that splits a command line back +// into argv. Nothing a renderer can put in an argument may reach either as syntax. +describe('cmd.exe command line', () => { + it('quotes every argument and neutralises the shell metacharacters', () => { + // The quotes are for the runtime that splits the line back into argv; the `^` are for + // cmd, which reads the line first and would otherwise act on what is inside them. + expect(escapeForCmd('status', false)).toBe('^"status^"') + expect(escapeForCmd('a&b', false)).toBe('^"a^&b^"') + expect(escapeForCmd('a|b', false)).toBe('^"a^|b^"') + expect(escapeForCmd('a>bb^ { + expect(escapeForCmd('say "hi"', false)).toBe('^"say^ \\^"hi\\^"^"') + // A trailing backslash run would otherwise escape the closing quote and swallow the + // argument after it. + expect(escapeForCmd('C:\\dir\\', false)).toBe('^"C:\\dir\\\\^"') + }) + + it('builds one /d /s /c line with the shim first', () => { + const args = cmdShimArgs('C:\\npm\\codeburn.cmd', ['export', '-o', 'C:\\out dir']) + expect(args.slice(0, 3)).toEqual(['/d', '/s', '/c']) + expect(args[3]).toBe('"^"C:\\npm\\codeburn.cmd^" ^^^"export^^^" ^^^"-o^^^" ^^^"C:\\out^^^ dir^^^""') + }) + + it.skipIf(process.platform !== 'win32')('runs a real .cmd shim end to end with its arguments intact', async () => { + // The shape a global npm install leaves on PATH: a batch file that re-expands %* into a + // node invocation, which is the second parse the double escaping above exists for. + const target = join(dir, 'echo-args.js') + writeFileSync(target, 'process.stdout.write(JSON.stringify({ args: process.argv.slice(2) }))\n') + const shim = join(dir, 'codeburn.cmd') + writeFileSync(shim, `@echo off\r\n"${process.execPath}" "${target}" %*\r\n`) + process.env.CODEBURN_BIN = shim + + await expect(spawnCli(['status', '--model', 'a & b'])).resolves.toEqual({ + args: ['status', '--model', 'a & b'], + }) + }) + + it('never lets an argument close the line and start a command', () => { + const line = cmdShimArgs('C:\\npm\\codeburn.cmd', ['status" & calc.exe & "'])[3]! + // Every quote the argument carried is escaped and so is every &, so neither parser can + // read the tail as a second command. + expect(line).not.toMatch(/(^|[^^])& calc/) + expect(line).not.toMatch(/(^|[^^\\])" /) + expect(line).toContain('^^^&') }) it('spawnCli runs the bundled entry end-to-end as Node', async () => { @@ -439,7 +525,7 @@ describe('no-output watchdog (timeoutMs bounds SILENCE, not total runtime)', () }) describe('graceful kill (SIGTERM, then SIGKILL after the grace)', () => { - it('sends SIGTERM first and SIGKILLs a child that ignores it', async () => { + posixOnly('sends SIGTERM first and SIGKILLs a child that ignores it', async () => { const signalFile = join(dir, 'signals') const pidFile = join(dir, 'stubborn-pid') fakeBin( @@ -463,7 +549,7 @@ describe('graceful kill (SIGTERM, then SIGKILL after the grace)', () => { }, 12_000) }, 20_000) - it('keeps a child inside the SIGTERM grace reapable, so quit cannot orphan it', async () => { + posixOnly('keeps a child inside the SIGTERM grace reapable, so quit cannot orphan it', async () => { // The grace timer dies with the app. A child that ignores SIGTERM must still // be in the reap set when quit sweeps, or it survives the app that spawned it. // @@ -491,7 +577,7 @@ describe('graceful kill (SIGTERM, then SIGKILL after the grace)', () => { }, 3_000) }) - it('lets a SIGTERM-handling child exit on its own without waiting for SIGKILL', async () => { + posixOnly('lets a SIGTERM-handling child exit on its own without waiting for SIGKILL', async () => { const cleanupFile = join(dir, 'cleanup') fakeBin( 'handles-sigterm.js', @@ -581,15 +667,15 @@ describe('spawn PATH augmentation (GUI-launched apps have a minimal PATH)', () = it("prepends the resolved binary's own directory so its env-shebang finds node", async () => { const bin = fakeBin('path-echo.js', 'process.stdout.write(JSON.stringify({ path: process.env.PATH }))') const result = await spawnCli(['status']) as { path: string } - expect(result.path.split(':')[0]).toBe(dirname(bin)) + expect(result.path.split(delimiter)[0]).toBe(dirname(bin)) }) it('spawnEnvFor dedupes and keeps the original PATH entries', () => { const env = spawnEnvFor('/some/tool/bin/codeburn') - const parts = (env.PATH ?? '').split(':') + const parts = (env.PATH ?? '').split(delimiter) expect(parts[0]).toBe('/some/tool/bin') expect(new Set(parts).size).toBe(parts.length) - for (const original of (process.env.PATH ?? '').split(':').filter(Boolean)) { + for (const original of (process.env.PATH ?? '').split(delimiter).filter(Boolean)) { expect(parts).toContain(original) } }) @@ -730,7 +816,7 @@ describe('resident serve single-flight', () => { expect(readMaybe(oneShotsFile)).toBe('o') }) - it('falls back instead of crashing when a live resident closes its stdin', async () => { + posixOnly('falls back instead of crashing when a live resident closes its stdin', async () => { const stdinClosedFile = join(dir, 'resident-stdin-closed') fakeBin( 'closes-stdin-resident.js', @@ -1014,7 +1100,7 @@ describe('resident serve single-flight', () => { expect(readMaybe(files.actionsFile)).toBe('a') }) - it('SIGTERMs the outgoing resident on a mutation restart instead of hard-killing it', async () => { + posixOnly('SIGTERMs the outgoing resident on a mutation restart instead of hard-killing it', async () => { // A settings mutation replaces a child that may hold the cache refresh lock. // Same hazard as a timeout, so it gets the same grace: only a catchable // signal lets the outgoing child unlink its own lock instead of leaving it diff --git a/app/electron/cli.ts b/app/electron/cli.ts index a25749a6..30e09232 100644 --- a/app/electron/cli.ts +++ b/app/electron/cli.ts @@ -25,7 +25,12 @@ export type SpawnPriority = 'interactive' | 'background' * acting as Node via `ELECTRON_RUN_AS_NODE`. */ export type CliTarget = { kind: 'external'; bin: string } | { kind: 'bundled'; entry: string } -type SpawnSpec = { bin: string; args: string[]; env: NodeJS.ProcessEnv } +/** + * `verbatim` marks a spec that goes through `cmd.exe`: its args are one already + * escaped command line that Windows must hand over untouched, and the real CLI + * runs a generation below, so ending it means ending the tree. + */ +type SpawnSpec = { bin: string; args: string[]; env: NodeJS.ProcessEnv; verbatim?: true } /** * Which resolution/spawn stage produced a `not-found`, as a non-sensitive enum @@ -108,13 +113,46 @@ function ownsProcessGroup(): boolean { return platform() !== 'win32' } +/** + * Children spawned through `cmd.exe`. The shim exits the moment it has started node, and + * the handle we hold is the shim's, so ending it leaves the parse running with nobody + * reading it. `taskkill /T` is what reaches the generation below on Windows. + */ +const shellChildren = new WeakSet() + +/** Everything but the stdio shape, which stays at the call site so its literal tuple keeps + * telling the type system which streams the child will have. */ +function spawnOptionsFor(spec: SpawnSpec) { + return { + shell: false as const, + env: spec.env, + detached: ownsProcessGroup(), + ...(spec.verbatim ? { windowsVerbatimArguments: true } : {}), + } +} + +/** Remember a child that runs behind `cmd.exe`, so ending it later ends the tree. */ +function trackSpawned(spec: SpawnSpec, child: T): T { + if (spec.verbatim) shellChildren.add(child) + return child +} + /** Signal the CLI and every subprocess it created. POSIX children are spawned - * as process-group leaders; Windows keeps the direct-child behavior here and - * relies on its existing orphan-reap path after a crash. */ + * as process-group leaders; on Windows only a child behind a `cmd.exe` shim has a tree + * worth reaching, and `taskkill` is the only way to reach it. */ function signalOwnedTree(child: ChildProcess, signal: NodeJS.Signals): boolean { if (ownsProcessGroup() && child.pid) { try { process.kill(-child.pid, signal); return true } catch { /* already gone or no group */ } } + if (!ownsProcessGroup() && child.pid && shellChildren.has(child)) { + // Best effort and fire-and-forget: the child handle is killed below either way, so a + // taskkill that cannot run leaves exactly the behaviour there was before. + try { + spawn(`${process.env.SystemRoot || 'C:\\Windows'}\\System32\\taskkill.exe`, + ['/pid', String(child.pid), '/T', '/F'], + { stdio: 'ignore', windowsHide: true }).on('error', () => {}) + } catch { /* fall through to the direct kill */ } + } try { return child.kill(signal) } catch { return false } } @@ -264,12 +302,78 @@ export function spawnEnvFor(bin: string): NodeJS.ProcessEnv { * as the first argument. PATH is still augmented so anything the CLI itself * shells out to (pairing, sync) resolves the same way an external CLI would. */ +/** A script run by this process's own runtime: Electron's binary acting as Node. */ +function nodeSpec(entry: string, args: string[]): SpawnSpec { + return { + bin: process.execPath, + args: [entry, ...args], + env: { ...spawnEnvFor(entry), ELECTRON_RUN_AS_NODE: '1' }, + } +} + +/** What a `codeburn` install looks like on Windows: an npm `.cmd` shim on PATH, or the + * repo's own `dist/cli.js` in dev. Neither is something `CreateProcess` can start. */ +const NODE_SCRIPT = /\.[cm]?js$/i +const CMD_SCRIPT = /\.(?:cmd|bat)$/i + +/** `cmd.exe` out of System32, never by bare name: Windows searches the current directory + * first, so anything dropped beside the app could answer for it. */ +function comspecPath(env: NodeJS.ProcessEnv = process.env): string { + const root = env.SystemRoot + const base = root && /^[a-zA-Z]:[\\/]/.test(root) ? root.replace(/[\\/]+$/, '') : 'C:\\Windows' + return `${base}\\System32\\cmd.exe` +} + +/** + * Quote one argument for a `cmd.exe /c` command line. + * + * Two parsers see this string, and each needs its own pass. The quotes and the + * backslash doubling are for the runtime that splits a command line back into argv; + * the `^` escapes are for cmd itself, which re-reads the line first and would + * otherwise act on a `&` or a `|` inside the quotes rather than pass it along. A + * `.cmd` shim re-expands its own arguments, so those meta characters are escaped + * twice: once for cmd reading this line, once for the shim reading what it gets. + * + * This is the rule `cross-spawn` applies, restated rather than depended on: the app's + * main process ships no npm dependencies (app/DISTRIBUTION.md). + */ +const CMD_META = /([()\][%!^"`<>&|;, *?])/g +export function escapeForCmd(arg: string, doubleEscape: boolean): string { + let escaped = String(arg) + // Any run of backslashes immediately before a quote is doubled, and the quote escaped. + .replace(/(\\*)"/g, '$1$1\\"') + // A trailing backslash run would otherwise escape the closing quote. + .replace(/(\\*)$/, '$1$1') + escaped = `"${escaped}"`.replace(CMD_META, '^$1') + return doubleEscape ? escaped.replace(CMD_META, '^$1') : escaped +} + +/** The `cmd.exe /d /s /c ""` argv for a `.cmd` or `.bat` CLI. Exported for tests: + * everything security-relevant about the shell route is in this one string. */ +export function cmdShimArgs(bin: string, args: string[]): string[] { + const line = [escapeForCmd(bin, false), ...args.map(arg => escapeForCmd(arg, true))].join(' ') + // /d skips AutoRun commands from the registry, /s fixes how the quotes around the whole + // line are read, /c runs it and exits. + return ['/d', '/s', '/c', `"${line}"`] +} + export function spawnSpecFor(target: CliTarget, args: string[]): SpawnSpec { - if (target.kind === 'bundled') { - return { - bin: process.execPath, - args: [target.entry, ...args], - env: { ...spawnEnvFor(target.entry), ELECTRON_RUN_AS_NODE: '1' }, + if (target.kind === 'bundled') return nodeSpec(target.entry, args) + + // Windows has no shebang. `CreateProcess` starts executables, so a `.js` CLI (the repo + // build in dev) and a `.cmd` shim (what a global npm install puts on PATH) both fail + // outright with EFTYPE, which is why nothing the desktop app spawned ever ran here. Each + // is given a runner that can start it. A POSIX `codeburn` is a script with a shebang and + // an exec bit and still runs directly, exactly as before. + if (platform() === 'win32') { + if (NODE_SCRIPT.test(target.bin)) return nodeSpec(target.bin, args) + if (CMD_SCRIPT.test(target.bin)) { + return { + bin: comspecPath(), + args: cmdShimArgs(target.bin, args), + env: spawnEnvFor(target.bin), + verbatim: true, + } } } return { bin: target.bin, args, env: spawnEnvFor(target.bin) } @@ -365,12 +469,24 @@ export function resolveTarget(): CliTarget | null { const persisted = readPersistedPath() if (persisted) return { kind: 'external', bin: persisted } - for (const bin of searchDirs().map(dir => join(dir, 'codeburn'))) { + for (const bin of searchDirs().flatMap(pathCandidates)) { if (isExecutableFile(bin)) return { kind: 'external', bin } } return null } +/** + * What a `codeburn` in one PATH directory can be called. A global npm install writes both + * `codeburn` (a shell script, useless here) and `codeburn.cmd` (the Windows shim) into the + * same directory, so the extensions have to come first or the lookup finds the one Windows + * cannot start. Elsewhere there is only ever the bare name. + */ +function pathCandidates(dir: string): string[] { + return platform() === 'win32' + ? [join(dir, 'codeburn.cmd'), join(dir, 'codeburn.exe'), join(dir, 'codeburn.bat'), join(dir, 'codeburn')] + : [join(dir, 'codeburn')] +} + /** The resolved CLI's path for display/status, or null. See {@link resolveTarget}. */ export function resolveCodeburnPath(): string | null { const target = resolveTarget() @@ -420,7 +536,7 @@ function withoutProgressLines(stderr: string): string { function runCli(spec: SpawnSpec, cmdLabel: string, timeoutMs: number, onStderr?: (chunk: string) => void): Promise { return new Promise((resolve, reject) => { - const child = spawn(spec.bin, spec.args, { shell: false, stdio: ['ignore', 'pipe', 'pipe'], env: spec.env, detached: ownsProcessGroup() }) + const child = trackSpawned(spec, spawn(spec.bin, spec.args, { stdio: ['ignore', 'pipe', 'pipe'], ...spawnOptionsFor(spec) })) activeChildren.add(child) let stdout = '' let stderr = '' @@ -574,7 +690,7 @@ class ServeClient { start(): void { if (this.child || this.disabled() || this.destroyed) return - const child = spawn(this.spec.bin, [...this.spec.args], { shell: false, stdio: ['pipe', 'pipe', 'ignore'], env: this.spec.env, detached: ownsProcessGroup() }) + const child = trackSpawned(this.spec, spawn(this.spec.bin, [...this.spec.args], { stdio: ['pipe', 'pipe', 'ignore'], ...spawnOptionsFor(this.spec) })) this.child = child if (this.pidFile && child.pid) { const record = JSON.stringify({ pid: child.pid, cmd: [this.spec.bin, ...this.spec.args].join(' '), processGroup: ownsProcessGroup() }) @@ -979,7 +1095,7 @@ export function spawnCliAction(args: string[], opts: { timeoutMs?: number; extra // no long silent stretch for a watchdog to misread. function runAction(spec: SpawnSpec, args: string[], timeoutMs: number): Promise { return new Promise(resolve => { - const child = spawn(spec.bin, spec.args, { shell: false, stdio: ['ignore', 'pipe', 'pipe'], env: spec.env, detached: ownsProcessGroup() }) + const child = trackSpawned(spec, spawn(spec.bin, spec.args, { stdio: ['ignore', 'pipe', 'pipe'], ...spawnOptionsFor(spec) })) activeChildren.add(child) let stdout = '' let stderr = ''