Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(ios-simulator): 让 shell 守卫匹配它声明的威胁模型,停止误拒普通命令 (#2414)
JiangJiahaoffcf9c3c7266
diff --git a/apps/desktop/src/main/maker-host/__tests__/shellCommandPolicy.test.ts b/apps/desktop/src/main/maker-host/__tests__/shellCommandPolicy.test.tsindex 4cd5502b0a..8609d65373 100644--- a/apps/desktop/src/main/maker-host/__tests__/shellCommandPolicy.test.ts+++ b/apps/desktop/src/main/maker-host/__tests__/shellCommandPolicy.test.ts@@ -39,9 +39,11 @@ describeMac('embedded iOS Simulator shell policy', () => {expect(getDesktopShellCommandPolicy(command)).toMatchObject({ decision: 'deny' });});+ // Documentation puts these prefixes in front of a recipe, so the recipe is+ // still spelled out and still reachable by reading the command word.it.each(['exec /usr/bin/xcrun simctl shutdown DEVICE',- 'command -p xcrun simctl boot DEVICE',+ 'command xcrun simctl boot DEVICE','builtin exec xcrun simctl install DEVICE /tmp/App.app','nohup -- xcrun simctl launch DEVICE com.example.app','env FOO=1 /usr/bin/xcrun simctl shutdown DEVICE',@@ -54,20 +56,522 @@ describeMac('embedded iOS Simulator shell policy', () => {"eval 'xcrun simctl erase DEVICE'",'echo "$(xcrun simctl shutdown DEVICE)"','echo >(xcrun simctl shutdown DEVICE)',- "env -S 'xcrun simctl shutdown DEVICE'",'CMD=xcrun\\ simctl\\ shutdown\\ DEVICE; eval "$CMD"','CMD=xcrun\\ simctl\\ shutdown\\ DEVICE; sh -c "$CMD"','CMD=xcrun\\ simctl\\ shutdown\\ DEVICE; $CMD',- 'printf "xcrun simctl shutdown DEVICE\\n" | sh','time xcrun simctl shutdown DEVICE',- 'time -p xcrun simctl boot DEVICE',- 'f(){ xcrun simctl shutdown DEVICE;}; f',- 'f() ( xcrun simctl shutdown DEVICE ); f',`function f () ( printf '%s' "$(date)"; /usr/bin/open -a Simulator ); f`,'/usr/bin/xcrun \\\n simctl shutdown DEVICE','/usr/bin/nice /usr/bin/xcrun simctl erase DEVICE',+ '/usr/bin/arch /usr/bin/xcrun simctl boot DEVICE',+ '/usr/bin/caffeinate /usr/bin/xcrun simctl shutdown DEVICE',+ 'xargs /usr/bin/xcrun simctl shutdown DEVICE',+ 'timeout 30 xcrun simctl boot DEVICE',+ 'timeout 1.5s gtimeout 2m xcrun simctl erase DEVICE',+ // A shell option that takes a value must not be read as the script operand.+ // Unlike a prefix, a shell's `-c` scan can only ever miss when it reads an+ // option wrongly, so the two value-taking options stay modelled here.+ "bash -o pipefail -c 'xcrun simctl shutdown DEVICE'",+ "bash -O extglob -c 'xcrun simctl shutdown DEVICE'",+ "bash +O extglob -c 'xcrun simctl boot DEVICE'",+ "zsh -o extendedglob -c 'xcrun simctl shutdown DEVICE'",+ // A stored recipe counts once something runs the variable that holds it.+ `CMD='xcrun simctl shutdown DEVICE'; eval "\${CMD}"`,+ `CMD='xcrun simctl boot DEVICE'; bash -lc "$CMD"`,+ `CMD='xcrun simctl boot DEVICE'; echo start; eval "$CMD"`,+ // An assignment builtin stores a recipe just like a bare `NAME=value`.+ `export CMD='xcrun simctl shutdown DEVICE'; eval "$CMD"`,+ `readonly CMD='xcrun simctl boot DEVICE'; eval "$CMD"`,+ `declare CMD='open -a Simulator'; eval "$CMD"`,+ `typeset CMD='xcrun simctl erase DEVICE'; eval "$CMD"`,+ `export -p CMD='xcrun simctl boot DEVICE'; eval "$CMD"`,+ // Heredoc reduction must not let a fake marker in a comment swallow a real+ // following command, and CRLF delimiters must end the data region correctly.+ `echo hi # <<'EOF'\nxcrun simctl shutdown DEVICE`,+ `cat <<'EOF'\r\ntext\r\nEOF\r\nxcrun simctl shutdown DEVICE`,+ `cat <<$'EOF' >/dev/null\ntext\nEOF\nxcrun simctl shutdown DEVICE`,+ `cat <<$"EOF" >/dev/null\ntext\nEOF\nxcrun simctl shutdown DEVICE`,+ // Arithmetic left-shift uses the same `<<` spelling as a heredoc opener;+ // it must not make the following command look like a body for delimiter 2.+ `echo $((1 << 2))\nxcrun simctl shutdown DEVICE`,+ `(( 1 << 2 ))\nxcrun simctl shutdown DEVICE`,+ `echo $[1 << 2]\nxcrun simctl shutdown DEVICE`,+ ])('denies a literal recipe behind a documentation-style prefix: %s', (command) => {+ expect(getDesktopShellCommandPolicy(command)).toMatchObject({ decision: 'deny' });+ });++ // ── An option on the prefix ends the peel ──────────────────────────────────+ //+ // Each command below was denied while the policy carried a per-prefix table of+ // which options consume the following token. Maintaining that table meant+ // encoding two things about every CLI: its option arity, and whether the+ // operands are executed at all. Getting either wrong denies ordinary work, and+ // both kept being wrong — `bash -O`, then `command -v`, then `sudo -l`, one per+ // review round. Stopping at the first option can only miss, so the table is+ // gone and these forms are missed on purpose.+ //+ // Documentation spells a recipe as `sudo xcrun simctl boot …`, not+ // `sudo -u me xcrun simctl boot …`; the plain spelling of every prefix above is+ // still covered. All of these were also allowed before the embedded simulator+ // existed, so this restores that behaviour rather than loosening past it.+ it.each([+ 'command -p xcrun simctl boot DEVICE',+ 'time -p xcrun simctl boot DEVICE',+ 'env -u FOO xcrun simctl shutdown DEVICE',+ 'env --unset=FOO xcrun simctl shutdown DEVICE',+ 'env -C /tmp xcrun simctl shutdown DEVICE',+ 'sudo -u me xcrun simctl shutdown DEVICE',+ 'sudo --user=me xcrun simctl boot DEVICE',+ 'sudo -g staff xcrun simctl shutdown DEVICE',+ 'nice -n 5 xcrun simctl shutdown DEVICE',+ 'timeout -k 5 30 xcrun simctl shutdown DEVICE',+ 'xargs -n 1 xcrun simctl shutdown DEVICE',+ 'xargs -I{} xcrun simctl boot {}',+ 'arch -arch arm64 xcrun simctl shutdown DEVICE','/usr/bin/arch -arm64 /usr/bin/xcrun simctl boot DEVICE',+ 'caffeinate -t 60 xcrun simctl shutdown DEVICE','/usr/bin/caffeinate -i /usr/bin/xcrun simctl shutdown DEVICE',+ 'exec -a label xcrun simctl shutdown DEVICE',+ 'exec -a label /usr/bin/xcrun simctl boot DEVICE',+ 'exec -cl -a label xcrun simctl erase DEVICE',+ ])('no longer denies a recipe behind an option-bearing prefix: %s', (command) => {+ expect(getDesktopShellCommandPolicy(command)).toBeUndefined();+ });++ // A stored recipe is only a recipe once something runs it. Classifying every+ // assignment denied commands that print or write the string and execute+ // nothing — and printing a command is exactly what a script does while+ // explaining itself.+ it.each([+ `CMD='xcrun simctl shutdown DEVICE'; printf '%s\\n' "$CMD"`,+ `CMD='xcrun simctl boot DEVICE'; echo "$CMD"`,+ `CMD='open -a Simulator'; echo "$CMD" > /tmp/note.txt`,+ `export CMD='xcrun simctl erase DEVICE'; echo "$CMD"`,+ `CMD='xcrun simctl boot DEVICE'; echo done`,+ `CMD='xcrun simctl boot DEVICE'`,+ `readonly DOC='run xcrun simctl boot DEVICE to start'; printf '%s' "$DOC"`,+ // A different name reaches the execution site, so this value never runs.+ `CMD='xcrun simctl boot DEVICE'; eval "$OTHER"`,+ // The execution point sees the latest value, not the complete assignment+ // history. The stored recipe was replaced before anything ran it.+ `CMD='xcrun simctl shutdown DEVICE'; CMD='echo safe'; eval "$CMD"`,+ `CMD='xcrun simctl shutdown DEVICE'; CMD='echo safe'; eval "$CMD" 2>&1`,+ `CMD='xcrun simctl shutdown DEVICE'; echo if; CMD='echo safe'; eval "$CMD"`,+ `CMD='xcrun simctl shutdown DEVICE' && true; CMD='echo safe'; eval "$CMD"`,+ `CMD='xcrun simctl shutdown DEVICE'+CMD='echo safe'+eval "$CMD"`,+ // A lone background separator is complete before the newline, so the next+ // assignment is unconditional in the parent shell and replaces the value.+ `CMD='xcrun simctl shutdown DEVICE'; false &\nCMD='echo safe'; eval "$CMD"`,+ // A command-scoped assignment shadows the exported parent value only for+ // that child command.+ `CMD='xcrun simctl shutdown DEVICE'; CMD='echo safe' sh -c '$CMD'`,+ ])('allows a stored recipe that nothing executes: %s', (command) => {+ expect(getDesktopShellCommandPolicy(command)).toBeUndefined();+ });++ it.each([+ `CMD='xcrun simctl shutdown DEVICE'; eval "$CMD"; CMD='echo safe'`,+ `CMD='echo safe'; CMD='xcrun simctl shutdown DEVICE'; eval "$CMD"`,+ `CMD='xcrun simctl shutdown DEVICE'; OTHER='echo safe'; eval "$CMD"`,+ // An assignment attached to another command only changes that command's+ // environment; it must not replace the shell-scoped value used by eval.+ `CMD='xcrun simctl shutdown DEVICE'; CMD='echo safe' /usr/bin/true; eval "$CMD"`,+ `CMD='echo safe'; CMD='xcrun simctl shutdown DEVICE' sh -c '$CMD'`,+ // The later text is not a guaranteed replacement when control flow can skip+ // it or keep it inside a child scope, so the earlier value stays possible.+ `CMD='xcrun simctl shutdown DEVICE'; false && CMD='echo safe'; eval "$CMD"`,+ `CMD='xcrun simctl shutdown DEVICE'; false &&\nCMD='echo safe'; eval "$CMD"`,+ `CMD='xcrun simctl shutdown DEVICE'; true ||\nCMD='echo safe'; eval "$CMD"`,+ `CMD='xcrun simctl shutdown DEVICE'; printf ignored |\nCMD='echo safe'; eval "$CMD"`,+ // A comment's separators and assignments are not shell syntax. Quoted+ // hashes remain ordinary data and must not disable comment scanning.+ `CMD='xcrun simctl shutdown DEVICE'; # note; CMD='echo safe'\neval "$CMD"`,+ `CMD='xcrun simctl shutdown DEVICE'; echo "# not a comment"; eval "$CMD"`,+ // Assignments in a pipeline or background segment run in a child shell;+ // they cannot replace the parent value consumed by the later eval.+ `CMD='xcrun simctl shutdown DEVICE'; CMD='echo safe' & eval "$CMD"`,+ `CMD='xcrun simctl shutdown DEVICE'; CMD='echo safe' | /usr/bin/cat; eval "$CMD"`,+ `CMD='xcrun simctl shutdown DEVICE'; (CMD='echo safe'); eval "$CMD"`,+ `CMD='xcrun simctl shutdown DEVICE'; if false; then CMD='echo safe'; fi; eval "$CMD"`,+ // `local` fails outside a function, and function bodies are intentionally+ // outside this literal-recipe parser. It cannot prove a top-level override.+ `CMD='xcrun simctl shutdown DEVICE'; local CMD='echo safe'; eval "$CMD"`,+ ])('denies the current stored recipe at its execution point: %s', (command) => {+ expect(getDesktopShellCommandPolicy(command)).toMatchObject({ decision: 'deny' });+ });++ // A recipe pasted into an interpreter one-liner is still literal text.+ it.each([+ `python3 -c 'import subprocess; subprocess.run(["/usr/bin/xcrun", "simctl", "shutdown", "DEVICE"])'`,+ `node -e 'require("node:child_process").execFileSync("xcrun", ["simctl", "erase", "DEVICE"])'`,+ `ruby -e 'system("xcrun simctl boot DEVICE")'`,+ `perl -e 'system("simctl shutdown DEVICE")'`,+ `env FOO=1 python3.12 -c 'import os; os.system("xcrun simctl install DEVICE /tmp/App.app")'`,+ `/usr/bin/python3 -c 'import os; os.system("simctl shutdown DEVICE")'`,+ `awk 'BEGIN { system("xcrun simctl erase DEVICE") }'`,+ `osascript -e 'do shell script "/usr/bin/xcrun simctl shutdown DEVICE"'`,+ `osascript -e 'do shell script "open -a Simulator"'`,+ `osascript -e 'set cmd to "/usr/bin/xcrun simctl shutdown DEVICE"' -e 'do shell script cmd'`,+ `osascript -l JavaScript -e 'ObjC.import("Foundation"); const task = $.NSTask.alloc.init; task.launchPath = "/usr/bin/xcrun"; task.arguments = ["simctl", "shutdown", "DEVICE"]; task.launch'`,+ `python3 -c 'import subprocess; subprocess.run(["/usr/bin/open","-a","Simulator"])'`,+ `node -e 'require("child_process").spawnSync("/usr/bin/open",["-na","Simulator"])'`,+ `ruby -e 'system("/usr/bin/open", "-a", "Simulator")'`,+ `/usr/bin/expect -c 'spawn /usr/bin/xcrun simctl shutdown DEVICE; expect eof'`,+ // The consumer can also follow the marker, so the heredoc's own pipeline —+ // not just the text before `<<` — decides whether the body is executable.+ `cat <<'SH' | sh+xcrun simctl boot DEVICE+SH`,+ `cat <<'SH' |+echo safe+SH+xcrun simctl shutdown DEVICE`,+ `cat <<'SH' | bash -s+xcrun simctl shutdown DEVICE+SH`,+ `cat <<'SH' | env FOO=1 bash+xcrun simctl erase DEVICE+SH`,+ `cat <<'SH' | bash | cat+open -a Simulator+SH`,+ `bash 2>/dev/null <<'SH'+xcrun simctl shutdown DEVICE+SH`,+ `bash>/dev/null <<'SH'+xcrun simctl shutdown DEVICE+SH`,+ `bash &>/dev/null <<'SH'+xcrun simctl shutdown DEVICE+SH`,+ `bash {log}>/dev/null <<'SH'+xcrun simctl shutdown DEVICE+SH`,+ `bash 0<<'SH'+xcrun simctl shutdown DEVICE+SH`,+ `cat <<'SH' | bash 2>/dev/null+open -a Simulator+SH`,+ // Multiple stdin heredocs on one consumer: only the last body reaches bash.+ `bash <<'DATA' <<'CODE'+echo safe+DATA+xcrun simctl shutdown DEVICE+CODE`,+ `cat <<'DATA' | bash <<'CODE'+echo safe+DATA+xcrun simctl shutdown DEVICE+CODE`,+ `printf '<<SH'; cat <<SH | bash+xcrun simctl shutdown DEVICE+SH`,+ // A non-zero fd redirection leaves stdin connected to the pipeline, so the+ // downstream shell still executes the producer's body.+ `cat <<'DATA' | bash 2<err+xcrun simctl shutdown DEVICE+DATA`,+ `cat <<'DATA' | bash {fd}<err+xcrun simctl shutdown DEVICE+DATA`,+ `cat <<'SH' | bash -s $((1 << 2))+xcrun simctl shutdown DEVICE+SH`,+ `cat <<'SH' | bash -s $[1 << 2]+xcrun simctl shutdown DEVICE+SH`,+ `cat <<'SH' | bash -o pipefail+xcrun simctl shutdown DEVICE+SH`,+ `cat <<'SH' | bash -O extglob+xcrun simctl shutdown DEVICE+SH`,+ `cat <<'DATA' | bash -s $(printf foo < /tmp/x)+xcrun simctl shutdown DEVICE+DATA`,+ // An unquoted delimiter still expands, so the body's substitutions run.+ `cat <<MSG+$(xcrun simctl boot DEVICE)+MSG`,+ `cat <<MSG+\`xcrun simctl shutdown DEVICE\`+MSG`,+ // Quote removal happens during tokenization exactly as a shell performs it,+ // so an interrupted spelling is still a literal recipe.+ `bash <<'SH'+xcr"un" sim"ctl" shutdown DEVICE+SH`,+ // Only the executor is assembled here; `simctl shutdown DEVICE` is spelled out.+ `python3 -c "import os; os.system(''.join(['xc','run']) + ' simctl shutdown DEVICE')"`,+ ])('denies a literal recipe inside an interpreter payload: %s', (command) => {+ expect(getDesktopShellCommandPolicy(command)).toMatchObject({ decision: 'deny' });+ });+++ it.each([+ 'xcrun simctl list devices',+ 'xcrun simctl listapps DEVICE',+ 'xcrun simctl list "$DEVICE"',+ 'xcrun simctl getenv "$DEVICE" HOME',+ 'xcrun --sdk iphonesimulator simctl list devices',+ 'xcrun swift --version',+ 'exec xcrun simctl list devices',+ 'command -p xcrun simctl listapps DEVICE',+ "bash -lc 'xcrun simctl list devices'",+ 'f(){ xcrun simctl list devices;}; f',+ 'f() ( xcrun simctl list devices ); f',+ 'echo "f() ( xcrun simctl shutdown DEVICE )"',+ 'command -v xcrun',+ 'xcodebuild -scheme FiloApp -sdk iphonesimulator build',+ 'open -a Xcode',+ 'echo "open -a Simulator"',+ 'osascript -e \'tell application "Simulator" to quit\'',+ `python3 -c 'print("ordinary project build")'`,+ `python3 -c 'print("Simulator")'`,+ `node -e 'console.log("ordinary project build")'`,+ 'swift test --filter IOSSimulatorTests',+ 'swift build --product IOSSimulatorRuntime',+ 'find . -maxdepth 1 -name simctl',+ 'git grep simctl',+ 'git log --grep=simctl',+ `sed -n '/simctl/p' README.md`,+ `jq '.simctl' config.json`,+ 'diff simctl-before.txt simctl-after.txt',+ 'cp simctl-notes.txt backup.txt',+ 'git grep simctl && python3 scripts/check.py',+ 'git grep simctl | python3 formatter.py',+ `git grep simctl | awk '{print $1}'`,+ `python3 -c 'print("ordinary")'; git grep simctl`,+ 'git grep simctl || python3',+ 'alias',+ 'alias sim',+ "alias ll='ls -la'; ll",+ 'echo "alias sim=\'xcrun simctl\'"',+ 'echo "$UNTRUSTED_EXECUTABLE"',+ '# ordinary shell comment',+ '#!/bin/sh\necho ordinary',+ 'command -v "$UNTRUSTED_EXECUTABLE"',+ '[ -n "$UNTRUSTED_EXECUTABLE" ]',+ '[[ -n "$UNTRUSTED_EXECUTABLE" ]]',+ '(( 1 + 2 > 0 ))',+ 'if (( 3 > 0 )); then echo ready; fi',+ 'sudo ls "$ORDINARY_PATH"',+ 'sudo -u "$ORDINARY_USER" /bin/echo ok',+ 'sudo FOO=bar /bin/echo "$ORDINARY_VALUE"',+ 'sudo >/dev/null /bin/echo "$ORDINARY_VALUE"',+ 'xargs echo "$ORDINARY_VALUE"',+ 'xargs -n "$ORDINARY_COUNT" /bin/echo ok',+ `sandbox-exec -p '(version 1) (allow default)' /bin/echo "$ORDINARY_VALUE"`,+ 'sandbox-exec -p "$ORDINARY_PROFILE" /bin/echo ok',+ 'launchctl submit -l "$ORDINARY_LABEL" -- /bin/echo ok',+ 'launchctl asuser "$ORDINARY_UID" /bin/echo ok',+ 'launchctl bsexec "$ORDINARY_PID" /bin/echo "$ORDINARY_VALUE"',+ 'watch -d /bin/echo "$ORDINARY_VALUE"',+ 'time -l /bin/echo "$ORDINARY_VALUE"',+ 'script -q /tmp/typescript /bin/echo "$ORDINARY_VALUE"',+ ])('allows a non-bypass command: %s', (command) => {+ expect(getDesktopShellCommandPolicy(command)).toBeUndefined();+ });++ // A heredoc body, an inline interpreter program and an arithmetic expression+ // are not shell argv. Classifying their contents as command words denied+ // ordinary work with no Simulator executor anywhere in the command.+ it.each([+ // Ordinary HTTPS read through a Python heredoc (issue #2404).+ `python3 - <<'PY'+import urllib.request+data = urllib.request.urlopen("https://example.com").read()+print(len(data))+PY`,+ `python3 - <<'PY'+print(1)+PY`,+ `python3 - <<'PY'+def main():+ print("hi")+main()+PY`,+ `node <<'JS'+console.log(1)+JS`,+ `sqlite3 /tmp/app.db <<'SQL'+SELECT count(*) FROM items;+SQL`,+ `jq . <<'JSON'+{"a": 1}+JSON`,+ `cat > /tmp/notes.txt <<'EOF'+hello (world)+EOF`,+ `cat > README.md <<'EOF'+xcrun simctl shutdown DEVICE+open -a Simulator+EOF`,+ `cat > README.md <<EOF+xcrun simctl shutdown DEVICE+open -a Simulator+EOF`,+ // A trailing pipe does not make the next physical line a consumer: it is+ // still heredoc body data. The command after the delimiter is separate.+ `cat <<'SH' |+xcrun simctl shutdown DEVICE+SH+bash`,+ `cat <<'DATA' |+xcrun simctl shutdown DEVICE+DATA`,+ `cat <<$'EOF' >/dev/null+xcrun simctl shutdown DEVICE+EOF`,+ // A commit message written through a heredoc is stdin data, never argv. A+ // line starting with a Markdown backtick span used to read as an executable+ // position filled by an unresolvable expansion, which denied the commit and+ // interrupted the turn — with no Simulator executor anywhere in the command.+ `git commit -s -F - <<'MSG'+fix(scope): 收窄判据++验证:\`pnpm --filter desktop typecheck\` 通过,\`@cindy/ios-simulator-runtime\` 36 文件+\`pnpm test:unit\` 全绿+MSG`,+ `git commit -F - <<'MSG'+\`ls\`+MSG`,+ `git commit -F - <<'MSG'+xcrun simctl shutdown DEVICE+MSG`,+ `git commit -F - <<MSG+xcrun simctl shutdown DEVICE+MSG`,+ `git commit 2>/dev/null -F - <<'MSG'+xcrun simctl shutdown DEVICE+MSG`,+ `bash '2>/dev/null' <<'SH'+xcrun simctl shutdown DEVICE+SH`,+ `bash '&>/dev/null' <<'SH'+xcrun simctl shutdown DEVICE+SH`,+ `git commit &>/dev/null -F - <<'MSG'+xcrun simctl shutdown DEVICE+MSG`,+ // A quoted delimiter suppresses expansion in every spelling, and `<<-`+ // strips leading tabs from the body and the closing delimiter.+ `git commit -F - <<"MSG"+\`ls\`+MSG`,+ `git commit -F - <<\\MSG+\`ls\`+MSG`,+ `git commit -F - <<-'MSG'+\t\`ls\`+\tMSG`,+ // An unquoted delimiter expands, but running `ls` to build the body is not a+ // Simulator bypass; only the substitution's own command is classified.+ `git commit -F - <<MSG+\`ls\` 通过+MSG`,+ `cat <<'A' > /tmp/a && cat <<'B' > /tmp/b+\`ls\`+A+\`pwd\`+B`,+ // An unterminated body must not fall back to argv classification either.+ `git commit -F - <<'MSG'+\`ls\``,+ `git commit -F - <<'MSG'+说明:不要直接用 simctl,走 cindy_ios_simulator+MSG`,+ `node -e "+function check() {+ console.log(1);+}+check();+"`,+ `python3 -c "+def check():+ print(1)+check()+"`,+ ])('allows an ordinary interpreter heredoc or inline program: %s', (command) => {+ expect(getDesktopShellCommandPolicy(command)).toBeUndefined();+ });++ it.each([+ 'n=3; (( n > 1 )) && echo yes',+ 'i=0; (( i++ )); echo "$i"',+ '(( $# > 0 )) && echo has-args',+ '(( $? == 0 )) && echo ok',+ 'echo $((1 << 2))',+ 'echo $[1 << 2]',+ '(( 1 << 2 ))',+ 'i=0; while (( i < 3 )); do echo "$i"; i=$((i+1)); done',+ 'if (( count > 0 )); then echo ready; fi',+ ])('allows shell arithmetic with no Simulator evidence: %s', (command) => {+ expect(getDesktopShellCommandPolicy(command)).toBeUndefined();+ });++ it.each([+ 'echo start\n*.ts\necho done',+ // A redirected group leaves `}` in command position, which is a shell+ // control token, not a glob-expanded executable name.+ '{ echo a; echo b; } > /tmp/out.log 2>&1',+ '{ pnpm build; pnpm test; } 2>&1 | tee /tmp/build.log',+ '( cd /tmp && ls ) > /tmp/out.txt',+ 'expected=200; actual=$(curl -s -o /dev/null -w \'%{http_code}\' https://example.com); if [ "$expected" != "$actual" ]; then echo bad; fi',+ 'rg -n "Rejected\\((.*)\\)" apps',+ "rg -n foo --glob '*.{ts,tsx}' apps",+ 'grep -rEn "(foo|bar)" apps',+ "awk '{print $1}' /tmp/app.log",+ 'ls /tmp/[abc]*.log',+ 'cp file.{ts,ts.bak}',+ // Options after the script operand belong to the script, not to the shell.+ // Reading them as a shell program denied ordinary work and interrupted it.+ "bash ./print-args.sh -c 'xcrun simctl shutdown DEVICE'",+ 'sh ./run.sh -c "xcrun simctl boot DEVICE"',+ "zsh tools/x.zsh -c 'open -a Simulator'",+ 'bash ./build.sh --release',+ // Some prefixes only report on the command they name. `command -v` prints+ // where it lives and `sudo -l` asks whether it would be permitted; neither+ // runs it. Ending the peel at the option covers them without the policy+ // having to know which prefixes behave this way.+ 'command -v simctl shutdown',+ 'command -V simctl',+ 'command -v xcrun simctl',+ 'command -pv simctl boot',+ 'sudo -l xcrun simctl boot DEVICE',+ 'sudo --list xcrun simctl shutdown DEVICE',+ // The same rule keeps ordinary option-bearing work out of the guard.+ 'sudo -u postgres psql -c "select 1"',+ 'env -u NODE_OPTIONS pnpm test',+ 'timeout -k 5 30 pnpm build',+ 'nice -n 10 make -j8',+ 'export PATH=/usr/bin:$PATH; echo ok',+ ])('allows an ordinary command whose shape is not an executable: %s', (command) => {+ expect(getDesktopShellCommandPolicy(command)).toBeUndefined();+ });++ // ── Reclassified by the stale-recipe threat model ──────────────────────────+ //+ // Every command below was denied before. Each one disguises the executor:+ // assembling it from variables or string fragments, completing it with a glob+ // or a substitution, forwarding it through eval, or storing it for an opaque+ // wrapper to run. A recipe copied from documentation never looks like this, so+ // none of them are in the threat model this policy defends.+ //+ // They are listed rather than deleted because the change is a deliberate+ // reduction in what the guard claims to stop, and a reviewer should be able to+ // see exactly what moved. Detecting these forms is not achievable from command+ // text anyway — `bash script.sh` carries the executor outside the command+ // entirely — and the machinery that attempted it is what denied ordinary work+ // such as a heredoc body, shell arithmetic and a redirected group.+ it.each([+ "env -S 'xcrun simctl shutdown DEVICE'",+ 'printf "xcrun simctl shutdown DEVICE\\n" | sh',+ 'f(){ xcrun simctl shutdown DEVICE;}; f',+ 'f() ( xcrun simctl shutdown DEVICE ); f',`/bin/sh -c '"$0" "$@"' /usr/bin/xcrun simctl shutdown DEVICE`,`/bin/sh -c '/usr/bin/open -a "$1"' ignored Simulator`,'$(/usr/bin/xcrun --find simctl) shutdown DEVICE',@@ -85,7 +589,6 @@ describeMac('embedded iOS Simulator shell policy', () => {`zsh -o extendedglob -c 'xcrun ^foo shutdown DEVICE'`,'xcrun --sdk "$SDK" simctl list devices','A=default; xcrun --toolchain "$A" swift --version',- 'xargs /usr/bin/xcrun simctl shutdown DEVICE',"find . -maxdepth 0 -exec /usr/bin/xcrun simctl shutdown DEVICE ';'",`printf 'simctl shutdown DEVICE' | xargs /usr/bin/xcrun`,'xcrun "$(printf simctl)" shutdown DEVICE',@@ -139,38 +642,14 @@ describeMac('embedded iOS Simulator shell policy', () => {"command -- alias sim='open -a Simulator'; eval sim","alias safe='ls -la' sim='xcrun simctl'; eval 'sim boot DEVICE'","alias sc='simctl'; eval 'sc shutdown DEVICE'",- ])('denies Simulator mutation hidden behind shell execution: %s', (command) => {- expect(getDesktopShellCommandPolicy(command)).toMatchObject({ decision: 'deny' });- });-- it.each(['(( $COUNT > 0 ))', '(( COUNT[$idx]++ ))', 'if (( $COUNT > 0 )); then echo ready; fi'])(- 'denies dynamic shell arithmetic that can recursively execute stored payloads: %s',- (command) => {- expect(getDesktopShellCommandPolicy(command)).toMatchObject({ decision: 'deny' });- },- );-- it.each([- `python3 -c 'import subprocess; subprocess.run(["/usr/bin/xcrun", "simctl", "shutdown", "DEVICE"])'`,- `node -e 'require("node:child_process").execFileSync("xcrun", ["simctl", "erase", "DEVICE"])'`,- `ruby -e 'system("xcrun simctl boot DEVICE")'`,- `perl -e 'system("simctl shutdown DEVICE")'`,- `env FOO=1 python3.12 -c 'import os; os.system("xcrun simctl install DEVICE /tmp/App.app")'`,- `/usr/bin/python3 -c 'import os; os.system("simctl shutdown DEVICE")'`,- `awk 'BEGIN { system("xcrun simctl erase DEVICE") }'`,- `osascript -e 'do shell script "/usr/bin/xcrun simctl shutdown DEVICE"'`,- `osascript -e 'do shell script "open -a Simulator"'`,+ '(( $COUNT > 0 ))',+ '(( COUNT[$idx]++ ))',+ 'if (( $COUNT > 0 )); then echo ready; fi',`printf '%s' 'import os; os.system("xcrun simctl shutdown DEVICE")' | python3`,`python3 <<'PY'import osos.system("xcrun simctl shutdown DEVICE")PY`,- `osascript -e 'set cmd to "/usr/bin/xcrun simctl shutdown DEVICE"' -e 'do shell script cmd'`,- `osascript -l JavaScript -e 'ObjC.import("Foundation"); const task = $.NSTask.alloc.init; task.launchPath = "/usr/bin/xcrun"; task.arguments = ["simctl", "shutdown", "DEVICE"]; task.launch'`,- `python3 -c 'import subprocess; subprocess.run(["/usr/bin/open","-a","Simulator"])'`,- `node -e 'require("child_process").spawnSync("/usr/bin/open",["-na","Simulator"])'`,- `ruby -e 'system("/usr/bin/open", "-a", "Simulator")'`,- `/usr/bin/expect -c 'spawn /usr/bin/xcrun simctl shutdown DEVICE; expect eof'`,`printf '%s' 'exec /usr/bin/xcrun simctl shutdown DEVICE' | /usr/bin/tclsh`,`printf '%s' 'import os; os.system("xcrun simctl shutdown DEVICE")' |& python3`,`bash <<< 'xcrun simctl shutdown DEVICE'`,@@ -178,72 +657,82 @@ PY`,`bash -c 'source /dev/stdin' <<< 'xcrun simctl shutdown DEVICE'`,`bash -c 'eval "$(cat)"' <<< 'xcrun simctl shutdown DEVICE'`,`printf 'xcrun simctl shutdown DEVICE' | bash -c 'eval "$(cat)"'`,- ])('denies Simulator mutation hidden behind a programmable interpreter: %s', (command) => {- expect(getDesktopShellCommandPolicy(command)).toMatchObject({ decision: 'deny' });+ `python3 -c 'import os; os.system("xcr" + "un" + " sim" + "ctl shutdown DEVICE")'`,+ `node -e 'require("child_process").execSync("xcr" + "un" + " sim" + "ctl shutdown DEVICE")'`,+ `python3 - <<'PY'+import os+os.system("xcr" + "un" + " sim" + "ctl shutdown DEVICE")+PY`,+ // The downstream heredoc replaces the pipe as bash's stdin, so DATA is+ // ordinary cat input even though it looks like a Simulator recipe.+ `cat <<'DATA' | bash <<'CODE'+xcrun simctl shutdown DEVICE+DATA+echo safe+CODE`,+ `bash <<'DATA' <<'CODE'+xcrun simctl shutdown DEVICE+DATA+echo safe+CODE`,+ `bash 3<<'DATA'+xcrun simctl shutdown DEVICE+DATA`,+ `bash {fd}<<'DATA'+xcrun simctl shutdown DEVICE+DATA`,+ `awk 'BEGIN { system("xcr" "un" " sim" "ctl shutdown DEVICE") }'`,+ 'xcr$TAIL boot DEVICE',+ 'sim$TAIL shutdown DEVICE',+ 'xc$TAIL boot DEVICE',+ '${DIR}crun boot DEVICE',+ 'simct$TAIL shutdown DEVICE',+ 'sim* shutdown DEVICE',+ '$DIR/build/$NAME --version',+ '"$PWD/build/$NAME" --version',+ '$DIR/simctl/$SUB shutdown DEVICE',+ // A substitution can supply characters in the middle of the name, and the+ // tokenizer splits on the whitespace inside it, so the command word arrives+ // as an unterminated remnant. Contiguity is not a safe test here.+ 'si$(printf m)ctl shutdown DEVICE',+ 'sim$(printf c)tl shutdown DEVICE',+ 'x$(printf c)run simctl shutdown DEVICE',+ 'sim`printf c`tl shutdown DEVICE',+ // A character class or brace list holds mutually exclusive candidates, so+ // merging their contents into the core would invent a literal that matches+ // nothing and hide the name the shell can expand to.+ '/usr/bin/[sx]crun s[ai]mctl shutdown DEVICE',+ '/Applications/Xcode.app/Contents/Developer/usr/bin/[sx]imctl shutdown DEVICE',+ '[sx]crun boot DEVICE',+ 's[ai]mctl shutdown DEVICE',+ 'x{cr,foo}un boot DEVICE',+ 's{imc,foo}tl shutdown DEVICE',+ `python3 - <<'PY'+import os+os.system(''.join(('xc','run')) + ' ' + ''.join(('sim','ctl')) + ' shutdown DEVICE')+PY`,+ ])('no longer denies a disguised executor: %s', (command) => {+ expect(getDesktopShellCommandPolicy(command)).toBeUndefined();});+ // The deliberate boundary of the narrowing: the executable name is knowable+ // and is not a Simulator executor, so denying it would be a guess about the+ // expansion rather than a product rule. Documented in the PR description.it.each([- 'xcrun simctl list devices',- 'xcrun simctl listapps DEVICE',- 'xcrun simctl list "$DEVICE"',- 'xcrun simctl getenv "$DEVICE" HOME',- 'xcrun --sdk iphonesimulator simctl list devices',- 'xcrun swift --version',- 'exec xcrun simctl list devices',- 'command -p xcrun simctl listapps DEVICE',- "bash -lc 'xcrun simctl list devices'",- 'f(){ xcrun simctl list devices;}; f',- 'f() ( xcrun simctl list devices ); f',- 'echo "f() ( xcrun simctl shutdown DEVICE )"',- 'command -v xcrun',- 'xcodebuild -scheme FiloApp -sdk iphonesimulator build',- 'open -a Xcode',- 'echo "open -a Simulator"',- 'osascript -e \'tell application "Simulator" to quit\'',- `python3 -c 'print("ordinary project build")'`,- `python3 -c 'print("Simulator")'`,- `node -e 'console.log("ordinary project build")'`,- 'swift test --filter IOSSimulatorTests',- 'swift build --product IOSSimulatorRuntime',- 'find . -maxdepth 1 -name simctl',- 'git grep simctl',- 'git log --grep=simctl',- `sed -n '/simctl/p' README.md`,- `jq '.simctl' config.json`,- 'diff simctl-before.txt simctl-after.txt',- 'cp simctl-notes.txt backup.txt',- 'git grep simctl && python3 scripts/check.py',- 'git grep simctl | python3 formatter.py',- `git grep simctl | awk '{print $1}'`,- `python3 -c 'print("ordinary")'; git grep simctl`,- 'git grep simctl || python3',- 'alias',- 'alias sim',- "alias ll='ls -la'; ll",- 'echo "alias sim=\'xcrun simctl\'"',- 'echo "$UNTRUSTED_EXECUTABLE"',- '# ordinary shell comment',- '#!/bin/sh\necho ordinary',- 'command -v "$UNTRUSTED_EXECUTABLE"',- '[ -n "$UNTRUSTED_EXECUTABLE" ]',- '[[ -n "$UNTRUSTED_EXECUTABLE" ]]',- '(( 1 + 2 > 0 ))',- 'if (( 3 > 0 )); then echo ready; fi',- 'sudo ls "$ORDINARY_PATH"',- 'sudo -u "$ORDINARY_USER" /bin/echo ok',- 'sudo FOO=bar /bin/echo "$ORDINARY_VALUE"',- 'sudo >/dev/null /bin/echo "$ORDINARY_VALUE"',- 'xargs echo "$ORDINARY_VALUE"',- 'xargs -n "$ORDINARY_COUNT" /bin/echo ok',- `sandbox-exec -p '(version 1) (allow default)' /bin/echo "$ORDINARY_VALUE"`,- 'sandbox-exec -p "$ORDINARY_PROFILE" /bin/echo ok',- 'launchctl submit -l "$ORDINARY_LABEL" -- /bin/echo ok',- 'launchctl asuser "$ORDINARY_UID" /bin/echo ok',- 'launchctl bsexec "$ORDINARY_PID" /bin/echo "$ORDINARY_VALUE"',- 'watch -d /bin/echo "$ORDINARY_VALUE"',- 'time -l /bin/echo "$ORDINARY_VALUE"',- 'script -q /tmp/typescript /bin/echo "$ORDINARY_VALUE"',- ])('allows a non-bypass command: %s', (command) => {+ '$DIR/build/tool --version',+ 'tool$SUFFIX --version',+ 'build$SUFFIX --version',+ ])('allows a resolvable non-Simulator executable name: %s', (command) => {+ expect(getDesktopShellCommandPolicy(command)).toBeUndefined();+ });++ // Adjacent string literals are data, not a join. Folding them used to fabricate+ // an executor name out of ordinary interpreter code.+ it.each([+ `python3 -c 'print("xcr", "un")'`,+ `node -e 'console.log(["sim", "ctl"])'`,+ `python3 -c 'print(["sim","ctl"])'`,+ ])('allows adjacent string literals that merely look like fragments: %s', (command) => {expect(getDesktopShellCommandPolicy(command)).toBeUndefined();});});diff --git a/apps/desktop/src/main/maker-host/shell-command-policy.ts b/apps/desktop/src/main/maker-host/shell-command-policy.tsindex ce7e10cd6c..a7ae5ab571 100644--- a/apps/desktop/src/main/maker-host/shell-command-policy.ts+++ b/apps/desktop/src/main/maker-host/shell-command-policy.ts@@ -1,14 +1,37 @@/*** Product-owned shell command policy for the embedded iOS Simulator.*- * Agent skills may contain legacy `simctl` / `open -a Simulator` recipes. Those- * commands bypass Cindy's ownership, admission, viewer, and cleanup contracts,- * so prompt guidance alone is not a sufficient boundary. This module detects- * literal executable shell segments and denies only the bypass paths; Cindy's- * own main process still uses simctl through the runtime adapter and is- * unaffected. This is defense in depth for command text, not an OS process- * sandbox: scripts whose contents are absent from the command cannot be proven- * safe here and remain subject to the normal shell permission boundary.+ * **Threat model: a stale recipe.** A Skill, a README or the model's own memory+ * still carries a pre-Cindy incantation (`xcrun simctl boot …`,+ * `open -a Simulator`) and the Agent copies it verbatim. Such recipes are+ * literal by construction — they come from documentation, so they never disguise+ * themselves — and a literal matcher catches all of them. Cindy's own main+ * process reaches simctl through the runtime adapter and is unaffected, and the+ * capability gate means this policy only applies where an embedded simulator+ * actually exists to protect.+ *+ * **Deliberately outside the threat model: writing around this policy.** Command+ * text cannot decide that case at all — `bash script.sh` moves the executor out+ * of the command entirely, and no amount of parsing recovers it. Trying anyway is+ * what made this module deny ordinary work: it had to fail closed on every shape+ * it could not resolve, and in shell that is most shapes, so `print(len(data))`+ * in a heredoc, `(( n > 1 ))`, a glob-leading line, `{ …; } > file` and a commit+ * message containing a Markdown backtick were all rejected with no Simulator+ * executor anywhere in the command. This matcher denies only what it can read+ * directly and lets everything else reach the normal shell permission flow.+ * "Directly" means that the executor occupies a command-word position this+ * policy already understands: a direct segment, one of the plain documentation+ * prefixes below, or a supported shell/interpreter payload. It does not scan+ * arbitrary argv for a command another program might execute. Opaque wrappers+ * such as `launchctl`, `sandbox-exec`, `doas`, `script`, `watch`, `parallel`,+ * `coproc` and `repeat` remain outside this boundary even when their argv holds+ * a complete literal recipe, because locating the executed operand requires a+ * per-wrapper execution contract rather than shell syntax.+ *+ * Heredocs need one narrow boundary: their bodies are stdin data unless the+ * receiving command executes stdin as a program. Data bodies are omitted from+ * command classification (while substitutions in an unquoted body still run),+ * so a commit message may quote a stale recipe without being mistaken for one.*/export interface ShellCommandPolicyDenial {@@ -27,24 +50,51 @@ const SAFE_SIMCTL_COMMANDS = new Set([const IOS_SIMULATOR_SHELL_DENIAL ='Cindy blocked a shell command that would bypass the embedded iOS Simulator. ' +- 'Use cindy_ios_simulator for device lifecycle, app install/launch, interaction, screenshots, and diagnostics. External Simulator.app automation is unavailable until Cindy can issue an explicit host authorization.';+ 'Use cindy_ios_simulator for device lifecycle, app install/launch, interaction, screenshots, and diagnostics.';++const MAX_RECURSION_DEPTH = 8;++interface ShellSegment {+ command: string;+ /** The operator that ran before this command; null for the first segment. */+ precedingOperator: ';' | '&&' | '||' | '|' | '&' | null;+ /** The operator that separates this command from the next segment, if any. */+ followingOperator: ';' | '&&' | '||' | '|' | '&' | null;+}-/** Split command lists without treating separators inside quotes as executable boundaries. */-function shellSegments(command: string): string[] {- const segments: string[] = [];+/** Split command lists without treating separators inside quotes as boundaries. */+function shellSegments(command: string): ShellSegment[] {+ const segments: ShellSegment[] = [];let current = '';let quote: "'" | '"' | null = null;let escaped = false;+ let atWordStart = true;+ let precedingOperator: ShellSegment['precedingOperator'] = null;++ const flush = (nextOperator: Exclude<ShellSegment['precedingOperator'], null>): void => {+ if (current.trim()) {+ segments.push({+ command: current.trim(),+ precedingOperator,+ followingOperator: nextOperator,+ });+ }+ current = '';+ precedingOperator = nextOperator;+ };- for (const char of command) {+ for (let index = 0; index < command.length; index += 1) {+ const char = command[index]!;if (escaped) {current += char;escaped = false;+ atWordStart = false;continue;}if (char === '\\' && quote !== "'") {current += char;escaped = true;+ atWordStart = false;continue;}if (quote) {@@ -55,19 +105,97 @@ function shellSegments(command: string): string[] {if (char === "'" || char === '"') {current += char;quote = char;+ atWordStart = false;+ continue;+ }+ if (char === '#' && atWordStart) {+ // A comment consumes the rest of the current physical line. Keep the+ // newline for the normal separator handling so assignments before the+ // comment retain their real shell scope.+ const newline = command.indexOf('\n', index);+ if (newline < 0) break;+ index = newline - 1;+ continue;+ }+ if (char === '\n' || char === ';') {+ // A newline immediately after `&&`, `||` or `|` continues that operator's+ // command. There is no empty command for the newline to run, so keep the+ // pending edge instead of turning it into an unconditional list separator.+ // A lone `&` is already a complete separator, so the next line is+ // unconditional in the parent shell.+ if (char === ';' || current.trim() || precedingOperator === '&') flush(';');+ atWordStart = true;+ continue;+ }+ if (+ (char === '&' && (command[index - 1] === '>' || command[index - 1] === '<')) ||+ (char === '&' && command[index + 1] === '>') ||+ (char === '|' && command[index - 1] === '>')+ ) {+ current += char;+ atWordStart = false;continue;}- if (char === '\n' || char === ';' || char === '|' || char === '&') {- if (current.trim()) segments.push(current.trim());- current = '';+ if (char === '|' || char === '&') {+ if (char === '|' && command[index + 1] === '&') {+ flush('|');+ index += 1;+ continue;+ }+ const doubled = command[index + 1] === char;+ flush(doubled ? (char === '|' ? '||' : '&&') : char);+ if (doubled) index += 1;+ atWordStart = true;continue;}current += char;+ atWordStart = /\s/.test(char);}- if (current.trim()) segments.push(current.trim());+ if (current.trim())+ segments.push({ command: current.trim(), precedingOperator, followingOperator: null });return segments;}+/** Whether a segment's assignments definitely replace values in the current scope. */+function assignmentDefinitelyRunsInCurrentScope(segment: ShellSegment): boolean {+ if (segment.precedingOperator !== null && segment.precedingOperator !== ';') return false;+ // Assignments in a pipeline or background segment execute in a child shell.+ // They must not be treated as replacing the value in the parent scope that a+ // later command (for example `eval "$CMD"`) will read.+ if (segment.followingOperator === '|' || segment.followingOperator === '&') return false;+ let quote: "'" | '"' | null = null;+ let escaped = false;+ let unquoted = '';+ for (const char of segment.command) {+ if (escaped) {+ unquoted += ' ';+ escaped = false;+ continue;+ }+ if (char === '\\' && quote !== "'") {+ unquoted += ' ';+ escaped = true;+ continue;+ }+ if (quote) {+ unquoted += ' ';+ if (char === quote) quote = null;+ continue;+ }+ if (char === "'" || char === '"') {+ unquoted += ' ';+ quote = char;+ continue;+ }+ if (char === '(' || char === ')' || char === '`') return false;+ unquoted += char;+ }+ const start = unquoted.trimStart();+ return !/^(?:(?:\{|!)\s*|(?:then|do|else|elif|if|while|until|for|select|case|function)\b)/.test(+ start,+ );+}+/** Lightweight argv tokenizer. Quotes group tokens but are not retained. */function tokenizeShellSegment(segment: string): string[] {const tokens: string[] = [];@@ -117,6 +245,7 @@ function executableName(token: string | undefined): string {.toLowerCase();}+/** Drop compound-command keywords and braces so the next token is the command word. */function stripShellControlTokens(tokens: string[]): string[] {const out = [...tokens];while (out.length > 0 && /^(?:\{|\(|!|then|do|else|elif|if|while|until)$/.test(out[0]!)) {@@ -126,8 +255,14 @@ function stripShellControlTokens(tokens: string[]): string[] {while (out[0] === '') out.shift();const last = out.length - 1;if (last >= 0) {- out[last] = out[last]!.replace(/[)}]+$/, '');- if (out[last] === '') out.pop();+ // A trailing `)` may close a substitution rather than a subshell. Stripping+ // it there would truncate `CMD='echo $(xcrun simctl boot X)'` into an+ // unterminated substitution that the recursive scan can no longer read.+ const closesSubstitution = /\$\(|<\(|>\(/.test(out[last]!);+ if (!closesSubstitution) {+ out[last] = out[last]!.replace(/[)}]+$/, '');+ if (out[last] === '') out.pop();+ }}return out;}@@ -137,25 +272,95 @@ function shellRedirectionSuffix(token: string): string | null {return match ? (match[1] ?? '') : null;}-function stripShellRedirections(input: string[]): string[] {- const tokens: string[] = [];- for (let index = 0; index < input.length; index += 1) {- const suffix = shellRedirectionSuffix(input[index]!);- if (suffix === null) {- tokens.push(input[index]!);+function redirectionAt(segment: string, index: number): string | null {+ if (+ (segment[index] === '<' || segment[index] === '>')+ && segment[index + 1] === '('+ ) return null;+ const wordStart = index === 0 || /\s/.test(segment[index - 1]!);+ const prefix = wordStart ? '(?:(?:\\d+|\\{[A-Za-z_][A-Za-z0-9_]*\\}))?' : '';+ return new RegExp(`^${prefix}(?:&>>?|<<<|<<-|<<|<>|>>|>&|<&|>\\||<|>)`).exec(+ segment.slice(index),+ )?.[0] ?? null;+}++/** Remove unquoted redirections before deciding whether stdin is the program. */+function tokenizeHeredocConsumer(segment: string): string[] {+ let command = '';+ let quote: "'" | '"' | null = null;+ let escaped = false;+ for (let index = 0; index < segment.length; index += 1) {+ const char = segment[index]!;+ if (escaped) {+ command += char;+ escaped = false;+ continue;+ }+ if (char === '\\' && quote !== "'") {+ command += char;+ escaped = true;+ continue;+ }+ if (char === "'" || char === '"') {+ command += char;+ if (quote === char) quote = null;+ else if (quote === null) quote = char;+ continue;+ }+ const redirection = quote === null ? redirectionAt(segment, index) : null;+ if (redirection === null) {+ command += char;continue;}- if (suffix === '' && index + 1 < input.length) index += 1;+ index += redirection.length;+ while (/\s/.test(segment[index] ?? '')) index += 1;+ let targetQuote: "'" | '"' | null = null;+ let targetEscaped = false;+ for (; index < segment.length; index += 1) {+ const target = segment[index]!;+ if (targetEscaped) {+ targetEscaped = false;+ continue;+ }+ if (target === '\\' && targetQuote !== "'") {+ targetEscaped = true;+ continue;+ }+ if (target === "'" || target === '"') {+ if (targetQuote === target) targetQuote = null;+ else if (targetQuote === null) targetQuote = target;+ continue;+ }+ if (targetQuote === null && (/\s/.test(target) || redirectionAt(segment, index))) break;+ }+ command += ' ';+ index -= 1;}- return tokens;+ return tokenizeShellSegment(command);+}++/** A `NAME=value` assignment, whose value may hold a whole recipe. */+interface ShellAssignment {+ name: string;+ value: string;+}++const SHELL_ASSIGNMENT = /^([A-Za-z_][A-Za-z0-9_]*)=([\s\S]*)$/;++interface Preamble {+ tokens: string[];+ assignments: ShellAssignment[];}-/** Remove leading assignments/redirections so the next token is the command word. */-function stripLeadingShellPreamble(input: string[]): string[] {+/** Remove leading assignments and redirections so the next token is the command word. */+function stripLeadingShellPreamble(input: string[]): Preamble {const tokens = [...input];+ const assignments: ShellAssignment[] = [];while (tokens.length > 0) {const token = tokens[0]!;- if (/^[A-Za-z_][A-Za-z0-9_]*=/.test(token)) {+ const assignment = SHELL_ASSIGNMENT.exec(token);+ if (assignment) {+ assignments.push({ name: assignment[1] ?? '', value: assignment[2] ?? '' });tokens.shift();continue;}@@ -164,375 +369,127 @@ function stripLeadingShellPreamble(input: string[]): string[] {tokens.shift();if (redirectionSuffix === '' && tokens.length > 0) tokens.shift();}- return tokens;-}--interface UnwrappedCommand {- tokens: string[];- nestedShell: string | null;- inspectionOnly: boolean;- unresolvedWrapper: boolean;+ return { tokens, assignments };}-const MAX_WRAPPER_UNWRAP_DEPTH = 16;const SHELL_EXECUTABLES = new Set(['bash', 'csh', 'dash', 'fish', 'ksh', 'sh', 'tcsh', 'zsh']);-const NON_EXECUTING_REFERENCE_COMMANDS = new Set([- 'cat',- 'echo',- 'egrep',- 'fgrep',- 'file',- 'grep',- 'head',- 'less',- 'ls',- 'more',- 'printf',- 'rg',- 'stat',- 'tail',- 'wc',-]);-const OPAQUE_EXECUTION_WRAPPERS = new Set([- 'coproc',- 'doas',+const PROGRAMMABLE_INTERPRETER =+ /^(?:python(?:\d+(?:\.\d+)*)?|pypy(?:\d+(?:\.\d+)*)?|node|nodejs|bun|deno|ruby(?:\d+(?:\.\d+)*)?|perl(?:\d+(?:\.\d+)*)?|php(?:\d+(?:\.\d+)*)?|lua(?:\d+(?:\.\d+)*)?|luajit|swift|expect(?:\d+(?:\.\d+)*)?|tclsh(?:\d+(?:\.\d+)*)?|wish(?:\d+(?:\.\d+)*)?|(?:g|m|n)?awk|osascript)$/;++/**+ * Prefixes documentation puts in front of a recipe, in the plain spelling it+ * actually uses: `sudo xcrun simctl …`, `env FOO=1 xcrun simctl …`,+ * `timeout 30 xcrun simctl …`.+ *+ * **An option on the prefix ends the peel.** Reading past one means knowing that+ * CLI's option arity *and* whether its operands are executed at all — `sudo -l`+ * and `command -v` merely report on the command they name. Both kinds of+ * knowledge were a standing source of defects here, in the direction that+ * matters: getting either wrong denies ordinary work. Stopping can only miss,+ * and a recipe copied out of documentation does not arrive decorated with+ * options.+ */+const LITERAL_COMMAND_PREFIXES = new Set([+ 'arch',+ 'builtin',+ 'caffeinate',+ 'command',+ 'env',+ 'exec','gtimeout',- 'launchctl',- 'parallel',- 'repeat',- 'sandbox-exec',- 'script',+ 'nice',+ 'nocorrect',+ 'noglob',+ 'nohup','sudo',+ 'time','timeout',- 'watch','xargs',]);-const SHELL_POSITIONAL_REFERENCE = /\$(?:[0-9]+|[@*#-]|\{(?:[0-9]+|[@*#-])\})/;-const PROGRAMMABLE_INTERPRETER =- /^(?:python(?:\d+(?:\.\d+)*)?|pypy(?:\d+(?:\.\d+)*)?|node|nodejs|bun|deno|ruby(?:\d+(?:\.\d+)*)?|perl(?:\d+(?:\.\d+)*)?|php(?:\d+(?:\.\d+)*)?|lua(?:\d+(?:\.\d+)*)?|luajit|swift|expect(?:\d+(?:\.\d+)*)?|tclsh(?:\d+(?:\.\d+)*)?|wish(?:\d+(?:\.\d+)*)?|(?:g|m|n)?awk)$/;-/** Peel only wrappers whose argv shape is fully understood; unknown options fail closed. */+interface UnwrappedCommand {+ tokens: string[];+ /** A literal program string handed to a shell via `-c`, classified recursively. */+ nestedShell: string | null;+ assignments: ShellAssignment[];+}++/** Builtins that declare `NAME=value`, an equally standard way to store a recipe. */+const SHELL_ASSIGNMENT_BUILTINS = new Set([+ 'declare',+ 'export',+ 'readonly',+ 'typeset',+]);++/** Peel documentation-style prefixes to reach the command word. */function unwrapCommand(input: string[]): UnwrappedCommand {- let tokens = stripLeadingShellPreamble(stripShellControlTokens(input));- for (let depth = 0; depth < MAX_WRAPPER_UNWRAP_DEPTH; depth += 1) {- tokens = stripLeadingShellPreamble(tokens);- if (tokens.length === 0) {- return { tokens, nestedShell: null, inspectionOnly: false, unresolvedWrapper: false };- }+ const first = stripLeadingShellPreamble(stripShellControlTokens(input));+ let tokens = first.tokens;+ const assignments = [...first.assignments];+ for (let depth = 0; depth < MAX_RECURSION_DEPTH; depth += 1) {+ const peeled = stripLeadingShellPreamble(tokens);+ tokens = peeled.tokens;+ assignments.push(...peeled.assignments);+ if (tokens.length === 0) return { tokens, nestedShell: null, assignments };const head = executableName(tokens[0]);- if (head === 'env') {- let index = 1;- let unresolved = false;- while (index < tokens.length) {- const token = tokens[index]!;- if (token === '--') {- index += 1;- break;- }- if (- token === '-' ||- token === '-i' ||- token === '--ignore-environment' ||- token === '-0' ||- token === '--null'- ) {- index += 1;- continue;- }- if (token === '-u' || token === '--unset' || token === '-C' || token === '--chdir') {- if (index + 1 >= tokens.length) unresolved = true;- index += 2;- continue;- }- if (- /^--(?:unset|chdir)=/.test(token) ||- /^-(?:u|C).+/.test(token) ||- /^[A-Za-z_][A-Za-z0-9_]*=/.test(token)- ) {- index += 1;- continue;- }- if (token.startsWith('-')) unresolved = true;- break;- }- tokens = tokens.slice(index);- if (unresolved) {- return { tokens, nestedShell: null, inspectionOnly: false, unresolvedWrapper: true };- }- continue;- }- if (head === 'command') {- let index = 1;- let inspectionOnly = false;- while (index < tokens.length) {- const token = tokens[index]!;- if (token === '--') {- index += 1;- break;- }- if (/^-[pVv]+$/.test(token)) {- inspectionOnly ||= /[Vv]/.test(token);- index += 1;- continue;- }- if (token.startsWith('-')) {- return {- tokens: tokens.slice(index),- nestedShell: null,- inspectionOnly: false,- unresolvedWrapper: true,- };- }- break;- }- if (inspectionOnly) {- return { tokens: [], nestedShell: null, inspectionOnly: true, unresolvedWrapper: false };- }- tokens = tokens.slice(index);- continue;- }- if (head === 'exec') {- let index = 1;- while (index < tokens.length) {- const token = tokens[index]!;- if (token === '--') {- index += 1;- break;- }- if (token === '-a') {- if (index + 1 >= tokens.length) {- return {- tokens: [],- nestedShell: null,- inspectionOnly: false,- unresolvedWrapper: true,- };- }- index += 2;- continue;- }- if (/^-a.+/.test(token) || /^-[cl]+$/.test(token)) {- index += 1;- continue;- }- if (token.startsWith('-')) {- return {- tokens: tokens.slice(index),- nestedShell: null,- inspectionOnly: false,- unresolvedWrapper: true,- };- }- break;- }- tokens = tokens.slice(index);- continue;- }- if (head === 'time') {- let index = 1;- while (index < tokens.length) {- const token = tokens[index]!;- if (token === '--') {- index += 1;- break;- }- if (/^-[alhp]+$/.test(token)) {- index += 1;- continue;- }- if (token === '-o') {- if (index + 1 >= tokens.length) {- return {- tokens: [],- nestedShell: null,- inspectionOnly: false,- unresolvedWrapper: true,- };- }- index += 2;- continue;- }- if (/^-o.+/.test(token)) {- index += 1;- continue;- }- if (token.startsWith('-')) {- return {- tokens: tokens.slice(index),- nestedShell: null,- inspectionOnly: false,- unresolvedWrapper: true,- };++ if (SHELL_ASSIGNMENT_BUILTINS.has(head)) {+ // `export CMD='xcrun simctl …'` stores the recipe just like a bare+ // assignment, so its operands feed the same stored-value path.+ for (const token of tokens.slice(1)) {+ const assignment = SHELL_ASSIGNMENT.exec(token);+ if (assignment) {+ assignments.push({ name: assignment[1] ?? '', value: assignment[2] ?? '' });}- break;- }- tokens = tokens.slice(index);- continue;- }- if (head === 'builtin' || head === 'nocorrect' || head === 'noglob' || head === 'nohup') {- let index = 1;- if (tokens[index] === '--') index += 1;- else if (tokens[index]?.startsWith('-')) {- return {- tokens: tokens.slice(index),- nestedShell: null,- inspectionOnly: false,- unresolvedWrapper: true,- };}- tokens = tokens.slice(index);- continue;+ return { tokens: [], nestedShell: null, assignments };}- if (head === 'nice') {++ if (SHELL_EXECUTABLES.has(head)) {+ // Only leading options belong to the shell. `bash ./run.sh -c 'x'` passes+ // `-c` to the script as `$1`, so scanning the whole argv would classify an+ // ordinary script argument as an executed shell program.let index = 1;while (index < tokens.length) {const token = tokens[index]!;- if (token === '--') {- index += 1;- break;- }- if (token === '-n' || token === '--adjustment') {- if (index + 1 >= tokens.length) {- return {- tokens: [],- nestedShell: null,- inspectionOnly: false,- unresolvedWrapper: true,- };- }- index += 2;- continue;- }- if (/^(?:--adjustment=.+|-\d+)$/.test(token)) {- index += 1;- continue;- }- if (token.startsWith('-')) {- return {- tokens: tokens.slice(index),- nestedShell: null,- inspectionOnly: false,- unresolvedWrapper: true,- };+ if (token === '--') break;+ if (!token.startsWith('-') && !token.startsWith('+')) break;+ if (/^-[A-Za-z]*c[A-Za-z]*$/.test(token)) {+ return { tokens: [], nestedShell: tokens[index + 1] ?? '', assignments };}- break;+ // `-o name` and `-O shopt_option` take a value; skipping one token would+ // read the option's value as the script operand and end the scan early.+ index += /^[-+][oO]$/.test(token) ? 2 : 1;}- tokens = tokens.slice(index);- continue;+ return { tokens, nestedShell: null, assignments };}- if (head === 'arch') {- let index = 1;- while (index < tokens.length) {- const token = tokens[index]!;- if (token === '--') {- index += 1;- break;- }- if (token === '-arch' || token === '--arch' || token === '-d' || token === '-e') {- if (index + 1 >= tokens.length) {- return {- tokens: [],- nestedShell: null,- inspectionOnly: false,- unresolvedWrapper: true,- };- }- index += 2;- continue;- }- if (/^-(?:arm64e?|x86_64|i386|32|64|c)$/.test(token)) {- index += 1;- continue;- }- if (token.startsWith('-')) {- return {- tokens: tokens.slice(index),- nestedShell: null,- inspectionOnly: false,- unresolvedWrapper: true,- };- }- break;- }- tokens = tokens.slice(index);- continue;+ if (head === 'eval') {+ return { tokens: [], nestedShell: tokens.slice(1).join(' '), assignments };}- if (head === 'caffeinate') {- let index = 1;- while (index < tokens.length) {- const token = tokens[index]!;- if (token === '--') {- index += 1;- break;- }- if (token === '-t' || token === '-w') {- if (index + 1 >= tokens.length) {- return {- tokens: [],- nestedShell: null,- inspectionOnly: false,- unresolvedWrapper: true,- };- }- index += 2;- continue;- }- if (/^-[dimsur]+$/.test(token)) {- index += 1;- continue;- }- if (token.startsWith('-')) {- return {- tokens: tokens.slice(index),- nestedShell: null,- inspectionOnly: false,- unresolvedWrapper: true,- };- }- break;- }- tokens = tokens.slice(index);- continue;+ if (!LITERAL_COMMAND_PREFIXES.has(head)) return { tokens, nestedShell: null, assignments };++ let index = 1;+ if (tokens[index] === '--') {+ // The only option-like token whose meaning needs no per-CLI knowledge.+ index += 1;+ } else if (tokens[index]?.startsWith('-')) {+ return { tokens, nestedShell: null, assignments };}- if (head === 'eval') {- return {- tokens: [],- nestedShell: tokens.slice(1).join(' '),- inspectionOnly: false,- unresolvedWrapper: false,- };+ // timeout takes a duration operand before the command it runs.+ if ((head === 'timeout' || head === 'gtimeout') && /^[\d.]+[smhd]?$/.test(tokens[index] ?? '')) {+ index += 1;}- if (SHELL_EXECUTABLES.has(head)) {- let index = 1;- while (index < tokens.length) {- const token = tokens[index]!;- if (token === '-o' || token === '-O') {- index += 2;- continue;- }- if (/^-[A-Za-z]*c[A-Za-z]*$/.test(token)) {- const nestedShell = tokens[index + 1] ?? '';- const positionalArgs = tokens.slice(index + 2);- return {- tokens: positionalArgs,- nestedShell,- inspectionOnly: false,- unresolvedWrapper:- index + 1 >= tokens.length ||- (SHELL_POSITIONAL_REFERENCE.test(nestedShell) &&- containsSimulatorExecutor(positionalArgs)),- };- }- if (token === '--') break;- if (!token.startsWith('-')) break;- index += 1;- }+ const next = tokens.slice(index);+ if (next.length === 0 || next.length === tokens.length) {+ return { tokens: next, nestedShell: null, assignments };}- return { tokens, nestedShell: null, inspectionOnly: false, unresolvedWrapper: false };+ tokens = next;}- return { tokens, nestedShell: null, inspectionOnly: false, unresolvedWrapper: true };+ return { tokens, nestedShell: null, assignments };}+/** `open -a Simulator` and the Simulator binary, in their documented spellings. */function isExternalSimulatorLaunch(tokens: string[]): boolean {const head = executableName(tokens[0]);if (head === 'open') {@@ -553,22 +510,19 @@ function isExternalSimulatorLaunch(tokens: string[]): boolean {);}+/** The simctl subcommand of a literal `[xcrun] simctl …` invocation, or null. */function simctlSubcommand(tokens: string[]): string | null {let index = 0;if (executableName(tokens[index]) === 'xcrun') {index += 1;while (index < tokens.length && tokens[index]!.startsWith('-')) {const option = tokens[index]!;- if (+ const takesValue =option === '--sdk' ||option === '-sdk' ||option === '--toolchain' ||- option === '-toolchain'- ) {- index += 2;- } else {- index += 1;- }+ option === '-toolchain';+ index += takesValue ? 2 : 1;}}if (executableName(tokens[index]) !== 'simctl') return null;@@ -582,19 +536,16 @@ function isSimulatorMutation(tokens: string[]): boolean {return subcommand !== null && !SAFE_SIMCTL_COMMANDS.has(subcommand);}-function containsSimulatorExecutor(tokens: string[]): boolean {- return tokens.some(- (token) =>- /(?:^|\/)simctl$/i.test(token) ||- /Simulator(?:\.app)?/i.test(token) ||- /\bxcrun\b[\s\S]*\bsimctl\b/i.test(token),- );+function isSimulatorRecipeArgv(tokens: string[]): boolean {+ return isExternalSimulatorLaunch(tokens) || isSimulatorMutation(tokens);}+/** A Simulator command spelled out in free text, used for interpreter payloads. */function containsLiteralSimulatorExecutor(value: string): boolean {const argvLike = value.replace(/[^A-Za-z0-9_./-]+/g, ' ').trim();return (- /\b(?:xcrun|simctl)\b/i.test(value) ||+ /\bxcrun\b[\s\S]*\bsimctl\b/i.test(value) ||+ /(?:^|[^\w./-])simctl\s+\S/i.test(argvLike) ||/\bSimulator\.app\b/i.test(value) ||/\bcom\.apple\.iphonesimulator\b/i.test(value) ||/(?:^|\s)(?:\S*\/)?open(?:\s+-[A-Za-z]+)*\s+Simulator(?:\.app)?(?:\s|$)/i.test(argvLike)@@ -602,45 +553,17 @@ function containsLiteralSimulatorExecutor(value: string): boolean {}/**- * General-purpose interpreters can spawn simctl without making it the shell- * executable. Treat a literal Simulator executor in their payload/argv as a- * mutation-capable wrapper; command-text policy cannot safely inspect the- * language semantics beneath this point.+ * A recipe pasted into an interpreter one-liner (`python3 -c 'os.system("xcrun+ * simctl boot X")'`) is still literal, so the payload is scanned as text. Only a+ * spelled-out command counts; assembling one from fragments is outside the threat+ * model.*/function containsInterpreterSimulatorPayload(tokens: string[]): boolean {- const interpreter = executableName(tokens[0]);- const payload = tokens.slice(1).join('\n');- if (PROGRAMMABLE_INTERPRETER.test(interpreter)) {- return containsLiteralSimulatorExecutor(payload);- }- if (interpreter === 'osascript') {- // AppleScript can execute through `do shell script`, while JavaScript for- // Automation can reach NSTask/NSProcessInfo directly. Once an osascript- // payload contains a literal Simulator executor, command-text policy cannot- // safely distinguish an inert reference from executable code.- return containsLiteralSimulatorExecutor(payload);- }- return false;+ if (!PROGRAMMABLE_INTERPRETER.test(executableName(tokens[0]))) return false;+ return containsLiteralSimulatorExecutor(tokens.slice(1).join('\n'));}-/**- * Fail closed when a command passes a literal Simulator executor to an opaque- * execution wrapper (for example xargs or find -exec). Commands whose only- * purpose is displaying/searching text remain outside this boundary.- */-function containsOpaqueSimulatorExecution(tokens: string[]): boolean {- const head = executableName(tokens[0]);- if (!head || NON_EXECUTING_REFERENCE_COMMANDS.has(head) || head === 'osascript') return false;- const findExec =- head === 'find' && tokens.some((token) => /^-(?:exec|execdir|ok|okdir)$/.test(token));- if (!findExec && !OPAQUE_EXECUTION_WRAPPERS.has(head)) return false;- // Direct simctl commands have already been classified above, including the- // explicitly read-only allowlist.- if (simctlSubcommand(tokens) !== null) return false;- return containsLiteralSimulatorExecutor(tokens.slice(1).join(' '));-}--/** Extract command/process substitutions because they execute even inside an otherwise safe command. */+/** Command and process substitutions execute, so their contents are classified too. */function shellSubcommands(command: string): string[] {const subcommands: string[] = [];let quote: "'" | '"' | null = null;@@ -706,496 +629,311 @@ function shellSubcommands(command: string): string[] {return subcommands;}-/** Split independent command clauses while retaining pipeline boundaries. */-function shellClauses(command: string): string[] {- const clauses: string[] = [];- let current = '';- let quote: "'" | '"' | null = null;- let escaped = false;- for (let index = 0; index < command.length; index += 1) {- const char = command[index]!;- if (escaped) {- current += char;- escaped = false;- continue;- }- if (char === '\\' && quote !== "'") {- current += char;- escaped = true;- continue;- }- if (quote) {- current += char;- if (char === quote) quote = null;- continue;- }- if (char === "'" || char === '"') {- current += char;- quote = char;- continue;- }- if (char === '|' && command[index + 1] === '|') {- if (current.trim()) clauses.push(current.trim());- current = '';- index += 1;- continue;- }- if (char === '&' && current.trimEnd().endsWith('|')) {- current += char;- continue;- }- if (char === '\n' || char === ';' || char === '&') {- if (current.trim()) clauses.push(current.trim());- current = '';- continue;- }- current += char;- }- if (current.trim()) clauses.push(current.trim());- return clauses;+function nestedShellConsumesStdinAsProgram(command: string): boolean {+ return (+ /(?:^|[;&|]\s*)(?:source|\.)\s+(?:\/dev\/stdin|\/dev\/fd\/0|-)(?:\s|$)/i.test(command) ||+ /\beval\b[\s\S]*\$\(\s*cat(?:\s+(?:-|\/dev\/stdin|\/dev\/fd\/0))?\s*\)/i.test(command)+ );}-function isLiteralSimulatorBypass(command: string): boolean {- for (const segment of shellSegments(command)) {- const unwrapped = unwrapCommand(tokenizeShellSegment(segment));- if (unwrapped.inspectionOnly || unwrapped.unresolvedWrapper) continue;- if (isExternalSimulatorLaunch(unwrapped.tokens) || isSimulatorMutation(unwrapped.tokens)) {- return true;- }+/** Leading shell options removed before deciding whether a script operand exists. */+function shellPositionalArgs(args: string[]): string[] {+ let index = 0;+ while (index < args.length) {+ const token = args[index]!;+ if (token === '--') return args.slice(index + 1);+ if (!token.startsWith('-') && !token.startsWith('+')) break;+ // Bash/zsh `-o name` and Bash `-O shopt_name` consume the next token; that+ // operand is not a script filename and does not displace heredoc stdin.+ index += /^[-+][oO]$/.test(token) ? 2 : 1;}- return false;-}--function isSimulatorExecutorValue(value: string): boolean {- const normalized = value- .trim()- .replace(/^['"]|['"]$/g, '')- .replace(/\\/g, '/');- return /(?:^|\/)(?:xcrun|simctl)$/i.test(normalized) || /Simulator(?:\.app)?/i.test(normalized);-}--/** Dynamic command names can resolve to a Simulator bypass, so execution must fail closed. */-function hasDynamicShellExpansion(token: string): boolean {- return /[$`*?[\]{}()^~]/.test(token) || token.indexOf('#') > 0;+ return args.slice(index);}-function hasUnresolvedExecutableExpansion(tokens: string[]): boolean {- const executableTokens = stripShellControlTokens(tokens);- while (executableTokens[0] && /^[A-Za-z_][A-Za-z0-9_]*=/.test(executableTokens[0])) {- executableTokens.shift();+/** Whether this literal command executes its stdin as source code. */+function consumesStdinAsProgram(tokens: string[]): boolean {+ const unwrapped = unwrapCommand(tokens);+ if (unwrapped.nestedShell !== null) {+ return nestedShellConsumesStdinAsProgram(unwrapped.nestedShell);}- const executable = executableTokens[0] ?? '';- // `[` and `[[` are literal shell condition builtins, not glob-expanded- // executable names. Other expansion syntax in command position is unsafe.- if (executable === '[' || executable === '[[') return false;- return hasDynamicShellExpansion(executable);-}--/** Arithmetic compound commands contain expressions, not an executable argv. */-function isArithmeticCompoundCommand(tokens: string[]): boolean {- let index = 0;- while (tokens[index] && /^[A-Za-z_][A-Za-z0-9_]*=/.test(tokens[index]!)) index += 1;- while (tokens[index] && /^(?:\{|\(|!|then|do|else|elif|if|while|until)$/.test(tokens[index]!)) {- index += 1;+ const executable = executableName(unwrapped.tokens[0]);+ const args = unwrapped.tokens.slice(1);+ if (SHELL_EXECUTABLES.has(executable)) {+ if (args.some((arg) => /^-[A-Za-z]*c[A-Za-z]*$/.test(arg))) return false;+ if (args.some((arg) => /^-[A-Za-z]*s[A-Za-z]*$/.test(arg))) return true;+ } else if (executable === 'osascript') {+ if (args.some((arg) => arg === '-e' || arg.startsWith('-e'))) return false;+ } else if (PROGRAMMABLE_INTERPRETER.test(executable)) {+ if (/^(?:(?:g|m|n)?awk)$/.test(executable)) return false;+ if (args.some((arg) => /^(?:-c|-e|-p|-m|--eval|--print|--input-type|--module)$/.test(arg))) {+ return false;+ }+ } else {+ return false;}- return tokens[index] === '((' || tokens[index]?.startsWith('((') === true;+ const positional = SHELL_EXECUTABLES.has(executable)+ ? shellPositionalArgs(args)[0]+ : args.find((arg) => !arg.startsWith('-'));+ return positional === undefined || positional === '-';}-/**- * Shell arithmetic recursively resolves bare variables and array subscripts,- * which can execute command substitutions stored in their values. Only- * expressions made entirely from decimal literals and operators are safe to- * classify without evaluating the shell environment.- */-function hasDynamicArithmeticEvaluation(segment: string): boolean {- const start = segment.indexOf('((');- const end = segment.lastIndexOf('))');- if (start < 0 || end < start + 2) return true;- const expression = segment.slice(start + 2, end);- return !/^[\s0-9()+\-*/%<>=!&|^~?:,]*$/.test(expression);+interface HeredocRedirection {+ start: number;+ marker: string;+ delimiter: string;+ expands: boolean;+ stripsTabs: boolean;}-/** Unknown wrapper option shapes cannot prove which expanded token becomes the command. */-function hasUnresolvedWrapperExpansion(unwrapped: UnwrappedCommand): boolean {- return (- unwrapped.unresolvedWrapper && unwrapped.tokens.some((token) => hasDynamicShellExpansion(token))- );+function heredocDescriptorBefore(+ segment: string,+ start: number,+): { value: string; start: number } | null {+ const beforeOperator = segment.slice(0, start);+ const match = /(?:^|[\s;&|()])(\d+|\{[A-Za-z_][A-Za-z0-9_]*\})$/.exec(beforeOperator);+ const value = match?.[1];+ return value === undefined ? null : { value, start: start - value.length };}-type OpaqueOptionShape = 'flag' | 'value' | 'command' | 'unknown';--function opaqueOptionShape(head: string, token: string): OpaqueOptionShape {- const option = token.replace(/=.*/s, '=');- if (head === 'sudo') {- if (- /^(?:-[CDghpRrTtUu]|--(?:chdir|close-from|group|host|prompt|role|command-timeout|type|other-user|user))$/.test(- token,- )- )- return 'value';- if (- /^(?:-[ABbEeHhKklnPSsVv]|--(?:askpass|bell|background|edit|preserve-env|set-home|help|remove-timestamp|reset-timestamp|list|non-interactive|stdin|shell|validate|version))$/.test(- token,- )- )- return 'flag';- if (/^(?:-[CDghpRrTtUu].+|--[^=]+=)/.test(token)) return 'flag';- }- if (head === 'doas') {- if (/^-(?:a|C|u)$/.test(token)) return 'value';- if (/^-(?:L|n|s)$/.test(token) || /^-(?:a|C|u).+/.test(token)) return 'flag';- }- if (head === 'xargs') {- if (- /^(?:-[EILnPRSs]|--(?:eof|replace|max-lines|max-args|max-procs|right|max-chars))$/.test(token)- )- return 'value';- if (/^(?:-[0oprtx]|--(?:null|open-tty|interactive|no-run-if-empty|verbose|exit))$/.test(token))- return 'flag';- if (/^(?:-[EILnPRSs].+|--[^=]+=)/.test(token)) return 'flag';- }- if (head === 'sandbox-exec') {- if (/^-(?:D|f|n|p)$/.test(token)) return 'value';- if (/^-(?:D|f|n|p).+/.test(token)) return 'flag';- }- if (head === 'launchctl') {- if (token === '-p') return 'command';- if (/^-(?:l|o|e)$/.test(token)) return 'value';- if (/^-(?:l|o|e).+/.test(token)) return 'flag';- }- if (head === 'timeout' || head === 'gtimeout') {- if (/^(?:-k|-s|--kill-after|--signal)$/.test(token)) return 'value';- if (/^(?:-v|--foreground|--preserve-status|--verbose)$/.test(token)) return 'flag';- if (/^(?:-[ks].+|--[^=]+=)/.test(token)) return 'flag';- }- if (head === 'watch') {- if (/^(?:-n|--interval)$/.test(token)) return 'value';- if (- /^(?:-[bcegpqrtwx]+|-d(?:=permanent)?|--(?:beep|color|differences(?:=permanent)?|chgexit|errexit|equexit|no-rerun|no-title|no-wrap|precise|exec))$/.test(- token,- )- )- return 'flag';- if (/^(?:-n.+|--interval=)/.test(option)) return 'flag';- }- if (head === 'script') {- if (/^(?:-c|--command)$/.test(token)) return 'command';- if (/^(?:-t|-T|--timing)$/.test(token)) return 'value';- if (/^-[adeFkpqr]+$/.test(token)) return 'flag';- }- return 'unknown';+/** Whether a heredoc redirection feeds the command's stdin rather than another fd. */+function heredocIsStdinRedirection(segment: string, start: number): boolean {+ const descriptor = heredocDescriptorBefore(segment, start);+ return descriptor === null || descriptor.value === '0';}-function hasDynamicWrappedCommand(tokens: string[], depth: number): boolean {- if (tokens.length === 0) return false;- if (depth > MAX_WRAPPER_UNWRAP_DEPTH) {- return tokens.some((token) => hasDynamicShellExpansion(token));- }- const unwrapped = unwrapCommand(tokens);- if (unwrapped.inspectionOnly) return false;- if (hasUnresolvedWrapperExpansion(unwrapped)) return true;- if (unwrapped.nestedShell !== null) {- if (containsSimulatorBypass(unwrapped.nestedShell, depth + 1)) return true;- return unwrapped.tokens.some((token) => hasDynamicShellExpansion(token));- }- if (hasUnresolvedExecutableExpansion(unwrapped.tokens)) return true;- return hasOpaqueWrapperExpansion(tokens, depth + 1);-}--/** Locate the command operand conservatively without mistaking later data argv for executables. */-function hasOpaqueWrapperExpansion(tokens: string[], depth = 0): boolean {- tokens = stripShellRedirections(tokens);- const head = executableName(tokens[0]);- if (head === 'find') {- for (let index = 1; index < tokens.length; index += 1) {- if (!/^-(?:exec|execdir|ok|okdir)$/.test(tokens[index]!)) continue;- const terminator = tokens.findIndex(- (token, candidateIndex) =>- candidateIndex > index && (token === ';' || token === '+' || token === '\\;'),- );- const commandEnd = terminator < 0 ? tokens.length : terminator;- return hasDynamicWrappedCommand(tokens.slice(index + 1, commandEnd), depth + 1);+/**+ * Skip a shell arithmetic expression while looking for heredoc operators.+ *+ * `<<` is also the arithmetic left-shift operator. Treating it as a heredoc+ * opener makes the following physical lines look like the body for a marker+ * named `2`, so a real command after the arithmetic expression can disappear+ * from classification. Both `$(( ... ))` expansions and `(( ... ))` commands+ * use the same balanced-parenthesis shape here.+ */+function skipArithmeticExpression(line: string, start: number): number {+ let depth = 1;+ let quote: "'" | '"' | null = null;+ let escaped = false;+ const expressionStart = line[start] === '$' ? start + 3 : start + 2;+ for (let index = expressionStart; index < line.length; index += 1) {+ const char = line[index]!;+ if (escaped) {+ escaped = false;+ continue;}- return false;- }- if (!OPAQUE_EXECUTION_WRAPPERS.has(head)) return false;- if (head === 'coproc') {- // Bash/zsh allow an optional coprocess name, so command position is- // ambiguous. Any expansion in this execution form must fail closed.- return tokens.slice(1).some((token) => hasDynamicShellExpansion(token));- }- if (head === 'repeat') {- // zsh evaluates the count arithmetically before executing argv.- if (!/^\d+$/.test(tokens[1] ?? '')) return true;- return hasDynamicWrappedCommand(tokens.slice(2), depth + 1);- }-- let index = 1;- if (head === 'launchctl') {- if (tokens[1] === 'submit') index = 2;- else if (tokens[1] === 'asuser' || tokens[1] === 'bsexec') index = 3;- }- while (index < tokens.length) {- const token = tokens[index]!;- if (token === '--') {- index += 1;- break;- }- if (!token.startsWith('-')) break;- const shape = opaqueOptionShape(head, token);- const possibleValue = tokens[index + 1];- if (shape === 'command') {- const commandValue = token.includes('=')- ? token.slice(token.indexOf('=') + 1)- : possibleValue;- if (hasDynamicShellExpansion(commandValue ?? '')) return true;- index += token.includes('=') ? 1 : 2;+ if (char === '\\' && quote !== "'") {+ escaped = true;continue;}- if (shape === 'value') {- index += 2;+ if (char === "'" || char === '"') {+ if (quote === char) quote = null;+ else if (quote === null) quote = char;continue;}- if (shape === 'flag') {- index += 1;+ if (quote) continue;+ if (char === '(') {+ depth += 1;continue;}- // Unknown option arity makes every later dynamic token ambiguous: it may- // be either an option value or the actual command. Fail closed instead of- // guessing and accidentally stepping past the executable.- return tokens.slice(index).some((value) => hasDynamicShellExpansion(value));+ if (char !== ')') continue;+ if (depth === 1 && line[index + 1] === ')') return index + 2;+ depth -= 1;}- if (head === 'sudo') {- while (/^[A-Za-z_][A-Za-z0-9_]*=/.test(tokens[index] ?? '')) index += 1;- }- // timeout consumes a duration before its command; macOS script consumes an- // output file before an optional command.- if (head === 'timeout' || head === 'gtimeout' || head === 'script') index += 1;- return hasDynamicWrappedCommand(tokens.slice(index), depth + 1);-}--function referencesVariable(command: string, variable: string): boolean {- const escaped = variable.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');- return new RegExp(`\\$(?:${escaped}\\b|\\{${escaped}\\})`).test(command);+ return line.length;}-const SHELL_ASSIGNMENT_BUILTINS = new Set(['declare', 'export', 'local', 'readonly', 'typeset']);--function collectShellAssignments(tokens: string[]): Array<{ name: string; value: string }> {- const assignments: Array<{ name: string; value: string }> = [];- let index = 0;- const head = executableName(tokens[0]);- if (SHELL_ASSIGNMENT_BUILTINS.has(head)) {- index = 1;- while (tokens[index]?.startsWith('-')) index += 1;- }- for (; index < tokens.length; index += 1) {- const assignment = /^([A-Za-z_][A-Za-z0-9_]*)=(.*)$/s.exec(tokens[index]!);- if (!assignment) {- if (!SHELL_ASSIGNMENT_BUILTINS.has(head)) break;+/** Skip Bash's legacy `$[ ... ]` arithmetic expansion. */+function skipLegacyArithmeticExpression(line: string, start: number): number {+ let depth = 1;+ let quote: "'" | '"' | null = null;+ let escaped = false;+ for (let index = start + 2; index < line.length; index += 1) {+ const char = line[index]!;+ if (escaped) {+ escaped = false;continue;}- assignments.push({ name: assignment[1]!, value: assignment[2] ?? '' });- }- return assignments;-}--/** Track simple shell assignments so a later eval/sh -c/$VAR cannot hide a bypass. */-function containsTaintedVariableExecution(command: string): boolean {- const tainted = new Set<string>();- const tokenizedSegments = shellSegments(command).map((segment) => ({- segment,- tokens: tokenizeShellSegment(segment),- }));- const assignments = tokenizedSegments.flatMap(({ tokens }) => collectShellAssignments(tokens));- for (const { segment } of tokenizedSegments) {- for (const match of segment.matchAll(/\b([A-Za-z_][A-Za-z0-9_]*)=\$\(([^)]*)\)/g)) {- if (containsLiteralSimulatorExecutor(match[2] ?? '')) tainted.add(match[1]!);+ if (char === '\\' && quote !== "'") {+ escaped = true;+ continue;}- }- for (const assignment of assignments) {- if (isLiteralSimulatorBypass(assignment.value) || isSimulatorExecutorValue(assignment.value)) {- tainted.add(assignment.name);+ if (char === "'" || char === '"') {+ if (quote === char) quote = null;+ else if (quote === null) quote = char;+ continue;}- }- if (tainted.size === 0) return false;-- for (const { segment, tokens } of tokenizedSegments) {- const unwrapped = unwrapCommand(tokens);- for (const variable of tainted) {- if (unwrapped.nestedShell !== null && referencesVariable(unwrapped.nestedShell, variable)) {- return true;- }- if (referencesVariable(unwrapped.tokens[0] ?? '', variable)) return true;- if (- executableName(unwrapped.tokens[0]) === 'xcrun' &&- unwrapped.tokens.some((token) => referencesVariable(token, variable))- ) {- return true;- }- // Unknown wrappers are unsafe when they consume a tainted command value.- if (unwrapped.unresolvedWrapper && referencesVariable(segment, variable)) return true;+ if (quote) continue;+ if (char === '[') {+ depth += 1;+ continue;}+ if (char === ']' && --depth === 0) return index + 1;}- return false;+ return line.length;}-function nestedShellConsumesStdinAsProgram(command: string): boolean {- return (- /(?:^|[;&|]\s*)(?:source|\.)\s+(?:\/dev\/stdin|\/dev\/fd\/0|-)(?:\s|$)/i.test(command) ||- /\beval\b[\s\S]*\$\(\s*cat(?:\s+(?:-|\/dev\/stdin|\/dev\/fd\/0))?\s*\)/i.test(command)- );-}--function consumesStdinAsProgram(tokens: string[]): boolean {- const unwrapped = unwrapCommand(tokens);- if (unwrapped.nestedShell !== null) {- return !unwrapped.unresolvedWrapper && nestedShellConsumesStdinAsProgram(unwrapped.nestedShell);- }- if (unwrapped.unresolvedWrapper) return false;- const executable = executableName(unwrapped.tokens[0]);- const args = unwrapped.tokens.slice(1);- if (SHELL_EXECUTABLES.has(executable)) {- if (args.some((arg) => /^-[A-Za-z]*c[A-Za-z]*$/.test(arg))) return false;- if (args.some((arg) => /^-[A-Za-z]*s[A-Za-z]*$/.test(arg))) return true;- } else if (executable === 'osascript') {- if (args.some((arg) => arg === '-e' || arg.startsWith('-e'))) return false;- } else if (PROGRAMMABLE_INTERPRETER.test(executable)) {- if (/^(?:(?:g|m|n)?awk)$/.test(executable)) return false;- if (args.some((arg) => /^(?:-c|-e|-p|-m|--eval|--print|--input-type|--module)$/.test(arg))) {- return false;+/** Heredoc markers on one shell line, excluding quoted text, comments and `<<<`. */+function heredocRedirections(line: string): HeredocRedirection[] {+ const redirections: HeredocRedirection[] = [];+ let quote: "'" | '"' | null = null;+ let escaped = false;+ for (let index = 0; index < line.length; index += 1) {+ const char = line[index]!;+ if (escaped) {+ escaped = false;+ continue;}- } else {- return false;- }- const positional = args.find((arg) => !arg.startsWith('-'));- return positional === undefined || positional === '-';-}--function containsInterpreterHeredocBypass(command: string): boolean {- const lines = command.split(/\r?\n/);- for (let index = 0; index < lines.length; index += 1) {- const line = lines[index] ?? '';- const marker = /<<-?\s*(['"]?)([A-Za-z_][A-Za-z0-9_]*)\1/.exec(line);- if (!marker) continue;+ if (char === '\\' && quote !== "'") {+ escaped = true;+ continue;+ }+ if (char === "'" || char === '"') {+ if (quote === char) quote = null;+ else if (quote === null) quote = char;+ continue;+ }+ if (quote) continue;+ // `<<` inside arithmetic syntax is left shift, not a shell heredoc. Skip+ // both current `$(( ... ))` / `(( ... ))` and Bash's legacy `$[ ... ]`.if (- !shellSegments(line.slice(0, marker.index)).some((segment) =>- consumesStdinAsProgram(tokenizeShellSegment(segment)),- )+ (char === '$' && line[index + 1] === '(' && line[index + 2] === '(') ||+ (char === '(' && line[index + 1] === '(')) {+ index = skipArithmeticExpression(line, index) - 1;continue;}- const delimiter = marker[2]!;- const body: string[] = [];- for (index += 1; index < lines.length; index += 1) {- if ((lines[index] ?? '').replace(/^\t+/, '').trim() === delimiter) break;- body.push(lines[index] ?? '');+ if (char === '$' && line[index + 1] === '[') {+ index = skipLegacyArithmeticExpression(line, index) - 1;+ continue;}- if (containsLiteralSimulatorExecutor(body.join('\n'))) return true;- }- return false;-}--/** A here-string is executable stdin just like a heredoc or producer pipeline. */-function containsInterpreterHereStringBypass(command: string): boolean {- for (const clause of shellClauses(command)) {- let quote: "'" | '"' | null = null;- let escaped = false;- for (let index = 0; index < clause.length - 2; index += 1) {- const char = clause[index]!;- if (escaped) {- escaped = false;+ // In shell grammar `#` starts a comment when it begins a word. A marker in+ // that comment must not consume later commands as a fake heredoc body.+ if (char === '#' && (index === 0 || /[\s;&|()]/.test(line[index - 1]!))) break;+ if (char !== '<' || line[index + 1] !== '<' || line[index + 2] === '<') continue;+ let cursor = index + 2;+ const stripsTabs = line[cursor] === '-';+ if (stripsTabs) cursor += 1;+ while (line[cursor] === ' ' || line[cursor] === '\t') cursor += 1;+ let delimiter = '';+ let expands = true;+ while (cursor < line.length) {+ const delimiterChar = line[cursor]!;+ if (+ delimiterChar === '$'+ && (line[cursor + 1] === "'" || line[cursor + 1] === '"')+ ) {+ // Bash's ANSI-C and locale quote prefixes are removed along with the+ // surrounding quotes for a simple literal delimiter (`$'EOF'`). Do not+ // grow this boundary into decoding ANSI-C escape sequences.+ expands = false;+ cursor += 1;continue;}- if (char === '\\' && quote !== "'") {- escaped = true;+ if (delimiterChar === "'" || delimiterChar === '"') {+ expands = false;+ const closing = line.indexOf(delimiterChar, cursor + 1);+ if (closing < 0) {+ delimiter += line.slice(cursor + 1);+ cursor = line.length;+ break;+ }+ delimiter += line.slice(cursor + 1, closing);+ cursor = closing + 1;continue;}- if (char === "'" || char === '"') {- if (quote === char) quote = null;- else if (quote === null) quote = char;+ if (delimiterChar === '\\') {+ expands = false;+ cursor += 1;+ if (cursor < line.length) {+ delimiter += line[cursor]!;+ cursor += 1;+ }continue;}- if (quote || clause.slice(index, index + 3) !== '<<<') continue;- const consumer = clause.slice(0, index).trim();- const payload = clause.slice(index + 3);- if (- shellSegments(consumer).some((segment) =>- consumesStdinAsProgram(tokenizeShellSegment(segment)),- ) &&- containsLiteralSimulatorExecutor(payload)- ) {- return true;- }- break;- }+ if (/[\s;&|<>()]/.test(delimiterChar)) break;+ delimiter += delimiterChar;+ cursor += 1;+ }+ if (delimiter !== '') {+ redirections.push({+ start: index,+ marker: line.slice(index, cursor),+ delimiter,+ expands,+ stripsTabs,+ });+ }+ index = cursor - 1;}- return false;+ return redirections;}-/** A literal command piped to a code-reading interpreter becomes executable input. */-function containsShellConsumedLiteralBypass(command: string): boolean {- if (containsInterpreterHeredocBypass(command) || containsInterpreterHereStringBypass(command)) {- return true;- }- for (const clause of shellClauses(command)) {- if (!clause.includes('|')) continue;- const segments = shellSegments(clause);- if (- segments.some((segment) => consumesStdinAsProgram(tokenizeShellSegment(segment))) &&- containsLiteralSimulatorExecutor(clause)- ) {- return true;- }+/** Remove heredoc operators before tokenizing the command that consumes them. */+function removeHeredocRedirections(command: string): string {+ const redirections = heredocRedirections(command);+ let result = command;+ for (let index = redirections.length - 1; index >= 0; index -= 1) {+ const redirection = redirections[index]!;+ const descriptor = heredocDescriptorBefore(command, redirection.start);+ const removalStart = descriptor?.start ?? redirection.start;+ result =+ result.slice(0, removalStart)+ + result.slice(redirection.start + redirection.marker.length);}- return false;+ return result;}-function isLiteralXcrunBoundaryToken(token: string): boolean {- return /^[A-Za-z0-9_./:+-]+$/.test(token);+/** Find the closing parenthesis for a shell `$(...)`, `<(...)` or `>(...)`. */+function skipShellSubstitution(input: string, start: number): number {+ let depth = 1;+ let quote: "'" | '"' | null = null;+ let escaped = false;+ for (let index = start + 2; index < input.length; index += 1) {+ const char = input[index]!;+ if (escaped) {+ escaped = false;+ continue;+ }+ if (char === '\\' && quote !== "'") {+ escaped = true;+ continue;+ }+ if (char === "'" || char === '"') {+ if (quote === char) quote = null;+ else if (quote === null) quote = char;+ continue;+ }+ if (quote !== null) continue;+ if (char === '(') depth += 1;+ else if (char === ')' && --depth === 0) return index;+ }+ return input.length - 1;}-function hasUnresolvedXcrunTool(tokens: string[]): boolean {- if (executableName(tokens[0]) !== 'xcrun') return false;- let index = 1;- while (index < tokens.length && tokens[index]!.startsWith('-')) {- const option = tokens[index]!;- if (/^(?:--sdk|-sdk|--toolchain|-toolchain)=/.test(option)) {- const value = option.slice(option.indexOf('=') + 1);- if (!isLiteralXcrunBoundaryToken(value)) return true;- index += 1;+/** Find the closing backtick for an old-style shell command substitution. */+function skipBacktickSubstitution(input: string, start: number): number {+ let escaped = false;+ for (let index = start + 1; index < input.length; index += 1) {+ const char = input[index]!;+ if (escaped) {+ escaped = false;continue;}- if (- option === '--sdk' ||- option === '-sdk' ||- option === '--toolchain' ||- option === '-toolchain'- ) {- const value = tokens[index + 1];- if (!value || !isLiteralXcrunBoundaryToken(value)) return true;- index += 2;+ if (char === '\\') {+ escaped = true;continue;}- index += 1;+ if (char === '`') return index;}- const firstToolToken = tokens[index] ?? '';- return firstToolToken !== '' && !isLiteralXcrunBoundaryToken(firstToolToken);+ return input.length - 1;}-const SHELL_FUNCTION_HEADER_SOURCE =- '(?:(?:function\\s+)?[A-Za-z_][A-Za-z0-9_]*\\s*\\(\\s*\\)|function\\s+[A-Za-z_][A-Za-z0-9_]*)';-const SHELL_FUNCTION_DEFINITION_PREFIX = new RegExp(`^${SHELL_FUNCTION_HEADER_SOURCE}\\s*[({]`);--function shellCompoundBodyEnd(command: string, openingIndex: number): number | null {- const opening = command[openingIndex];- if (opening !== '{' && opening !== '(') return null;- const closing = opening === '{' ? '}' : ')';- let nesting = 1;- let quote: "'" | '"' | '`' | null = null;+/** Whether a pipeline segment explicitly replaces its stdin source. */+function hasUnquotedStdinRedirection(segment: string): boolean {+ let quote: "'" | '"' | null = null;let escaped = false;- for (let index = openingIndex + 1; index < command.length; index += 1) {- const char = command[index]!;+ for (let index = 0; index < segment.length; index += 1) {+ const char = segment[index]!;if (escaped) {escaped = false;continue;@@ -1208,108 +946,195 @@ function shellCompoundBodyEnd(command: string, openingIndex: number): number | nif (char === quote) quote = null;continue;}- if (char === "'" || char === '"' || char === '`') {+ if (char === "'" || char === '"') {quote = char;continue;}- if (char === opening) nesting += 1;- else if (char === closing) {- nesting -= 1;- if (nesting === 0) return index;+ if (+ (char === '$' && segment[index + 1] === '(' && segment[index + 2] === '(') ||+ (char === '(' && segment[index + 1] === '(')+ ) {+ index = skipArithmeticExpression(segment, index) - 1;+ continue;+ }+ if (char === '$' && segment[index + 1] === '[') {+ index = skipLegacyArithmeticExpression(segment, index) - 1;+ continue;+ }+ if (+ (char === '$' || char === '<' || char === '>')+ && segment[index + 1] === '('+ ) {+ index = skipShellSubstitution(segment, index);+ continue;+ }+ if (char === '`') {+ index = skipBacktickSubstitution(segment, index);+ continue;}+ if (char !== '<') continue;+ const redirection = redirectionAt(segment, index);+ if (redirection === null) continue;+ // A descriptor other than 0 redirects a separate input channel and does+ // not replace the pipeline's stdin. Cover both `2<file` and Bash's+ // allocated-fd spelling `{fd}<file`.+ const beforeOperator = segment.slice(0, index);+ const explicitDescriptor =+ /(?:^|[\s;&|()])(\d+)$/.exec(beforeOperator)?.[1]+ ?? /(?:^|[\s;&|()])(\{[A-Za-z_][A-Za-z0-9_]*\})$/.exec(beforeOperator)?.[1]+ ?? null;+ if (explicitDescriptor !== null && explicitDescriptor !== '0') {+ index += redirection.length - 1;+ continue;+ }+ return true;}- return null;+ return false;}-/** Function bodies are executable later, so reject unsafe bodies at definition time. */-function containsSimulatorFunctionBody(command: string, depth: number): boolean {- const functionPattern = new RegExp(- `(?:^|[;\\n]\\s*)${SHELL_FUNCTION_HEADER_SOURCE}\\s*([({])`,- 'g',+/** Whether the heredoc's own clause hands its body to a code-reading consumer. */+function heredocBodyIsProgram(line: string, markerStart: number): boolean {+ const segments = shellSegments(line);+ let searchCursor = 0;+ let openingSegmentStart = -1;+ const openingIndex = segments.findIndex((segment) => {+ const segmentStart = line.indexOf(segment.command, searchCursor);+ if (segmentStart < 0) return false;+ searchCursor = segmentStart + segment.command.length;+ if (markerStart < segmentStart || markerStart >= searchCursor) return false;+ openingSegmentStart = segmentStart;+ return true;+ });+ if (openingIndex < 0) return false;+ const openingSegment = segments[openingIndex]!;+ const localMarkerStart = markerStart - openingSegmentStart;+ const openingRedirections = heredocRedirections(openingSegment.command);+ const openingRedirection = openingRedirections.find(+ (redirection) => redirection.start === localMarkerStart,);- while (functionPattern.exec(command) !== null) {- const openingIndex = functionPattern.lastIndex - 1;- const closingIndex = shellCompoundBodyEnd(command, openingIndex);- if (closingIndex === null) continue;- if (containsSimulatorBypass(command.slice(openingIndex + 1, closingIndex), depth + 1)) {- return true;- }- functionPattern.lastIndex = closingIndex + 1;+ if (+ !openingRedirection+ || !heredocIsStdinRedirection(openingSegment.command, openingRedirection.start)+ ) return false;+ // Bash applies multiple stdin heredocs on one consumer from left to right;+ // only the final stdin redirection supplies the process's input. A previous+ // body is data even when the later body is the program we should inspect.+ if (+ openingRedirections.some(+ (redirection) =>+ redirection.start > openingRedirection.start+ && heredocIsStdinRedirection(openingSegment.command, redirection.start),+ )+ ) return false;+ for (let index = openingIndex; index < segments.length; index += 1) {+ const segment = segments[index]!;+ if (index > openingIndex && segment.precedingOperator !== '|') break;+ // A downstream stdin redirection takes precedence over the pipe, so the+ // current heredoc body cannot become that command's input program.+ if (index > openingIndex && hasUnquotedStdinRedirection(segment.command)) break;+ if (+ consumesStdinAsProgram(+ tokenizeHeredocConsumer(removeHeredocRedirections(segment.command)),+ )+ ) return true;}return false;}-/** Alias bodies are executable later, so reject unsafe definitions up front. */-function containsSimulatorAliasDefinition(tokens: string[], depth: number): boolean {- if (executableName(tokens[0]) !== 'alias') return false;- let index = tokens[1] === '--' ? 2 : 1;- for (; index < tokens.length; index += 1) {- const definition = tokens[index]!;- const separator = definition.indexOf('=');- // `alias` and `alias name` only inspect the current shell state.- if (separator <= 0) continue;- const body = definition.slice(separator + 1);- if (containsLiteralSimulatorExecutor(body) || containsSimulatorBypass(body, depth + 1)) {- return true;+/**+ * Remove stdin-only heredoc prose before classifying command words.+ *+ * Bodies executed by a shell/interpreter remain visible. Data bodies disappear,+ * except that an unquoted delimiter still executes command/process substitutions.+ */+function stripHeredocBodies(command: string): string {+ if (!command.includes('<<')) return command;+ const lines = command.split(/\r?\n/);+ const executable: string[] = [];+ for (let index = 0; index < lines.length; index += 1) {+ const line = lines[index]!;+ executable.push(line);+ for (const heredoc of heredocRedirections(line)) {+ const body: string[] = [];+ index += 1;+ for (; index < lines.length; index += 1) {+ const candidate = lines[index]!;+ const unindented = heredoc.stripsTabs ? candidate.replace(/^\t+/, '') : candidate;+ if (unindented === heredoc.delimiter) break;+ body.push(candidate);+ }+ if (heredocBodyIsProgram(line, heredoc.start)) executable.push(...body);+ else if (heredoc.expands) executable.push(...shellSubcommands(body.join('\n')));+ if (index >= lines.length) break;}}- return false;+ return executable.join('\n');}-function containsSimulatorBypass(command: string, depth = 0): boolean {- if (depth > 8) return /\b(?:simctl|Simulator(?:\.app)?)\b/i.test(command);- if (- containsTaintedVariableExecution(command) ||- containsShellConsumedLiteralBypass(command) ||- containsSimulatorFunctionBody(command, depth)- ) {- return true;- }- for (const nested of shellSubcommands(command)) {- if (containsSimulatorBypass(nested, depth + 1)) return true;+function containsSimulatorRecipe(command: string, depth = 0): boolean {+ if (depth > MAX_RECURSION_DEPTH) return false;+ const executableCommand = stripHeredocBodies(command);+ for (const nested of shellSubcommands(executableCommand)) {+ if (containsSimulatorRecipe(nested, depth + 1)) return true;}- for (const segment of shellSegments(command)) {- // Function bodies were classified recursively above. The leading- // `name(){` token is not an execution wrapper in its own right.- if (SHELL_FUNCTION_DEFINITION_PREFIX.test(segment)) {- continue;+ const assignments = new Map<string, string[]>();+ const referencedAssignmentContainsRecipe = (+ reference: string,+ visibleAssignments: Map<string, string[]> = assignments,+ ): boolean => {+ for (const [name, values] of visibleAssignments) {+ // The name matched `[A-Za-z_][A-Za-z0-9_]*`, so it carries no regex syntax.+ if (!new RegExp(`\\$\\{?${name}\\b`).test(reference)) continue;+ if (values.some((value) => containsSimulatorRecipe(value, depth + 1))) return true;}- const tokens = tokenizeShellSegment(segment);- const arithmeticCompound = isArithmeticCompoundCommand(tokens);- if (arithmeticCompound && hasDynamicArithmeticEvaluation(segment)) return true;- const unwrapped = unwrapCommand(tokens);- if (unwrapped.inspectionOnly) continue;- // Known wrappers are peeled first so `env "$TOOL"` and `exec "$TOOL"`- // cannot hide a dynamically constructed executable. Shell `-c`- // positional arguments are not executables by themselves; its nested- // program is classified recursively below instead.- if (- !arithmeticCompound &&- unwrapped.nestedShell === null &&- hasUnresolvedExecutableExpansion(unwrapped.tokens)- ) {- return true;+ return false;+ };+ for (const segment of shellSegments(executableCommand)) {+ const unwrapped = unwrapCommand(tokenizeShellSegment(segment.command));+ const commandScopedAssignments = new Map<string, string[]>();+ // Shell assignments replace the previous value before the command in this+ // segment runs. A `;`/newline-separated assignment therefore supersedes the+ // previous value, while a conditional, pipeline or background edge can skip+ // it or isolate its scope, so both values remain possible there.+ for (const assignment of unwrapped.assignments) {+ if (assignment.name === '') continue;+ const persistentAssignment =+ assignmentDefinitelyRunsInCurrentScope(segment)+ && unwrapped.tokens.length === 0+ && unwrapped.nestedShell === null;+ if (persistentAssignment) {+ assignments.set(assignment.name, [assignment.value]);+ } else if (unwrapped.tokens.length > 0 || unwrapped.nestedShell !== null) {+ // A leading assignment shadows the exported value only for this+ // command. Use its last value while classifying the child, then leave+ // the parent-shell possibilities unchanged for later segments.+ commandScopedAssignments.set(assignment.name, [assignment.value]);+ } else {+ const possibleValues = assignments.get(assignment.name) ?? [];+ possibleValues.push(assignment.value);+ assignments.set(assignment.name, possibleValues);+ }}- if (hasUnresolvedWrapperExpansion(unwrapped) || hasOpaqueWrapperExpansion(tokens)) {- return true;+ const visibleAssignments = new Map(assignments);+ for (const [name, values] of commandScopedAssignments) {+ visibleAssignments.set(name, values);}- if (containsSimulatorAliasDefinition(unwrapped.tokens, depth)) return true;if (unwrapped.nestedShell !== null) {- if (unwrapped.unresolvedWrapper)- return containsSimulatorExecutor(tokenizeShellSegment(segment));- if (containsSimulatorBypass(unwrapped.nestedShell, depth + 1)) return true;+ // `eval "$CMD"` and `sh -c "$CMD"` run a variable this scan cannot resolve.+ if (referencedAssignmentContainsRecipe(unwrapped.nestedShell, visibleAssignments)) {+ return true;+ }+ if (containsSimulatorRecipe(unwrapped.nestedShell, depth + 1)) return true;continue;}- if (unwrapped.unresolvedWrapper && containsSimulatorExecutor(unwrapped.tokens)) return true;+ // A variable in the command word position is run as the command itself.+ const commandWord = unwrapped.tokens[0];if (- hasUnresolvedXcrunTool(unwrapped.tokens) ||- containsInterpreterSimulatorPayload(unwrapped.tokens) ||- isExternalSimulatorLaunch(unwrapped.tokens) ||- isSimulatorMutation(unwrapped.tokens) ||- containsOpaqueSimulatorExecution(unwrapped.tokens)- ) {- return true;- }+ commandWord?.includes('$')+ && referencedAssignmentContainsRecipe(commandWord, visibleAssignments)+ ) return true;+ if (isSimulatorRecipeArgv(unwrapped.tokens)) return true;+ if (containsInterpreterSimulatorPayload(unwrapped.tokens)) return true;}return false;}@@ -1320,9 +1145,8 @@ export function getDesktopShellCommandPolicy(): ShellCommandPolicyDenial | undefined {if (process.platform !== 'darwin') return undefined;// POSIX shells remove an unquoted backslash-newline before tokenization.- // Mirror that expansion so the policy cannot be bypassed with continuations.const expandedCommand = command.replace(/\\\r?\n/g, '');- if (containsSimulatorBypass(expandedCommand)) {+ if (containsSimulatorRecipe(expandedCommand)) {return { decision: 'deny', reason: IOS_SIMULATOR_SHELL_DENIAL };}return undefined;diff --git a/packages/maker-core/src/agents/codex/index.test.ts b/packages/maker-core/src/agents/codex/index.test.tsindex 9996f5f09c..ebd35eed81 100644--- a/packages/maker-core/src/agents/codex/index.test.ts+++ b/packages/maker-core/src/agents/codex/index.test.ts@@ -13011,6 +13011,10 @@ describe('CodexAgent MCP thread context hooks', () => {behavior: 'allow',}));handle.setInteractionResolver(resolver);+ const events: AgentEvent[] = [];+ const collectEvents = (async () => {+ for await (const event of handle.events()) events.push(event);+ })();const command = 'API_TOKEN=super-secret open -a Simulator';const result = await handlers.commandExecutionApproval({@@ -13034,9 +13038,585 @@ describe('CodexAgent MCP thread context hooks', () => {});expect(JSON.stringify(warn.mock.calls)).not.toContain('super-secret');await handle.close();+ await collectEvents;+ // Declining silently is indistinguishable from a user cancellation, so the+ // product reason has to reach the user.+ expect(events).toEqual(+ expect.arrayContaining([+ expect.objectContaining({+ type: 'error',+ data: expect.objectContaining({+ message: 'use the embedded iOS Simulator',+ isTerminal: false,+ }),+ }),+ ]),+ );+ });++ it('keeps an approval-path policy denial as the terminal turn reason', async () => {+ const policy = vi.fn(() => ({+ decision: 'deny' as const,+ reason: 'use the embedded iOS Simulator',+ }));+ const agent = new CodexAgent(createDeps({}, { getShellCommandPolicy: policy }));+ const host = installFakeHost(agent, (method) =>+ method === Method.TurnInterrupt ? {} : undefined,+ );+ const handle = await agent.startSession({+ sessionId: 'session-command-approval-policy-terminal-reason',+ model: 'gpt-5.4',+ workingDir: '/repo',+ permissionMode: 'bypassPermissions',+ });+ const handlers = host.getThreadHandlers();+ if (!handlers?.commandExecutionApproval || !handlers.itemCompleted || !handlers.turnCompleted) {+ throw new Error('expected commandExecutionApproval, itemCompleted and turnCompleted handlers');+ }+ const events: AgentEvent[] = [];+ const collectEvents = (async () => {+ for await (const event of handle.events()) events.push(event);+ })();++ await expect(+ handlers.commandExecutionApproval({+ threadId: 'start-thread-id',+ turnId: 'turn-approval-policy',+ itemId: 'cmd-approval-policy',+ command: 'open -a Simulator',+ cwd: '/repo',+ }),+ ).resolves.toEqual({ decision: 'decline' });+ // A declined command may still emit its own completion before the+ // abort-shaped turn completion. That is not recovery progress and must+ // not clear the policy reason.+ handlers.itemCompleted({+ threadId: 'start-thread-id',+ turnId: 'turn-approval-policy',+ item: {+ id: 'cmd-approval-policy',+ type: 'commandExecution',+ command: 'open -a Simulator',+ cwd: '/repo',+ },+ });+ handlers.turnCompleted({+ threadId: 'start-thread-id',+ turn: {+ id: 'turn-approval-policy',+ status: 'interrupted',+ error: { message: 'aborted by user' },+ },+ } as never);++ await handle.close();+ await collectEvents;+ const terminal = events.filter(+ (event) =>+ (event as { type?: string }).type === 'error' &&+ (event as { data?: { isTerminal?: boolean } }).data?.isTerminal === true,+ );+ expect(terminal).toEqual([+ expect.objectContaining({+ data: expect.objectContaining({+ message: 'use the embedded iOS Simulator',+ isTerminal: true,+ }),+ }),+ ]);+ expect(JSON.stringify(terminal)).not.toContain('aborted by user');+ });++ it('keeps all declined approval items attached to an interrupted turn', async () => {+ const policy = vi.fn(({ command }: { command: string }) => ({+ decision: 'deny' as const,+ reason: command.startsWith('open ') ? 'first policy reason' : 'latest policy reason',+ }));+ const agent = new CodexAgent(createDeps({}, { getShellCommandPolicy: policy }));+ const host = installFakeHost(agent);+ const handle = await agent.startSession({+ sessionId: 'session-command-approval-policy-multiple-denials',+ model: 'gpt-5.4',+ workingDir: '/repo',+ permissionMode: 'bypassPermissions',+ });+ const handlers = host.getThreadHandlers();+ if (!handlers?.commandExecutionApproval || !handlers.itemCompleted || !handlers.turnCompleted) {+ throw new Error('expected commandExecutionApproval, itemCompleted and turnCompleted handlers');+ }+ const events: AgentEvent[] = [];+ const collectEvents = (async () => {+ for await (const event of handle.events()) events.push(event);+ })();++ const turnId = 'turn-approval-policy-multiple-denials';+ await expect(Promise.all([+ handlers.commandExecutionApproval({+ threadId: 'start-thread-id',+ turnId,+ itemId: 'cmd-approval-policy-first',+ command: 'open -a Simulator',+ cwd: '/repo',+ }),+ handlers.commandExecutionApproval({+ threadId: 'start-thread-id',+ turnId,+ itemId: 'cmd-approval-policy-second',+ command: 'xcrun simctl shutdown DEVICE',+ cwd: '/repo',+ }),+ ])).resolves.toEqual([+ { decision: 'decline' },+ { decision: 'decline' },+ ]);++ // Completion of either declined item is not recovery progress. The+ // interrupted turn must still retain the policy attribution.+ handlers.itemCompleted({+ threadId: 'start-thread-id',+ turnId,+ item: {+ id: 'cmd-approval-policy-first',+ type: 'commandExecution',+ command: 'open -a Simulator',+ cwd: '/repo',+ },+ });+ handlers.turnCompleted({+ threadId: 'start-thread-id',+ turn: {+ id: turnId,+ status: 'interrupted',+ error: { message: 'aborted by user' },+ },+ } as never);++ await handle.close();+ await collectEvents;+ const terminal = events.filter(+ (event) =>+ (event as { type?: string }).type === 'error' &&+ (event as { data?: { isTerminal?: boolean } }).data?.isTerminal === true,+ );+ expect(terminal).toEqual([+ expect.objectContaining({+ data: expect.objectContaining({+ message: 'latest policy reason',+ isTerminal: true,+ }),+ }),+ ]);+ expect(JSON.stringify(terminal)).not.toContain('aborted by user');+ });++ it('keeps an approval denial through late updates from a pre-existing parallel item', async () => {+ const policy = vi.fn(({ command }: { command: string }) =>+ command === 'open -a Simulator'+ ? { decision: 'deny' as const, reason: 'use the embedded iOS Simulator' }+ : undefined,+ );+ const agent = new CodexAgent(createDeps({}, { getShellCommandPolicy: policy }));+ const host = installFakeHost(agent);+ const handle = await agent.startSession({+ sessionId: 'session-command-approval-policy-parallel-sibling',+ model: 'gpt-5.4',+ workingDir: '/repo',+ permissionMode: 'bypassPermissions',+ });+ const handlers = host.getThreadHandlers();+ if (+ !handlers?.commandExecutionApproval+ || !handlers.itemStarted+ || !handlers.itemUpdated+ || !handlers.itemCompleted+ || !handlers.turnDiffUpdated+ || !handlers.turnCompleted+ ) {+ throw new Error('expected approval, item lifecycle and turn diff handlers');+ }+ const events: AgentEvent[] = [];+ const collectEvents = (async () => {+ for await (const event of handle.events()) events.push(event);+ })();++ const turnId = 'turn-approval-policy-parallel-sibling';+ // This item was already running when the other parallel command was+ // declined. Its late completion must not erase the denial attribution.+ handlers.itemStarted({+ threadId: 'start-thread-id',+ turnId,+ item: {+ id: 'cmd-parallel-sibling',+ type: 'commandExecution',+ command: 'printf safe',+ cwd: '/repo',+ },+ });+ await expect(+ handlers.commandExecutionApproval({+ threadId: 'start-thread-id',+ turnId,+ itemId: 'cmd-denied-parallel',+ command: 'open -a Simulator',+ cwd: '/repo',+ }),+ ).resolves.toEqual({ decision: 'decline' });+ handlers.turnDiffUpdated({+ threadId: 'start-thread-id',+ turnId,+ diff: 'diff --git a/safe.txt b/safe.txt\n--- a/safe.txt\n+++ b/safe.txt\n',+ });+ handlers.itemUpdated({+ threadId: 'start-thread-id',+ turnId,+ item: {+ id: 'cmd-parallel-sibling',+ type: 'commandExecution',+ command: 'printf safe',+ cwd: '/repo',+ },+ });+ handlers.itemCompleted({+ threadId: 'start-thread-id',+ turnId,+ item: {+ id: 'cmd-parallel-sibling',+ type: 'commandExecution',+ command: 'printf safe',+ cwd: '/repo',+ },+ });+ handlers.turnCompleted({+ threadId: 'start-thread-id',+ turn: {+ id: turnId,+ status: 'interrupted',+ error: { message: 'aborted by user' },+ },+ } as never);++ await handle.close();+ await collectEvents;+ const terminal = events.filter(+ (event) =>+ (event as { type?: string }).type === 'error' &&+ (event as { data?: { isTerminal?: boolean } }).data?.isTerminal === true,+ );+ expect(terminal).toEqual([+ expect.objectContaining({+ data: expect.objectContaining({+ message: 'use the embedded iOS Simulator',+ isTerminal: true,+ }),+ }),+ ]);+ expect(JSON.stringify(terminal)).not.toContain('aborted by user');+ });++ it('keeps an approval denial through an approval item that was already pending', async () => {+ const policy = vi.fn(({ command }: { command: string }) =>+ command === 'open -a Simulator'+ ? { decision: 'deny' as const, reason: 'use the embedded iOS Simulator' }+ : undefined,+ );+ const decision = deferred<InteractionDecision>();+ const agent = new CodexAgent(createDeps({}, { getShellCommandPolicy: policy }));+ const host = installFakeHost(agent);+ const handle = await agent.startSession({+ sessionId: 'session-command-approval-policy-pending-sibling',+ model: 'gpt-5.4',+ workingDir: '/repo',+ permissionMode: 'ask',+ });+ const interactionResolver = vi.fn(() => decision.promise);+ handle.setInteractionResolver(interactionResolver);+ const handlers = host.getThreadHandlers();+ if (+ !handlers?.commandExecutionApproval+ || !handlers.itemStarted+ || !handlers.itemCompleted+ || !handlers.turnCompleted+ ) {+ throw new Error('expected approval, item lifecycle and turn completion handlers');+ }+ const events: AgentEvent[] = [];+ const collectEvents = (async () => {+ for await (const event of handle.events()) events.push(event);+ })();++ const turnId = 'turn-approval-policy-pending-sibling';+ const pendingApproval = handlers.commandExecutionApproval({+ threadId: 'start-thread-id',+ turnId,+ itemId: 'cmd-pending-sibling',+ command: 'printf safe',+ cwd: '/repo',+ });+ await waitForExpectation(() => expect(interactionResolver).toHaveBeenCalledTimes(1));+ // The resolver promise is held, so this approval is present in the pending+ // map before the policy denial for the parallel command arrives.+ await expect(+ handlers.commandExecutionApproval({+ threadId: 'start-thread-id',+ turnId,+ itemId: 'cmd-denied-after-pending',+ command: 'open -a Simulator',+ cwd: '/repo',+ }),+ ).resolves.toEqual({ decision: 'decline' });++ decision.resolve({ kind: 'permission', behavior: 'allow' });+ await expect(pendingApproval).resolves.toEqual({ decision: 'accept' });+ handlers.itemStarted({+ threadId: 'start-thread-id',+ turnId,+ item: {+ id: 'cmd-pending-sibling',+ type: 'commandExecution',+ command: 'printf safe',+ cwd: '/repo',+ },+ });+ handlers.itemCompleted({+ threadId: 'start-thread-id',+ turnId,+ item: {+ id: 'cmd-pending-sibling',+ type: 'commandExecution',+ command: 'printf safe',+ cwd: '/repo',+ },+ });+ handlers.turnCompleted({+ threadId: 'start-thread-id',+ turn: {+ id: turnId,+ status: 'interrupted',+ error: { message: 'aborted by user' },+ },+ } as never);++ await handle.close();+ await collectEvents;+ const terminal = events.filter(+ (event) =>+ (event as { type?: string }).type === 'error' &&+ (event as { data?: { isTerminal?: boolean } }).data?.isTerminal === true,+ );+ expect(terminal).toEqual([+ expect.objectContaining({+ data: expect.objectContaining({+ message: 'use the embedded iOS Simulator',+ isTerminal: true,+ }),+ }),+ ]);+ expect(JSON.stringify(terminal)).not.toContain('aborted by user');+ });++ it('clears an approval denial when a new native plan item continues the turn', async () => {+ const policy = vi.fn(({ command }: { command: string }) =>+ command === 'open -a Simulator'+ ? { decision: 'deny' as const, reason: 'use the embedded iOS Simulator' }+ : undefined,+ );+ const agent = new CodexAgent(createDeps({}, { getShellCommandPolicy: policy }));+ const host = installFakeHost(agent, (method) =>+ method === Method.TurnStart ? { turn: { id: 'turn-plan-after-denial' } } : undefined,+ );+ const handle = await agent.startSession({+ sessionId: 'session-command-approval-policy-plan-continuation',+ model: 'gpt-5.4',+ workingDir: '/repo',+ permissionMode: 'bypassPermissions',+ planMode: true,+ });+ const handlers = host.getThreadHandlers();+ if (!handlers?.commandExecutionApproval || !handlers.itemStarted || !handlers.turnCompleted) {+ throw new Error('expected approval, itemStarted and turnCompleted handlers');+ }+ const events: AgentEvent[] = [];+ const collectEvents = (async () => {+ for await (const event of handle.events()) events.push(event);+ })();++ const turnId = 'turn-plan-after-denial';+ await handle.send({ type: 'user', content: 'make a plan' });+ await expect(+ handlers.commandExecutionApproval({+ threadId: 'start-thread-id',+ turnId,+ itemId: 'cmd-denied-before-plan',+ command: 'open -a Simulator',+ cwd: '/repo',+ }),+ ).resolves.toEqual({ decision: 'decline' });+ handlers.itemStarted({+ threadId: 'start-thread-id',+ turnId,+ item: {+ id: 'plan-after-denial',+ type: 'plan',+ text: '1. inspect\n2. edit',+ },+ } as never);+ handlers.turnCompleted({+ threadId: 'start-thread-id',+ turn: {+ id: turnId,+ status: 'failed',+ error: { message: 'plan continuation failed' },+ },+ } as never);++ await handle.close();+ await collectEvents;+ const terminal = events.filter(+ (event) =>+ (event as { type?: string }).type === 'error'+ && (event as { data?: { isTerminal?: boolean } }).data?.isTerminal === true,+ );+ expect(terminal).toEqual([+ expect.objectContaining({+ data: expect.objectContaining({+ message: 'plan continuation failed',+ isTerminal: true,+ }),+ }),+ ]);+ expect(JSON.stringify(terminal)).not.toContain('use the embedded iOS Simulator');+ });++ it('lets an approval-path denial recover to a normal completed turn', async () => {+ const policy = vi.fn(() => ({+ decision: 'deny' as const,+ reason: 'use the embedded iOS Simulator',+ }));+ const agent = new CodexAgent(createDeps({}, { getShellCommandPolicy: policy }));+ const host = installFakeHost(agent);+ const handle = await agent.startSession({+ sessionId: 'session-command-approval-policy-recovery',+ model: 'gpt-5.4',+ workingDir: '/repo',+ permissionMode: 'bypassPermissions',+ });+ const handlers = host.getThreadHandlers();+ if (!handlers?.commandExecutionApproval || !handlers.turnCompleted) {+ throw new Error('expected commandExecutionApproval and turnCompleted handlers');+ }+ const events: AgentEvent[] = [];+ const collectEvents = (async () => {+ for await (const event of handle.events()) events.push(event);+ })();++ await expect(+ handlers.commandExecutionApproval({+ threadId: 'start-thread-id',+ turnId: 'turn-approval-policy-recovery',+ itemId: 'cmd-approval-policy-recovery',+ command: 'open -a Simulator',+ cwd: '/repo',+ }),+ ).resolves.toEqual({ decision: 'decline' });+ handlers.turnCompleted({+ threadId: 'start-thread-id',+ turn: {+ id: 'turn-approval-policy-recovery',+ status: 'completed',+ },+ } as never);++ await handle.close();+ await collectEvents;+ expect(events.filter((event) => (event as { type?: string }).type === 'error')).toEqual([+ expect.objectContaining({+ data: expect.objectContaining({+ message: 'use the embedded iOS Simulator',+ isTerminal: false,+ }),+ }),+ ]);+ expect(events).toEqual(+ expect.arrayContaining([+ expect.objectContaining({ type: 'done' }),+ ]),+ );+ expect(JSON.stringify(events)).not.toContain('isTerminal":true');+ });++ it('clears an approval denial once a replacement command continues the turn', async () => {+ const policy = vi.fn(({ command }: { command: string }) =>+ command === 'open -a Simulator'+ ? { decision: 'deny' as const, reason: 'use the embedded iOS Simulator' }+ : undefined,+ );+ const agent = new CodexAgent(createDeps({}, { getShellCommandPolicy: policy }));+ const host = installFakeHost(agent);+ const handle = await agent.startSession({+ sessionId: 'session-command-approval-policy-replacement-failure',+ model: 'gpt-5.4',+ workingDir: '/repo',+ permissionMode: 'bypassPermissions',+ });+ const handlers = host.getThreadHandlers();+ if (!handlers?.commandExecutionApproval || !handlers.itemStarted || !handlers.turnCompleted) {+ throw new Error('expected approval, itemStarted and turnCompleted handlers');+ }+ const events: AgentEvent[] = [];+ const collectEvents = (async () => {+ for await (const event of handle.events()) events.push(event);+ })();++ await expect(+ handlers.commandExecutionApproval({+ threadId: 'start-thread-id',+ turnId: 'turn-approval-policy-replacement-failure',+ itemId: 'cmd-approval-policy-replacement-failure',+ command: 'open -a Simulator',+ cwd: '/repo',+ }),+ ).resolves.toEqual({ decision: 'decline' });+ handlers.itemStarted({+ threadId: 'start-thread-id',+ turnId: 'turn-approval-policy-replacement-failure',+ item: {+ id: 'cmd-safe-replacement',+ type: 'commandExecution',+ command: 'printf safe',+ cwd: '/repo',+ },+ });+ handlers.turnCompleted({+ threadId: 'start-thread-id',+ turn: {+ id: 'turn-approval-policy-replacement-failure',+ status: 'failed',+ error: { message: 'replacement failed' },+ },+ } as never);++ await handle.close();+ await collectEvents;+ expect(events).toEqual(+ expect.arrayContaining([+ expect.objectContaining({+ type: 'error',+ data: expect.objectContaining({+ message: 'replacement failed',+ isTerminal: true,+ }),+ }),+ ]),+ );+ const terminalErrors = events.filter(+ (event) =>+ (event as { type?: string }).type === 'error'+ && (event as { data?: { isTerminal?: boolean } }).data?.isTerminal === true,+ );+ expect(JSON.stringify(terminalErrors)).not.toContain('use the embedded iOS Simulator');});- it('interrupts an already-started absolute-path shell bypass as a fail-safe', async () => {+ it('interrupts an already-started shell bypass and reports the policy reason', async () => {const { logger, warn } = createLoggerSpy();const policy = vi.fn(() => ({decision: 'deny' as const,@@ -13546,6 +14126,65 @@ describe('CodexAgent MCP thread context hooks', () => {await handle.close();});+ it('keeps the policy reason as the terminal outcome of the interrupted turn', async () => {+ const policy = vi.fn(() => ({+ decision: 'deny' as const,+ reason: 'use the embedded iOS Simulator',+ }));+ const agent = new CodexAgent(createDeps({}, { getShellCommandPolicy: policy }));+ const host = installFakeHost(agent, (method) =>+ method === Method.TurnInterrupt ? {} : undefined,+ );+ const handle = await agent.startSession({+ sessionId: 'session-policy-terminal-reason',+ model: 'gpt-5.4',+ workingDir: '/repo',+ permissionMode: 'bypassPermissions',+ });+ const handlers = host.getThreadHandlers();+ if (!handlers?.itemStarted || !handlers.turnCompleted) {+ throw new Error('expected itemStarted and turnCompleted handlers');+ }+ const events: AgentEvent[] = [];+ const collectEvents = (async () => {+ for await (const event of handle.events()) events.push(event);+ })();++ handlers.itemStarted({+ threadId: 'start-thread-id',+ turnId: 'turn-1',+ item: { id: 'cmd-1', type: 'commandExecution', command: 'open -a Simulator', cwd: '/repo' },+ });+ // Codex answers our interrupt with an abort-shaped completion. The renderer+ // clears a non-terminal error once the turn completes, so the product reason+ // has to win here or the denial reads as a user action.+ handlers.turnCompleted({+ threadId: 'start-thread-id',+ turn: {+ id: 'turn-1',+ status: 'interrupted',+ error: { message: 'aborted by user' },+ },+ } as never);++ await handle.close();+ await collectEvents;+ const terminal = events.filter(+ (event) =>+ (event as { type?: string }).type === 'error' &&+ (event as { data?: { isTerminal?: boolean } }).data?.isTerminal === true,+ );+ expect(terminal).toEqual([+ expect.objectContaining({+ data: expect.objectContaining({+ message: 'use the embedded iOS Simulator',+ isTerminal: true,+ }),+ }),+ ]);+ expect(JSON.stringify(terminal)).not.toContain('aborted by user');+ });+it('interrupts a raw function_call exec_command shell bypass as a fail-safe', async () => {const policy = vi.fn(() => ({decision: 'deny' as const,diff --git a/packages/maker-core/src/agents/codex/index.ts b/packages/maker-core/src/agents/codex/index.tsindex 044d423f1f..7145e0f53d 100644--- a/packages/maker-core/src/agents/codex/index.ts+++ b/packages/maker-core/src/agents/codex/index.ts@@ -3035,6 +3035,31 @@ export class CodexAgent extends BaseAgent {}| { source: 'user-stop' }>();+ // Approval can be declined before execution starts. Codex may still recover+ // and complete the turn, so this reason only owns abort-shaped completions.+ // Keep every declined item id: app-server can emit several approval+ // requests for one turn and may still complete each declined item after the+ // decline. A single item id would let a later denial overwrite an earlier+ // one, then make that earlier completion look like recovery progress.+ const approvalPolicyDeniedTurnReasons = new Map<+ string,+ {+ reason: string;+ itemIds: Set<string>;+ // A sibling item may already be running when the denied approval+ // arrives. Its later update/completion is not recovery progress: the+ // turn is still in the abort caused by the denial. Snapshot the item+ // ids seen before the first denial so only genuinely new work clears+ // the policy attribution.+ preexistingItemIds: Set<string>;+ }+ >();+ // Item ids observed before an approval-path denial. A turn may have+ // parallel work in flight when one command is declined; that sibling can+ // emit updated/completed after the denial without representing a+ // replacement continuation. The snapshot is per-turn and is discarded+ // with the turn's denial state at terminal completion.+ const observedModelItemIdsByTurn = new Map<string, Set<string>>();// daemon 后端 retry-loop 的终局升级 (issue #677): 远端摸不到 Codex 后端时// daemon 无限 willRetry, turn 永不收口。同 turn 重试超阈值 → 合成终态错误,// 走与终态 error 完全相同的收口路径 (terminalErroredTurnIds + Done status)。@@ -5222,6 +5247,8 @@ export class CodexAgent extends BaseAgent {resolve: (decision: ApprovalDecision) => void;kind: 'commandExecution' | 'fileChange' | 'mcpServerElicitation';settled: boolean;+ turnId: string | null;+ itemId?: string;/** prompt-each-time 高风险审批: 宽松模式也必须弹 UI, dismissAllPending('allow') 不得放行 */forcePrompt?: boolean;}@@ -5453,7 +5480,11 @@ export class CodexAgent extends BaseAgent {requestId: string,kind: 'commandExecution' | 'fileChange' | 'mcpServerElicitation',req: InteractionRequest,- opts?: { forcePrompt?: boolean; autoReviewAction?: ReviewableAction },+ opts?: {+ forcePrompt?: boolean;+ autoReviewAction?: ReviewableAction;+ itemId?: string;+ },): Promise<ApprovalDecision> {const timingPauseId = `approval:${kind}:${requestId}`;return withCodexGenerationPaused(requestThreadId, turnId, timingPauseId, async () => {@@ -5536,7 +5567,14 @@ export class CodexAgent extends BaseAgent {? { ...req, suggestions: undefined }: req;return await new Promise<ApprovalDecision>((resolve) => {- const entry: PendingEntry = { resolve, kind, settled: false, forcePrompt };+ const entry: PendingEntry = {+ resolve,+ kind,+ settled: false,+ turnId,+ ...(opts?.itemId ? { itemId: opts.itemId } : {}),+ forcePrompt,+ };pendingApprovals.set(requestId, entry);const finalize = (d: ApprovalDecision) => {if (entry.settled) return;@@ -6237,6 +6275,36 @@ export class CodexAgent extends BaseAgent {requestId: params.approvalId ?? params.itemId,reason: hostPolicy.reason,});+ // The decline is followed by an abort-shaped turn completion. Keep the+ // policy reason attached to this turn so completion cannot replace it+ // with a generic cancellation/error message.+ const existingDenial = approvalPolicyDeniedTurnReasons.get(params.turnId);+ if (existingDenial) {+ existingDenial.reason = hostPolicy.reason;+ existingDenial.itemIds.add(params.itemId);+ } else {+ const preexistingItemIds = new Set(+ observedModelItemIdsByTurn.get(params.turnId) ?? [],+ );+ for (const pending of pendingApprovals.values()) {+ if (pending.turnId === params.turnId && pending.itemId) {+ preexistingItemIds.add(pending.itemId);+ }+ }+ approvalPolicyDeniedTurnReasons.set(params.turnId, {+ reason: hostPolicy.reason,+ itemIds: new Set([params.itemId]),+ preexistingItemIds,+ });+ }+ // Declining without ever showing the user why renders as a bare failed+ // command, which is indistinguishable from a cancellation. Surface the+ // product reason so the denial is attributed to the policy, not the user.+ eventQueue.push({+ type: 'error',+ data: { message: hostPolicy.reason, isTerminal: false },+ source: 'codex',+ });return { decision: 'decline' };}// requestId: approvalId 优先 (zsh-exec-bridge 多 callback 场景); 否则用 itemId@@ -6262,6 +6330,7 @@ export class CodexAgent extends BaseAgent {? { cwd: opts.workingDir }: { cwdUnknown: true }),},+ itemId: params.itemId,});return { decision };};@@ -6284,7 +6353,10 @@ export class CodexAgent extends BaseAgent {description: params.reason ?? undefined,suggestions: codexSessionApprovalSuggestions(),metadata: params.reason ? { reason: params.reason } : undefined,- }, { autoReviewAction: { kind: 'file-write', path: params.grantRoot ?? undefined } });+ }, {+ autoReviewAction: { kind: 'file-write', path: params.grantRoot ?? undefined },+ itemId: params.itemId,+ });return { decision };};@@ -6585,7 +6657,7 @@ export class CodexAgent extends BaseAgent {description: params.reason ?? undefined,suggestions: codexSessionApprovalSuggestions(),metadata: params.reason ? { reason: params.reason } : undefined,- });+ }, { itemId: params.itemId ?? undefined });if (decision === 'accept') {return { permissions: params.permissions as Record<string, unknown>, scope: 'turn' };}@@ -7686,16 +7758,28 @@ export class CodexAgent extends BaseAgent {* update_plan 工具行 (避免同一份计划在聊天里出现两次)。* 非计划模式不拦截; 普通 Codex turn 也可能产生原生 plan item。*/- function interceptProposedPlanItem(item: unknown): boolean {+ function interceptProposedPlanItem(turnId: string, item: unknown): boolean {if (!currentTurnPlanModeActive) return false;- const candidate = item as { type?: unknown; text?: unknown } | null | undefined;+ const candidate = item as {+ id?: unknown;+ type?: unknown;+ text?: unknown;+ } | null | undefined;if (!candidate || candidate.type !== 'plan') return false;+ noteObservedModelItem(turnId, candidate);+ if (typeof candidate.id === 'string') {+ clearApprovalPolicyDenialOnProgress(turnId, candidate.id);+ }if (typeof candidate.text === 'string') proposedPlanText = candidate.text;return true;}function handleTurnCompleted(params: TurnCompletedParams): void {const turn = params.turn;+ // Every branch below represents an authoritative terminal notification,+ // including the paths that defer UI settlement or return early. Item+ // history is only needed while approval attribution is still mutable.+ observedModelItemIdsByTurn.delete(turn.id);const interruptOrigin = turnInterruptOrigins.get(turn.id);turnInterruptOrigins.delete(turn.id);if (@@ -7925,12 +8009,29 @@ export class CodexAgent extends BaseAgent {// 已经 return, 所以退避中的正常重投(死 turn 恒有墓碑)不会被误撤。revokeOverloadRetryOnTerminalSettle(`turn_${turn.status}`);+ const approvalPolicyDenialReason = approvalPolicyDeniedTurnReasons.get(turn.id)?.reason;+ const policyDenialReason =+ (turn.status === 'failed' || turn.status === 'interrupted')+ ? approvalPolicyDenialReason+ : undefined;+ approvalPolicyDeniedTurnReasons.delete(turn.id);+ if (policyDenialReason !== undefined) {+ eventQueue.push({+ type: 'error',+ data: { message: policyDenialReason, isTerminal: true },+ source: 'codex',+ });+ }+if (turn.status === 'failed' || turn.status === 'interrupted') {// 失败 / 中断的 plan turn 不发审批 — 半截计划没有审批意义, 循环就此结束。proposedPlanText = null;planCycleActive = false;currentTurnPlanModeActive = false;- if (turn.error?.message) {+ if (policyDenialReason !== undefined) {+ // Already reported above as the authoritative terminal outcome; the+ // interrupt-derived message must not overwrite it.+ } else if (turn.error?.message) {eventQueue.push({type: 'error',data: { message: turn.error.message, isTerminal: true },@@ -8042,6 +8143,43 @@ export class CodexAgent extends BaseAgent {return type === null || !ITEM_TYPES_WITHOUT_MODEL_WORK.has(type);};+ const noteObservedModelItem = (+ turnId: string,+ item: { id?: unknown; type?: unknown } | null | undefined,+ ): void => {+ if (+ !item+ || !itemRepresentsModelWork(item)+ || typeof item.id !== 'string'+ || item.id.length === 0+ ) {+ return;+ }+ const itemIds = observedModelItemIdsByTurn.get(turnId) ?? new Set<string>();+ itemIds.add(item.id);+ observedModelItemIdsByTurn.set(turnId, itemIds);+ };++ // An approval decline is only attributable to the immediate abort it+ // causes. Work that was already observed before the denial may still emit+ // progress while that abort settles; only model work first observed after+ // the denial clears the policy attribution as a genuine continuation.+ const clearApprovalPolicyDenialOnProgress = (turnId: string, itemId?: string): void => {+ const denial = approvalPolicyDeniedTurnReasons.get(turnId);+ if (!denial) return;+ // Turn-level progress (diffs, plans, or text deltas without an item id)+ // cannot prove that a replacement item started after the denial. Keep+ // the attribution until an item lifecycle event identifies new work.+ if (itemId === undefined) return;+ if (+ denial.itemIds.has(itemId)+ || denial.preexistingItemIds.has(itemId)+ ) {+ return;+ }+ approvalPolicyDeniedTurnReasons.delete(turnId);+ };+/** 取消挂起的过载重投(会话关闭 / 用户打断 / 新 turn 覆盖时调用)。 */const cancelOverloadRetry = (reason: string): void => {const state = overloadRetry;@@ -9009,10 +9147,14 @@ export class CodexAgent extends BaseAgent {discardPendingSpawnLineageIds(reservedChildThreadIds);return;}- if (interceptProposedPlanItem(params.item)) {+ if (interceptProposedPlanItem(params.turnId, params.item)) {discardPendingSpawnLineageIds(reservedChildThreadIds);return;}+ if (itemRepresentsModelWork(params.item)) {+ noteObservedModelItem(params.turnId, params.item);+ clearApprovalPolicyDenialOnProgress(params.turnId, params.item.id);+ }const shellCommand = shellCommandFromCodexItem(params.item);if (shellCommand) {const hostPolicy = this.deps.getShellCommandPolicy?.({@@ -9114,11 +9256,15 @@ export class CodexAgent extends BaseAgent {discardPendingSpawnLineageIds(reservedChildThreadIds);return;}- if (interceptProposedPlanItem(params.item)) {+ if (interceptProposedPlanItem(params.turnId, params.item)) {discardPendingSpawnLineageIds(reservedChildThreadIds);return;}- if (itemRepresentsModelWork(params.item)) producedOutputTurnIds.add(params.turnId);+ if (itemRepresentsModelWork(params.item)) {+ noteObservedModelItem(params.turnId, params.item);+ clearApprovalPolicyDenialOnProgress(params.turnId, params.item.id);+ producedOutputTurnIds.add(params.turnId);+ }noteActiveToolContext(params.item, params.turnId);// updated 也要登记映射,顺序与 started / completed 一致(先登记 → 翻译 → 后发重放帧)。// V1 的 spawn 是长跑 item(started → updated* → completed):started 那帧若没到我们手里@@ -9164,12 +9310,16 @@ export class CodexAgent extends BaseAgent {}isLateCollabTerminal = true;}- if (interceptProposedPlanItem(params.item)) {+ if (interceptProposedPlanItem(params.turnId, params.item)) {discardPendingSpawnLineageIds(reservedChildThreadIds);return;}if (collabTerminalKey) handledCollabTerminalItemIds.add(collabTerminalKey);- if (itemRepresentsModelWork(params.item)) producedOutputTurnIds.add(params.turnId);+ if (itemRepresentsModelWork(params.item)) {+ noteObservedModelItem(params.turnId, params.item);+ clearApprovalPolicyDenialOnProgress(params.turnId, params.item.id);+ producedOutputTurnIds.add(params.turnId);+ }noteActiveToolContext(params.item, params.turnId);// This late item belongs to an already-terminal parent. The parent// cleanup already cleared its pending tools; touching the shared@@ -9233,6 +9383,7 @@ export class CodexAgent extends BaseAgent {modelWork: true,})) return;if (shouldIgnoreStaleTurnEvent(params.turnId)) return;+ clearApprovalPolicyDenialOnProgress(params.turnId, params.itemId);producedOutputTurnIds.add(params.turnId);translateAgentMessageDelta(params, eventQueue, { rt: translatorRt, log });},@@ -9247,6 +9398,7 @@ export class CodexAgent extends BaseAgent {if (enqueueIfBufferedTurn(params.turnId, () => handlers.reasoningSummaryTextDelta?.(params), { modelWork: true })) return;if (shouldIgnoreStaleTurnEvent(params.turnId)) return;// thinking 流也算产出:模型已经在这一轮里工作了,整体重放不再等价。+ clearApprovalPolicyDenialOnProgress(params.turnId, params.itemId);producedOutputTurnIds.add(params.turnId);translateReasoningSummaryTextDelta(params, eventQueue, { rt: translatorRt, log });},@@ -9254,6 +9406,7 @@ export class CodexAgent extends BaseAgent {// thinking 流同样算产出(与非缓冲路径一致)。if (enqueueIfBufferedTurn(params.turnId, () => handlers.reasoningSummaryPartAdded?.(params), { modelWork: true })) return;if (shouldIgnoreStaleTurnEvent(params.turnId)) return;+ clearApprovalPolicyDenialOnProgress(params.turnId, params.itemId);producedOutputTurnIds.add(params.turnId);translateReasoningSummaryPartAdded(params, eventQueue, { rt: translatorRt, log });},@@ -9261,6 +9414,7 @@ export class CodexAgent extends BaseAgent {// thinking 流同样算产出(与非缓冲路径一致)。if (enqueueIfBufferedTurn(params.turnId, () => handlers.reasoningTextDelta?.(params), { modelWork: true })) return;if (shouldIgnoreStaleTurnEvent(params.turnId)) return;+ clearApprovalPolicyDenialOnProgress(params.turnId, params.itemId);producedOutputTurnIds.add(params.turnId);translateReasoningTextDelta(params, eventQueue, { rt: translatorRt, log });},