From 71725cb9abbb13e290438ae2cde4bdf01b0bdb28 Mon Sep 17 00:00:00 2001 From: bbingz Date: Sun, 12 Jul 2026 19:21:41 +0800 Subject: [PATCH 1/4] fix(codex): use argv-safe POSIX hook commands MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Codex direct-execs hooks.json commands via argv split, not a shell. wrapPosixHookCommand's if/then/fi guard became argv0=`if` → exit 127 and Broken pipe on every managed hook (#8110). Emit `/bin/sh ''` for Codex local/WSL/SSH installs, keep the guarded wrapper for shell-based agents, and still recognize legacy guarded trust hashes on remove. Co-Authored-By: Claude --- src/main/agent-hooks/installer-utils.test.ts | 37 +++++++++ src/main/agent-hooks/installer-utils.ts | 9 ++ .../codex/hook-service-wsl-runtime.test.ts | 10 +-- src/main/codex/hook-service.test.ts | 21 +++++ src/main/codex/hook-service.ts | 82 ++++++++++++------- 5 files changed, 123 insertions(+), 36 deletions(-) diff --git a/src/main/agent-hooks/installer-utils.test.ts b/src/main/agent-hooks/installer-utils.test.ts index ba0dad4a0abb..5fbbbedf811e 100644 --- a/src/main/agent-hooks/installer-utils.test.ts +++ b/src/main/agent-hooks/installer-utils.test.ts @@ -20,6 +20,7 @@ import { getSharedManagedScriptPath, hookDefinitionHasManagedCommand, removeManagedCommands, + wrapPosixDirectHookCommand, wrapPosixHookCommand, wrapWindowsCmdHookCommand, wrapWindowsGitBashHookCommand, @@ -341,6 +342,42 @@ describe('wrapPosixHookCommand', () => { ) }) +describe('wrapPosixDirectHookCommand', () => { + // Why: Codex direct-execs hooks.json commands (#8110). argv0 must be /bin/sh, + // never shell control-flow tokens from the guarded wrapper. + it('emits an argv-safe /bin/sh launcher without if/then/fi', () => { + const cmd = wrapPosixDirectHookCommand('/Users/a/.orca/agent-hooks/codex-hook.sh') + expect(cmd).toBe("/bin/sh '/Users/a/.orca/agent-hooks/codex-hook.sh'") + expect(cmd).not.toMatch(/\bif\b|\bthen\b|\bfi\b/) + }) + + it('escapes embedded single quotes the same way as the guarded wrapper', () => { + const cmd = wrapPosixDirectHookCommand("/path/with'quote/x.sh") + expect(cmd).toBe("/bin/sh '/path/with'\\''quote/x.sh'") + }) + + it.skipIf(process.platform === 'win32')( + 'runs under argv split the way Codex does (not shell -c)', + () => { + const scriptPath = join(tmpDir, 'ok.sh') + writeFileSync(scriptPath, '#!/bin/sh\nexit 0\n', 'utf-8') + chmodSync(scriptPath, 0o755) + const cmd = wrapPosixDirectHookCommand(scriptPath) + // Why: Codex splits the command string on whitespace and execs argv; this + // approximates that without a shell so a regression to if/then/fi fails. + const argv = cmd.match(/(?:[^\s']+|'[^']*')+/g) ?? [] + const unquoted = argv.map((part) => + part.startsWith("'") && part.endsWith("'") + ? part.slice(1, -1).replaceAll("'\\''", "'") + : part + ) + const result = spawnSync(unquoted[0]!, unquoted.slice(1)) + expect(result.status).toBe(0) + expect(unquoted[0]).toBe('/bin/sh') + } + ) +}) + const qualifiedWindowsPowerShellCommand = /^[A-Za-z]:\/[^"]*\/System32\/WindowsPowerShell\/v1\.0\/powershell\.exe -NoProfile -ExecutionPolicy Bypass -EncodedCommand \S+$/ diff --git a/src/main/agent-hooks/installer-utils.ts b/src/main/agent-hooks/installer-utils.ts index 86bb58607caf..56170da88f50 100644 --- a/src/main/agent-hooks/installer-utils.ts +++ b/src/main/agent-hooks/installer-utils.ts @@ -143,6 +143,15 @@ export function wrapPosixHookCommand(scriptPath: string, env: Record'` so argv0 is the shell and the script path is one argument. +export function wrapPosixDirectHookCommand(scriptPath: string): string { + const quoted = `'${scriptPath.replaceAll("'", "'\\''")}'` + return `/bin/sh ${quoted}` +} + function quotePowerShellString(value: string): string { return `'${value.replaceAll("'", "''")}'` } diff --git a/src/main/codex/hook-service-wsl-runtime.test.ts b/src/main/codex/hook-service-wsl-runtime.test.ts index 232725e5f66d..e9356b5f0184 100644 --- a/src/main/codex/hook-service-wsl-runtime.test.ts +++ b/src/main/codex/hook-service-wsl-runtime.test.ts @@ -133,7 +133,7 @@ describe('Codex WSL runtime hook install', () => { trustConfigPath: '/old/home/hooks.json' } expect(_internals.installManagedHooksIntoWslRuntime(oldPlan).state).toBe('installed') - const oldCommand = `if [ -r '${oldPlan.commandScriptPath}' ]; then /bin/sh '${oldPlan.commandScriptPath}'; fi` + const oldCommand = `/bin/sh '${oldPlan.commandScriptPath}'` const oldKey = computeTrustKey(getManagedTrustEntry(oldPlan, oldCommand)) const newPlan = { @@ -142,7 +142,7 @@ describe('Codex WSL runtime hook install', () => { trustConfigPath: '/new/home/hooks.json' } expect(_internals.installManagedHooksIntoWslRuntime(newPlan).state).toBe('installed') - const newCommand = `if [ -r '${newPlan.commandScriptPath}' ]; then /bin/sh '${newPlan.commandScriptPath}'; fi` + const newCommand = `/bin/sh '${newPlan.commandScriptPath}'` const newKey = computeTrustKey(getManagedTrustEntry(newPlan, newCommand)) const trustEntries = readHookTrustEntries(plan.tomlPath) @@ -351,9 +351,9 @@ describe('Codex WSL runtime hook install', () => { const installed = JSON.parse(readFileSync(plan.configPath, 'utf-8')) as HooksConfig expect(Object.keys(installed.hooks).sort()).toEqual([...managedEvents].sort()) const managedCommand = installed.hooks.UserPromptSubmit[0]?.hooks?.[0]?.command - expect(managedCommand).toBe( - `if [ -r '${plan.commandScriptPath}' ]; then /bin/sh '${plan.commandScriptPath}'; fi` - ) + // Why: Codex argv-execs hooks.json; guarded if/then/fi becomes argv0=`if` (#8110). + expect(managedCommand).toBe(`/bin/sh '${plan.commandScriptPath}'`) + expect(managedCommand).not.toMatch(/\bif\b|\bthen\b|\bfi\b/) expect(installed.hooks.UserPromptSubmit[1]?.hooks?.[0]?.command).toBe(userCommand) expect(readFileSync(plan.scriptPath, 'utf-8')).toContain('command -v curl.exe') diff --git a/src/main/codex/hook-service.test.ts b/src/main/codex/hook-service.test.ts index 526a64d99ab0..06325ed61abd 100644 --- a/src/main/codex/hook-service.test.ts +++ b/src/main/codex/hook-service.test.ts @@ -158,6 +158,27 @@ describe('CodexHookService', () => { expect(trustConfig).toContain(':permission_request:0:0') }) + // Why: Codex direct-execs hooks.json commands (#8110). The shared + // wrapPosixHookCommand if/then/fi guard becomes argv0=`if` → exit 127. + it.skipIf(process.platform === 'win32')( + 'writes argv-safe POSIX managed commands without shell control-flow', + () => { + expect(new CodexHookService().install().state).toBe('installed') + + const managedCodexHome = join(userDataDir, 'codex-runtime-home', 'home') + const hooksConfig = JSON.parse( + readFileSync(join(managedCodexHome, 'hooks.json'), 'utf-8') + ) as { hooks: Record } + + for (const eventName of localManagedCodexEvents()) { + const command = hooksConfig.hooks[eventName]?.[0]?.hooks?.[0]?.command ?? '' + expect(command).toMatch(/^\/bin\/sh '/) + expect(command).toContain('agent-hooks/codex-hook.sh') + expect(command).not.toMatch(/\bif\b|\bthen\b|\bfi\b/) + } + } + ) + it('drops plugin manager metadata from runtime hooks.json during install', () => { const managedCodexHome = join(userDataDir, 'codex-runtime-home', 'home') mkdirSync(managedCodexHome, { recursive: true }) diff --git a/src/main/codex/hook-service.ts b/src/main/codex/hook-service.ts index 0ad81dede261..ad766fc1ded7 100644 --- a/src/main/codex/hook-service.ts +++ b/src/main/codex/hook-service.ts @@ -12,6 +12,7 @@ import { MANAGED_HOOK_TIMEOUT_SECONDS, readHooksJson, removeManagedCommands, + wrapPosixDirectHookCommand, wrapPosixHookCommand, wrapWindowsCmdHookCommand, writeHooksJson, @@ -127,17 +128,29 @@ function getManagedScriptPath(): string { function getManagedCommand(scriptPath: string): string { return process.platform === 'win32' ? wrapWindowsCmdHookCommand(scriptPath) - : wrapPosixHookCommand(scriptPath) + : wrapPosixDirectHookCommand(scriptPath) } export { createCodexWslRuntimeHookInstallPlan } export type { CodexWslRuntimeHookInstallPlan } +// Why: WSL runtime hooks are written from Windows through UNC; /bin/sh only +// needs the script readable. Same argv-safe shape as local POSIX (#8110) — +// Codex direct-execs hooks.json, so if/then/fi must not appear in the command. function wrapReadablePosixHookCommand(scriptPath: string): string { + return wrapPosixDirectHookCommand(scriptPath) +} + +// Why: remove/status trust matching must still recognize pre-#8110 guarded +// commands so upgrade reinstall/remove can clear their hashes. +function codexPosixTrustCommandVariants(scriptPath: string): string[] { + const direct = wrapPosixDirectHookCommand(scriptPath) const quoted = `'${scriptPath.replaceAll("'", "'\\''")}'` - // Why: WSL runtime hooks are written from Windows through UNC, where the - // executable bit is not reliable. /bin/sh only needs the script to be readable. - return `if [ -r ${quoted} ]; then /bin/sh ${quoted}; fi` + return [ + direct, + wrapPosixHookCommand(scriptPath), + `if [ -r ${quoted} ]; then /bin/sh ${quoted}; fi` + ] } function getSystemConfigPath(): string { @@ -629,7 +642,6 @@ function removeRuntimeManagedHookTrustEntries(configPath: string): void { const tomlPath = getCodexConfigTomlPath() const existingEntries = readHookTrustEntries(tomlPath) const scriptPath = getManagedScriptPath() - const command = getManagedCommand(scriptPath) const managedEventLabels = new Set( CODEX_EVENTS.map((event) => CODEX_EVENT_LABEL[event]) ) @@ -639,6 +651,10 @@ function removeRuntimeManagedHookTrustEntries(configPath: string): void { // wipe the user's manually-approved entries. const ourKeys: string[] = [] const canonicalConfigPath = getCodexCanonicalTrustPath(configPath) + const commandVariants = + process.platform === 'win32' + ? [getManagedCommand(scriptPath)] + : codexPosixTrustCommandVariants(scriptPath) for (const [key, state] of existingEntries) { const parts = parseTrustKey(key) if (parts === null) { @@ -650,20 +666,21 @@ function removeRuntimeManagedHookTrustEntries(configPath: string): void { if (!managedEventLabels.has(parts.eventLabel)) { continue } - const expectedEntry: CodexTrustEntry = { - sourcePath: configPath, - eventLabel: parts.eventLabel, - groupIndex: parts.groupIndex, - handlerIndex: parts.handlerIndex, - command, - // Why: match the timeout install() wrote, or remove() would fail to - // recognize (and clean up) its own managed trust entries. - timeoutSec: MANAGED_HOOK_TIMEOUT_SECONDS + const recognizedHashes = new Set() + for (const command of commandVariants) { + const expectedEntry: CodexTrustEntry = { + sourcePath: configPath, + eventLabel: parts.eventLabel, + groupIndex: parts.groupIndex, + handlerIndex: parts.handlerIndex, + command, + // Why: match the timeout install() wrote, or remove() would fail to + // recognize (and clean up) its own managed trust entries. + timeoutSec: MANAGED_HOOK_TIMEOUT_SECONDS + } + recognizedHashes.add(computeTrustedHash(expectedEntry)) + recognizedHashes.add(computeTrustedHash({ ...expectedEntry, timeoutSec: undefined })) } - const recognizedHashes = new Set([ - computeTrustedHash(expectedEntry), - computeTrustedHash({ ...expectedEntry, timeoutSec: undefined }) - ]) if (!state.trustedHash || !recognizedHashes.has(state.trustedHash)) { continue } @@ -749,19 +766,22 @@ function removeStaleWslRuntimeManagedHookTrustEntries( continue } const runtimeHome = sourcePath.slice(0, -'/hooks.json'.length) - const command = wrapReadablePosixHookCommand(`${runtimeHome}/.orca/agent-hooks/codex-hook.sh`) - const expectedEntry: CodexTrustEntry = { - sourcePath: parts.sourcePath, - eventLabel: parts.eventLabel, - groupIndex: parts.groupIndex, - handlerIndex: parts.handlerIndex, - command, - timeoutSec: MANAGED_HOOK_TIMEOUT_SECONDS + const commandVariants = codexPosixTrustCommandVariants( + `${runtimeHome}/.orca/agent-hooks/codex-hook.sh` + ) + const recognizedHashes = new Set() + for (const command of commandVariants) { + const expectedEntry: CodexTrustEntry = { + sourcePath: parts.sourcePath, + eventLabel: parts.eventLabel, + groupIndex: parts.groupIndex, + handlerIndex: parts.handlerIndex, + command, + timeoutSec: MANAGED_HOOK_TIMEOUT_SECONDS + } + recognizedHashes.add(computeTrustedHash(expectedEntry)) + recognizedHashes.add(computeTrustedHash({ ...expectedEntry, timeoutSec: undefined })) } - const recognizedHashes = new Set([ - computeTrustedHash(expectedEntry), - computeTrustedHash({ ...expectedEntry, timeoutSec: undefined }) - ]) if (state.trustedHash && recognizedHashes.has(state.trustedHash)) { ourKeys.push(key) } @@ -1366,7 +1386,7 @@ export class CodexHookService { } } - const command = wrapPosixHookCommand(remoteScriptPath) + const command = wrapPosixDirectHookCommand(remoteScriptPath) const nextHooks = { ...config.hooks } const managedEvents = new Set(CODEX_EVENTS) const isManagedCommand = createManagedCommandMatcher('codex-hook.sh') From b7f94802a1b01eae206039085b034ccdb2a41d38 Mon Sep 17 00:00:00 2001 From: bbingz Date: Sun, 12 Jul 2026 20:19:46 +0800 Subject: [PATCH 2/4] fix(codex): dual-model POSIX hook command without literal quotes MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Current Codex launches hooks via $SHELL -lc with the full command as one arg, so if/then/fi would work — but #8110's 127 also matches pure whitespace argv-exec (argv0=`if`) and quoted `/bin/sh 'path'` fails that model because quotes stay in the path token. Emit unquoted `/bin/sh ` when the path is argv-safe; fall back to single-quoted paths for spaces/metacharacters. Keep legacy trust variants for remove. Co-Authored-By: Claude --- src/main/agent-hooks/installer-utils.test.ts | 43 ++++++++++++------- src/main/agent-hooks/installer-utils.ts | 21 +++++++-- .../codex/hook-service-wsl-runtime.test.ts | 4 +- src/main/codex/hook-service.test.ts | 8 ++-- src/main/codex/hook-service.ts | 10 +++-- 5 files changed, 58 insertions(+), 28 deletions(-) diff --git a/src/main/agent-hooks/installer-utils.test.ts b/src/main/agent-hooks/installer-utils.test.ts index 5fbbbedf811e..07a8eb7b1b1a 100644 --- a/src/main/agent-hooks/installer-utils.test.ts +++ b/src/main/agent-hooks/installer-utils.test.ts @@ -343,12 +343,17 @@ describe('wrapPosixHookCommand', () => { }) describe('wrapPosixDirectHookCommand', () => { - // Why: Codex direct-execs hooks.json commands (#8110). argv0 must be /bin/sh, - // never shell control-flow tokens from the guarded wrapper. - it('emits an argv-safe /bin/sh launcher without if/then/fi', () => { + // Why: #8110 — never emit if/then/fi; prefer unquoted path when argv-safe. + it('emits unquoted /bin/sh for argv-safe paths', () => { const cmd = wrapPosixDirectHookCommand('/Users/a/.orca/agent-hooks/codex-hook.sh') - expect(cmd).toBe("/bin/sh '/Users/a/.orca/agent-hooks/codex-hook.sh'") + expect(cmd).toBe('/bin/sh /Users/a/.orca/agent-hooks/codex-hook.sh') expect(cmd).not.toMatch(/\bif\b|\bthen\b|\bfi\b/) + expect(cmd).not.toContain("'") + }) + + it('single-quotes paths with spaces so shell -lc still works', () => { + const cmd = wrapPosixDirectHookCommand('/Users/Jorge Silva/.orca/agent-hooks/codex-hook.sh') + expect(cmd).toBe("/bin/sh '/Users/Jorge Silva/.orca/agent-hooks/codex-hook.sh'") }) it('escapes embedded single quotes the same way as the guarded wrapper', () => { @@ -357,23 +362,31 @@ describe('wrapPosixDirectHookCommand', () => { }) it.skipIf(process.platform === 'win32')( - 'runs under argv split the way Codex does (not shell -c)', + 'runs under pure whitespace argv-split without stripping quotes', () => { + // Why: naive argv-exec keeps quote characters inside argv tokens. The + // dual-model form must not rely on a shell (or a test helper) to strip them. const scriptPath = join(tmpDir, 'ok.sh') writeFileSync(scriptPath, '#!/bin/sh\nexit 0\n', 'utf-8') chmodSync(scriptPath, 0o755) const cmd = wrapPosixDirectHookCommand(scriptPath) - // Why: Codex splits the command string on whitespace and execs argv; this - // approximates that without a shell so a regression to if/then/fi fails. - const argv = cmd.match(/(?:[^\s']+|'[^']*')+/g) ?? [] - const unquoted = argv.map((part) => - part.startsWith("'") && part.endsWith("'") - ? part.slice(1, -1).replaceAll("'\\''", "'") - : part - ) - const result = spawnSync(unquoted[0]!, unquoted.slice(1)) + const argv = cmd.split(/\s+/) + expect(argv[0]).toBe('/bin/sh') + expect(argv[1]).toBe(scriptPath) + const result = spawnSync(argv[0]!, argv.slice(1)) + expect(result.status).toBe(0) + } + ) + + it.skipIf(process.platform === 'win32')( + 'runs under shell -lc the way current Codex command_runner does', + () => { + const scriptPath = join(tmpDir, 'ok-lc.sh') + writeFileSync(scriptPath, '#!/bin/sh\nexit 0\n', 'utf-8') + chmodSync(scriptPath, 0o755) + const cmd = wrapPosixDirectHookCommand(scriptPath) + const result = spawnSync('/bin/sh', ['-lc', cmd]) expect(result.status).toBe(0) - expect(unquoted[0]).toBe('/bin/sh') } ) }) diff --git a/src/main/agent-hooks/installer-utils.ts b/src/main/agent-hooks/installer-utils.ts index 56170da88f50..be2d82561c1d 100644 --- a/src/main/agent-hooks/installer-utils.ts +++ b/src/main/agent-hooks/installer-utils.ts @@ -143,15 +143,28 @@ export function wrapPosixHookCommand(scriptPath: string, env: Record'` so argv0 is the shell and the script path is one argument. +// Why: #8110 surfaces exit 127 + Broken pipe when Codex runs Orca-managed +// hooks. Current Codex (codex-rs hooks command_runner) launches via +// `$SHELL -lc ` with the whole string as one arg — so if/then/fi +// and single-quoted paths both parse. Reports of pure whitespace argv-exec +// still match the observed 127 when argv0 becomes `if` or the path keeps +// literal quote characters. Emit `/bin/sh ` without shell control-flow: +// unquoted when the path is argv-safe (no IFS/metacharacters), otherwise +// POSIX single-quoted so shell -lc still works for spaced home dirs. export function wrapPosixDirectHookCommand(scriptPath: string): string { + if (isPosixArgvSafePath(scriptPath)) { + return `/bin/sh ${scriptPath}` + } const quoted = `'${scriptPath.replaceAll("'", "'\\''")}'` return `/bin/sh ${quoted}` } +// Absolute POSIX path free of whitespace and shell metacharacters so both +// `$SHELL -lc` and naive whitespace argv-split yield the same two-arg form. +function isPosixArgvSafePath(scriptPath: string): boolean { + return /^\/[A-Za-z0-9._/@%+=:,-]+$/.test(scriptPath) +} + function quotePowerShellString(value: string): string { return `'${value.replaceAll("'", "''")}'` } diff --git a/src/main/codex/hook-service-wsl-runtime.test.ts b/src/main/codex/hook-service-wsl-runtime.test.ts index e9356b5f0184..40cf49f2084c 100644 --- a/src/main/codex/hook-service-wsl-runtime.test.ts +++ b/src/main/codex/hook-service-wsl-runtime.test.ts @@ -351,8 +351,8 @@ describe('Codex WSL runtime hook install', () => { const installed = JSON.parse(readFileSync(plan.configPath, 'utf-8')) as HooksConfig expect(Object.keys(installed.hooks).sort()).toEqual([...managedEvents].sort()) const managedCommand = installed.hooks.UserPromptSubmit[0]?.hooks?.[0]?.command - // Why: Codex argv-execs hooks.json; guarded if/then/fi becomes argv0=`if` (#8110). - expect(managedCommand).toBe(`/bin/sh '${plan.commandScriptPath}'`) + // Why: dual-model Codex launcher — no if/then/fi; unquoted when path is safe (#8110). + expect(managedCommand).toBe(`/bin/sh ${plan.commandScriptPath}`) expect(managedCommand).not.toMatch(/\bif\b|\bthen\b|\bfi\b/) expect(installed.hooks.UserPromptSubmit[1]?.hooks?.[0]?.command).toBe(userCommand) expect(readFileSync(plan.scriptPath, 'utf-8')).toContain('command -v curl.exe') diff --git a/src/main/codex/hook-service.test.ts b/src/main/codex/hook-service.test.ts index 06325ed61abd..d2711f9d4dd9 100644 --- a/src/main/codex/hook-service.test.ts +++ b/src/main/codex/hook-service.test.ts @@ -158,10 +158,10 @@ describe('CodexHookService', () => { expect(trustConfig).toContain(':permission_request:0:0') }) - // Why: Codex direct-execs hooks.json commands (#8110). The shared - // wrapPosixHookCommand if/then/fi guard becomes argv0=`if` → exit 127. + // Why: #8110 — managed Codex commands must not use if/then/fi; dual-model + // wrapper emits `/bin/sh ` (quoted only when the path needs it). it.skipIf(process.platform === 'win32')( - 'writes argv-safe POSIX managed commands without shell control-flow', + 'writes dual-model POSIX managed commands without shell control-flow', () => { expect(new CodexHookService().install().state).toBe('installed') @@ -172,7 +172,7 @@ describe('CodexHookService', () => { for (const eventName of localManagedCodexEvents()) { const command = hooksConfig.hooks[eventName]?.[0]?.hooks?.[0]?.command ?? '' - expect(command).toMatch(/^\/bin\/sh '/) + expect(command).toMatch(/^\/bin\/sh /) expect(command).toContain('agent-hooks/codex-hook.sh') expect(command).not.toMatch(/\bif\b|\bthen\b|\bfi\b/) } diff --git a/src/main/codex/hook-service.ts b/src/main/codex/hook-service.ts index ad766fc1ded7..e467b2ac3f5a 100644 --- a/src/main/codex/hook-service.ts +++ b/src/main/codex/hook-service.ts @@ -135,19 +135,23 @@ export { createCodexWslRuntimeHookInstallPlan } export type { CodexWslRuntimeHookInstallPlan } // Why: WSL runtime hooks are written from Windows through UNC; /bin/sh only -// needs the script readable. Same argv-safe shape as local POSIX (#8110) — -// Codex direct-execs hooks.json, so if/then/fi must not appear in the command. +// needs the script readable. Same dual-model shape as local POSIX (#8110) — +// no if/then/fi tokens in the command string. function wrapReadablePosixHookCommand(scriptPath: string): string { return wrapPosixDirectHookCommand(scriptPath) } // Why: remove/status trust matching must still recognize pre-#8110 guarded -// commands so upgrade reinstall/remove can clear their hashes. +// commands and the intermediate quoted `/bin/sh '…'` form so upgrade +// reinstall/remove can clear their hashes. function codexPosixTrustCommandVariants(scriptPath: string): string[] { const direct = wrapPosixDirectHookCommand(scriptPath) const quoted = `'${scriptPath.replaceAll("'", "'\\''")}'` + const quotedDirect = `/bin/sh ${quoted}` return [ direct, + // Intermediate #8390 form before dual-model unquoted paths. + ...(quotedDirect === direct ? [] : [quotedDirect]), wrapPosixHookCommand(scriptPath), `if [ -r ${quoted} ]; then /bin/sh ${quoted}; fi` ] From bef0a652459612e7e0054ce2e683cd71a04bf399 Mon Sep 17 00:00:00 2001 From: bbingz Date: Mon, 13 Jul 2026 18:52:44 +0800 Subject: [PATCH 3/4] test(codex): expect direct remote hook commands --- src/main/agent-hooks/remote-hook-service-installers.test.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/agent-hooks/remote-hook-service-installers.test.ts b/src/main/agent-hooks/remote-hook-service-installers.test.ts index 8489048d0f5b..8d7dabc7da00 100644 --- a/src/main/agent-hooks/remote-hook-service-installers.test.ts +++ b/src/main/agent-hooks/remote-hook-service-installers.test.ts @@ -243,8 +243,8 @@ describe('remote hook service installers', () => { 'Stop' ]) { const command = hooks.hooks[eventName]?.[0]?.hooks?.[0]?.command - expect(command).toContain('/home/dev/.orca/agent-hooks/codex-hook.sh') - expect(command).toMatch(/^if \[ -f /) + expect(command).toBe('/bin/sh /home/dev/.orca/agent-hooks/codex-hook.sh') + expect(command).not.toMatch(/\bif\b|\bthen\b|\bfi\b/) } expect(fs.files.get('/home/dev/.orca/agent-hooks/codex-hook.sh')).toContain('#!/bin/sh') expect(fs.modes.get('/home/dev/.orca/agent-hooks/codex-hook.sh')).toBe(0o755) From 305bf6b8ecc5826e06b3e414eafba4ff129f70aa Mon Sep 17 00:00:00 2001 From: bbingz Date: Mon, 13 Jul 2026 19:04:31 +0800 Subject: [PATCH 4/4] fix(codex): restore guarded POSIX hook launchers --- src/main/agent-hooks/installer-utils.test.ts | 70 +++-------- src/main/agent-hooks/installer-utils.ts | 18 --- .../remote-hook-service-installers.test.ts | 4 +- .../codex/hook-service-wsl-runtime.test.ts | 109 +++++++++++++++--- src/main/codex/hook-service.test.ts | 13 ++- src/main/codex/hook-service.ts | 42 ++++--- 6 files changed, 146 insertions(+), 110 deletions(-) diff --git a/src/main/agent-hooks/installer-utils.test.ts b/src/main/agent-hooks/installer-utils.test.ts index 2ad1193f2b2b..cb1d6f01d9a4 100644 --- a/src/main/agent-hooks/installer-utils.test.ts +++ b/src/main/agent-hooks/installer-utils.test.ts @@ -11,7 +11,7 @@ import { chmodSync } from 'node:fs' import { homedir, tmpdir } from 'node:os' -import { join } from 'node:path' +import { dirname, join } from 'node:path' import { spawnSync } from 'node:child_process' import { buildWindowsAgentHookPostCommand, @@ -20,7 +20,6 @@ import { getSharedManagedScriptPath, hookDefinitionHasManagedCommand, removeManagedCommands, - wrapPosixDirectHookCommand, wrapPosixHookCommand, wrapWindowsCmdHookCommand, wrapWindowsGitBashHookCommand, @@ -318,6 +317,24 @@ describe('wrapPosixHookCommand', () => { ) }) + for (const shellFlag of ['-c', '-lc'] as const) { + it.skipIf(process.platform === 'win32')( + `runs hook paths containing spaces and single quotes under shell ${shellFlag}`, + () => { + for (const homeName of ['Jorge Silva', "O'Brien"]) { + const scriptPath = join(tmpDir, homeName, '.orca', 'agent-hooks', 'codex-hook.sh') + mkdirSync(dirname(scriptPath), { recursive: true }) + writeFileSync(scriptPath, '#!/bin/sh\nexit 0\n', 'utf-8') + chmodSync(scriptPath, 0o755) + + const result = spawnSync('/bin/sh', [shellFlag, wrapPosixHookCommand(scriptPath)]) + expect(result.error, `${homeName} spawn error`).toBeUndefined() + expect(result.status, `${homeName} exit status`).toBe(0) + } + } + ) + } + it('can scope environment variables to the guarded script invocation', () => { const cmd = wrapPosixHookCommand('/does/not/exist.sh', { ORCA_COPILOT_HOOK_EVENT: 'UserPromptSubmit' @@ -382,55 +399,6 @@ describe('wrapPosixHookCommand', () => { ) }) -describe('wrapPosixDirectHookCommand', () => { - // Why: #8110 — never emit if/then/fi; prefer unquoted path when argv-safe. - it('emits unquoted /bin/sh for argv-safe paths', () => { - const cmd = wrapPosixDirectHookCommand('/Users/a/.orca/agent-hooks/codex-hook.sh') - expect(cmd).toBe('/bin/sh /Users/a/.orca/agent-hooks/codex-hook.sh') - expect(cmd).not.toMatch(/\bif\b|\bthen\b|\bfi\b/) - expect(cmd).not.toContain("'") - }) - - it('single-quotes paths with spaces so shell -lc still works', () => { - const cmd = wrapPosixDirectHookCommand('/Users/Jorge Silva/.orca/agent-hooks/codex-hook.sh') - expect(cmd).toBe("/bin/sh '/Users/Jorge Silva/.orca/agent-hooks/codex-hook.sh'") - }) - - it('escapes embedded single quotes the same way as the guarded wrapper', () => { - const cmd = wrapPosixDirectHookCommand("/path/with'quote/x.sh") - expect(cmd).toBe("/bin/sh '/path/with'\\''quote/x.sh'") - }) - - it.skipIf(process.platform === 'win32')( - 'runs under pure whitespace argv-split without stripping quotes', - () => { - // Why: naive argv-exec keeps quote characters inside argv tokens. The - // dual-model form must not rely on a shell (or a test helper) to strip them. - const scriptPath = join(tmpDir, 'ok.sh') - writeFileSync(scriptPath, '#!/bin/sh\nexit 0\n', 'utf-8') - chmodSync(scriptPath, 0o755) - const cmd = wrapPosixDirectHookCommand(scriptPath) - const argv = cmd.split(/\s+/) - expect(argv[0]).toBe('/bin/sh') - expect(argv[1]).toBe(scriptPath) - const result = spawnSync(argv[0]!, argv.slice(1)) - expect(result.status).toBe(0) - } - ) - - it.skipIf(process.platform === 'win32')( - 'runs under shell -lc the way current Codex command_runner does', - () => { - const scriptPath = join(tmpDir, 'ok-lc.sh') - writeFileSync(scriptPath, '#!/bin/sh\nexit 0\n', 'utf-8') - chmodSync(scriptPath, 0o755) - const cmd = wrapPosixDirectHookCommand(scriptPath) - const result = spawnSync('/bin/sh', ['-lc', cmd]) - expect(result.status).toBe(0) - } - ) -}) - const qualifiedWindowsPowerShellCommand = /^[A-Za-z]:\/[^"]*\/System32\/WindowsPowerShell\/v1\.0\/powershell\.exe -NoProfile -ExecutionPolicy Bypass -EncodedCommand \S+$/ diff --git a/src/main/agent-hooks/installer-utils.ts b/src/main/agent-hooks/installer-utils.ts index 2bc4c8f28c97..6b9e93edad5f 100644 --- a/src/main/agent-hooks/installer-utils.ts +++ b/src/main/agent-hooks/installer-utils.ts @@ -150,24 +150,6 @@ export function wrapPosixHookCommand(scriptPath: string, env: Record` with the whole string as one arg — so if/then/fi -// and single-quoted paths both parse. Reports of pure whitespace argv-exec -// still match the observed 127 when argv0 becomes `if` or the path keeps -// literal quote characters. Emit `/bin/sh ` without shell control-flow: -// unquoted when the path is argv-safe (no IFS/metacharacters), otherwise -// POSIX single-quoted so shell -lc still works for spaced home dirs. -export function wrapPosixDirectHookCommand(scriptPath: string): string { - return `/bin/sh ${isPosixArgvSafePath(scriptPath) ? scriptPath : quotePosixShellString(scriptPath)}` -} - -// Absolute POSIX path free of whitespace and shell metacharacters so both -// `$SHELL -lc` and naive whitespace argv-split yield the same two-arg form. -function isPosixArgvSafePath(scriptPath: string): boolean { - return /^\/[A-Za-z0-9._/@%+=:,-]+$/.test(scriptPath) -} - function quotePowerShellString(value: string): string { return `'${value.replaceAll("'", "''")}'` } diff --git a/src/main/agent-hooks/remote-hook-service-installers.test.ts b/src/main/agent-hooks/remote-hook-service-installers.test.ts index 8d7dabc7da00..c703730a5fe4 100644 --- a/src/main/agent-hooks/remote-hook-service-installers.test.ts +++ b/src/main/agent-hooks/remote-hook-service-installers.test.ts @@ -35,6 +35,7 @@ import { grokHookService } from '../grok/hook-service' import { hermesHookService } from '../hermes/hook-service' import { kimiHookService } from '../kimi/hook-service' import { MANAGED_AGENT_HOOK_INSTALLERS } from './managed-agent-hook-controls' +import { wrapPosixHookCommand } from './installer-utils' import { installRemoteManagedAgentHooks, REMOTE_MANAGED_HOOK_INSTALLER_AGENTS @@ -243,8 +244,7 @@ describe('remote hook service installers', () => { 'Stop' ]) { const command = hooks.hooks[eventName]?.[0]?.hooks?.[0]?.command - expect(command).toBe('/bin/sh /home/dev/.orca/agent-hooks/codex-hook.sh') - expect(command).not.toMatch(/\bif\b|\bthen\b|\bfi\b/) + expect(command).toBe(wrapPosixHookCommand('/home/dev/.orca/agent-hooks/codex-hook.sh')) } expect(fs.files.get('/home/dev/.orca/agent-hooks/codex-hook.sh')).toContain('#!/bin/sh') expect(fs.modes.get('/home/dev/.orca/agent-hooks/codex-hook.sh')).toBe(0o755) diff --git a/src/main/codex/hook-service-wsl-runtime.test.ts b/src/main/codex/hook-service-wsl-runtime.test.ts index c4002b67ec2e..2498132abf87 100644 --- a/src/main/codex/hook-service-wsl-runtime.test.ts +++ b/src/main/codex/hook-service-wsl-runtime.test.ts @@ -1,13 +1,10 @@ import { afterEach, describe, expect, it } from 'vitest' import { chmodSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' -import { spawnSync } from 'node:child_process' +import { spawn, spawnSync } from 'node:child_process' import { tmpdir } from 'node:os' import { dirname, join, win32 as pathWin32 } from 'node:path' -import { - MANAGED_HOOK_TIMEOUT_SECONDS, - wrapPosixDirectHookCommand -} from '../agent-hooks/installer-utils' +import { MANAGED_HOOK_TIMEOUT_SECONDS } from '../agent-hooks/installer-utils' import { computeTrustKey, computeTrustedHash, @@ -24,6 +21,11 @@ type HooksConfig = { hooks: Record } +type HookRun = { + exitCode: number | null + stdinErrors: NodeJS.ErrnoException[] +} + const managedEvents = [ 'SessionStart', 'UserPromptSubmit', @@ -70,11 +72,35 @@ function getManagedTrustEntry( } function expectedManagedCommand(scriptPath: string): string { - return wrapPosixDirectHookCommand(scriptPath) + const quoted = `'${scriptPath.replaceAll("'", "'\\''")}'` + return `if [ -f ${quoted} ] && [ -r ${quoted} ]; then /bin/sh ${quoted}; else cat >/dev/null 2>&1 || :; fi` +} + +function expectedLegacyDirectCommand(scriptPath: string): string { + return `/bin/sh ${scriptPath}` } -function expectedCurrentMainManagedCommand(scriptPath: string): string { - return `if [ -f '${scriptPath}' ] && [ -r '${scriptPath}' ]; then /bin/sh '${scriptPath}'; else cat >/dev/null 2>&1 || :; fi` +function runInstalledHook(command: string, shellFlag: '-c' | '-lc'): Promise { + return new Promise((resolve, reject) => { + const child = spawn('/bin/sh', [shellFlag, command], { + stdio: ['pipe', 'ignore', 'ignore'] + }) + const stdinErrors: NodeJS.ErrnoException[] = [] + const timeout = setTimeout(() => { + child.kill('SIGKILL') + reject(new Error('installed Codex hook did not finish after stdin closed')) + }, 10_000) + child.on('error', (error) => { + clearTimeout(timeout) + reject(error) + }) + child.stdin.on('error', (error: NodeJS.ErrnoException) => stdinErrors.push(error)) + child.on('close', (exitCode) => { + clearTimeout(timeout) + resolve({ exitCode, stdinErrors }) + }) + child.stdin.end(Buffer.alloc(1_000_000, 'x')) + }) } describe('Codex WSL runtime hook install', () => { @@ -161,7 +187,7 @@ describe('Codex WSL runtime hook install', () => { expect(trustEntries.has(newKey)).toBe(true) }) - it('removes current-main guarded WSL trust when upgrading to a direct launcher', () => { + it('removes legacy direct WSL trust when returning to a guarded launcher', () => { const plan = createTestPlan() writeFileSync(plan.configPath, '{"hooks":{}}\n', 'utf-8') @@ -172,7 +198,7 @@ describe('Codex WSL runtime hook install', () => { } const oldEntry = getManagedTrustEntry( oldPlan, - expectedCurrentMainManagedCommand(oldPlan.commandScriptPath) + expectedLegacyDirectCommand(oldPlan.commandScriptPath) ) const oldKey = computeTrustKey(oldEntry) writeFileSync( @@ -220,8 +246,8 @@ describe('Codex WSL runtime hook install', () => { const command = installed.hooks.UserPromptSubmit[0]?.hooks?.[0]?.command expect(command).toBe(expectedManagedCommand(plan.commandScriptPath)) - // Why: Codex cannot carry a guarded launcher in both execution models; - // the managed script itself must own stdin before any early return. + // Why: WSL files written through UNC may not preserve executable bits; + // a readable guard must still launch the script through /bin/sh. const result = spawnSync('/bin/sh', ['-c', command!], { input: Buffer.alloc(1_000_000, 'x') }) @@ -230,6 +256,61 @@ describe('Codex WSL runtime hook install', () => { } ) + for (const shellFlag of ['-c', '-lc'] as const) { + it.skipIf(process.platform === 'win32')( + `runs WSL hook paths containing spaces and single quotes under shell ${shellFlag}`, + async () => { + for (const homeName of ['Jorge Silva', "O'Brien"]) { + const basePlan = createTestPlan() + const scriptPath = join( + dirname(basePlan.configPath), + homeName, + '.orca', + 'agent-hooks', + 'codex-hook.sh' + ) + const plan = { + ...basePlan, + scriptPath, + commandScriptPath: scriptPath + } + writeFileSync(plan.configPath, '{"hooks":{}}\n', 'utf-8') + writeFileSync(plan.tomlPath, '', 'utf-8') + + expect(_internals.installManagedHooksIntoWslRuntime(plan).state).toBe('installed') + const installed = JSON.parse(readFileSync(plan.configPath, 'utf-8')) as HooksConfig + const command = installed.hooks.UserPromptSubmit[0]?.hooks?.[0]?.command + expect(command).toBe(expectedManagedCommand(scriptPath)) + + const result = await runInstalledHook(command!, shellFlag) + expect(result).toEqual({ exitCode: 0, stdinErrors: [] }) + } + } + ) + + it.skipIf(process.platform === 'win32')( + `drains large stdin when the WSL runtime script is missing under shell ${shellFlag}`, + async () => { + const basePlan = createTestPlan() + const plan = { + ...basePlan, + commandScriptPath: basePlan.scriptPath + } + writeFileSync(plan.configPath, '{"hooks":{}}\n', 'utf-8') + writeFileSync(plan.tomlPath, '', 'utf-8') + + expect(_internals.installManagedHooksIntoWslRuntime(plan).state).toBe('installed') + const installed = JSON.parse(readFileSync(plan.configPath, 'utf-8')) as HooksConfig + const command = installed.hooks.UserPromptSubmit[0]?.hooks?.[0]?.command + expect(command).toBeDefined() + rmSync(plan.scriptPath, { force: true }) + + const result = await runInstalledHook(command!, shellFlag) + expect(result).toEqual({ exitCode: 0, stdinErrors: [] }) + } + ) + } + it('sweeps all managed WSL trust for disable or confirmed absence', () => { // Why: disable and confirmed absence intentionally pass []. Transient // unavailability must NOT use this path — last known-good trust remains. @@ -431,9 +512,9 @@ describe('Codex WSL runtime hook install', () => { const installed = JSON.parse(readFileSync(plan.configPath, 'utf-8')) as HooksConfig expect(Object.keys(installed.hooks).sort()).toEqual([...managedEvents].sort()) const managedCommand = installed.hooks.UserPromptSubmit[0]?.hooks?.[0]?.command - // Why: dual-model Codex launcher — no if/then/fi; unquoted when path is safe (#8110). + // Why: Codex executes through a POSIX shell, so the launcher must guard + // missing scripts and own stdin before returning successfully. expect(managedCommand).toBe(expectedManagedCommand(plan.commandScriptPath)) - expect(managedCommand).not.toMatch(/\bif\b|\bthen\b|\bfi\b/) expect(installed.hooks.UserPromptSubmit[1]?.hooks?.[0]?.command).toBe(userCommand) expect(readFileSync(plan.scriptPath, 'utf-8')).toContain('command -v curl.exe') diff --git a/src/main/codex/hook-service.test.ts b/src/main/codex/hook-service.test.ts index d2711f9d4dd9..b291614771e7 100644 --- a/src/main/codex/hook-service.test.ts +++ b/src/main/codex/hook-service.test.ts @@ -158,10 +158,10 @@ describe('CodexHookService', () => { expect(trustConfig).toContain(':permission_request:0:0') }) - // Why: #8110 — managed Codex commands must not use if/then/fi; dual-model - // wrapper emits `/bin/sh ` (quoted only when the path needs it). + // Why: Codex runs hook commands through a POSIX shell and writes the full + // payload to stdin, so missing managed scripts must drain before exit. it.skipIf(process.platform === 'win32')( - 'writes dual-model POSIX managed commands without shell control-flow', + 'writes guarded POSIX managed commands for every event', () => { expect(new CodexHookService().install().state).toBe('installed') @@ -169,12 +169,13 @@ describe('CodexHookService', () => { const hooksConfig = JSON.parse( readFileSync(join(managedCodexHome, 'hooks.json'), 'utf-8') ) as { hooks: Record } + const expectedCommand = wrapPosixHookCommand( + join(tmpHome, '.orca', 'agent-hooks', 'codex-hook.sh') + ) for (const eventName of localManagedCodexEvents()) { const command = hooksConfig.hooks[eventName]?.[0]?.hooks?.[0]?.command ?? '' - expect(command).toMatch(/^\/bin\/sh /) - expect(command).toContain('agent-hooks/codex-hook.sh') - expect(command).not.toMatch(/\bif\b|\bthen\b|\bfi\b/) + expect(command).toBe(expectedCommand) } } ) diff --git a/src/main/codex/hook-service.ts b/src/main/codex/hook-service.ts index 017e8f56cd3b..1bfb529ea68a 100644 --- a/src/main/codex/hook-service.ts +++ b/src/main/codex/hook-service.ts @@ -12,7 +12,6 @@ import { MANAGED_HOOK_TIMEOUT_SECONDS, readHooksJson, removeManagedCommands, - wrapPosixDirectHookCommand, wrapPosixHookCommand, wrapWindowsCmdHookCommand, writeHooksJson, @@ -134,35 +133,40 @@ function getManagedScriptPath(): string { function getManagedCommand(scriptPath: string): string { return process.platform === 'win32' ? wrapWindowsCmdHookCommand(scriptPath) - : wrapPosixDirectHookCommand(scriptPath) + : wrapPosixHookCommand(scriptPath) } export { createCodexWslRuntimeHookInstallPlan } export type { CodexWslRuntimeHookInstallPlan } -// Why: WSL runtime hooks are written from Windows through UNC; /bin/sh only -// needs the script readable. Same dual-model shape as local POSIX (#8110) — -// no if/then/fi tokens in the command string. function wrapReadablePosixHookCommand(scriptPath: string): string { - return wrapPosixDirectHookCommand(scriptPath) + const quoted = `'${scriptPath.replaceAll("'", "'\\''")}'` + // Why: WSL runtime hooks are written from Windows through UNC, where the + // executable bit is not reliable; a missing script must still own stdin. + return `if [ -f ${quoted} ] && [ -r ${quoted} ]; then /bin/sh ${quoted}; else ${POSIX_HOOK_STDIN_DRAIN_COMMAND}; fi` +} + +function getLegacyDirectPosixHookCommand(scriptPath: string): string { + const quoted = `'${scriptPath.replaceAll("'", "'\\''")}'` + // Why: #8390 wrote this command into hooks.json and trust hashes; cleanup + // must keep recognizing it after guarded launchers become current again. + return `/bin/sh ${/^\/[A-Za-z0-9._/@%+=:,-]+$/.test(scriptPath) ? scriptPath : quoted}` } -// Why: remove/status trust matching must still recognize pre-#8110 guarded -// commands and the intermediate quoted `/bin/sh '…'` form so upgrade -// reinstall/remove can clear their hashes. +// Why: remove/status trust matching must recognize every launcher Orca wrote +// so upgrade reinstall/remove can clear stale hashes without user cleanup. function codexPosixTrustCommandVariants(scriptPath: string): string[] { - const direct = wrapPosixDirectHookCommand(scriptPath) + const guarded = wrapPosixHookCommand(scriptPath) + const guardedReadable = wrapReadablePosixHookCommand(scriptPath) + const legacyDirect = getLegacyDirectPosixHookCommand(scriptPath) const quoted = `'${scriptPath.replaceAll("'", "'\\''")}'` const quotedDirect = `/bin/sh ${quoted}` - const guardedReadableWithDrain = `if [ -f ${quoted} ] && [ -r ${quoted} ]; then /bin/sh ${quoted}; else ${POSIX_HOOK_STDIN_DRAIN_COMMAND}; fi` return [ - direct, - // Intermediate #8390 form before dual-model unquoted paths. - ...(quotedDirect === direct ? [] : [quotedDirect]), - // Current-main launchers must remain removable after switching Codex to - // its control-flow-free direct command shape. - wrapPosixHookCommand(scriptPath), - guardedReadableWithDrain, + guarded, + ...(guardedReadable === guarded ? [] : [guardedReadable]), + legacyDirect, + // Intermediate #8390 form before conditional unquoted direct paths. + ...(quotedDirect === legacyDirect ? [] : [quotedDirect]), `if [ -x ${quoted} ]; then /bin/sh ${quoted}; fi`, `if [ -r ${quoted} ]; then /bin/sh ${quoted}; fi` ] @@ -1397,7 +1401,7 @@ export class CodexHookService { } } - const command = wrapPosixDirectHookCommand(remoteScriptPath) + const command = wrapPosixHookCommand(remoteScriptPath) const nextHooks = { ...config.hooks } const managedEvents = new Set(CODEX_EVENTS) const isManagedCommand = createManagedCommandMatcher('codex-hook.sh')