Skip to content

Commit bc630f2

Browse files
committed
fix(codex): validate shim installs before commit
1 parent 90ad67a commit bc630f2

2 files changed

Lines changed: 128 additions & 2 deletions

File tree

‎src/codex/shim.ts‎

Lines changed: 53 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import { randomUUID } from "node:crypto";
2+
import { spawnSync } from "node:child_process";
23
import { delimiter, dirname, extname, join, posix } from "node:path";
34
import {
45
chmodSync,
@@ -33,6 +34,9 @@ const CODEX_SHIM_PROBE_BYTES = 16 * 1024;
3334
export const CODEX_SHIM_REPLACEMENT_STABLE_MS = 100;
3435
export const CODEX_SHIM_STATE_MAX_BYTES = 1024 * 1024;
3536
const CODEX_SHIM_RESTORE_LOCK_STALE_MS = 30_000;
37+
const CODEX_SHIM_INSTALL_PROBE_TIMEOUT_MS = 5_000;
38+
const CODEX_SHIM_REENTRY_EXIT_CODE = 126;
39+
const CODEX_SHIM_REENTRY_DIAGNOSTIC = "opencodex: saved Codex launcher resolved back to the autostart shim; run ocx restore and reinstall Codex before enabling codexAutoStart.";
3640
const MAX_DIAGNOSTIC_VALUE_BYTES = 8 * 1024;
3741
let lastShimDiscoveryError: string | null = null;
3842
/** Last human-readable reason discovery returned null (exposed for doctor/tests). */
@@ -384,8 +388,8 @@ export function buildUnixCodexShim(realCodexPath: string, bunPath: string, cliPa
384388
return `#!/usr/bin/env sh
385389
# ${SHIM_MARKER}
386390
if [ "\${OCX_SHIM_ACTIVE_PID:-}" = "$$" ]; then
387-
printf '%s\n' 'opencodex: saved Codex launcher resolved back to the autostart shim; run ocx restore and reinstall Codex before enabling codexAutoStart.' >&2
388-
exit 126
391+
printf '%s\n' ${shQuote(CODEX_SHIM_REENTRY_DIAGNOSTIC)} >&2
392+
exit ${CODEX_SHIM_REENTRY_EXIT_CODE}
389393
fi
390394
# Dynamic launchers such as mise exec -- codex may resolve the command name
391395
# back to this wrapper. An exec chain keeps the same PID; a legitimate nested
@@ -435,6 +439,40 @@ exec ${shQuote(realCodexPath)} "$@"
435439
`;
436440
}
437441

442+
function probeUnixShimInstall(wrapperPath: string): "recursive" | "timeout" | null {
443+
if (process.platform === "win32") return null;
444+
const env: NodeJS.ProcessEnv = { ...process.env, OCX_SHIM_BYPASS: "1" };
445+
delete env.OCX_SHIM_ACTIVE_PID;
446+
const result = spawnSync("/bin/sh", [wrapperPath, "--version"], {
447+
encoding: "utf8",
448+
env,
449+
timeout: CODEX_SHIM_INSTALL_PROBE_TIMEOUT_MS,
450+
killSignal: "SIGKILL",
451+
});
452+
if ((result.error as NodeJS.ErrnoException | undefined)?.code === "ETIMEDOUT") return "timeout";
453+
if (result.status === CODEX_SHIM_REENTRY_EXIT_CODE && result.stderr.includes(CODEX_SHIM_REENTRY_DIAGNOSTIC)) {
454+
return "recursive";
455+
}
456+
return null;
457+
}
458+
459+
function rollbackFreshShimInstall(targets: readonly ShimFileState[]): void {
460+
const errors: Error[] = [];
461+
for (const target of [...targets].reverse()) {
462+
try {
463+
if (!target.preserveOnly && existsSync(target.wrapperPath) && isShim(target.wrapperPath)) unlinkSync(target.wrapperPath);
464+
} catch (error) {
465+
errors.push(error instanceof Error ? error : new Error(String(error)));
466+
}
467+
try {
468+
if (existsSync(target.backupPath) && !existsSync(target.originalPath)) renameSync(target.backupPath, target.originalPath);
469+
} catch (error) {
470+
errors.push(error instanceof Error ? error : new Error(String(error)));
471+
}
472+
}
473+
if (errors.length > 0) throw new AggregateError(errors, "Codex shim install validation rollback failed");
474+
}
475+
438476
function windowsBatchValue(value: string): string {
439477
return value
440478
.replace(/%/g, "%%")
@@ -1073,6 +1111,19 @@ function installCodexShimInternal(options: InstallCodexShimInternalOptions): { i
10731111
if (existsSync(target.originalPath)) renameSync(target.originalPath, target.backupPath);
10741112
if (!target.preserveOnly) writeShim(target.wrapperPath, target.realPath ?? target.backupPath);
10751113
}
1114+
if (process.platform !== "win32") {
1115+
const unsafe = targets.map(target => probeUnixShimInstall(target.wrapperPath)).find(result => result !== null);
1116+
if (unsafe) {
1117+
rollbackFreshShimInstall(targets);
1118+
const reason = unsafe === "recursive"
1119+
? "the saved launcher resolved back to the generated shim"
1120+
: `the saved launcher did not finish --version within ${CODEX_SHIM_INSTALL_PROBE_TIMEOUT_MS}ms`;
1121+
return {
1122+
installed: false,
1123+
message: `Refusing Codex autostart shim because ${reason}. The original launcher was restored; reinstall Codex as a concrete executable before enabling codexAutoStart.`,
1124+
};
1125+
}
1126+
}
10761127
writeState(primaryState(targets));
10771128
return {
10781129
installed: true,

‎tests/codex-shim.test.ts‎

Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -254,6 +254,81 @@ exit 64
254254
}
255255
});
256256

257+
test("Unix install rejects a recursive dynamic launcher and restores the original", () => {
258+
if (process.platform === "win32") return;
259+
260+
const binDir = mkdtempSync(join(tmpdir(), "ocx-shim-install-reentry-bin-"));
261+
const home = mkdtempSync(join(tmpdir(), "ocx-shim-install-reentry-home-"));
262+
const oldPath = process.env.PATH;
263+
const oldHome = process.env.OPENCODEX_HOME;
264+
const codexPath = join(binDir, "codex");
265+
const misePath = join(binDir, "mise");
266+
const original = `#!/bin/sh\nexec "${misePath}" exec -- codex "$@"\n`;
267+
try {
268+
process.env.PATH = `${binDir}:${oldPath ?? ""}`;
269+
process.env.OPENCODEX_HOME = home;
270+
writeFileSync(misePath, `#!/bin/sh
271+
if [ "$1" = exec ] && [ "$2" = -- ] && [ "$3" = codex ]; then
272+
shift 3
273+
exec codex "$@"
274+
fi
275+
exit 64
276+
`, "utf8");
277+
writeFileSync(codexPath, original, "utf8");
278+
chmodSync(misePath, 0o755);
279+
chmodSync(codexPath, 0o755);
280+
281+
const installed = installCodexShim();
282+
283+
expect(installed.installed).toBe(false);
284+
expect(installed.message).toContain("saved launcher resolved back to the generated shim");
285+
expect(installed.message).toContain("original launcher was restored");
286+
expect(readFileSync(codexPath, "utf8")).toBe(original);
287+
expect(existsSync(`${codexPath}.opencodex-real`)).toBe(false);
288+
expect(existsSync(join(home, "codex-shim.json"))).toBe(false);
289+
} finally {
290+
if (oldPath === undefined) delete process.env.PATH;
291+
else process.env.PATH = oldPath;
292+
if (oldHome === undefined) delete process.env.OPENCODEX_HOME;
293+
else process.env.OPENCODEX_HOME = oldHome;
294+
rmSync(binDir, { recursive: true, force: true });
295+
rmSync(home, { recursive: true, force: true });
296+
}
297+
});
298+
299+
test("Unix install rolls back when launcher validation times out", () => {
300+
if (process.platform === "win32") return;
301+
302+
const binDir = mkdtempSync(join(tmpdir(), "ocx-shim-install-timeout-bin-"));
303+
const home = mkdtempSync(join(tmpdir(), "ocx-shim-install-timeout-home-"));
304+
const oldPath = process.env.PATH;
305+
const oldHome = process.env.OPENCODEX_HOME;
306+
const codexPath = join(binDir, "codex");
307+
const original = "#!/bin/sh\nexec /bin/sleep 30\n";
308+
try {
309+
process.env.PATH = `${binDir}:${oldPath ?? ""}`;
310+
process.env.OPENCODEX_HOME = home;
311+
writeFileSync(codexPath, original, "utf8");
312+
chmodSync(codexPath, 0o755);
313+
314+
const installed = installCodexShim();
315+
316+
expect(installed.installed).toBe(false);
317+
expect(installed.message).toContain("did not finish --version within 5000ms");
318+
expect(installed.message).toContain("original launcher was restored");
319+
expect(readFileSync(codexPath, "utf8")).toBe(original);
320+
expect(existsSync(`${codexPath}.opencodex-real`)).toBe(false);
321+
expect(existsSync(join(home, "codex-shim.json"))).toBe(false);
322+
} finally {
323+
if (oldPath === undefined) delete process.env.PATH;
324+
else process.env.PATH = oldPath;
325+
if (oldHome === undefined) delete process.env.OPENCODEX_HOME;
326+
else process.env.OPENCODEX_HOME = oldHome;
327+
rmSync(binDir, { recursive: true, force: true });
328+
rmSync(home, { recursive: true, force: true });
329+
}
330+
}, 10_000);
331+
257332
test("Unix shim permits a real Codex process to start a new child invocation", () => {
258333
if (process.platform === "win32") return;
259334

0 commit comments

Comments
 (0)