Skip to content

Commit ce65a75

Browse files
committed
fix: harden Codex shim auto-restore
1 parent ae18374 commit ce65a75

7 files changed

Lines changed: 384 additions & 52 deletions

File tree

‎src/cli/codex-shim-autorestore.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,8 @@ export function maybeAutoRestoreCodexShim(
3232
});
3333
if (result.status === "restored") {
3434
deps.warn(`⚠️ ${result.message} (automatic repair after Codex update)`);
35+
} else if ((result.status === "deferred" || result.status === "ineligible") && result.message) {
36+
deps.warn(`⚠️ ${result.message}`);
3537
}
3638
} catch (error) {
3739
deps.warn(

‎src/cli/index.ts‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -50,8 +50,9 @@ if (command === "--version" || command === "-v" || command === "version") {
5050
process.exit(0);
5151
}
5252

53-
if (command === "help" && args[1]) {
54-
printSubcommandUsage(args[1]);
53+
if (command === undefined || command === "help" || command === "--help" || command === "-h") {
54+
if (command === "help" && args[1]) printSubcommandUsage(args[1]);
55+
else printUsage();
5556
process.exit(0);
5657
}
5758

‎src/codex/shim.ts‎

Lines changed: 178 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -3,13 +3,15 @@ import {
33
chmodSync,
44
closeSync,
55
existsSync,
6+
fstatSync,
67
lstatSync,
78
mkdirSync,
89
openSync,
910
readFileSync,
1011
readSync,
1112
renameSync,
1213
statSync,
14+
type Stats,
1315
unlinkSync,
1416
writeFileSync,
1517
} from "node:fs";
@@ -22,6 +24,8 @@ import { isWslRuntime, wslAutomountRoot } from "./home";
2224
const SHIM_MARKER = "opencodex codex autostart shim";
2325
const CODEX_SHIM_PROBE_BYTES = 16 * 1024;
2426
export const CODEX_SHIM_REPLACEMENT_STABLE_MS = 100;
27+
export const CODEX_SHIM_STATE_MAX_BYTES = 1024 * 1024;
28+
const CODEX_SHIM_RESTORE_LOCK_STALE_MS = 30_000;
2529
let lastShimDiscoveryError: string | null = null;
2630
/** Last human-readable reason discovery returned null (exposed for doctor/tests). */
2731
export function lastCodexDiscoveryError(): string | null {
@@ -105,7 +109,8 @@ interface InstallCodexShimInternalOptions {
105109
}
106110

107111
export type CodexShimAutoRestoreResult =
108-
| { status: "not-installed" | "healthy" | "ineligible" | "deferred" | "disabled" }
112+
| { status: "not-installed" | "healthy" | "disabled" }
113+
| { status: "ineligible" | "deferred"; message?: string }
109114
| { status: "restored"; message: string };
110115

111116
function cliEntry(): { bun: string; cli: string } {
@@ -214,10 +219,8 @@ function stableShimPathProbe(path: string): StableShimPathProbe | null {
214219
return contentSize > 0 ? { fingerprint, prefix } : null;
215220
}
216221

217-
function fingerprintIsOldEnough(fingerprint: ShimPathFingerprint, nowMs: number): boolean {
218-
const timestamps = [fingerprint.mtimeMs, fingerprint.ctimeMs];
219-
if (fingerprint.target) timestamps.push(fingerprint.target.mtimeMs, fingerprint.target.ctimeMs);
220-
return nowMs - Math.max(...timestamps) >= CODEX_SHIM_REPLACEMENT_STABLE_MS;
222+
function sameStableShimPathProbe(left: StableShimPathProbe, right: StableShimPathProbe): boolean {
223+
return left.prefix === right.prefix && sameFingerprint(left.fingerprint, right.fingerprint);
221224
}
222225

223226
function isHealthyShimProbe(probe: StableShimPathProbe, platform: NodeJS.Platform): boolean {
@@ -490,12 +493,62 @@ exit $LASTEXITCODE
490493
`;
491494
}
492495

493-
function readState(): ShimState | null {
496+
interface ShimStateReadResult {
497+
state: ShimState | null;
498+
warning?: string;
499+
}
500+
501+
function fileErrorCode(error: unknown): string | undefined {
502+
return error && typeof error === "object" && "code" in error
503+
? String((error as { code?: unknown }).code)
504+
: undefined;
505+
}
506+
507+
function readBoundedRegularFile(path: string, maxBytes: number): { content: string } | { warning: string } | null {
508+
let fd: number;
509+
try {
510+
fd = openSync(path, "r");
511+
} catch (error) {
512+
if (fileErrorCode(error) === "ENOENT") return null;
513+
return { warning: `Codex shim state could not be opened as a regular file at ${path}.` };
514+
}
515+
try {
516+
const before = fstatSync(fd);
517+
if (!before.isFile()) return { warning: `Codex shim state is not a regular file at ${path}; auto-restore skipped.` };
518+
if (before.size > maxBytes) {
519+
return { warning: `Codex shim state exceeds the 1 MiB startup limit at ${path}; auto-restore skipped.` };
520+
}
521+
const buffer = Buffer.allocUnsafe(before.size);
522+
let offset = 0;
523+
while (offset < buffer.length) {
524+
const bytesRead = readSync(fd, buffer, offset, buffer.length - offset, offset);
525+
if (bytesRead === 0) return { warning: `Codex shim state changed while being read at ${path}; auto-restore skipped.` };
526+
offset += bytesRead;
527+
}
528+
const extra = Buffer.allocUnsafe(1);
529+
if (readSync(fd, extra, 0, 1, offset) !== 0) {
530+
return { warning: `Codex shim state exceeds the 1 MiB startup limit at ${path}; auto-restore skipped.` };
531+
}
532+
const after = fstatSync(fd);
533+
if (before.dev !== after.dev || before.ino !== after.ino || before.size !== after.size
534+
|| before.mtimeMs !== after.mtimeMs || before.ctimeMs !== after.ctimeMs) {
535+
return { warning: `Codex shim state changed while being read at ${path}; auto-restore skipped.` };
536+
}
537+
return { content: buffer.toString("utf8") };
538+
} finally {
539+
closeSync(fd);
540+
}
541+
}
542+
543+
function readStateResult(): ShimStateReadResult {
544+
const bounded = readBoundedRegularFile(statePath(), CODEX_SHIM_STATE_MAX_BYTES);
545+
if (!bounded) return { state: null };
546+
if ("warning" in bounded) return { state: null, warning: bounded.warning };
494547
try {
495-
const value = JSON.parse(readFileSync(statePath(), "utf8")) as unknown;
496-
if (!value || typeof value !== "object") return null;
548+
const value = JSON.parse(bounded.content) as unknown;
549+
if (!value || typeof value !== "object") return { state: null };
497550
const state = value as Record<string, unknown>;
498-
if (typeof state.platform !== "string") return null;
551+
if (typeof state.platform !== "string") return { state: null };
499552
const validFile = (item: unknown): item is ShimFileState => {
500553
if (!item || typeof item !== "object") return false;
501554
const file = item as Record<string, unknown>;
@@ -506,16 +559,20 @@ function readState(): ShimState | null {
506559
&& (file.preserveOnly === undefined || typeof file.preserveOnly === "boolean");
507560
};
508561
if (state.wrappers !== undefined) {
509-
if (!Array.isArray(state.wrappers) || state.wrappers.length === 0 || !state.wrappers.every(validFile)) return null;
562+
if (!Array.isArray(state.wrappers) || state.wrappers.length === 0 || !state.wrappers.every(validFile)) return { state: null };
510563
} else if (!validFile(state)) {
511-
return null;
564+
return { state: null };
512565
}
513-
return state as unknown as ShimState;
566+
return { state: state as unknown as ShimState };
514567
} catch {
515-
return null;
568+
return { state: null };
516569
}
517570
}
518571

572+
function readState(): ShimState | null {
573+
return readStateResult().state;
574+
}
575+
519576
function statePath(): string {
520577
return join(getConfigDir(), "codex-shim.json");
521578
}
@@ -619,6 +676,70 @@ interface GuardedRefreshJournalEntry {
619676

620677
let guardedRefreshTransactionId = 0;
621678

679+
interface ShimRestoreLock {
680+
release(): void;
681+
}
682+
683+
function restoreLockPath(): string {
684+
return join(getConfigDir(), "codex-shim.autorestore.lock");
685+
}
686+
687+
function sameFileIdentity(left: Stats, right: Stats): boolean {
688+
return left.dev === right.dev && left.ino === right.ino;
689+
}
690+
691+
function reclaimStaleRestoreLock(path: string): boolean {
692+
const before = statFingerprint(path, false);
693+
if (!before || before.kind !== "file" || Date.now() - before.mtimeMs <= CODEX_SHIM_RESTORE_LOCK_STALE_MS) return false;
694+
const after = statFingerprint(path, false);
695+
if (!after || !sameFingerprint(before, after)) return false;
696+
try {
697+
unlinkSync(path);
698+
return true;
699+
} catch (error) {
700+
if (fileErrorCode(error) === "ENOENT") return true;
701+
return false;
702+
}
703+
}
704+
705+
function tryAcquireShimRestoreLock(): ShimRestoreLock | null {
706+
const dir = getConfigDir();
707+
if (!existsSync(dir)) mkdirSync(dir, { recursive: true, mode: 0o700 });
708+
const path = restoreLockPath();
709+
for (let attempt = 0; attempt < 2; attempt += 1) {
710+
let fd: number | null = null;
711+
let identity: Stats | null = null;
712+
try {
713+
fd = openSync(path, "wx", 0o600);
714+
identity = fstatSync(fd);
715+
writeFileSync(fd, `${JSON.stringify({ acquiredAt: Date.now(), pid: process.pid })}\n`, "utf8");
716+
identity = fstatSync(fd);
717+
let released = false;
718+
return {
719+
release(): void {
720+
if (released) return;
721+
released = true;
722+
try { closeSync(fd!); } catch { /* stale recovery handles an uncertain lock */ }
723+
try {
724+
if (identity && sameFileIdentity(identity, lstatSync(path))) unlinkSync(path);
725+
} catch { /* stale recovery handles release failures */ }
726+
},
727+
};
728+
} catch (error) {
729+
if (fd !== null) {
730+
try { closeSync(fd); } catch { /* best-effort close before ownership cleanup */ }
731+
try {
732+
if (identity && sameFileIdentity(identity, lstatSync(path))) unlinkSync(path);
733+
} catch { /* leave an uncertain lock for stale recovery */ }
734+
}
735+
if (fileErrorCode(error) !== "EEXIST") throw error;
736+
if (attempt === 0 && reclaimStaleRestoreLock(path)) continue;
737+
return null;
738+
}
739+
}
740+
return null;
741+
}
742+
622743
function planGuardedRefreshTransaction(
623744
files: readonly ShimFileState[],
624745
expectedReplacements: ReadonlyMap<string, ShimPathFingerprint>,
@@ -835,18 +956,24 @@ export function installCodexShim(): { installed: boolean; message: string } {
835956

836957
export function autoRestoreCodexShim(options: {
837958
enabled: () => boolean;
838-
nowMs?: number;
959+
stabilitySleep?: (ms: number) => void;
960+
/** Narrow deterministic seam used to hold the interprocess lock in tests. */
961+
afterRestoreLockAcquired?: () => void;
839962
/** Narrow deterministic race seam for the guarded transaction tests. */
840963
beforeGuardedRefresh?: (wrapperPath: string, index: number) => void;
841964
}): CodexShimAutoRestoreResult {
842-
const state = readState();
843-
if (!state) return { status: existsSync(statePath()) ? "ineligible" : "not-installed" };
965+
const stateRead = readStateResult();
966+
const state = stateRead.state;
967+
if (!state) {
968+
if (stateRead.warning) return { status: "ineligible", message: stateRead.warning };
969+
return { status: existsSync(statePath()) ? "ineligible" : "not-installed" };
970+
}
844971
if (state.platform !== process.platform) return { status: "ineligible" };
845972

846973
const files = stateFiles(state);
847-
const expectedReplacements = new Map<string, ShimPathFingerprint>();
974+
const replacementProbes = new Map<string, StableShimPathProbe>();
848975
const seen = new Set<string>();
849-
const nowMs = options.nowMs ?? Date.now();
976+
let healthyCount = 0;
850977
for (const file of files) {
851978
if (seen.has(file.wrapperPath)) return { status: "ineligible" };
852979
seen.add(file.wrapperPath);
@@ -859,22 +986,44 @@ export function autoRestoreCodexShim(options: {
859986
if (!probe) return { status: "deferred" };
860987
if (probe.prefix.includes(SHIM_MARKER)) {
861988
if (!isHealthyShimProbe(probe, state.platform)) return { status: "ineligible" };
989+
healthyCount += 1;
862990
continue;
863991
}
864-
if (!fingerprintIsOldEnough(probe.fingerprint, nowMs)) return { status: "deferred" };
865-
expectedReplacements.set(file.wrapperPath, probe.fingerprint);
992+
replacementProbes.set(file.wrapperPath, probe);
866993
}
867994

868-
if (expectedReplacements.size === 0) return { status: "healthy" };
995+
if (replacementProbes.size === 0) return { status: "healthy" };
869996
if (!options.enabled()) return { status: "disabled" };
870-
const result = installCodexShimInternal({
871-
allowFreshInstall: false,
872-
expectedReplacements,
873-
beforeGuardedRefresh: options.beforeGuardedRefresh,
874-
});
875-
return result.installed
876-
? { status: "restored", message: result.message }
877-
: { status: "deferred" };
997+
if (files.length > 1 && healthyCount > 0) {
998+
return {
999+
status: "deferred",
1000+
message: "Codex shim auto-restore deferred because tracked launcher siblings are in a mixed shim/replacement state.",
1001+
};
1002+
}
1003+
1004+
const lock = tryAcquireShimRestoreLock();
1005+
if (!lock) return { status: "deferred" };
1006+
try {
1007+
options.afterRestoreLockAcquired?.();
1008+
(options.stabilitySleep ?? Bun.sleepSync)(CODEX_SHIM_REPLACEMENT_STABLE_MS);
1009+
const expectedReplacements = new Map<string, ShimPathFingerprint>();
1010+
for (const [path, firstProbe] of replacementProbes) {
1011+
const secondProbe = stableShimPathProbe(path);
1012+
if (!secondProbe || secondProbe.prefix.includes(SHIM_MARKER)
1013+
|| !sameStableShimPathProbe(firstProbe, secondProbe)) return { status: "deferred" };
1014+
expectedReplacements.set(path, secondProbe.fingerprint);
1015+
}
1016+
const result = installCodexShimInternal({
1017+
allowFreshInstall: false,
1018+
expectedReplacements,
1019+
beforeGuardedRefresh: options.beforeGuardedRefresh,
1020+
});
1021+
return result.installed
1022+
? { status: "restored", message: result.message }
1023+
: { status: "deferred" };
1024+
} finally {
1025+
lock.release();
1026+
}
8781027
}
8791028

8801029
export function uninstallCodexShim(): { removed: boolean; message: string } {

‎structure/01_runtime.md‎

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -38,12 +38,14 @@ config/catalog, then serves until shutdown. Normal shutdown restores native Code
3838
`OCX_SERVICE=1`, so managed restarts do not repeatedly restore/reinject; explicit service stop and
3939
uninstall still restore.
4040

41-
An installed Codex shim is checked on ordinary CLI startup with bounded state, metadata, and prefix
42-
reads. A complete replacement must remain stable for at least 100 ms; changing or mixed sibling
43-
launchers are silently deferred. Guarded repair preflights every tracked sibling before mutation,
44-
revalidates each source before rename, and rolls back earlier siblings in reverse order on a later
45-
race. Failures warn without changing the requested command's exit behavior. The probe uses
46-
read-only config diagnostics only for a confirmed candidate and never reads adjacent auth state.
41+
An installed Codex shim is checked on ordinary CLI startup with a regular-file/1 MiB state bound plus
42+
bounded metadata and prefix reads. A complete replacement must produce identical fingerprints and
43+
prefixes across a 100 ms observation interval; changing launchers are silently deferred, while mixed
44+
sibling sets warn and defer as a unit. Guarded repair holds an O_EXCL interprocess lock across its
45+
final revalidation, rename, shim write, and state commit; it preflights every tracked sibling before
46+
mutation and rolls back earlier siblings in reverse order on a later race. Failures warn without
47+
changing the requested command's exit behavior. The probe uses read-only config diagnostics only for
48+
a confirmed candidate and never reads adjacent auth state.
4749

4850
The bridge enforces a heartbeat stall deadline: after 5 minutes (150 ticks at the default 2 s
4951
interval) of upstream silence with no real events, the stream is closed and the upstream request

‎tests/cli-help.test.ts‎

Lines changed: 36 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import { describe, expect, test } from "bun:test";
22
import { spawnSync } from "node:child_process";
3-
import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
3+
import { chmodSync, existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
44
import { tmpdir } from "node:os";
55
import { dirname, join } from "node:path";
66
import { fileURLToPath } from "node:url";
@@ -45,6 +45,41 @@ describe("CLI subcommand help", () => {
4545
expect(result.stdout).toContain("Start the proxy server and sync models to Codex.");
4646
});
4747

48+
test("top-level help forms exit before Codex shim auto-restore can mutate launchers", () => {
49+
const opencodexHome = mkdtempSync(join(tmpdir(), "ocx-help-shim-home-"));
50+
const binDir = mkdtempSync(join(tmpdir(), "ocx-help-shim-bin-"));
51+
try {
52+
const wrapper = join(binDir, process.platform === "win32" ? "codex.cmd" : "codex");
53+
const backup = join(binDir, process.platform === "win32" ? "codex.opencodex-real.cmd" : "codex.opencodex-real");
54+
const statePath = join(opencodexHome, "codex-shim.json");
55+
const replacement = "replacement that help must not promote\n";
56+
writeFileSync(wrapper, replacement, "utf8");
57+
writeFileSync(backup, "known-good prior launcher\n", "utf8");
58+
if (process.platform !== "win32") chmodSync(wrapper, 0o755);
59+
writeFileSync(statePath, `${JSON.stringify({
60+
platform: process.platform,
61+
wrapperPath: wrapper,
62+
originalPath: wrapper,
63+
backupPath: backup,
64+
}, null, 2)}\n`, "utf8");
65+
const stateBefore = readFileSync(statePath);
66+
const backupBefore = readFileSync(backup);
67+
Bun.sleepSync(120);
68+
69+
for (const args of [[], ["help"], ["--help"], ["-h"]]) {
70+
const result = runCli(args, { OPENCODEX_HOME: opencodexHome, PATH: binDir });
71+
expect(result.status).toBe(0);
72+
expect(result.stdout).toContain("opencodex (ocx)");
73+
expect(readFileSync(wrapper, "utf8")).toBe(replacement);
74+
expect(readFileSync(backup)).toEqual(backupBefore);
75+
expect(readFileSync(statePath)).toEqual(stateBefore);
76+
}
77+
} finally {
78+
rmSync(opencodexHome, { recursive: true, force: true });
79+
rmSync(binDir, { recursive: true, force: true });
80+
}
81+
});
82+
4883
test("tray help documents the install-only no-start flag", () => {
4984
const result = runCli(["help", "tray"]);
5085
expect(result.status).toBe(0);

0 commit comments

Comments
 (0)