Merge remote-tracking branch 'origin/brennanb2025/codex-real-home-phase1' into brennanb2025/codex-session-dedup-index-heal
# Conflicts: # src/main/codex/codex-app-server-client.ts
This commit is contained in:
@@ -22,6 +22,7 @@
|
||||
"../src/main/codex/codex-hook-identity.ts",
|
||||
"../src/main/codex/codex-hook-trust-grant.ts",
|
||||
"../src/main/codex/codex-managed-trust-reconciliation.ts",
|
||||
"../src/main/codex/codex-process-exit-deadline.ts",
|
||||
"../src/main/codex/codex-trust-config-rollback.ts",
|
||||
"../src/main/codex/codex-trust-grant-host.ts",
|
||||
"../src/main/codex/codex-trust-grant-ledger.ts",
|
||||
|
||||
@@ -2,6 +2,7 @@ import {
|
||||
existsSync,
|
||||
mkdirSync,
|
||||
readFileSync,
|
||||
statSync,
|
||||
writeFileSync,
|
||||
chmodSync,
|
||||
copyFileSync,
|
||||
@@ -353,7 +354,11 @@ function writeScriptWithAclRetry(scriptPath: string, content: string): void {
|
||||
}
|
||||
}
|
||||
|
||||
export function writeHooksJson(configPath: string, config: HooksConfig): void {
|
||||
export function writeHooksJson(
|
||||
configPath: string,
|
||||
config: HooksConfig,
|
||||
options?: { preserveMode?: boolean }
|
||||
): void {
|
||||
const dir = dirname(configPath)
|
||||
mkdirSync(dir, { recursive: true })
|
||||
|
||||
@@ -368,6 +373,8 @@ export function writeHooksJson(configPath: string, config: HooksConfig): void {
|
||||
// UUID suffix makes the tmp path unique per call.
|
||||
const tmpPath = join(dir, `.${Date.now()}-${randomUUID()}.tmp`)
|
||||
const serialized = `${JSON.stringify(config, null, 2)}\n`
|
||||
const existingMode =
|
||||
options?.preserveMode === true && existsSync(configPath) ? statSync(configPath).mode : undefined
|
||||
|
||||
// Why: skip the write (and therefore the .bak rotation) when the on-disk
|
||||
// content is already identical. Without this, every install() rewrites the
|
||||
@@ -386,7 +393,7 @@ export function writeHooksJson(configPath: string, config: HooksConfig): void {
|
||||
}
|
||||
|
||||
try {
|
||||
writeFileSync(tmpPath, serialized, 'utf-8')
|
||||
writeFileSync(tmpPath, serialized, { encoding: 'utf-8', mode: existingMode })
|
||||
// Why: single rolling backup — one file, no accumulation in ~/.claude.
|
||||
// Protects against a merge-logic bug producing bad JSON; the original is
|
||||
// always recoverable from <configPath>.bak until the next write.
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { afterEach, describe, expect, it } from 'vitest'
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import { mkdtempSync, readFileSync, rmSync, writeFileSync, existsSync } from 'node:fs'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
@@ -90,6 +90,7 @@ function writeFileSyncSafe(file, contents) { require('node:fs').writeFileSync(fi
|
||||
let tempRoots: string[] = []
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks()
|
||||
for (const root of tempRoots) {
|
||||
rmSync(root, { recursive: true, force: true })
|
||||
}
|
||||
@@ -149,6 +150,8 @@ function managedHook(key: string, trustStatus = 'untrusted'): StubHook {
|
||||
|
||||
describe('runCodexHookTrustGrantSession', () => {
|
||||
it('grants and verifies exactly the expected managed entries', async () => {
|
||||
const setTimeoutSpy = vi.spyOn(globalThis, 'setTimeout')
|
||||
const clearTimeoutSpy = vi.spyOn(globalThis, 'clearTimeout')
|
||||
const keys = [
|
||||
'/home/a/.codex/hooks.json:session_start:0:0',
|
||||
'/home/a/.codex/hooks.json:stop:0:0'
|
||||
@@ -191,6 +194,13 @@ describe('runCodexHookTrustGrantSession', () => {
|
||||
expect(written.edits[0].mergeStrategy).toBe('upsert')
|
||||
expect(Object.keys(written.edits[0].value).sort()).toEqual([...keys].sort())
|
||||
expect(written.reloadUserConfig).toBe(true)
|
||||
// Why: the entry process waits on these handles after setting exitCode, so
|
||||
// an uncleared grace timer adds its full delay to synchronous launch prep.
|
||||
const timerHandles = setTimeoutSpy.mock.results.map(({ value }) => value)
|
||||
expect(timerHandles).toHaveLength(2)
|
||||
expect(clearTimeoutSpy.mock.calls.map(([handle]) => handle)).toEqual(
|
||||
expect.arrayContaining(timerHandles)
|
||||
)
|
||||
})
|
||||
|
||||
it('skips config/batchWrite when every expected entry is already trusted', async () => {
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { spawn, type ChildProcessWithoutNullStreams } from 'node:child_process'
|
||||
import { waitForProcessExitUntil } from './codex-process-exit-deadline'
|
||||
|
||||
// Why: `codex app-server` is Orca's sanctioned RPC surface into Codex-owned
|
||||
// state (hook trust hashes, the sqlite thread index). This module owns the
|
||||
@@ -252,11 +253,10 @@ export async function runCodexAppServerSession<T>(
|
||||
if (!exited) {
|
||||
// Why: the server exits promptly on stdin EOF; the grace period only
|
||||
// bounds a wedged child before the guaranteed SIGKILL reap.
|
||||
const grace = new Promise<void>((resolve) => setTimeout(resolve, 1500))
|
||||
await Promise.race([exitPromise, grace])
|
||||
await waitForProcessExitUntil(exitPromise, 1500)
|
||||
if (!exited) {
|
||||
child.kill('SIGKILL')
|
||||
await Promise.race([exitPromise, new Promise<void>((resolve) => setTimeout(resolve, 1000))])
|
||||
await waitForProcessExitUntil(exitPromise, 1000)
|
||||
}
|
||||
}
|
||||
clearTimeout(deadline)
|
||||
|
||||
@@ -268,6 +268,9 @@ describe('syncSystemConfigIntoManagedCodexHome', () => {
|
||||
[
|
||||
'model = "runtime-model"',
|
||||
'',
|
||||
'[hooks.state]',
|
||||
'# runtime-owned parent',
|
||||
'',
|
||||
'[hooks.state."runtime-hooks:stop:0:0"]',
|
||||
'enabled = false',
|
||||
'trusted_hash = "sha256:runtime"',
|
||||
@@ -286,6 +289,9 @@ describe('syncSystemConfigIntoManagedCodexHome', () => {
|
||||
[
|
||||
'model = "system-model"',
|
||||
'',
|
||||
'[hooks.state]',
|
||||
'# system-owned parent',
|
||||
'',
|
||||
'[projects."/repo"] # explicit revocation',
|
||||
'trust_level = "untrusted"',
|
||||
'',
|
||||
@@ -310,6 +316,8 @@ describe('syncSystemConfigIntoManagedCodexHome', () => {
|
||||
expect(runtimeConfig).toContain('[projects."/system-only"]')
|
||||
expect(runtimeConfig).toContain('[hooks.state."runtime-hooks:stop:0:0"]')
|
||||
expect(runtimeConfig).not.toContain('[hooks.state."system-hooks:stop:0:0"]')
|
||||
expect(runtimeConfig).toContain('# runtime-owned parent')
|
||||
expect(runtimeConfig).not.toContain('# system-owned parent')
|
||||
expect(runtimeConfig).toContain('trust_level = "untrusted"')
|
||||
expect(runtimeConfig.match(/\[projects\."\/repo"\]/g)?.length).toBe(1)
|
||||
})
|
||||
|
||||
@@ -275,7 +275,10 @@ function isRuntimePreservedTomlSection(header: string): boolean {
|
||||
}
|
||||
|
||||
function isRuntimeHookTrustTomlSection(header: string): boolean {
|
||||
return header.trimStart().startsWith('[hooks.state.')
|
||||
const trimmed = header.trim()
|
||||
// Why: Codex's config writer materializes the parent table on Windows. It is
|
||||
// part of runtime-owned trust and must survive the next config mirror too.
|
||||
return trimmed === '[hooks.state]' || trimmed.startsWith('[hooks.state.')
|
||||
}
|
||||
|
||||
function isRuntimeProjectTomlSection(header: string): boolean {
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
export async function waitForProcessExitUntil(
|
||||
exitPromise: Promise<void>,
|
||||
timeoutMs: number
|
||||
): Promise<void> {
|
||||
let timer: ReturnType<typeof setTimeout> | undefined
|
||||
const timeout = new Promise<void>((resolve) => {
|
||||
timer = setTimeout(resolve, timeoutMs)
|
||||
})
|
||||
try {
|
||||
await Promise.race([exitPromise, timeout])
|
||||
} finally {
|
||||
// Why: this runs in a short-lived entry; a live grace timer delays the
|
||||
// parent spawnSync even after the app-server process has already exited.
|
||||
if (timer !== undefined) {
|
||||
clearTimeout(timer)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,16 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
|
||||
import {
|
||||
chmodSync,
|
||||
existsSync,
|
||||
lstatSync,
|
||||
mkdirSync,
|
||||
mkdtempSync,
|
||||
readFileSync,
|
||||
rmSync,
|
||||
statSync,
|
||||
symlinkSync,
|
||||
writeFileSync
|
||||
} from 'node:fs'
|
||||
import type * as NodeOs from 'node:os'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
@@ -138,6 +149,67 @@ describe('ensureRealHomeCodexHookState (install)', () => {
|
||||
).toBe(`${JSON.stringify(userConfig, null, 2)}\n`)
|
||||
})
|
||||
|
||||
it('updates a symlinked hooks.json target without replacing the symlink', () => {
|
||||
grantSucceeds()
|
||||
const dotfilesDir = join(fakeHomeDir, 'dotfiles')
|
||||
const targetPath = join(dotfilesDir, 'hooks.json')
|
||||
mkdirSync(dotfilesDir, { recursive: true })
|
||||
writeFileSync(
|
||||
targetPath,
|
||||
`${JSON.stringify({ hooks: { Stop: [{ hooks: [{ type: 'command', command: 'mine.sh' }] }] } }, null, 2)}\n`,
|
||||
'utf-8'
|
||||
)
|
||||
symlinkSync(targetPath, getRealHooksJsonPath())
|
||||
|
||||
expect(ensureRealHomeCodexHookState({ hooksEnabled: true, userDataPath: userDataDir })).toBe(
|
||||
'installed'
|
||||
)
|
||||
|
||||
expect(lstatSync(getRealHooksJsonPath()).isSymbolicLink()).toBe(true)
|
||||
expect(JSON.parse(readFileSync(targetPath, 'utf-8')).hooks.Stop).toHaveLength(2)
|
||||
})
|
||||
|
||||
it('keeps the managed lane and original bytes when the pristine backup cannot be created', () => {
|
||||
grantSucceeds()
|
||||
const original = `${JSON.stringify({ hooks: { Stop: [] } }, null, 2)}\n`
|
||||
writeFileSync(getRealHooksJsonPath(), original, 'utf-8')
|
||||
writeFileSync(join(userDataDir, 'codex-real-home-hooks'), 'blocks backup directory', 'utf-8')
|
||||
|
||||
expect(ensureRealHomeCodexHookState({ hooksEnabled: true, userDataPath: userDataDir })).toBe(
|
||||
'unavailable'
|
||||
)
|
||||
|
||||
expect(readFileSync(getRealHooksJsonPath(), 'utf-8')).toBe(original)
|
||||
expect(grantMock).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it.skipIf(process.platform === 'win32')('preserves restrictive hooks.json permissions', () => {
|
||||
grantSucceeds()
|
||||
writeFileSync(getRealHooksJsonPath(), '{ "hooks": {} }\n', 'utf-8')
|
||||
chmodSync(getRealHooksJsonPath(), 0o600)
|
||||
|
||||
expect(ensureRealHomeCodexHookState({ hooksEnabled: true, userDataPath: userDataDir })).toBe(
|
||||
'installed'
|
||||
)
|
||||
|
||||
expect(statSync(getRealHooksJsonPath()).mode & 0o777).toBe(0o600)
|
||||
})
|
||||
|
||||
it.skipIf(process.platform === 'win32')(
|
||||
'restores restrictive hooks.json permissions after grant fallback',
|
||||
() => {
|
||||
grantUnavailable()
|
||||
writeFileSync(getRealHooksJsonPath(), '{ "hooks": {} }\n', 'utf-8')
|
||||
chmodSync(getRealHooksJsonPath(), 0o600)
|
||||
|
||||
expect(ensureRealHomeCodexHookState({ hooksEnabled: true, userDataPath: userDataDir })).toBe(
|
||||
'unavailable'
|
||||
)
|
||||
|
||||
expect(statSync(getRealHooksJsonPath()).mode & 0o777).toBe(0o600)
|
||||
}
|
||||
)
|
||||
|
||||
it('rolls the file back byte-exactly when the grant lane is unavailable', () => {
|
||||
grantUnavailable()
|
||||
const userRaw = `${JSON.stringify({ hooks: { Stop: [{ hooks: [{ type: 'command', command: 'mine.sh' }] }] } }, null, 2)}\n`
|
||||
|
||||
@@ -1,4 +1,12 @@
|
||||
import { copyFileSync, existsSync, mkdirSync, readFileSync, unlinkSync } from 'node:fs'
|
||||
import {
|
||||
existsSync,
|
||||
lstatSync,
|
||||
mkdirSync,
|
||||
readFileSync,
|
||||
realpathSync,
|
||||
statSync,
|
||||
unlinkSync
|
||||
} from 'node:fs'
|
||||
import { join } from 'node:path'
|
||||
import { writeFileAtomically } from '../codex-accounts/fs-utils'
|
||||
import {
|
||||
@@ -61,6 +69,30 @@ function getRealHomeConfigTomlPath(): string {
|
||||
return join(getSystemCodexHomePath(), 'config.toml')
|
||||
}
|
||||
|
||||
function resolveRealHomeHooksWritePath(hooksJsonPath: string): string {
|
||||
let isSymlink = false
|
||||
try {
|
||||
isSymlink = lstatSync(hooksJsonPath).isSymbolicLink()
|
||||
} catch (error) {
|
||||
if ((error as NodeJS.ErrnoException).code === 'ENOENT') {
|
||||
return hooksJsonPath
|
||||
}
|
||||
throw error
|
||||
}
|
||||
if (!isSymlink) {
|
||||
return hooksJsonPath
|
||||
}
|
||||
try {
|
||||
// Why: replacing the link itself would silently disconnect a user's
|
||||
// dotfiles-managed hooks.json. Atomic writes belong at its real target.
|
||||
return realpathSync.native(hooksJsonPath)
|
||||
} catch (error) {
|
||||
throw new Error(`Could not resolve symlinked Codex hooks file ${hooksJsonPath}`, {
|
||||
cause: error
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/** Orca-side state dir; nothing extra is ever written into the user's ~/.codex. */
|
||||
function getRealHomeHookStateDir(userDataPath: string): string {
|
||||
return join(userDataPath, 'codex-real-home-hooks')
|
||||
@@ -102,6 +134,7 @@ export function ensureRealHomeCodexHookState(args: {
|
||||
function installRealHomeCodexHook(userDataPath: string): RealHomeCodexHookLane {
|
||||
const material = getCodexManagedHookInstallMaterial()
|
||||
const hooksJsonPath = getRealHomeHooksJsonPath()
|
||||
const hooksWritePath = resolveRealHomeHooksWritePath(hooksJsonPath)
|
||||
const config = readHooksJson(hooksJsonPath)
|
||||
if (!config) {
|
||||
// Why: an unparseable user file must never be clobbered; without a hook
|
||||
@@ -146,10 +179,13 @@ function installRealHomeCodexHook(userDataPath: string): RealHomeCodexHookLane {
|
||||
}
|
||||
|
||||
const previousRaw = existsSync(hooksJsonPath) ? readFileSync(hooksJsonPath, 'utf-8') : null
|
||||
backupRealHomeHooksJsonOnce(userDataPath, hooksJsonPath, previousRaw)
|
||||
const previousMode = previousRaw === null ? undefined : statSync(hooksWritePath).mode
|
||||
backupRealHomeHooksJsonOnce(userDataPath, previousRaw)
|
||||
// Why: unknown top-level fields belong to the user (other managers'
|
||||
// metadata); unlike the managed-home writer, preserve them verbatim.
|
||||
writeHooksJson(hooksJsonPath, { ...config, hooks: nextHooks } as HooksConfig)
|
||||
writeHooksJson(hooksWritePath, { ...config, hooks: nextHooks } as HooksConfig, {
|
||||
preserveMode: true
|
||||
})
|
||||
|
||||
const grant = grantManagedCodexHookTrust({
|
||||
runtimeHomePath: getSystemCodexHomePath(),
|
||||
@@ -166,7 +202,7 @@ function installRealHomeCodexHook(userDataPath: string): RealHomeCodexHookLane {
|
||||
// would surface as "Hooks need review". Roll the file back to its prior
|
||||
// bytes and keep this host on the managed-home lane; the grant client
|
||||
// already logged the fallback reason.
|
||||
restoreRealHomeHooksJson(hooksJsonPath, previousRaw)
|
||||
restoreRealHomeHooksJson(hooksWritePath, previousRaw, previousMode)
|
||||
installRetryAfterMs = getInstallRetryAfterMs(grant.reason)
|
||||
console.warn(
|
||||
`[codex-real-home-hooks] trust grant unavailable (${grant.reason}); entry rolled back, managed lane kept`
|
||||
@@ -248,7 +284,14 @@ function sweepRealHomeCodexHook(): RealHomeCodexHookLane {
|
||||
}
|
||||
}
|
||||
if (removedAny) {
|
||||
writeHooksJson(hooksJsonPath, { ...config, hooks: nextHooks } as HooksConfig)
|
||||
writeHooksJson(
|
||||
resolveRealHomeHooksWritePath(hooksJsonPath),
|
||||
{
|
||||
...config,
|
||||
hooks: nextHooks
|
||||
} as HooksConfig,
|
||||
{ preserveMode: true }
|
||||
)
|
||||
// Why: dead [hooks.state] blocks for a removed hook are Orca-owned records;
|
||||
// dropping them keeps the user's config.toml from accumulating orphans.
|
||||
// Verify ownership by the expected hash or grant ledger: stale/mixed hook
|
||||
@@ -270,28 +313,26 @@ function sweepRealHomeCodexHook(): RealHomeCodexHookLane {
|
||||
}
|
||||
|
||||
/** One-time pristine copy of the user's file, kept under Orca's userData. */
|
||||
function backupRealHomeHooksJsonOnce(
|
||||
userDataPath: string,
|
||||
hooksJsonPath: string,
|
||||
previousRaw: string | null
|
||||
): void {
|
||||
function backupRealHomeHooksJsonOnce(userDataPath: string, previousRaw: string | null): void {
|
||||
if (previousRaw === null) {
|
||||
return
|
||||
}
|
||||
try {
|
||||
const backupDir = getRealHomeHookStateDir(userDataPath)
|
||||
const backupPath = join(backupDir, 'hooks.json.pre-orca')
|
||||
if (existsSync(backupPath)) {
|
||||
return
|
||||
}
|
||||
mkdirSync(backupDir, { recursive: true })
|
||||
copyFileSync(hooksJsonPath, backupPath)
|
||||
} catch (error) {
|
||||
console.warn('[codex-real-home-hooks] failed to write pristine backup:', error)
|
||||
const backupDir = getRealHomeHookStateDir(userDataPath)
|
||||
const backupPath = join(backupDir, 'hooks.json.pre-orca')
|
||||
if (existsSync(backupPath)) {
|
||||
return
|
||||
}
|
||||
// Why: this lane mutates the user's real Codex home. If the required
|
||||
// pristine recovery copy cannot be created, keep the managed lane intact.
|
||||
mkdirSync(backupDir, { recursive: true })
|
||||
writeFileAtomically(backupPath, previousRaw, { mode: 0o600 })
|
||||
}
|
||||
|
||||
function restoreRealHomeHooksJson(hooksJsonPath: string, previousRaw: string | null): void {
|
||||
function restoreRealHomeHooksJson(
|
||||
hooksJsonPath: string,
|
||||
previousRaw: string | null,
|
||||
previousMode?: number
|
||||
): void {
|
||||
try {
|
||||
if (previousRaw === null) {
|
||||
if (existsSync(hooksJsonPath)) {
|
||||
@@ -301,7 +342,7 @@ function restoreRealHomeHooksJson(hooksJsonPath: string, previousRaw: string | n
|
||||
}
|
||||
// Why: rollback is part of the safety boundary. Use the shared atomic
|
||||
// writer so Windows file-lock retries and failed-temp cleanup are covered.
|
||||
writeFileAtomically(hooksJsonPath, previousRaw)
|
||||
writeFileAtomically(hooksJsonPath, previousRaw, { mode: previousMode })
|
||||
} catch (error) {
|
||||
console.warn('[codex-real-home-hooks] failed to roll back hooks.json:', error)
|
||||
}
|
||||
|
||||
@@ -1,5 +1,15 @@
|
||||
import { afterEach, describe, expect, it } from 'vitest'
|
||||
import { chmodSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs'
|
||||
import {
|
||||
chmodSync,
|
||||
lstatSync,
|
||||
mkdirSync,
|
||||
mkdtempSync,
|
||||
readFileSync,
|
||||
rmSync,
|
||||
statSync,
|
||||
symlinkSync,
|
||||
writeFileSync
|
||||
} from 'node:fs'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import { captureCodexTrustConfig, restoreCodexTrustConfig } from './codex-trust-config-rollback'
|
||||
@@ -36,6 +46,21 @@ describe('Codex trust config rollback', () => {
|
||||
expect(() => readFileSync(configPath)).toThrowError(/ENOENT/)
|
||||
})
|
||||
|
||||
it('removes an RPC-created dangling-symlink target without deleting the user link', () => {
|
||||
const configPath = tempConfigPath()
|
||||
const targetDir = join(configPath, '..', 'dotfiles')
|
||||
const targetPath = join(targetDir, 'codex-config.toml')
|
||||
mkdirSync(targetDir)
|
||||
symlinkSync(join('dotfiles', 'codex-config.toml'), configPath)
|
||||
const snapshot = captureCodexTrustConfig(configPath)
|
||||
writeFileSync(targetPath, 'rpc mutation')
|
||||
|
||||
restoreCodexTrustConfig(configPath, snapshot)
|
||||
|
||||
expect(lstatSync(configPath).isSymbolicLink()).toBe(true)
|
||||
expect(() => readFileSync(targetPath)).toThrowError(/ENOENT/)
|
||||
})
|
||||
|
||||
it('atomically recreates exact contents and mode after the file disappears', () => {
|
||||
const configPath = tempConfigPath()
|
||||
const original = Buffer.from('# comment\r\n[hooks]\r\n')
|
||||
@@ -52,6 +77,22 @@ describe('Codex trust config rollback', () => {
|
||||
}
|
||||
})
|
||||
|
||||
it('restores a symlink target without replacing the config.toml symlink', () => {
|
||||
const configPath = tempConfigPath()
|
||||
const targetDir = join(configPath, '..', 'dotfiles')
|
||||
const targetPath = join(targetDir, 'codex-config.toml')
|
||||
mkdirSync(targetDir)
|
||||
writeFileSync(targetPath, '# original\n')
|
||||
symlinkSync(targetPath, configPath)
|
||||
const snapshot = captureCodexTrustConfig(configPath)
|
||||
rmSync(targetPath)
|
||||
|
||||
restoreCodexTrustConfig(configPath, snapshot)
|
||||
|
||||
expect(lstatSync(configPath).isSymbolicLink()).toBe(true)
|
||||
expect(readFileSync(targetPath, 'utf8')).toBe('# original\n')
|
||||
})
|
||||
|
||||
it.skipIf(process.platform === 'win32')(
|
||||
'restores the captured mode when the contents already match',
|
||||
() => {
|
||||
|
||||
@@ -2,25 +2,53 @@ import {
|
||||
chmodSync,
|
||||
closeSync,
|
||||
fstatSync,
|
||||
lstatSync,
|
||||
openSync,
|
||||
readFileSync,
|
||||
readlinkSync,
|
||||
realpathSync,
|
||||
unlinkSync,
|
||||
writeFileSync
|
||||
} from 'node:fs'
|
||||
import { randomUUID } from 'node:crypto'
|
||||
import { dirname, resolve } from 'node:path'
|
||||
import { renameFileWithWindowsRetry } from '../codex-accounts/fs-utils'
|
||||
|
||||
export type CodexTrustConfigSnapshot =
|
||||
| { existed: false }
|
||||
| { existed: true; contents: Buffer; mode: number }
|
||||
| { existed: false; restorePath?: string }
|
||||
| { existed: true; contents: Buffer; mode: number; restorePath: string }
|
||||
|
||||
export function captureCodexTrustConfig(tomlPath: string): CodexTrustConfigSnapshot {
|
||||
let descriptor: number
|
||||
function resolveConfigRestorePath(tomlPath: string): string {
|
||||
try {
|
||||
descriptor = openSync(tomlPath, 'r')
|
||||
if (!lstatSync(tomlPath).isSymbolicLink()) {
|
||||
return tomlPath
|
||||
}
|
||||
try {
|
||||
return realpathSync.native(tomlPath)
|
||||
} catch (error) {
|
||||
if ((error as NodeJS.ErrnoException).code !== 'ENOENT') {
|
||||
throw error
|
||||
}
|
||||
// Why: a dangling dotfiles link is still user-owned state. Target the
|
||||
// lexical destination so rollback removes an RPC-created file, not the link.
|
||||
return resolve(dirname(tomlPath), readlinkSync(tomlPath))
|
||||
}
|
||||
} catch (error) {
|
||||
if ((error as NodeJS.ErrnoException).code === 'ENOENT') {
|
||||
return { existed: false }
|
||||
return tomlPath
|
||||
}
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
export function captureCodexTrustConfig(tomlPath: string): CodexTrustConfigSnapshot {
|
||||
const restorePath = resolveConfigRestorePath(tomlPath)
|
||||
let descriptor: number
|
||||
try {
|
||||
descriptor = openSync(restorePath, 'r')
|
||||
} catch (error) {
|
||||
if ((error as NodeJS.ErrnoException).code === 'ENOENT') {
|
||||
return restorePath === tomlPath ? { existed: false } : { existed: false, restorePath }
|
||||
}
|
||||
throw error
|
||||
}
|
||||
@@ -30,7 +58,8 @@ export function captureCodexTrustConfig(tomlPath: string): CodexTrustConfigSnaps
|
||||
return {
|
||||
existed: true,
|
||||
contents: readFileSync(descriptor),
|
||||
mode: fstatSync(descriptor).mode
|
||||
mode: fstatSync(descriptor).mode,
|
||||
restorePath
|
||||
}
|
||||
} finally {
|
||||
closeSync(descriptor)
|
||||
@@ -43,7 +72,7 @@ export function restoreCodexTrustConfig(
|
||||
): void {
|
||||
if (!snapshot.existed) {
|
||||
try {
|
||||
unlinkSync(tomlPath)
|
||||
unlinkSync(snapshot.restorePath ?? tomlPath)
|
||||
} catch (error) {
|
||||
if ((error as NodeJS.ErrnoException).code !== 'ENOENT') {
|
||||
throw error
|
||||
@@ -51,11 +80,12 @@ export function restoreCodexTrustConfig(
|
||||
}
|
||||
return
|
||||
}
|
||||
const { restorePath } = snapshot
|
||||
try {
|
||||
if (readFileSync(tomlPath).equals(snapshot.contents)) {
|
||||
if (readFileSync(restorePath).equals(snapshot.contents)) {
|
||||
// Why: the RPC may change permissions without changing bytes; rollback
|
||||
// restores the complete captured file state, not only its contents.
|
||||
chmodSync(tomlPath, snapshot.mode)
|
||||
chmodSync(restorePath, snapshot.mode)
|
||||
return
|
||||
}
|
||||
} catch (error) {
|
||||
@@ -65,10 +95,12 @@ export function restoreCodexTrustConfig(
|
||||
}
|
||||
// Why: rollback protects config integrity too; direct truncating writes can
|
||||
// leave Codex unusable if Orca exits midway through recovery.
|
||||
const tempPath = `${tomlPath}.${process.pid}.${randomUUID()}.rollback.tmp`
|
||||
// Why: Codex's writer preserves config.toml symlinks. Restore through their
|
||||
// real target too, or Orca's atomic rename would disconnect dotfiles users.
|
||||
const tempPath = `${restorePath}.${process.pid}.${randomUUID()}.rollback.tmp`
|
||||
try {
|
||||
writeFileSync(tempPath, snapshot.contents, { mode: snapshot.mode })
|
||||
renameFileWithWindowsRetry(tempPath, tomlPath)
|
||||
renameFileWithWindowsRetry(tempPath, restorePath)
|
||||
} catch (error) {
|
||||
try {
|
||||
unlinkSync(tempPath)
|
||||
|
||||
@@ -3,10 +3,12 @@ import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'nod
|
||||
import { tmpdir } from 'node:os'
|
||||
import type * as Os from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import { existsSync } from 'node:fs'
|
||||
import { wrapPosixHookCommand } from '../agent-hooks/installer-utils'
|
||||
import {
|
||||
computeTrustKey,
|
||||
computeTrustedHash,
|
||||
escapeTomlString,
|
||||
parseTrustKey,
|
||||
readHookTrustEntries,
|
||||
upsertHookTrustEntries,
|
||||
@@ -72,6 +74,32 @@ afterEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
// Why: model codex's own config/batchWrite — exactly one
|
||||
// `[hooks.state."<key>"]` table per reported key, keyed verbatim, blank-line
|
||||
// separated (the shape the real 0.144.x binary writes). Orca's
|
||||
// upsertHookTrustEntries writes BOTH separator variants for a Windows key (a
|
||||
// fallback-lane compat shim real codex never does), which would fabricate
|
||||
// duplicate tables on win32 that the RPC path never produces.
|
||||
function writeCodexLikeTrust(configPath: string, entries: CodexTrustEntry[]): void {
|
||||
let content = existsSync(configPath) ? readFileSync(configPath, 'utf-8') : ''
|
||||
if (!/^\[hooks\.state\][ \t]*$/m.test(content)) {
|
||||
const separator = content.length === 0 ? '' : content.endsWith('\n') ? '' : '\n'
|
||||
content += `${separator}[hooks.state]\n`
|
||||
}
|
||||
for (const entry of entries) {
|
||||
const header = `[hooks.state."${escapeTomlString(computeTrustKey(entry))}"]`
|
||||
// Why: replace any existing table for this exact key so re-grants upgrade
|
||||
// in place instead of duplicating (mirrors codex's upsert merge strategy).
|
||||
const existingBlock = new RegExp(
|
||||
`(?:\\n)?${header.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}\\n(?:[^[\\n].*\\n?|\\n)*`,
|
||||
'g'
|
||||
)
|
||||
content = content.replace(existingBlock, '')
|
||||
content += `${content.endsWith('\n') ? '' : '\n'}\n${header}\ntrusted_hash = "${escapeTomlString(entry.trustedHash!)}"\n`
|
||||
}
|
||||
writeFileSync(configPath, content)
|
||||
}
|
||||
|
||||
function installCodexLikeGrantRunner(): ReturnType<typeof vi.fn> {
|
||||
const codexHash = (key: string): string =>
|
||||
`sha256:codex-${parseTrustKey(key)?.eventLabel ?? 'unknown'}`
|
||||
@@ -86,7 +114,7 @@ function installCodexLikeGrantRunner(): ReturnType<typeof vi.fn> {
|
||||
trustedHash: codexHash(key)
|
||||
}
|
||||
})
|
||||
upsertHookTrustEntries(join(codexHome!, 'config.toml'), entries)
|
||||
writeCodexLikeTrust(join(codexHome!, 'config.toml'), entries)
|
||||
return {
|
||||
outcome: 'granted' as const,
|
||||
wroteTrust: true,
|
||||
@@ -199,7 +227,7 @@ describe('CodexHookService app-server trust grant lane', () => {
|
||||
})
|
||||
})
|
||||
|
||||
it('upgrades self-computed trust in place without duplicate tables', () => {
|
||||
it('upgrades self-computed trust in place without duplicate logical entries', () => {
|
||||
prepareSystemHome()
|
||||
const service = new CodexHookService()
|
||||
process.env.ORCA_DISABLE_CODEX_TRUST_RPC = '1'
|
||||
@@ -210,6 +238,9 @@ describe('CodexHookService app-server trust grant lane', () => {
|
||||
|
||||
expect(service.install().state).toBe('installed')
|
||||
const upgraded = readFileSync(join(managedHome, 'config.toml'), 'utf-8')
|
||||
// Why: the legacy Windows fallback intentionally writes slash variants;
|
||||
// duplicate detection is about the normalized trust identity.
|
||||
const upgradedEntries = readHookTrustEntries(join(managedHome, 'config.toml'))
|
||||
for (const eventLabel of [
|
||||
'session_start',
|
||||
'user_prompt_submit',
|
||||
@@ -218,13 +249,12 @@ describe('CodexHookService app-server trust grant lane', () => {
|
||||
'post_tool_use',
|
||||
'stop'
|
||||
]) {
|
||||
const count = upgraded
|
||||
.split('\n')
|
||||
.filter(
|
||||
(line) => line.startsWith('[hooks.state.') && line.includes(`:${eventLabel}:0:0`)
|
||||
).length
|
||||
expect(count, `duplicate trust tables for ${eventLabel}`).toBe(1)
|
||||
const count = [...upgradedEntries.keys()].filter((key) =>
|
||||
key.endsWith(`:${eventLabel}:0:0`)
|
||||
).length
|
||||
expect(count, `duplicate trust entries for ${eventLabel}`).toBe(1)
|
||||
}
|
||||
expect(upgraded).toContain('sha256:codex-session_start')
|
||||
})
|
||||
|
||||
it('leaves user trust byte-untouched while granting managed entries', () => {
|
||||
|
||||
@@ -209,7 +209,8 @@ describe('Codex WSL runtime hook install', () => {
|
||||
settlement: { status: 'unavailable' },
|
||||
isCurrentGeneration: true,
|
||||
installedTrustConfigPath: '/mnt/d/home/hooks.json',
|
||||
resolvedTrustConfigPath: null
|
||||
resolvedTrustConfigPath: null,
|
||||
installSucceeded: false
|
||||
})
|
||||
).toBe('none')
|
||||
|
||||
@@ -218,7 +219,8 @@ describe('Codex WSL runtime hook install', () => {
|
||||
settlement: { status: 'missing' },
|
||||
isCurrentGeneration: false,
|
||||
installedTrustConfigPath: '/mnt/d/home/hooks.json',
|
||||
resolvedTrustConfigPath: null
|
||||
resolvedTrustConfigPath: null,
|
||||
installSucceeded: false
|
||||
})
|
||||
).toBe('none')
|
||||
|
||||
@@ -227,25 +229,42 @@ describe('Codex WSL runtime hook install', () => {
|
||||
settlement: { status: 'missing' },
|
||||
isCurrentGeneration: true,
|
||||
installedTrustConfigPath: '/mnt/d/home/hooks.json',
|
||||
resolvedTrustConfigPath: null
|
||||
resolvedTrustConfigPath: null,
|
||||
installSucceeded: false
|
||||
})
|
||||
).toBe('remove')
|
||||
|
||||
// Why: a `missing` probe right after a verified grant is a false negative;
|
||||
// revoking would delete the fresh trust the launching pane reads (#8847).
|
||||
expect(
|
||||
_internals.getWslHookReconciliationAction({
|
||||
settlement: { status: 'resolved', canonicalPath: '/windows/d/home' },
|
||||
settlement: { status: 'missing' },
|
||||
isCurrentGeneration: true,
|
||||
installedTrustConfigPath: '/windows/d/home/hooks.json',
|
||||
resolvedTrustConfigPath: '/windows/d/home/hooks.json'
|
||||
installedTrustConfigPath: '/mnt/d/home/hooks.json',
|
||||
resolvedTrustConfigPath: null,
|
||||
installSucceeded: true
|
||||
})
|
||||
).toBe('none')
|
||||
|
||||
expect(
|
||||
_internals.getWslHookReconciliationAction({
|
||||
settlement: { status: 'resolved', canonicalPath: '/windows/d/home' },
|
||||
isCurrentGeneration: true,
|
||||
installedTrustConfigPath: '/windows/d/home/hooks.json',
|
||||
resolvedTrustConfigPath: '/windows/d/home/hooks.json',
|
||||
installSucceeded: true
|
||||
})
|
||||
).toBe('none')
|
||||
|
||||
// Why: a genuinely moved home resolves to a different path and still
|
||||
// reinstalls, even though the original install succeeded.
|
||||
expect(
|
||||
_internals.getWslHookReconciliationAction({
|
||||
settlement: { status: 'resolved', canonicalPath: '/windows/d/home' },
|
||||
isCurrentGeneration: true,
|
||||
installedTrustConfigPath: '/mnt/d/home/hooks.json',
|
||||
resolvedTrustConfigPath: '/windows/d/home/hooks.json'
|
||||
resolvedTrustConfigPath: '/windows/d/home/hooks.json',
|
||||
installSucceeded: true
|
||||
})
|
||||
).toBe('reinstall')
|
||||
})
|
||||
@@ -522,7 +541,11 @@ describe('Codex WSL runtime hook install app-server grant lane', () => {
|
||||
const basePlan = createTestPlan()
|
||||
writeFileSync(basePlan.configPath, '{"hooks":{}}\n', 'utf-8')
|
||||
writeFileSync(basePlan.tomlPath, '', 'utf-8')
|
||||
let staleKeyExpectedRemoved: string | null = null
|
||||
const runner = vi.fn((request: CodexHookTrustGrantRequest) => {
|
||||
if (staleKeyExpectedRemoved) {
|
||||
expect(readHookTrustEntries(basePlan.tomlPath).has(staleKeyExpectedRemoved)).toBe(false)
|
||||
}
|
||||
const entries = request.expectedTrustKeys.map((key) => {
|
||||
const parsed = parseTrustKey(key)!
|
||||
return {
|
||||
@@ -557,6 +580,7 @@ describe('Codex WSL runtime hook install app-server grant lane', () => {
|
||||
const oldKey = computeTrustKey(
|
||||
getManagedTrustEntry(oldPlan, expectedManagedCommand(oldPlan.commandScriptPath))
|
||||
)
|
||||
staleKeyExpectedRemoved = oldKey
|
||||
|
||||
const newPlan = {
|
||||
...basePlan,
|
||||
|
||||
@@ -904,6 +904,13 @@ function installManagedHooksIntoWslRuntime(
|
||||
// Why: a successful re-grant replaces the ledger. Keep the previous
|
||||
// records long enough to prove ownership of stale canonical-path keys.
|
||||
const previousLedgerHome = readCodexTrustGrantLedgerHomeForReconciliation(runtimeHomePath)
|
||||
// Why: Codex's verified RPC write must be the final config mutation. A
|
||||
// host-side rewrite after verification can race or invalidate that grant.
|
||||
removeStaleWslRuntimeManagedHookTrustEntries(
|
||||
plan.tomlPath,
|
||||
trustEntries,
|
||||
previousLedgerHome ? [previousLedgerHome] : []
|
||||
)
|
||||
const grant = grantManagedCodexHookTrust({
|
||||
runtimeHomePath,
|
||||
tomlPath: plan.tomlPath,
|
||||
@@ -911,17 +918,10 @@ function installManagedHooksIntoWslRuntime(
|
||||
managedEntries: trustEntries,
|
||||
host: { kind: 'wsl', distro: plan.wslDistro, linuxRuntimeHome: plan.linuxRuntimeHome }
|
||||
})
|
||||
if (grant.lane === 'rpc') {
|
||||
removeStaleWslRuntimeManagedHookTrustEntries(
|
||||
plan.tomlPath,
|
||||
grant.entries,
|
||||
previousLedgerHome ? [previousLedgerHome] : []
|
||||
)
|
||||
} else {
|
||||
if (grant.lane === 'fallback') {
|
||||
// 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 {
|
||||
@@ -992,12 +992,19 @@ function getWslHookReconciliationAction(args: {
|
||||
isCurrentGeneration: boolean
|
||||
installedTrustConfigPath: string | null
|
||||
resolvedTrustConfigPath: string | null
|
||||
/** Whether the synchronous install for this generation wrote trust. */
|
||||
installSucceeded: boolean
|
||||
}): 'none' | 'remove' | 'reinstall' {
|
||||
if (!args.isCurrentGeneration) {
|
||||
return 'none'
|
||||
}
|
||||
if (args.settlement.status === 'missing') {
|
||||
return 'remove'
|
||||
// Why: a `missing` directory probe right after a verified install/grant is
|
||||
// a false negative — the RPC (or fallback) just wrote and read trust in
|
||||
// that home, so it exists. Revoking here would delete the fresh grant the
|
||||
// launching pane needs, resurfacing "hooks need review". A genuinely moved
|
||||
// home resolves to a different path and takes the `reinstall` branch below.
|
||||
return args.installSucceeded ? 'none' : 'remove'
|
||||
}
|
||||
if (
|
||||
args.settlement.status !== 'resolved' ||
|
||||
@@ -1034,6 +1041,10 @@ export class CodexHookService {
|
||||
): AgentHookInstallStatus | null {
|
||||
const generation = this.supersedeWslReconciliation(runtimeHomePath)
|
||||
let installedTrustConfigPath: string | null = null
|
||||
// Why: JS is single-threaded, so the synchronous install below finishes
|
||||
// before any async `wsl.exe` settlement callback runs — this flag is
|
||||
// always set by the time the callback reads it.
|
||||
let installSucceeded = false
|
||||
const onCanonicalPathSettled = (settlement: WslCanonicalPathSettlement): void => {
|
||||
if (!runtimeHomePath) {
|
||||
return
|
||||
@@ -1051,7 +1062,8 @@ export class CodexHookService {
|
||||
settlement,
|
||||
isCurrentGeneration: this.wslReconciliationGeneration.get(key) === generation,
|
||||
installedTrustConfigPath,
|
||||
resolvedTrustConfigPath: resolvedPlan?.trustConfigPath ?? null
|
||||
resolvedTrustConfigPath: resolvedPlan?.trustConfigPath ?? null,
|
||||
installSucceeded
|
||||
})
|
||||
if (action === 'none') {
|
||||
return
|
||||
@@ -1076,6 +1088,7 @@ export class CodexHookService {
|
||||
return
|
||||
}
|
||||
installedTrustConfigPath = resolvedPlan.trustConfigPath
|
||||
installSucceeded = status.state === 'installed'
|
||||
}
|
||||
const wslPlan = createCodexWslRuntimeHookInstallPlan(
|
||||
runtimeHomePath,
|
||||
@@ -1084,7 +1097,9 @@ export class CodexHookService {
|
||||
onCanonicalPathSettled
|
||||
)
|
||||
installedTrustConfigPath = wslPlan?.trustConfigPath ?? null
|
||||
return wslPlan ? installManagedHooksIntoWslRuntime(wslPlan) : null
|
||||
const status = wslPlan ? installManagedHooksIntoWslRuntime(wslPlan) : null
|
||||
installSucceeded = status?.state === 'installed'
|
||||
return status
|
||||
}
|
||||
|
||||
refreshRuntimeUserHooksForRuntimeHome(
|
||||
|
||||
Reference in New Issue
Block a user