Repository navigation
fix(windows): one chokepoint for every child process - #15746
Conversation
Six decisions have to be made every time Orca starts a child process -- console visibility, argument quoting, .cmd interpretation, binary resolution, timeout policy, and how the tree is later terminated. POSIX forgives all six. Windows punishes each differently, and made per-call site across 172 files they were right in some and wrong in others. runProcess/spawnProcess make them once: - windowsHide unconditionally, shell:false unconditionally (shell:true concatenates argv unescaped and silently disables windowsHide) - .cmd/.bat routed through cmd.exe /d /v:off /s /c with a verbatim line, because Node refuses to spawn them otherwise (EINVAL) The encoding was derived by measurement on Windows 11, not from the docs. An embedded quote is written "" rather than \" so cmd's naive quote count stays even -- with \" the parity flips and every later & | < > on the line stops being data. Measured before the fix, argv ["a b", 'c"d', "e%F%g", "h&i", "j^k"] arrived as ["a b", 'c"d', "e^%F^%g", "h"]: the & truncated the argument and ran its remainder as a command. Each % is broken out of the quoted run as "^%" because %VAR% expands even inside quotes. The import-boundary test is a ratchet seeded at today's 172 files; it only shrinks.
…epoint The ssh -G config probe fires on every connect and reconnect, and ssh.exe is console-subsystem, so a GUI-subsystem parent gets a fresh visible conhost that takes foreground -- keystrokes typed into an Orca terminal at that moment go into the black box (#10488, #14543). Same for the ProxyJump tunnel, the ProxyCommand cmd.exe wrapper, the font enumeration and the DPAPI cookie decrypt. Also stops spawning powershell by bare name: PATH under Electron is not the user's, so where policy has pruned the System32 entry the spawn fails and the font picker silently reports five hardcoded families rather than an error (#11771). Deletes system-fonts' 40-line bespoke execFileText -- timeout, output cap and kill are the chokepoint's job now. Adds runProcessSync so the sync callers have a compliant path; without one the ratchet could never reach zero. The three suites that mocked child_process directly now mock runProcess, which is the point: how a process gets started is no longer each module's business. Ratchet 173 -> 170.
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Repository UI Review profile: CHILL Plan: Pro Plus Run ID: 📒 Files selected for processing (5)
Included review availability: Your plan provides up to 10 included reviews per hour; 9 remain after this review. 📝 WalkthroughWalkthroughThe change adds centralized asynchronous and synchronous child-process runners with structured results, bounded output capture, timeout handling, abort support, and Windows spawn resolution. It adds Windows command-line quoting and system-binary path utilities with corpus-based tests. Browser, SSH, font, emulator, filesystem, memory, PowerShell, and macOS login-shell process calls now use the shared helpers. Tests and an import-boundary guard validate the migration and process behavior. 🚥 Pre-merge checks | ✅ 3 | ❌ 2❌ Failed checks (2 warnings)
✅ Passed checks (3 passed)
✨ Finishing Touches 💡 1📝 Generate docstrings 💡
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 7
🧹 Nitpick comments (3)
src/shared/child-process/child-process-import-allowlist.ts (1)
1-13: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueReduce the policy comments to their local invariants.
src/shared/child-process/child-process-import-allowlist.ts#L1-L13: retain the allowlist purpose and migration instruction.src/shared/child-process/child-process-import-boundary.test.ts#L6-L17: retain the boundary invariant and the required runner path.As per coding guidelines, comments must be concise, non-obvious, and brief—prefer one line; do not explain obvious behavior or walk through code.
Source: Coding guidelines
src/shared/child-process/run-process.ts (1)
100-104: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winNarrow the
spawnProcessparameter type.
spawnProcessaccepts a fullProcessSpecbut honours onlyprogram,args,cwd, andenv. A caller that passestimeoutMs,input,maxOutputBytes, orsignalgets silent no-ops. Accept a launch-only type so the compiler rejects the ignored fields.♻️ Proposed refactor
+export type ProcessLaunchSpec = Pick<ProcessSpec, 'program' | 'args' | 'cwd' | 'env'> + /** Start a child process. Use for long-lived or streaming children. */ -export function spawnProcess(spec: ProcessSpec): ChildProcess { +export function spawnProcess(spec: ProcessLaunchSpec): ChildProcess { const resolved = resolveSpawn(spec, process.platform) return nodeSpawn(resolved.file, [...resolved.args], resolved.options) }src/shared/child-process/run-process.test.ts (1)
1-61: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winAdd tests for the
runProcessruntime paths.This suite covers
resolveSpawnonly. The lifecycle policies that the module exists to centralize have no coverage:timeoutMsexpiry and thetimedOutflag,AbortSignalcancellation including an already-aborted signal,maxOutputBytestruncation,inputdelivery to a child that exits early, and rejection when the program cannot be started. These are the same paths I flagged inrun-process.ts. Tests here can use a portable child such asprocess.execPathwith-e, so they run on macOS, Linux, and Windows.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: a1f518a3-5783-4566-b2f0-6522f6a8ae73
📒 Files selected for processing (15)
src/main/browser/browser-cookie-import.tssrc/main/ssh/ssh-config-resolver.test.tssrc/main/ssh/ssh-g-config-resolution.tssrc/main/ssh/ssh-proxy-command.tssrc/main/system-fonts.test.tssrc/main/system-fonts.tssrc/shared/child-process/child-process-import-allowlist.tssrc/shared/child-process/child-process-import-boundary.test.tssrc/shared/child-process/run-process.test.tssrc/shared/child-process/run-process.tssrc/shared/child-process/windows-command-line-corpus.tssrc/shared/child-process/windows-command-line.test.tssrc/shared/child-process/windows-command-line.tssrc/shared/child-process/windows-command-line.win32.test.tssrc/shared/child-process/windows-system-binary.ts
Included review availability: Your plan provides up to 10 included reviews per hour; 9 remain after this review.
| const IMPORT_PATTERN = | ||
| /(?:from\s+['"]node:child_process['"]|from\s+['"]child_process['"]|require\(\s*['"]node:child_process['"]|require\(\s*['"]child_process['"])/ | ||
|
|
||
| const OWNER_DIRECTORY = 'src/shared/child-process' | ||
| const SCANNED_EXTENSIONS = ['.ts', '.tsx'] |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟠 Major | ⚡ Quick win
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
set -eu
printf '%s\n' '--- tracked candidate files ---'
git ls-files | rg '(^|/)(child-process-import-boundary\.test\.ts|child-process-import-allowlist\.ts)$|child-process'
printf '%s\n' '--- file outline ---'
if command -v ast-grep >/dev/null 2>&1; then
ast-grep outline src/shared/child-process/child-process-import-boundary.test.ts
ast-grep outline src/shared/child-process/child-process-import-allowlist.ts
fi
printf '%s\n' '--- boundary test ---'
cat -n src/shared/child-process/child-process-import-boundary.test.ts
printf '%s\n' '--- allowlist ---'
cat -n src/shared/child-process/child-process-import-allowlist.ts
printf '%s\n' '--- related references ---'
rg -n --glob '*.{ts,tsx,js,jsx}' 'IMPORT_PATTERN|SCANNED_EXTENSIONS|child-process-import|node:child_process|from ['"'"'"]child_process|require\(' src package.json 2>/dev/null || trueRepository: stablyai/orca
Length of output: 50372
🏁 Script executed:
#!/bin/bash
set -eu
cat -n src/shared/child-process/child-process-import-boundary.test.ts
cat -n src/shared/child-process/child-process-import-allowlist.ts
rg -n --glob '*.{ts,tsx,js,jsx}' 'IMPORT_PATTERN|SCANNED_EXTENSIONS|child-process-import|node:child_process|from ["'"'"']child_process|require\(' src package.json 2>/dev/null || trueRepository: stablyai/orca
Length of output: 50370
🏁 Script executed:
#!/bin/bash
set -eu
python3 - <<'PY'
from pathlib import Path
import re
root = Path("src")
extensions = {".ts", ".tsx"}
all_source = []
scanned = []
js_like = []
direct_js_like = []
pattern = re.compile(
r"""(?:from\s+['"]node:child_process['"]|from\s+['"]child_process['"]|require\(\s*['"]node:child_process['"]|require\(\s*['"]child_process['"])"""
)
samples = {
"named import": "import { spawn } from 'node:child_process'",
"side-effect import": "import 'node:child_process'",
"dynamic import": "const cp = import('node:child_process')",
"require": "const cp = require('node:child_process')",
"bare child_process import": "import { spawn } from 'child_process'",
"bare side-effect import": "import 'child_process'",
"bare dynamic import": "const cp = import('child_process')",
}
print("--- pattern behavior ---")
for name, text in samples.items():
print(f"{name}: {'MATCH' if pattern.search(text) else 'MISS'}")
for path in root.rglob("*"):
if not path.is_file():
continue
all_source.append(path)
if path.suffix in extensions:
scanned.append(path)
if path.suffix in {".js", ".jsx"}:
js_like.append(path)
text = path.read_text(encoding="utf-8", errors="replace")
if "child_process" in text:
direct_js_like.append(path)
print("--- source counts ---")
print(f"src files: {len(all_source)}")
print(f"scanned .ts/.tsx files: {len(scanned)}")
print(f".js/.jsx files: {len(js_like)}")
print(f".js/.jsx files containing child_process text: {len(direct_js_like)}")
for path in direct_js_like[:20]:
print(path)
hypothetical = Path("src/example-production.ts")
text = "const cp = import('node:child_process')"
print("--- hypothetical production file ---")
print(f"extension scanned: {hypothetical.suffix in extensions}")
print(f"pattern matched: {bool(pattern.search(text))}")
print(f"would be an offender: {hypothetical.suffix in extensions and bool(pattern.search(text))}")
PYRepository: stablyai/orca
Length of output: 593
🏁 Script executed:
#!/bin/bash
set -eu
python3 - <<'PY'
from pathlib import Path
import re
root = Path("src")
extensions = {".ts", ".tsx"}
pattern = re.compile(
r"""(?:from\s+['"]node:child_process['"]|from\s+['"]child_process['"]|require\(\s*['"]node:child_process['"]|require\(\s*['"]child_process['"])"""
)
samples = {
"named import": "import { spawn } from 'node:child_process'",
"side-effect import": "import 'node:child_process'",
"dynamic import": "const cp = import('node:child_process')",
"require": "const cp = require('node:child_process')",
"bare side-effect import": "import 'child_process'",
"bare dynamic import": "const cp = import('child_process')",
}
print("--- pattern behavior ---")
for name, text in samples.items():
print(f"{name}: {'MATCH' if pattern.search(text) else 'MISS'}")
all_files = [p for p in root.rglob("*") if p.is_file()]
js_like = [p for p in all_files if p.suffix in {".js", ".jsx"}]
direct_js_like = [
p for p in js_like
if "child_process" in p.read_text(encoding="utf-8", errors="replace")
]
print("--- source counts ---")
print(f"src files: {len(all_files)}")
print(f"scanned .ts/.tsx files: {sum(p.suffix in extensions for p in all_files)}")
print(f".js/.jsx files: {len(js_like)}")
print(f".js/.jsx files containing child_process text: {len(direct_js_like)}")
for path in direct_js_like[:20]:
print(path)
text = "const cp = import('node:child_process')"
print("--- hypothetical production file ---")
print(f"extension scanned: {Path('src/example-production.ts').suffix in extensions}")
print(f"pattern matched: {bool(pattern.search(text))}")
PYRepository: stablyai/orca
Length of output: 532
Cover dynamic and side-effect child_process imports.
IMPORT_PATTERN misses import('node:child_process') and import 'node:child_process', so a new .ts or .tsx production importer can bypass the boundary. Cover these forms and scan .js/.jsx when supported. Add regression cases.
Source: Coding guidelines
| const collect = (chunks: Buffer[], chunk: Buffer, bytes: number): number => { | ||
| const remaining = maxOutputBytes - bytes | ||
| if (remaining <= 0) { | ||
| return bytes | ||
| } | ||
| chunks.push(chunk.length > remaining ? chunk.subarray(0, remaining) : chunk) | ||
| return bytes + chunk.length | ||
| } |
There was a problem hiding this comment.
🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win
Align the maxOutputBytes contract across the async and sync runners.
The doc comment on lines 38-39 states the process is killed beyond the cap. The async path does not kill it: collect truncates and the child keeps running and writing. The sync path passes the value as maxBuffer on line 223, so Node aborts the child and reports ENOBUFS, which line 226 rethrows. A caller that moves between runProcess and runProcessSync therefore changes failure mode from silent truncation to a thrown error.
Pick one behaviour and document it. Truncation also cuts at an arbitrary byte offset, so a split multi-byte UTF-8 sequence decodes as U+FFFD; use a StringDecoder if the truncated tail must stay valid.
🐛 Proposed fix: make the async path fail the same way
const collect = (chunks: Buffer[], chunk: Buffer, bytes: number): number => {
const remaining = maxOutputBytes - bytes
if (remaining <= 0) {
return bytes
}
chunks.push(chunk.length > remaining ? chunk.subarray(0, remaining) : chunk)
+ if (bytes + chunk.length > maxOutputBytes) {
+ outputOverflowed = true
+ terminate(child)
+ }
return bytes + chunk.length
}Then surface outputOverflowed on ProcessResult, or align the sync path to truncate instead of throwing.
🧰 Tools
🪛 ast-grep (0.45.1)
[warning] 5: Importing child_process exposes a command-execution surface; ensure any command/argument built from input is validated, and prefer execFile/spawn with an argument array over exec.
Context: import {
spawn as nodeSpawn,
spawnSync as nodeSpawnSync,
type ChildProcess,
type SpawnOptions as NodeSpawnOptions
} from 'node:child_process'
Note: [CWE-78] Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection').
(detect-child-process-typescript)
|
Validated on real Windows 11 (build 26200, Node 24.18) rather than only in the model-based unit tests: The 22 win32 cases are the ones that matter — they push each adversarial argument through a real |
runProcessSync inferred a timeout from signal === 'SIGTERM'. Measured: a real timeout sets error.code ETIMEDOUT and kills with SIGTERM, but so does anything else that terminates the child -- and those cases set no error at all. Reading the signal alone reports a process someone stopped on purpose as having timed out, which callers retry.
There was a problem hiding this comment.
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
src/shared/child-process/run-process.ts (1)
219-223: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick winMake the synchronous timeout terminal.
When a POSIX child handles
SIGTERM,spawnSynccan wait indefinitely aftertimeoutMs. SetkillSignaltoSIGKILLand add a POSIX regression test with a child that ignoresSIGTERM.Proposed fix
input: spec.input, timeout: spec.timeoutMs ?? DEFAULT_PROCESS_TIMEOUT_MS, + killSignal: 'SIGKILL', maxBuffer: spec.maxOutputBytes ?? DEFAULT_MAX_OUTPUT_BYTES,
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: fe2d166b-1778-412b-bb12-db7632a1b6db
📒 Files selected for processing (2)
src/shared/child-process/run-process.test.tssrc/shared/child-process/run-process.ts
Included review availability: Your plan provides up to 10 included reviews per hour; 8 remain after this review.
The allowlist and the adversarial argument corpus are read only by tests, so they were production modules in name only; they move to __fixtures__. pwsh.ts carried isTimeoutError() purely to reconcile two spellings of the same event -- execFileSync reports a timeout as ETIMEDOUT, the execFile callback as a SIGTERM kill with no code. runProcess reports one timedOut flag, so the helper and the reasoning behind it both go. Its sync probe also spawned without windowsHide, which flashes a console and steals foreground on every cold cache read.
Each one deletes a hand-rolled promise/timeout/kill wrapper and stops re-deciding console visibility for itself. Ratchet 170 -> 164. Two things this surfaced, both kept: runProcess now accepts string chunks as well as buffers. A stream someone called setEncoding on emits strings, and concatenating those as buffers throws inside a data handler -- where the rejection has nowhere to go and the caller simply hangs rather than failing. ProcessSpec keeps its AbortSignal. I had removed it as unused; the macOS PAM preflight passes one through from its own caller. ipc/app.ts is deliberately NOT migrated. Its probe spawns a three-stage pipeline detached so a timeout can reap the group with one negative-pid SIGKILL; runProcess kills only the root, which would orphan the plutil stages. Migrating it needs the chokepoint to own POSIX process-group termination first -- the same guarantee job objects give on Windows. Reverted and left on the ratchet.
Elegance passThe stack was +735 net production lines; it is now +451. Where that came from, and where it didn't: Test data was miscounted as production code (−227). The ratchet allowlist and the adversarial argument corpus are imported only by tests. They are now fixtures, which is also just what they are. Six more call sites migrated (−107). Each deletes a hand-rolled promise/timeout/kill wrapper:
That helper and the reasoning behind it are gone; Three defects the pass surfaced
One migration deliberately reverted
That is the most useful thing this pass found: the chokepoint has no POSIX process-group termination. It is the POSIX analogue of the job object in #15755, and it is what the next batch of migrations needs before they are safe. On net-negativeHonest arithmetic: the new shared capability is ~660 lines; migrations have paid back ~270. Reaching net-negative needs roughly 15–20 more migrations at the observed rate, and the ratchet guarantees they only go one way. I could get there today by deleting the identity/taskkill fallback (~170 prod + ~250 test), but that fallback is load-bearing on hosts where job assignment is refused, and trading it for a line count is the wrong trade. 30,199 tests green, |
There was a problem hiding this comment.
🧹 Nitpick comments (2)
src/shared/child-process/__fixtures__/windows-argument-corpus.ts (1)
1-12: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winCondense the new comments.
Keep one concise line for each non-obvious constraint.
src/shared/child-process/__fixtures__/windows-argument-corpus.ts#L1-L12: State only the corpus purpose.src/shared/child-process/__fixtures__/windows-argument-corpus.ts#L36-L39: State only that the environment makes expansion cases deterministic.src/shared/child-process/run-process.ts#L107-L113: State only that the sink accepts buffers and strings.src/shared/child-process/run-process.ts#L186-L188: State only that stdin closes to deliver EOF.As per coding guidelines, “Comments must be concise, non-obvious, and brief—prefer one line.”
Source: Coding guidelines
src/main/memory/collector.test.ts (1)
30-32: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueShorten this test comment.
Use one line for the mock rationale.
As per coding guidelines, “Comments must be concise, non-obvious, and brief—prefer one line.”
Proposed change
-// Why mock the chokepoint for the Windows sweep: maxBuffer, timeout and the -// hidden console are its contract now, so the assertions below are about which -// query runs, not how a process is started. +// Mock the chokepoint so Windows tests verify query specifications.Source: Coding guidelines
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 9f1493f3-d998-4096-bf72-52a017ae2f3c
📒 Files selected for processing (18)
src/main/emulator/serve-sim-execution.tssrc/main/local-worktree-filesystem.test.tssrc/main/local-worktree-filesystem.tssrc/main/memory/collector.test.tssrc/main/memory/host-memory.test.tssrc/main/memory/host-memory.tssrc/main/memory/windows-process-resource-collector.tssrc/main/providers/macos-tcc-login-shell.test.tssrc/main/providers/macos-tcc-login-shell.tssrc/main/pwsh.test.tssrc/main/pwsh.tssrc/shared/child-process/__fixtures__/child-process-import-allowlist.txtsrc/shared/child-process/__fixtures__/windows-argument-corpus.tssrc/shared/child-process/child-process-import-boundary.test.tssrc/shared/child-process/run-process.test.tssrc/shared/child-process/run-process.tssrc/shared/child-process/windows-command-line.test.tssrc/shared/child-process/windows-command-line.win32.test.ts
Included review availability: Your plan provides up to 10 included reviews per hour; 6 remain after this review.
Windows has no signals, so the same deliberate kill reports an exit code there and a signal on POSIX. What has to hold on both is that neither shape reads as a timeout. Caught by running the suite on Windows. (cherry picked from commit 0a6e990)
…kill close only fires once the child is actually gone, so a child that traps SIGTERM never emits it and the promise outlives its own deadline forever. That is the same wedge shape just fixed for the process table, and it is worse here: pwsh.ts and the snapshot reader both cache an in-flight probe, so one unkillable child hands every later caller the same dead promise. After the deadline it now escalates to SIGKILL and settles regardless, reporting timedOut with whatever output arrived. (cherry picked from commit 78ac169)
The grace escalation I added covered the timeout path and left abort on the old one, so an aborted caller with an unkillable child still waited forever -- the same defect, one path over. The macOS PAM preflight is a real caller that passes an AbortSignal. Both paths now share one stop-and-settle, and the result reports timedOut honestly: false when the caller aborted. (cherry picked from commit 7e9523a)
escapePercentForCmd ran as a post-pass over the quoted string, so it inserted a quote wherever a percent was -- including straight after a backslash. CommandLineToArgvW reads backslash-quote as an escaped quote, so C:\Users\%USERNAME%\x arrived corrupted. That is about as common as Windows paths get, and my 20-case corpus had no backslash-before-percent entry to catch it. Percent handling is now part of the quoting loop, where the backslash run is known and can be doubled before the inserted quote. Two corpus cases cover the shape. The program path gets the same treatment. It was quoted but not percent-escaped, so a launcher under C:\Users\%USERNAME%\ had its own path expanded on the cmd hop. quoteWindowsArgument no longer takes a boolean. Passing it to values.map() handed map's index in as the flag -- which is how the first version of this fix was written, and the corpus test caught it. Separately: an AbortSignal that was already aborted never fires the event, so runProcess ran the child to its full timeout for a caller who had already given up. (cherry picked from commit f7e2e56)
|
Merged to Closed by this stack: #10488, #15209, #9045, #10475, #10897, #9195, #10415. Commented, not closed — partially addressed or needing a reporter re-test: #14543, #11771, #15036, #10686, #10087, #8275, #10150, #10358, #10857. Withdrawn: #15549 — I claimed it early and hardware testing disproved it. Job liveness reports Windows CI now gates the argv encoder against real |
* feat(process): add the Windows-correct child-process chokepoint Six decisions have to be made every time Orca starts a child process -- console visibility, argument quoting, .cmd interpretation, binary resolution, timeout policy, and how the tree is later terminated. POSIX forgives all six. Windows punishes each differently, and made per-call site across 172 files they were right in some and wrong in others. runProcess/spawnProcess make them once: - windowsHide unconditionally, shell:false unconditionally (shell:true concatenates argv unescaped and silently disables windowsHide) - .cmd/.bat routed through cmd.exe /d /v:off /s /c with a verbatim line, because Node refuses to spawn them otherwise (EINVAL) The encoding was derived by measurement on Windows 11, not from the docs. An embedded quote is written "" rather than \" so cmd's naive quote count stays even -- with \" the parity flips and every later & | < > on the line stops being data. Measured before the fix, argv ["a b", 'c"d', "e%F%g", "h&i", "j^k"] arrived as ["a b", 'c"d', "e^%F^%g", "h"]: the & truncated the argument and ran its remainder as a command. Each % is broken out of the quoted run as "^%" because %VAR% expands even inside quotes. The import-boundary test is a ratchet seeded at today's 172 files; it only shrinks. * fix(process): route the console-flashing spawn sites through the chokepoint The ssh -G config probe fires on every connect and reconnect, and ssh.exe is console-subsystem, so a GUI-subsystem parent gets a fresh visible conhost that takes foreground -- keystrokes typed into an Orca terminal at that moment go into the black box (stablyai#10488, stablyai#14543). Same for the ProxyJump tunnel, the ProxyCommand cmd.exe wrapper, the font enumeration and the DPAPI cookie decrypt. Also stops spawning powershell by bare name: PATH under Electron is not the user's, so where policy has pruned the System32 entry the spawn fails and the font picker silently reports five hardcoded families rather than an error (stablyai#11771). Deletes system-fonts' 40-line bespoke execFileText -- timeout, output cap and kill are the chokepoint's job now. Adds runProcessSync so the sync callers have a compliant path; without one the ratchet could never reach zero. The three suites that mocked child_process directly now mock runProcess, which is the point: how a process gets started is no longer each module's business. Ratchet 173 -> 170. * fix(process): do not report a deliberately killed child as timed out runProcessSync inferred a timeout from signal === 'SIGTERM'. Measured: a real timeout sets error.code ETIMEDOUT and kills with SIGTERM, but so does anything else that terminates the child -- and those cases set no error at all. Reading the signal alone reports a process someone stopped on purpose as having timed out, which callers retry. * refactor(process): hold the ratchet as data and migrate the pwsh probes The allowlist and the adversarial argument corpus are read only by tests, so they were production modules in name only; they move to __fixtures__. pwsh.ts carried isTimeoutError() purely to reconcile two spellings of the same event -- execFileSync reports a timeout as ETIMEDOUT, the execFile callback as a SIGTERM kill with no code. runProcess reports one timedOut flag, so the helper and the reasoning behind it both go. Its sync probe also spawned without windowsHide, which flashes a console and steals foreground on every cold cache read. * refactor(process): migrate five more spawn sites onto the chokepoint Each one deletes a hand-rolled promise/timeout/kill wrapper and stops re-deciding console visibility for itself. Ratchet 170 -> 164. Two things this surfaced, both kept: runProcess now accepts string chunks as well as buffers. A stream someone called setEncoding on emits strings, and concatenating those as buffers throws inside a data handler -- where the rejection has nowhere to go and the caller simply hangs rather than failing. ProcessSpec keeps its AbortSignal. I had removed it as unused; the macOS PAM preflight passes one through from its own caller. ipc/app.ts is deliberately NOT migrated. Its probe spawns a three-stage pipeline detached so a timeout can reap the group with one negative-pid SIGKILL; runProcess kills only the root, which would orphan the plutil stages. Migrating it needs the chokepoint to own POSIX process-group termination first -- the same guarantee job objects give on Windows. Reverted and left on the ratchet. * test(process): do not assert a POSIX signal on Windows Windows has no signals, so the same deliberate kill reports an exit code there and a signal on POSIX. What has to hold on both is that neither shape reads as a timeout. Caught by running the suite on Windows. (cherry picked from commit 0a6e990) * fix(process): settle a timed-out run even when the child ignores the kill close only fires once the child is actually gone, so a child that traps SIGTERM never emits it and the promise outlives its own deadline forever. That is the same wedge shape just fixed for the process table, and it is worse here: pwsh.ts and the snapshot reader both cache an in-flight probe, so one unkillable child hands every later caller the same dead promise. After the deadline it now escalates to SIGKILL and settles regardless, reporting timedOut with whatever output arrived. (cherry picked from commit 78ac169) * fix(process): escalate an aborted child too, not just a timed-out one The grace escalation I added covered the timeout path and left abort on the old one, so an aborted caller with an unkillable child still waited forever -- the same defect, one path over. The macOS PAM preflight is a real caller that passes an AbortSignal. Both paths now share one stop-and-settle, and the result reports timedOut honestly: false when the caller aborted. (cherry picked from commit 7e9523a) * fix(windows): stop percent escaping from forging an escaped quote escapePercentForCmd ran as a post-pass over the quoted string, so it inserted a quote wherever a percent was -- including straight after a backslash. CommandLineToArgvW reads backslash-quote as an escaped quote, so C:\Users\%USERNAME%\x arrived corrupted. That is about as common as Windows paths get, and my 20-case corpus had no backslash-before-percent entry to catch it. Percent handling is now part of the quoting loop, where the backslash run is known and can be doubled before the inserted quote. Two corpus cases cover the shape. The program path gets the same treatment. It was quoted but not percent-escaped, so a launcher under C:\Users\%USERNAME%\ had its own path expanded on the cmd hop. quoteWindowsArgument no longer takes a boolean. Passing it to values.map() handed map's index in as the flag -- which is how the first version of this fix was written, and the corpus test caught it. Separately: an AbortSignal that was already aborted never fires the event, so runProcess ran the child to its full timeout for a caller who had already given up. (cherry picked from commit f7e2e56) (cherry picked from commit b7e79b7)
v1.4.190 makes runWslProcess the one chokepoint for wsl.exe (stablyai#15903, stablyai#15923) and runProcess the one chokepoint for child processes (stablyai#15746), and both are now ratcheted. The fork's live-plugin-marketplace WSL source still called execFile('wsl.exe', buildWslExecArgs(...)) directly, which broke five checks from one cause: - child-process-import-boundary: a direct node:child_process import, and the offender count 153 over its 152 ceiling - wsl-invocation-boundary (unit and package (windows)): a direct wsl.exe spawn - skill-discovery-wsl-plugins: upstream's test mocks runWslProcess and expects two calls; the fork's execFile bypassed the mock, so the scan consumed the metadata frames and parseWslSkillDiscoveryOutput rejected record kind F - the feature's own WSL tests, which mocked child_process Adopt the sibling reader's migrated shape (loginPath 'none', shell 'bash', maxOutputBytes, throw on non-zero or timeout) — the payload is that reader's and stays bash. The runner takes the script unencoded, so the test's base64 decode is gone; the --exec assertion is replaced by one on the spec the fork now owns, since --exec and payload transport moved into the runner.
* feat(process): add the Windows-correct child-process chokepoint Six decisions have to be made every time Orca starts a child process -- console visibility, argument quoting, .cmd interpretation, binary resolution, timeout policy, and how the tree is later terminated. POSIX forgives all six. Windows punishes each differently, and made per-call site across 172 files they were right in some and wrong in others. runProcess/spawnProcess make them once: - windowsHide unconditionally, shell:false unconditionally (shell:true concatenates argv unescaped and silently disables windowsHide) - .cmd/.bat routed through cmd.exe /d /v:off /s /c with a verbatim line, because Node refuses to spawn them otherwise (EINVAL) The encoding was derived by measurement on Windows 11, not from the docs. An embedded quote is written "" rather than \" so cmd's naive quote count stays even -- with \" the parity flips and every later & | < > on the line stops being data. Measured before the fix, argv ["a b", 'c"d', "e%F%g", "h&i", "j^k"] arrived as ["a b", 'c"d', "e^%F^%g", "h"]: the & truncated the argument and ran its remainder as a command. Each % is broken out of the quoted run as "^%" because %VAR% expands even inside quotes. The import-boundary test is a ratchet seeded at today's 172 files; it only shrinks. * fix(process): route the console-flashing spawn sites through the chokepoint The ssh -G config probe fires on every connect and reconnect, and ssh.exe is console-subsystem, so a GUI-subsystem parent gets a fresh visible conhost that takes foreground -- keystrokes typed into an Orca terminal at that moment go into the black box (stablyai#10488, stablyai#14543). Same for the ProxyJump tunnel, the ProxyCommand cmd.exe wrapper, the font enumeration and the DPAPI cookie decrypt. Also stops spawning powershell by bare name: PATH under Electron is not the user's, so where policy has pruned the System32 entry the spawn fails and the font picker silently reports five hardcoded families rather than an error (stablyai#11771). Deletes system-fonts' 40-line bespoke execFileText -- timeout, output cap and kill are the chokepoint's job now. Adds runProcessSync so the sync callers have a compliant path; without one the ratchet could never reach zero. The three suites that mocked child_process directly now mock runProcess, which is the point: how a process gets started is no longer each module's business. Ratchet 173 -> 170. * fix(process): do not report a deliberately killed child as timed out runProcessSync inferred a timeout from signal === 'SIGTERM'. Measured: a real timeout sets error.code ETIMEDOUT and kills with SIGTERM, but so does anything else that terminates the child -- and those cases set no error at all. Reading the signal alone reports a process someone stopped on purpose as having timed out, which callers retry. * refactor(process): hold the ratchet as data and migrate the pwsh probes The allowlist and the adversarial argument corpus are read only by tests, so they were production modules in name only; they move to __fixtures__. pwsh.ts carried isTimeoutError() purely to reconcile two spellings of the same event -- execFileSync reports a timeout as ETIMEDOUT, the execFile callback as a SIGTERM kill with no code. runProcess reports one timedOut flag, so the helper and the reasoning behind it both go. Its sync probe also spawned without windowsHide, which flashes a console and steals foreground on every cold cache read. * refactor(process): migrate five more spawn sites onto the chokepoint Each one deletes a hand-rolled promise/timeout/kill wrapper and stops re-deciding console visibility for itself. Ratchet 170 -> 164. Two things this surfaced, both kept: runProcess now accepts string chunks as well as buffers. A stream someone called setEncoding on emits strings, and concatenating those as buffers throws inside a data handler -- where the rejection has nowhere to go and the caller simply hangs rather than failing. ProcessSpec keeps its AbortSignal. I had removed it as unused; the macOS PAM preflight passes one through from its own caller. ipc/app.ts is deliberately NOT migrated. Its probe spawns a three-stage pipeline detached so a timeout can reap the group with one negative-pid SIGKILL; runProcess kills only the root, which would orphan the plutil stages. Migrating it needs the chokepoint to own POSIX process-group termination first -- the same guarantee job objects give on Windows. Reverted and left on the ratchet. * test(process): do not assert a POSIX signal on Windows Windows has no signals, so the same deliberate kill reports an exit code there and a signal on POSIX. What has to hold on both is that neither shape reads as a timeout. Caught by running the suite on Windows. (cherry picked from commit 0a6e990) * fix(process): settle a timed-out run even when the child ignores the kill close only fires once the child is actually gone, so a child that traps SIGTERM never emits it and the promise outlives its own deadline forever. That is the same wedge shape just fixed for the process table, and it is worse here: pwsh.ts and the snapshot reader both cache an in-flight probe, so one unkillable child hands every later caller the same dead promise. After the deadline it now escalates to SIGKILL and settles regardless, reporting timedOut with whatever output arrived. (cherry picked from commit 78ac169) * fix(process): escalate an aborted child too, not just a timed-out one The grace escalation I added covered the timeout path and left abort on the old one, so an aborted caller with an unkillable child still waited forever -- the same defect, one path over. The macOS PAM preflight is a real caller that passes an AbortSignal. Both paths now share one stop-and-settle, and the result reports timedOut honestly: false when the caller aborted. (cherry picked from commit 7e9523a) * fix(windows): stop percent escaping from forging an escaped quote escapePercentForCmd ran as a post-pass over the quoted string, so it inserted a quote wherever a percent was -- including straight after a backslash. CommandLineToArgvW reads backslash-quote as an escaped quote, so C:\Users\%USERNAME%\x arrived corrupted. That is about as common as Windows paths get, and my 20-case corpus had no backslash-before-percent entry to catch it. Percent handling is now part of the quoting loop, where the backslash run is known and can be doubled before the inserted quote. Two corpus cases cover the shape. The program path gets the same treatment. It was quoted but not percent-escaped, so a launcher under C:\Users\%USERNAME%\ had its own path expanded on the cmd hop. quoteWindowsArgument no longer takes a boolean. Passing it to values.map() handed map's index in as the flag -- which is how the first version of this fix was written, and the corpus test caught it. Separately: an AbortSignal that was already aborted never fires the event, so runProcess ran the child to its full timeout for a caller who had already given up. (cherry picked from commit f7e2e56)
The child_process chokepoint landed in stablyai#15746 after this branch was written; rebasing onto it made the direct node:child_process import a ratchet violation. runProcess also encapsulates the Windows .cmd argument encoding this file was doing by hand, so getSpawnArgsForWindows is no longer needed here — only the absolute-path resolution is, since runProcess spawns without a shell. runProcess reports failure in its result rather than throwing, so non-zero exits and timeouts are converted to a thrown error to preserve the token cache's failure-cooldown behavior. Claude-Session: https://claude.ai/code/session_01CR2s8B3hk7fUHZTe58zdzy
* feat(process): add the Windows-correct child-process chokepoint Six decisions have to be made every time Orca starts a child process -- console visibility, argument quoting, .cmd interpretation, binary resolution, timeout policy, and how the tree is later terminated. POSIX forgives all six. Windows punishes each differently, and made per-call site across 172 files they were right in some and wrong in others. runProcess/spawnProcess make them once: - windowsHide unconditionally, shell:false unconditionally (shell:true concatenates argv unescaped and silently disables windowsHide) - .cmd/.bat routed through cmd.exe /d /v:off /s /c with a verbatim line, because Node refuses to spawn them otherwise (EINVAL) The encoding was derived by measurement on Windows 11, not from the docs. An embedded quote is written "" rather than \" so cmd's naive quote count stays even -- with \" the parity flips and every later & | < > on the line stops being data. Measured before the fix, argv ["a b", 'c"d', "e%F%g", "h&i", "j^k"] arrived as ["a b", 'c"d', "e^%F^%g", "h"]: the & truncated the argument and ran its remainder as a command. Each % is broken out of the quoted run as "^%" because %VAR% expands even inside quotes. The import-boundary test is a ratchet seeded at today's 172 files; it only shrinks. * fix(process): route the console-flashing spawn sites through the chokepoint The ssh -G config probe fires on every connect and reconnect, and ssh.exe is console-subsystem, so a GUI-subsystem parent gets a fresh visible conhost that takes foreground -- keystrokes typed into an Orca terminal at that moment go into the black box (stablyai#10488, stablyai#14543). Same for the ProxyJump tunnel, the ProxyCommand cmd.exe wrapper, the font enumeration and the DPAPI cookie decrypt. Also stops spawning powershell by bare name: PATH under Electron is not the user's, so where policy has pruned the System32 entry the spawn fails and the font picker silently reports five hardcoded families rather than an error (stablyai#11771). Deletes system-fonts' 40-line bespoke execFileText -- timeout, output cap and kill are the chokepoint's job now. Adds runProcessSync so the sync callers have a compliant path; without one the ratchet could never reach zero. The three suites that mocked child_process directly now mock runProcess, which is the point: how a process gets started is no longer each module's business. Ratchet 173 -> 170. * fix(process): do not report a deliberately killed child as timed out runProcessSync inferred a timeout from signal === 'SIGTERM'. Measured: a real timeout sets error.code ETIMEDOUT and kills with SIGTERM, but so does anything else that terminates the child -- and those cases set no error at all. Reading the signal alone reports a process someone stopped on purpose as having timed out, which callers retry. * refactor(process): hold the ratchet as data and migrate the pwsh probes The allowlist and the adversarial argument corpus are read only by tests, so they were production modules in name only; they move to __fixtures__. pwsh.ts carried isTimeoutError() purely to reconcile two spellings of the same event -- execFileSync reports a timeout as ETIMEDOUT, the execFile callback as a SIGTERM kill with no code. runProcess reports one timedOut flag, so the helper and the reasoning behind it both go. Its sync probe also spawned without windowsHide, which flashes a console and steals foreground on every cold cache read. * refactor(process): migrate five more spawn sites onto the chokepoint Each one deletes a hand-rolled promise/timeout/kill wrapper and stops re-deciding console visibility for itself. Ratchet 170 -> 164. Two things this surfaced, both kept: runProcess now accepts string chunks as well as buffers. A stream someone called setEncoding on emits strings, and concatenating those as buffers throws inside a data handler -- where the rejection has nowhere to go and the caller simply hangs rather than failing. ProcessSpec keeps its AbortSignal. I had removed it as unused; the macOS PAM preflight passes one through from its own caller. ipc/app.ts is deliberately NOT migrated. Its probe spawns a three-stage pipeline detached so a timeout can reap the group with one negative-pid SIGKILL; runProcess kills only the root, which would orphan the plutil stages. Migrating it needs the chokepoint to own POSIX process-group termination first -- the same guarantee job objects give on Windows. Reverted and left on the ratchet. * test(process): do not assert a POSIX signal on Windows Windows has no signals, so the same deliberate kill reports an exit code there and a signal on POSIX. What has to hold on both is that neither shape reads as a timeout. Caught by running the suite on Windows. (cherry picked from commit 0a6e990) * fix(process): settle a timed-out run even when the child ignores the kill close only fires once the child is actually gone, so a child that traps SIGTERM never emits it and the promise outlives its own deadline forever. That is the same wedge shape just fixed for the process table, and it is worse here: pwsh.ts and the snapshot reader both cache an in-flight probe, so one unkillable child hands every later caller the same dead promise. After the deadline it now escalates to SIGKILL and settles regardless, reporting timedOut with whatever output arrived. (cherry picked from commit 78ac169) * fix(process): escalate an aborted child too, not just a timed-out one The grace escalation I added covered the timeout path and left abort on the old one, so an aborted caller with an unkillable child still waited forever -- the same defect, one path over. The macOS PAM preflight is a real caller that passes an AbortSignal. Both paths now share one stop-and-settle, and the result reports timedOut honestly: false when the caller aborted. (cherry picked from commit 7e9523a) * fix(windows): stop percent escaping from forging an escaped quote escapePercentForCmd ran as a post-pass over the quoted string, so it inserted a quote wherever a percent was -- including straight after a backslash. CommandLineToArgvW reads backslash-quote as an escaped quote, so C:\Users\%USERNAME%\x arrived corrupted. That is about as common as Windows paths get, and my 20-case corpus had no backslash-before-percent entry to catch it. Percent handling is now part of the quoting loop, where the backslash run is known and can be doubled before the inserted quote. Two corpus cases cover the shape. The program path gets the same treatment. It was quoted but not percent-escaped, so a launcher under C:\Users\%USERNAME%\ had its own path expanded on the cmd hop. quoteWindowsArgument no longer takes a boolean. Passing it to values.map() handed map's index in as the flag -- which is how the first version of this fix was written, and the corpus test caught it. Separately: an AbortSignal that was already aborted never fires the event, so runProcess ran the child to its full timeout for a caller who had already given up. (cherry picked from commit f7e2e56)
Why
There is no one place in Orca where "run a program on Windows" is defined. 179
child_processcalls across 109 files each independently re-decide: hide the console or not, how to quote forcmd.exe, whether the target needscmd.exeat all, how to resolve the binary, what timeout to use. POSIX forgives all six. Windows punishes each differently, so the same gap reaches users as several unrelated-looking bugs.This PR adds the chokepoint and migrates the sites where the gap is most visible.
What the measurements showed
I derived the Windows argument encoding on a real Windows 11 box rather than from documentation, and the results changed the design:
spawn('foo.cmd', args, {shell:false})EINVAL— Node blocks it outright (CVE-2024-27980 mitigation)spawn('foo.cmd', args, {shell:true})cmd.exe /d /v:off /s /c+ the encoding hereshell: trueis worse than mangling. Senta&b, the child received"a"andbran as a command. That is argument injection, and it is the shape agent prompts take (Fix "src/a b.ts" & run tests 100%).shell: truealso silently makeswindowsHidea no-op, which is the console flash in #14543.The non-obvious part: the usual
\"escaping is wrong here.CommandLineToArgvWunderstands\", butcmd.execounts"naively — so\"flips cmd's quote parity and every later&|<>on the line stops being data. Writing""instead keeps both parsers happy. Each%is additionally broken out of the quoted run as"^%", because%VAR%expands even inside quotes (x%ORCATEST%yarrived asxBOOMy).Measured before/after on the composed case:
Node's own quoting is already correct for real
.exetargets (19/19), so the chokepoint only special-cases.cmd/.bat. That keeps the surface small.What changed
src/shared/child-process/—runProcess,runProcessSync,spawnProcess.windowsHideunconditionally,shell: falseunconditionally, one timeout policy,.cmdrouted through a verbatimcmd.exeline.resolveSpawnis pure and exported, so the Windows branch is testable from macOS/Linux. These decisions must not be observable only on the platform that breaks.ssh -Gprobe, the ProxyJump tunnel, the ProxyCommand wrapper, font enumeration, the DPAPI cookie decrypt.system-fonts' 40-line bespokeexecFileText.Tests
CommandLineToArgvWand against cmd's quote-parity rule — not against itself.windows-command-line.win32.test.tsruns the same corpus through a real.cmdshim, with%F%/%VAR%set as live variables so the percent cases cannot pass by accident. Includes an explicit assertion that the tail of an&argument does not execute.child_processdirectly now mockrunProcess. That is the point: how a process starts is no longer each module's business.child-process-import-boundary.test.tsis a ratchet seeded at today's count, currently 173 → 170. It only shrinks. It also fails on a stale entry, so a migrated file cannot stay listed and hide the next regression, and it asserts it scanned enough files so it can never go vacuous.Issues
Closes #10488. Addresses the
windowsHidehalf of #14543 and the bare-name half of #11771. Lays the groundwork for #8793, #11374, #6694 (the.cmdargv encoding they need is here; their call sites migrate next).Follow-ups
HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Fontsvia the registry dependency already inpackage.jsonwould remove that; filed separately since deriving families from per-style registry names is a behaviour change.