fix(codex): harden WSL hook path trust lifecycle (#8191)
* Fix WSL Codex hook path trust lifecycle * fix(codex): keep WSL hook trust across transient path rechecks Failed async wslpath/readlink revalidation no longer drops the last known-good cache or wipes managed trust. That path turned cold/wedged distro timeouts into silent untrusted hooks, and forced the next launch onto the logical /mnt guess under custom automount roots. Settlement now reinstalls only when the generation is current and the canonical trust path actually changed. * fix(codex): revoke trust for missing WSL hook paths
This commit is contained in:
@@ -38,10 +38,19 @@ describe('canonicalizeWslLinuxPath', () => {
|
||||
expect(execFileMock).toHaveBeenCalledTimes(1)
|
||||
const [file, args] = execFileMock.mock.calls[0]
|
||||
expect(file).toBe('wsl.exe')
|
||||
expect(args).toEqual(['-d', 'Ubuntu', '--', 'readlink', '-f', '--', '/home/alias'])
|
||||
expect(args).toEqual([
|
||||
'-d',
|
||||
'Ubuntu',
|
||||
'--',
|
||||
'sh',
|
||||
'-c',
|
||||
`if [ ! -d "$1" ]; then printf '%s\\n' '__ORCA_WSL_PATH_MISSING__'; exit 0; fi; readlink -f -- "$1"`,
|
||||
'sh',
|
||||
'/home/alias'
|
||||
])
|
||||
})
|
||||
|
||||
it('caches the resolved canonical path and stops spawning wsl.exe', () => {
|
||||
it('returns the cached path while revalidating it asynchronously', () => {
|
||||
setPlatform('win32')
|
||||
expect(_internals.canonicalizeWslLinuxPath('Ubuntu', '/home/alias')).toBeNull()
|
||||
|
||||
@@ -49,7 +58,42 @@ describe('canonicalizeWslLinuxPath', () => {
|
||||
callback(null, '/home/alice\n')
|
||||
|
||||
expect(_internals.canonicalizeWslLinuxPath('Ubuntu', '/home/alias')).toBe('/home/alice')
|
||||
expect(execFileMock).toHaveBeenCalledTimes(1)
|
||||
expect(execFileMock).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
|
||||
it('resolves a custom automount root and notifies the first launch', () => {
|
||||
setPlatform('win32')
|
||||
const settled = vi.fn()
|
||||
const windowsPath = 'D:\\orca\\codex-runtime-home\\home'
|
||||
|
||||
expect(
|
||||
_internals.canonicalizeWslLinuxPath(
|
||||
'Ubuntu',
|
||||
'/mnt/d/orca/codex-runtime-home/home',
|
||||
windowsPath,
|
||||
settled
|
||||
)
|
||||
).toBeNull()
|
||||
|
||||
const [file, args, options, callback] = execFileMock.mock.calls[0]
|
||||
expect(file).toBe('wsl.exe')
|
||||
expect(args).toEqual([
|
||||
'-d',
|
||||
'Ubuntu',
|
||||
'--',
|
||||
'sh',
|
||||
'-c',
|
||||
`resolved=$(wslpath -a -u "$1") || exit; if [ ! -d "$resolved" ]; then printf '%s\\n' '__ORCA_WSL_PATH_MISSING__'; exit 0; fi; readlink -f -- "$resolved"`,
|
||||
'sh',
|
||||
windowsPath
|
||||
])
|
||||
expect(options).toMatchObject({ timeout: 5000, windowsHide: true })
|
||||
|
||||
callback(null, '/windows/d/orca/codex-runtime-home/home\n')
|
||||
expect(settled).toHaveBeenCalledWith({
|
||||
status: 'resolved',
|
||||
canonicalPath: '/windows/d/orca/codex-runtime-home/home'
|
||||
})
|
||||
})
|
||||
|
||||
it('does not spawn a second subprocess while one is in flight', () => {
|
||||
@@ -70,6 +114,81 @@ describe('canonicalizeWslLinuxPath', () => {
|
||||
expect(execFileMock).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
|
||||
it('keeps the last known-good cache when revalidation later fails', () => {
|
||||
setPlatform('win32')
|
||||
_internals.canonicalizeWslLinuxPath('Ubuntu', '/home/alias')
|
||||
const firstCallback = execFileMock.mock.calls[0][3] as (
|
||||
error: Error | null,
|
||||
stdout: string
|
||||
) => void
|
||||
firstCallback(null, '/home/alice\n')
|
||||
|
||||
const settled = vi.fn()
|
||||
expect(
|
||||
_internals.canonicalizeWslLinuxPath('Ubuntu', '/home/alias', '/home/alias', settled)
|
||||
).toBe('/home/alice')
|
||||
const secondCallback = execFileMock.mock.calls[1][3] as (
|
||||
error: Error | null,
|
||||
stdout: string
|
||||
) => void
|
||||
secondCallback(new Error('path disappeared'), '')
|
||||
|
||||
// Why: a cold or wedged distro times out without proving the path changed.
|
||||
// Dropping the cache would force the next launch onto /mnt/... and rewrite
|
||||
// trust under a path Codex will not use when automount is customized.
|
||||
expect(settled).toHaveBeenCalledWith({ status: 'unavailable' })
|
||||
expect(_internals.canonicalizeWslLinuxPath('Ubuntu', '/home/alias')).toBe('/home/alice')
|
||||
})
|
||||
|
||||
it('drops the cached identity when WSL confirms the path is missing', () => {
|
||||
setPlatform('win32')
|
||||
_internals.canonicalizeWslLinuxPath('Ubuntu', '/home/alias')
|
||||
const firstCallback = execFileMock.mock.calls[0][3] as (
|
||||
error: Error | null,
|
||||
stdout: string
|
||||
) => void
|
||||
firstCallback(null, '/home/alice\n')
|
||||
|
||||
const settled = vi.fn()
|
||||
expect(
|
||||
_internals.canonicalizeWslLinuxPath('Ubuntu', '/home/alias', '/home/alias', settled)
|
||||
).toBe('/home/alice')
|
||||
const secondCallback = execFileMock.mock.calls[1][3] as (
|
||||
error: Error | null,
|
||||
stdout: string
|
||||
) => void
|
||||
secondCallback(null, '__ORCA_WSL_PATH_MISSING__\n')
|
||||
|
||||
expect(settled).toHaveBeenCalledWith({ status: 'missing' })
|
||||
expect(_internals.canonicalizeWslLinuxPath('Ubuntu', '/home/alias')).toBeNull()
|
||||
})
|
||||
|
||||
it('replaces a cached path when its canonical identity changes', () => {
|
||||
setPlatform('win32')
|
||||
_internals.canonicalizeWslLinuxPath('Ubuntu', '/home/alias')
|
||||
const firstCallback = execFileMock.mock.calls[0][3] as (
|
||||
error: Error | null,
|
||||
stdout: string
|
||||
) => void
|
||||
firstCallback(null, '/home/alice-old\n')
|
||||
|
||||
const settled = vi.fn()
|
||||
expect(
|
||||
_internals.canonicalizeWslLinuxPath('Ubuntu', '/home/alias', '/home/alias', settled)
|
||||
).toBe('/home/alice-old')
|
||||
const secondCallback = execFileMock.mock.calls[1][3] as (
|
||||
error: Error | null,
|
||||
stdout: string
|
||||
) => void
|
||||
secondCallback(null, '/home/alice-new\n')
|
||||
|
||||
expect(settled).toHaveBeenCalledWith({
|
||||
status: 'resolved',
|
||||
canonicalPath: '/home/alice-new'
|
||||
})
|
||||
expect(_internals.canonicalizeWslLinuxPath('Ubuntu', '/home/alias')).toBe('/home/alice-new')
|
||||
})
|
||||
|
||||
it('ignores non-absolute readlink output', () => {
|
||||
setPlatform('win32')
|
||||
_internals.canonicalizeWslLinuxPath('Ubuntu', '/home/alias')
|
||||
|
||||
@@ -15,7 +15,19 @@ export type CodexWslRuntimeHookInstallPlan = {
|
||||
trustConfigPath: string
|
||||
}
|
||||
|
||||
export type CanonicalizeWslLinuxPath = (distro: string, linuxPath: string) => string | null
|
||||
export type WslCanonicalPathSettlement =
|
||||
| { status: 'resolved'; canonicalPath: string }
|
||||
| { status: 'missing' }
|
||||
| { status: 'unavailable' }
|
||||
|
||||
export type WslCanonicalPathSettled = (settlement: WslCanonicalPathSettlement) => void
|
||||
|
||||
export type CanonicalizeWslLinuxPath = (
|
||||
distro: string,
|
||||
linuxPath: string,
|
||||
windowsPath?: string,
|
||||
onSettled?: WslCanonicalPathSettled
|
||||
) => string | null
|
||||
|
||||
function trimTrailingSlash(value: string): string {
|
||||
return value.length > 1 ? value.replace(/\/+$/, '') : value
|
||||
@@ -30,61 +42,118 @@ function toDefaultWslLinuxPath(windowsPath: string): string {
|
||||
}
|
||||
|
||||
const WSL_CANONICALIZE_TIMEOUT_MS = 5000
|
||||
const WSL_PATH_MISSING_OUTPUT = '__ORCA_WSL_PATH_MISSING__'
|
||||
|
||||
// Why: `readlink -f` over wsl.exe stalls up to the timeout on a cold or wedged
|
||||
// distro. Running it synchronously on the Electron main process froze the UI on
|
||||
// every Codex WSL launch, so resolve it off-thread and cache the stable result.
|
||||
// every Codex WSL launch, so resolve it off-thread and cache the latest result.
|
||||
const canonicalWslPathCache = new Map<string, string>()
|
||||
const inFlightWslCanonicalizations = new Set<string>()
|
||||
const inFlightWslCanonicalizations = new Map<string, Set<WslCanonicalPathSettled>>()
|
||||
|
||||
function wslCanonicalizeCacheKey(distro: string, linuxPath: string): string {
|
||||
return `${distro}\x00${linuxPath}`
|
||||
}
|
||||
|
||||
function scheduleWslLinuxPathCanonicalization(distro: string, linuxPath: string): void {
|
||||
function scheduleWslLinuxPathCanonicalization(
|
||||
distro: string,
|
||||
linuxPath: string,
|
||||
windowsPath: string,
|
||||
onSettled?: WslCanonicalPathSettled
|
||||
): void {
|
||||
const key = wslCanonicalizeCacheKey(distro, linuxPath)
|
||||
// Why: cap the wedged-WSL blast radius to a single background subprocess per
|
||||
// (distro, path); the cache holds the answer once one resolution succeeds.
|
||||
if (canonicalWslPathCache.has(key) || inFlightWslCanonicalizations.has(key)) {
|
||||
const listeners = inFlightWslCanonicalizations.get(key)
|
||||
if (listeners) {
|
||||
if (onSettled) {
|
||||
listeners.add(onSettled)
|
||||
}
|
||||
return
|
||||
}
|
||||
inFlightWslCanonicalizations.add(key)
|
||||
const nextListeners = new Set<WslCanonicalPathSettled>()
|
||||
if (onSettled) {
|
||||
nextListeners.add(onSettled)
|
||||
}
|
||||
inFlightWslCanonicalizations.set(key, nextListeners)
|
||||
const drivePath = /^[A-Za-z]:[/\\]/.test(windowsPath)
|
||||
// Why: wslpath reads each distro's automount root, so a custom root such as
|
||||
// /windows is discovered without synchronously starting WSL on Electron main.
|
||||
const args = drivePath
|
||||
? [
|
||||
'-d',
|
||||
distro,
|
||||
'--',
|
||||
'sh',
|
||||
'-c',
|
||||
`resolved=$(wslpath -a -u "$1") || exit; if [ ! -d "$resolved" ]; then printf '%s\\n' '${WSL_PATH_MISSING_OUTPUT}'; exit 0; fi; readlink -f -- "$resolved"`,
|
||||
'sh',
|
||||
windowsPath
|
||||
]
|
||||
: [
|
||||
'-d',
|
||||
distro,
|
||||
'--',
|
||||
'sh',
|
||||
'-c',
|
||||
`if [ ! -d "$1" ]; then printf '%s\\n' '${WSL_PATH_MISSING_OUTPUT}'; exit 0; fi; readlink -f -- "$1"`,
|
||||
'sh',
|
||||
linuxPath
|
||||
]
|
||||
execFile(
|
||||
'wsl.exe',
|
||||
['-d', distro, '--', 'readlink', '-f', '--', linuxPath],
|
||||
args,
|
||||
{ encoding: 'utf-8', timeout: WSL_CANONICALIZE_TIMEOUT_MS, windowsHide: true },
|
||||
(error, stdout) => {
|
||||
inFlightWslCanonicalizations.delete(key)
|
||||
if (error) {
|
||||
return
|
||||
}
|
||||
const canonicalPath = stdout.trim()
|
||||
if (canonicalPath.startsWith('/')) {
|
||||
const resolvedPath = !error && canonicalPath.startsWith('/') ? canonicalPath : null
|
||||
const pathMissing = !error && canonicalPath === WSL_PATH_MISSING_OUTPUT
|
||||
const settlement: WslCanonicalPathSettlement = resolvedPath
|
||||
? { status: 'resolved', canonicalPath: resolvedPath }
|
||||
: pathMissing
|
||||
? { status: 'missing' }
|
||||
: { status: 'unavailable' }
|
||||
if (settlement.status === 'resolved') {
|
||||
canonicalWslPathCache.set(key, canonicalPath)
|
||||
} else if (settlement.status === 'missing') {
|
||||
// Why: a successful directory probe is stronger than a transport error;
|
||||
// clear the identity so stale trust can be revoked and later rediscovered.
|
||||
canonicalWslPathCache.delete(key)
|
||||
}
|
||||
// Why: keep the last known-good cache on timeout/transient WSL failures.
|
||||
// Dropping it forces the next launch onto the logical `/mnt/...` guess,
|
||||
// which is wrong under custom automount roots and rewrites trust keys.
|
||||
const settledListeners = inFlightWslCanonicalizations.get(key) ?? new Set()
|
||||
inFlightWslCanonicalizations.delete(key)
|
||||
for (const listener of settledListeners) {
|
||||
try {
|
||||
listener(settlement)
|
||||
} catch (listenerError) {
|
||||
console.warn('[codex-wsl-hook-path] failed to reconcile canonical path', listenerError)
|
||||
}
|
||||
}
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
function canonicalizeWslLinuxPath(distro: string, linuxPath: string): string | null {
|
||||
function canonicalizeWslLinuxPath(
|
||||
distro: string,
|
||||
linuxPath: string,
|
||||
windowsPath = linuxPath,
|
||||
onSettled?: WslCanonicalPathSettled
|
||||
): string | null {
|
||||
if (process.platform !== 'win32') {
|
||||
return linuxPath
|
||||
}
|
||||
const cached = canonicalWslPathCache.get(wslCanonicalizeCacheKey(distro, linuxPath))
|
||||
if (cached) {
|
||||
return cached
|
||||
}
|
||||
// Why: no canonical path resolved yet — start the off-thread resolution and
|
||||
// let the caller use the logical path for now (identical unless HOME crosses a
|
||||
// symlink). The next launch reads the cached canonical path.
|
||||
scheduleWslLinuxPathCanonicalization(distro, linuxPath)
|
||||
return null
|
||||
// Why: every launch revalidates asynchronously. Returning the cache keeps
|
||||
// launch prep synchronous while settlement repairs or revokes trust in-place.
|
||||
scheduleWslLinuxPathCanonicalization(distro, linuxPath, windowsPath, onSettled)
|
||||
return cached ?? null
|
||||
}
|
||||
|
||||
export function createCodexWslRuntimeHookInstallPlan(
|
||||
runtimeHomePath: string | null | undefined,
|
||||
target?: CodexWslRuntimeHookTarget,
|
||||
canonicalize: CanonicalizeWslLinuxPath = canonicalizeWslLinuxPath
|
||||
canonicalize: CanonicalizeWslLinuxPath = canonicalizeWslLinuxPath,
|
||||
onCanonicalPathSettled?: WslCanonicalPathSettled
|
||||
): CodexWslRuntimeHookInstallPlan | null {
|
||||
if (!runtimeHomePath) {
|
||||
return null
|
||||
@@ -106,7 +175,8 @@ export function createCodexWslRuntimeHookInstallPlan(
|
||||
// Why: Codex canonicalizes hook sources inside WSL; resolving there keeps
|
||||
// trust keys valid when HOME or the runtime directory crosses a symlink.
|
||||
const linuxRuntimeHome = trimTrailingSlash(
|
||||
canonicalize(distro, logicalLinuxRuntimeHome) ?? logicalLinuxRuntimeHome
|
||||
canonicalize(distro, logicalLinuxRuntimeHome, runtimeHomePath, onCanonicalPathSettled) ??
|
||||
logicalLinuxRuntimeHome
|
||||
)
|
||||
|
||||
return {
|
||||
|
||||
@@ -1515,6 +1515,34 @@ describe('readHookTrustEntries', () => {
|
||||
}
|
||||
)
|
||||
|
||||
it.skipIf(process.platform !== 'win32')(
|
||||
'keeps WSL hook trust paths case-sensitive on a Windows host',
|
||||
() => {
|
||||
const upperKey = '/windows/d/Repo/hooks.json:session_start:0:0'
|
||||
const lowerKey = '/windows/d/repo/hooks.json:session_start:0:0'
|
||||
writeFileSync(
|
||||
configPath,
|
||||
[
|
||||
`[hooks.state."${upperKey}"]`,
|
||||
'enabled = true',
|
||||
'trusted_hash = "sha256:UPPER"',
|
||||
'',
|
||||
`[hooks.state."${lowerKey}"]`,
|
||||
'enabled = true',
|
||||
'trusted_hash = "sha256:LOWER"',
|
||||
''
|
||||
].join('\n'),
|
||||
'utf-8'
|
||||
)
|
||||
|
||||
const result = readHookTrustEntries(configPath)
|
||||
|
||||
expect(result.get(upperKey)?.trustedHash).toBe('sha256:UPPER')
|
||||
expect(result.get(lowerKey)?.trustedHash).toBe('sha256:LOWER')
|
||||
expect(result.size).toBe(2)
|
||||
}
|
||||
)
|
||||
|
||||
it('reads entries from a CRLF-terminated config', () => {
|
||||
const key = '/x/hooks.json:pre_tool_use:0:0'
|
||||
const original = [
|
||||
|
||||
@@ -529,7 +529,11 @@ export function normalizeHookTrustKeyForLookup(key: string): string {
|
||||
const separated = parsed
|
||||
? `${normalizeWindowsPathSeparators(parsed.sourcePath)}:${parsed.eventLabel}:${parsed.groupIndex}:${parsed.handlerIndex}`
|
||||
: normalizeWindowsPathSeparators(key)
|
||||
return process.platform === 'win32' ? separated.toLowerCase() : separated
|
||||
// Why: Windows-native paths are case-insensitive, but WSL and SSH trust
|
||||
// sources remain case-sensitive even when Orca's host process is Windows.
|
||||
const caseInsensitiveWindowsPath =
|
||||
process.platform === 'win32' && usesWindowsPathSeparators(parsed?.sourcePath ?? key)
|
||||
return caseInsensitiveWindowsPath ? separated.toLowerCase() : separated
|
||||
}
|
||||
|
||||
function findTrustBlockRanges(content: string, key: string): TrustBlockRange[] {
|
||||
|
||||
@@ -122,6 +122,94 @@ describe('Codex WSL runtime hook install', () => {
|
||||
expect(plan?.configPath).toBe(pathWin32.join(runtimeHome, 'hooks.json'))
|
||||
})
|
||||
|
||||
it('removes managed trust when the WSL canonical path changes', () => {
|
||||
const plan = createTestPlan()
|
||||
writeFileSync(plan.configPath, '{"hooks":{}}\n', 'utf-8')
|
||||
writeFileSync(plan.tomlPath, '', 'utf-8')
|
||||
|
||||
const oldPlan = {
|
||||
...plan,
|
||||
commandScriptPath: '/old/home/.orca/agent-hooks/codex-hook.sh',
|
||||
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 oldKey = computeTrustKey(getManagedTrustEntry(oldPlan, oldCommand))
|
||||
|
||||
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 newCommand = `if [ -r '${newPlan.commandScriptPath}' ]; then /bin/sh '${newPlan.commandScriptPath}'; fi`
|
||||
const newKey = computeTrustKey(getManagedTrustEntry(newPlan, newCommand))
|
||||
const trustEntries = readHookTrustEntries(plan.tomlPath)
|
||||
|
||||
expect(trustEntries.has(oldKey)).toBe(false)
|
||||
expect(trustEntries.has(newKey)).toBe(true)
|
||||
})
|
||||
|
||||
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.
|
||||
const plan = createTestPlan()
|
||||
writeFileSync(plan.configPath, '{"hooks":{}}\n', 'utf-8')
|
||||
writeFileSync(plan.tomlPath, '', 'utf-8')
|
||||
expect(_internals.installManagedHooksIntoWslRuntime(plan).state).toBe('installed')
|
||||
|
||||
_internals.removeStaleWslRuntimeManagedHookTrustEntries(plan.tomlPath, [])
|
||||
|
||||
expect(readHookTrustEntries(plan.tomlPath).size).toBe(0)
|
||||
})
|
||||
|
||||
it('reconciles only current, conclusive WSL path settlements', () => {
|
||||
expect(
|
||||
_internals.getWslHookReconciliationAction({
|
||||
settlement: { status: 'unavailable' },
|
||||
isCurrentGeneration: true,
|
||||
installedTrustConfigPath: '/mnt/d/home/hooks.json',
|
||||
resolvedTrustConfigPath: null
|
||||
})
|
||||
).toBe('none')
|
||||
|
||||
expect(
|
||||
_internals.getWslHookReconciliationAction({
|
||||
settlement: { status: 'missing' },
|
||||
isCurrentGeneration: false,
|
||||
installedTrustConfigPath: '/mnt/d/home/hooks.json',
|
||||
resolvedTrustConfigPath: null
|
||||
})
|
||||
).toBe('none')
|
||||
|
||||
expect(
|
||||
_internals.getWslHookReconciliationAction({
|
||||
settlement: { status: 'missing' },
|
||||
isCurrentGeneration: true,
|
||||
installedTrustConfigPath: '/mnt/d/home/hooks.json',
|
||||
resolvedTrustConfigPath: null
|
||||
})
|
||||
).toBe('remove')
|
||||
|
||||
expect(
|
||||
_internals.getWslHookReconciliationAction({
|
||||
settlement: { status: 'resolved', canonicalPath: '/windows/d/home' },
|
||||
isCurrentGeneration: true,
|
||||
installedTrustConfigPath: '/windows/d/home/hooks.json',
|
||||
resolvedTrustConfigPath: '/windows/d/home/hooks.json'
|
||||
})
|
||||
).toBe('none')
|
||||
|
||||
expect(
|
||||
_internals.getWslHookReconciliationAction({
|
||||
settlement: { status: 'resolved', canonicalPath: '/windows/d/home' },
|
||||
isCurrentGeneration: true,
|
||||
installedTrustConfigPath: '/mnt/d/home/hooks.json',
|
||||
resolvedTrustConfigPath: '/windows/d/home/hooks.json'
|
||||
})
|
||||
).toBe('reinstall')
|
||||
})
|
||||
|
||||
it('generates a POSIX hook that bridges WSL loopback failures through Windows curl', () => {
|
||||
const script = _internals.getManagedScript('posix')
|
||||
expect(script).toContain('load_hook_endpoint()')
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
/* eslint-disable max-lines -- Why: getStatus + install + remove all share the managed-command and trust-key derivation. Splitting would hide that the three operations must agree on group index, event label, and command bytes. */
|
||||
import { existsSync, readFileSync, unlinkSync } from 'node:fs'
|
||||
import { join } from 'node:path'
|
||||
import { join, win32 as pathWin32 } from 'node:path'
|
||||
import type { SFTPWrapper } from 'ssh2'
|
||||
import type { AgentHookInstallState, AgentHookInstallStatus } from '../../shared/agent-hook-types'
|
||||
import {
|
||||
@@ -46,7 +46,8 @@ import { syncSystemConfigIntoManagedCodexHome } from './codex-config-mirror'
|
||||
import {
|
||||
createCodexWslRuntimeHookInstallPlan,
|
||||
type CodexWslRuntimeHookInstallPlan,
|
||||
type CodexWslRuntimeHookTarget
|
||||
type CodexWslRuntimeHookTarget,
|
||||
type WslCanonicalPathSettlement
|
||||
} from './codex-wsl-hook-install-plan'
|
||||
import {
|
||||
CODEX_HOOK_EVENT_LABEL,
|
||||
@@ -723,6 +724,52 @@ function removeWslRuntimeManagedHookTrustEntries(plan: CodexWslRuntimeHookInstal
|
||||
}
|
||||
}
|
||||
|
||||
function removeStaleWslRuntimeManagedHookTrustEntries(
|
||||
tomlPath: string,
|
||||
desiredEntries: readonly CodexTrustEntry[]
|
||||
): void {
|
||||
const desiredKeys = new Set(
|
||||
desiredEntries.map((entry) => normalizeHookTrustKeyForLookup(computeTrustKey(entry)))
|
||||
)
|
||||
const existingEntries = readHookTrustEntries(tomlPath)
|
||||
const ourKeys: string[] = []
|
||||
for (const [key, state] of existingEntries) {
|
||||
if (desiredKeys.has(normalizeHookTrustKeyForLookup(key))) {
|
||||
continue
|
||||
}
|
||||
const parts = parseTrustKey(key)
|
||||
if (!parts || !CODEX_MANAGED_EVENT_LABELS.has(parts.eventLabel)) {
|
||||
continue
|
||||
}
|
||||
const sourcePath = parts.sourcePath
|
||||
// Why: this cleanup owns only guest-side WSL trust. A runtime config can
|
||||
// still contain user Windows/remote hooks, which must remain untouched.
|
||||
if (!sourcePath.startsWith('/') || !sourcePath.endsWith('/hooks.json')) {
|
||||
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 recognizedHashes = new Set([
|
||||
computeTrustedHash(expectedEntry),
|
||||
computeTrustedHash({ ...expectedEntry, timeoutSec: undefined })
|
||||
])
|
||||
if (state.trustedHash && recognizedHashes.has(state.trustedHash)) {
|
||||
ourKeys.push(key)
|
||||
}
|
||||
}
|
||||
if (ourKeys.length > 0) {
|
||||
removeHookTrustEntries(tomlPath, ourKeys)
|
||||
}
|
||||
}
|
||||
|
||||
function getManagedScript(target: 'local' | 'posix' = 'local'): string {
|
||||
if (target === 'local' && process.platform === 'win32') {
|
||||
return [
|
||||
@@ -876,6 +923,7 @@ function installManagedHooksIntoWslRuntime(
|
||||
// Why: WSL runtime homes may carry user hook approvals we did not rebuild
|
||||
// here; only upsert Orca's entries instead of sweeping the whole source.
|
||||
upsertHookTrustEntries(plan.tomlPath, trustEntries)
|
||||
removeStaleWslRuntimeManagedHookTrustEntries(plan.tomlPath, trustEntries)
|
||||
} catch (error) {
|
||||
return {
|
||||
agent: 'codex',
|
||||
@@ -922,6 +970,13 @@ function refreshWslRuntimeUserHooks(plan: CodexWslRuntimeHookInstallPlan): Agent
|
||||
}
|
||||
writeCodexHooksJson(plan.configPath, nextHooks)
|
||||
removeWslRuntimeManagedHookTrustEntries(plan)
|
||||
try {
|
||||
// Why: the disabled path may be reached after the WSL mount root changed,
|
||||
// so cleanup cannot be scoped only to the plan's current source path.
|
||||
removeStaleWslRuntimeManagedHookTrustEntries(plan.tomlPath, [])
|
||||
} catch (error) {
|
||||
console.warn('[codex-hook-service] failed to clean stale WSL trust entries', error)
|
||||
}
|
||||
return {
|
||||
agent: 'codex',
|
||||
state: 'not_installed',
|
||||
@@ -931,12 +986,99 @@ function refreshWslRuntimeUserHooks(plan: CodexWslRuntimeHookInstallPlan): Agent
|
||||
}
|
||||
}
|
||||
|
||||
// Why: transport failures preserve the last known-good identity, while a
|
||||
// successful absence probe is strong enough to revoke trust immediately.
|
||||
function getWslHookReconciliationAction(args: {
|
||||
settlement: WslCanonicalPathSettlement
|
||||
isCurrentGeneration: boolean
|
||||
installedTrustConfigPath: string | null
|
||||
resolvedTrustConfigPath: string | null
|
||||
}): 'none' | 'remove' | 'reinstall' {
|
||||
if (!args.isCurrentGeneration) {
|
||||
return 'none'
|
||||
}
|
||||
if (args.settlement.status === 'missing') {
|
||||
return 'remove'
|
||||
}
|
||||
if (
|
||||
args.settlement.status !== 'resolved' ||
|
||||
!args.resolvedTrustConfigPath ||
|
||||
args.resolvedTrustConfigPath === args.installedTrustConfigPath
|
||||
) {
|
||||
return 'none'
|
||||
}
|
||||
return 'reinstall'
|
||||
}
|
||||
|
||||
export class CodexHookService {
|
||||
private readonly wslReconciliationGeneration = new Map<string, number>()
|
||||
|
||||
private supersedeWslReconciliation(runtimeHomePath: string | null | undefined): number {
|
||||
if (!runtimeHomePath) {
|
||||
return 0
|
||||
}
|
||||
const key = process.platform === 'win32' ? runtimeHomePath.toLowerCase() : runtimeHomePath
|
||||
const generation = (this.wslReconciliationGeneration.get(key) ?? 0) + 1
|
||||
this.wslReconciliationGeneration.set(key, generation)
|
||||
return generation
|
||||
}
|
||||
|
||||
installForRuntimeHome(
|
||||
runtimeHomePath: string | null | undefined,
|
||||
target?: CodexWslRuntimeHookTarget
|
||||
): AgentHookInstallStatus | null {
|
||||
const wslPlan = createCodexWslRuntimeHookInstallPlan(runtimeHomePath, target)
|
||||
const generation = this.supersedeWslReconciliation(runtimeHomePath)
|
||||
let installedTrustConfigPath: string | null = null
|
||||
const onCanonicalPathSettled = (settlement: WslCanonicalPathSettlement): void => {
|
||||
if (!runtimeHomePath) {
|
||||
return
|
||||
}
|
||||
const key = process.platform === 'win32' ? runtimeHomePath.toLowerCase() : runtimeHomePath
|
||||
const resolvedPlan =
|
||||
settlement.status === 'resolved'
|
||||
? createCodexWslRuntimeHookInstallPlan(
|
||||
runtimeHomePath,
|
||||
target,
|
||||
() => settlement.canonicalPath
|
||||
)
|
||||
: null
|
||||
const action = getWslHookReconciliationAction({
|
||||
settlement,
|
||||
isCurrentGeneration: this.wslReconciliationGeneration.get(key) === generation,
|
||||
installedTrustConfigPath,
|
||||
resolvedTrustConfigPath: resolvedPlan?.trustConfigPath ?? null
|
||||
})
|
||||
if (action === 'none') {
|
||||
return
|
||||
}
|
||||
if (action === 'remove') {
|
||||
try {
|
||||
removeStaleWslRuntimeManagedHookTrustEntries(
|
||||
pathWin32.join(runtimeHomePath, 'config.toml'),
|
||||
[]
|
||||
)
|
||||
} catch (error) {
|
||||
console.warn('[codex-hook-service] failed to revoke stale WSL hook trust', error)
|
||||
}
|
||||
return
|
||||
}
|
||||
if (!resolvedPlan) {
|
||||
return
|
||||
}
|
||||
const status = installManagedHooksIntoWslRuntime(resolvedPlan)
|
||||
if (status.state === 'error') {
|
||||
console.warn('[codex-hook-service] failed to reconcile WSL hook path', status.detail)
|
||||
return
|
||||
}
|
||||
installedTrustConfigPath = resolvedPlan.trustConfigPath
|
||||
}
|
||||
const wslPlan = createCodexWslRuntimeHookInstallPlan(
|
||||
runtimeHomePath,
|
||||
target,
|
||||
undefined,
|
||||
onCanonicalPathSettled
|
||||
)
|
||||
installedTrustConfigPath = wslPlan?.trustConfigPath ?? null
|
||||
return wslPlan ? installManagedHooksIntoWslRuntime(wslPlan) : null
|
||||
}
|
||||
|
||||
@@ -944,6 +1086,7 @@ export class CodexHookService {
|
||||
runtimeHomePath: string | null | undefined,
|
||||
target?: CodexWslRuntimeHookTarget
|
||||
): AgentHookInstallStatus | null {
|
||||
this.supersedeWslReconciliation(runtimeHomePath)
|
||||
const wslPlan = createCodexWslRuntimeHookInstallPlan(runtimeHomePath, target)
|
||||
return wslPlan ? refreshWslRuntimeUserHooks(wslPlan) : null
|
||||
}
|
||||
@@ -1413,5 +1556,7 @@ export const codexHookService = new CodexHookService()
|
||||
export const _internals = {
|
||||
getManagedScript,
|
||||
installManagedHooksIntoWslRuntime,
|
||||
refreshWslRuntimeUserHooks
|
||||
refreshWslRuntimeUserHooks,
|
||||
removeStaleWslRuntimeManagedHookTrustEntries,
|
||||
getWslHookReconciliationAction
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user