Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 19 additions & 1 deletion src/main/agent-hooks/installer-utils.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -317,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'
Expand Down
4 changes: 2 additions & 2 deletions src/main/agent-hooks/remote-hook-service-installers.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -243,8 +244,7 @@ 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(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)
Expand Down
143 changes: 139 additions & 4 deletions src/main/codex/hook-service-wsl-runtime.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
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'

Expand All @@ -21,6 +21,11 @@ type HooksConfig = {
hooks: Record<string, { hooks?: { command?: string }[] }[]>
}

type HookRun = {
exitCode: number | null
stdinErrors: NodeJS.ErrnoException[]
}

const managedEvents = [
'SessionStart',
'UserPromptSubmit',
Expand Down Expand Up @@ -67,7 +72,35 @@ function getManagedTrustEntry(
}

function expectedManagedCommand(scriptPath: string): string {
return `if [ -f '${scriptPath}' ] && [ -r '${scriptPath}' ]; then /bin/sh '${scriptPath}'; else cat >/dev/null 2>&1 || :; fi`
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 runInstalledHook(command: string, shellFlag: '-c' | '-lc'): Promise<HookRun> {
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', () => {
Expand Down Expand Up @@ -154,13 +187,56 @@ describe('Codex WSL runtime hook install', () => {
expect(trustEntries.has(newKey)).toBe(true)
})

it('removes legacy direct WSL trust when returning to a guarded launcher', () => {
const plan = createTestPlan()
writeFileSync(plan.configPath, '{"hooks":{}}\n', 'utf-8')

const oldPlan = {
...plan,
commandScriptPath: '/old/home/.orca/agent-hooks/codex-hook.sh',
trustConfigPath: '/old/home/hooks.json'
}
const oldEntry = getManagedTrustEntry(
oldPlan,
expectedLegacyDirectCommand(oldPlan.commandScriptPath)
)
const oldKey = computeTrustKey(oldEntry)
writeFileSync(
plan.tomlPath,
[
`[hooks.state."${oldKey}"]`,
'enabled = true',
`trusted_hash = "${computeTrustedHash(oldEntry)}"`,
''
].join('\n'),
'utf-8'
)

const newPlan = {
...plan,
commandScriptPath: '/new/home/.orca/agent-hooks/codex-hook.sh',
trustConfigPath: '/new/home/hooks.json'
}
expect(_internals.installManagedHooksIntoWslRuntime(newPlan).state).toBe('installed')

const newEntry = getManagedTrustEntry(
newPlan,
expectedManagedCommand(newPlan.commandScriptPath)
)
const trustEntries = readHookTrustEntries(plan.tomlPath)
expect(trustEntries.has(oldKey)).toBe(false)
expect(trustEntries.get(computeTrustKey(newEntry))?.trustedHash).toBe(
computeTrustedHash(newEntry)
)
})

it.skipIf(process.platform === 'win32')(
'drains stdin when the WSL runtime script is missing',
'drains stdin before the WSL runtime script exits early',
() => {
const basePlan = createTestPlan()
const plan = {
...basePlan,
commandScriptPath: join(dirname(basePlan.configPath), 'missing-codex-hook.sh')
commandScriptPath: basePlan.scriptPath
}
writeFileSync(plan.configPath, '{"hooks":{}}\n', 'utf-8')
writeFileSync(plan.tomlPath, '', 'utf-8')
Expand All @@ -170,6 +246,8 @@ describe('Codex WSL runtime hook install', () => {
const command = installed.hooks.UserPromptSubmit[0]?.hooks?.[0]?.command
expect(command).toBe(expectedManagedCommand(plan.commandScriptPath))

// 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')
})
Expand All @@ -178,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.
Expand Down Expand Up @@ -379,6 +512,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 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(installed.hooks.UserPromptSubmit[1]?.hooks?.[0]?.command).toBe(userCommand)
expect(readFileSync(plan.scriptPath, 'utf-8')).toContain('command -v curl.exe')
Expand Down
22 changes: 22 additions & 0 deletions src/main/codex/hook-service.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -158,6 +158,28 @@ describe('CodexHookService', () => {
expect(trustConfig).toContain(':permission_request:0:0')
})

// 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 guarded POSIX managed commands for every event',
() => {
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<string, { hooks?: { command?: string }[] }[]> }
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).toBe(expectedCommand)
}
}
)

it('drops plugin manager metadata from runtime hooks.json during install', () => {
const managedCodexHome = join(userDataDir, 'codex-runtime-home', 'home')
mkdirSync(managedCodexHome, { recursive: true })
Expand Down
85 changes: 59 additions & 26 deletions src/main/codex/hook-service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -146,6 +146,32 @@ function wrapReadablePosixHookCommand(scriptPath: string): string {
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 recognize every launcher Orca wrote
// so upgrade reinstall/remove can clear stale hashes without user cleanup.
function codexPosixTrustCommandVariants(scriptPath: string): string[] {
const guarded = wrapPosixHookCommand(scriptPath)
const guardedReadable = wrapReadablePosixHookCommand(scriptPath)
const legacyDirect = getLegacyDirectPosixHookCommand(scriptPath)
const quoted = `'${scriptPath.replaceAll("'", "'\\''")}'`
const quotedDirect = `/bin/sh ${quoted}`
return [
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`
]
}

function getSystemConfigPath(): string {
return join(getSystemCodexHomePath(), 'hooks.json')
}
Expand Down Expand Up @@ -635,7 +661,6 @@ function removeRuntimeManagedHookTrustEntries(configPath: string): void {
const tomlPath = getCodexConfigTomlPath()
const existingEntries = readHookTrustEntries(tomlPath)
const scriptPath = getManagedScriptPath()
const command = getManagedCommand(scriptPath)
const managedEventLabels = new Set<CodexEventLabel>(
CODEX_EVENTS.map((event) => CODEX_EVENT_LABEL[event])
)
Expand All @@ -645,6 +670,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) {
Expand All @@ -656,20 +685,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<string>()
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
}
Expand Down Expand Up @@ -755,19 +785,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<string>()
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)
}
Expand Down
Loading