Skip to content

Commit fc1f6ab

Browse files
committed
fix(codex): guard native profile recovery state
1 parent 899ddb2 commit fc1f6ab

4 files changed

Lines changed: 208 additions & 3 deletions

File tree

‎docs-site/src/content/docs/reference/cli/providers-accounts.md‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -219,8 +219,9 @@ ocx account main doctor
219219
ocx account main list
220220
ocx account main register <name>
221221
ocx account main add <name>
222-
ocx account main switch <name>
222+
ocx account main switch <name> --yes
223223
ocx account main recover
224+
ocx account main recover --rollback --yes
224225
```
225226

226227
Version 1 supports file-based Codex authentication, encrypts stored profiles with AES-256-GCM, and

‎src/codex/native-profile-manager.ts‎

Lines changed: 46 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -220,6 +220,15 @@ export class NativeProfileManager {
220220
try { unlinkSync(this.context.journalPath); } catch (error) { if (errorCode(error) !== "ENOENT") throw error; }
221221
}
222222

223+
private assertNoPendingRecovery(): void {
224+
if (!readNativeProfileJournal(this.context)) return;
225+
throw new NativeProfileError(
226+
"RECOVERY_REQUIRED",
227+
"A native-profile recovery journal is pending. Run `ocx account main recover` or `ocx account main recover --rollback --yes` before registering or adding profiles.",
228+
409,
229+
);
230+
}
231+
223232
private requireVault(): NativeMainProfileVaultV1 {
224233
const vault = readNativeProfileVault(this.context);
225234
if (!vault) throw new NativeProfileError("PROFILE_NOT_FOUND", "Register the current native login before adding or switching profiles.", 404);
@@ -246,6 +255,7 @@ export class NativeProfileManager {
246255

247256
async register(labelInput: string): Promise<{ effectiveCodexHome: string; profile: NativeProfilePublic }> {
248257
return this.withLock(async () => {
258+
this.assertNoPendingRecovery();
249259
requireFileCredentialStore(this.context);
250260
const label = validateNativeProfileLabel(labelInput);
251261
const envelope = readNativeEnvelope(this.context.authPath);
@@ -417,6 +427,7 @@ export class NativeProfileManager {
417427

418428
async prepareStage(): Promise<{ stageId: string; stagingCodexHome: string; effectiveCodexHome: string }> {
419429
return this.withLock(async () => {
430+
this.assertNoPendingRecovery();
420431
this.sweepStaleStages();
421432
requireFileCredentialStore(this.context);
422433
const vault = this.requireVault();
@@ -445,6 +456,7 @@ export class NativeProfileManager {
445456

446457
async finishStage(stageId: string, labelInput: string): Promise<{ effectiveCodexHome: string; profile: NativeProfilePublic }> {
447458
return this.withLock(async () => {
459+
this.assertNoPendingRecovery();
448460
this.stagePath(stageId);
449461
let target: NativeEnvelopeSnapshot | null = null;
450462
let current: NativeEnvelopeSnapshot | null = null;
@@ -650,10 +662,43 @@ export class NativeProfileManager {
650662
journal.sourcePayload,
651663
key,
652664
);
665+
let rollbackVault = journal.beforeVault;
666+
let rollbackVaultPublished = false;
667+
if (current.envelope.digest !== journal.targetPayload.envelopeSha256) {
668+
rollbackVault = structuredClone(journal.beforeVault);
669+
const targetProfile = rollbackVault.profiles.find(profile =>
670+
profile.id === journal.targetProfileId
671+
&& profile.identityHash === journal.targetIdentityHash
672+
&& profile.state === "inactive"
673+
);
674+
if (!targetProfile) {
675+
throw new NativeProfileError(
676+
"VAULT_INVALID",
677+
"Recovery could not preserve the refreshed target login in its inactive profile and made no credential write.",
678+
409,
679+
);
680+
}
681+
const refreshedTargetPayload = encryptNativeEnvelope(
682+
this.context,
683+
targetProfile.id,
684+
targetProfile.identityHash,
685+
current.envelope,
686+
key,
687+
);
688+
targetProfile.payload = refreshedTargetPayload;
689+
targetProfile.updatedAt = new Date(this.now()).toISOString();
690+
rollbackVault.revision += 1;
691+
const preservedJournal = structuredClone(journal);
692+
preservedJournal.targetPayload = refreshedTargetPayload;
693+
preservedJournal.beforeVault = structuredClone(rollbackVault);
694+
await this.writeJournal(preservedJournal);
695+
await this.writeVault(rollbackVault);
696+
rollbackVaultPublished = true;
697+
}
653698
await this.atomicWrite(this.context.authPath, sourceEnvelope.text);
654699
const restored = this.verifyWrittenEnvelope(sourceEnvelope.digest, journal.sourceIdentityHash, key);
655700
restored.raw.fill(0);
656-
await this.writeVault(journal.beforeVault);
701+
if (!rollbackVaultPublished) await this.writeVault(rollbackVault);
657702
this.applyTransition(current.envelope.accountId, sourceEnvelope.accountId);
658703
this.removeJournal();
659704
return { ok: true, recovered: true, action: "rollback-source", effectiveCodexHome: this.context.codexHome, restartRequired: true };

‎tests/native-profile-api.test.ts‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import { tmpdir } from "node:os";
44
import type { OcxConfig } from "../src/types";
55
import { handleNativeProfileAPI } from "../src/codex/native-profile-api";
66
import type { NativeProfileManager } from "../src/codex/native-profile-manager";
7+
import { NativeProfileError } from "../src/codex/native-profile-types";
78
import { setDraining, tryAdmitTurn } from "../src/server/lifecycle";
89

910
const originalCodexHome = process.env.CODEX_HOME;
@@ -112,4 +113,20 @@ describe("native main profile management API", () => {
112113
expect(payload).not.toContain(missingHome);
113114
expect(payload).not.toContain(process.env.USERNAME ?? "Administrator");
114115
});
116+
117+
test("pending-recovery errors retain actionable public recovery commands", async () => {
118+
const message = "A native-profile recovery journal is pending. Run `ocx account main recover` or `ocx account main recover --rollback --yes` before registering or adding profiles.";
119+
const manager = {
120+
register: async () => { throw new NativeProfileError("RECOVERY_REQUIRED", message, 409); },
121+
} as unknown as NativeProfileManager;
122+
const request = new Request("http://localhost/api/native-main-profiles/register", {
123+
method: "POST",
124+
body: JSON.stringify({ label: "personal" }),
125+
});
126+
127+
const response = await handleNativeProfileAPI(request, new URL(request.url), {} as OcxConfig, { manager });
128+
129+
expect(response?.status).toBe(409);
130+
expect(await response?.json()).toMatchObject({ code: "RECOVERY_REQUIRED", error: message });
131+
});
115132
});

‎tests/native-profile-manager.test.ts‎

Lines changed: 143 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,9 @@
11
import { afterEach, describe, expect, test } from "bun:test";
2-
import { existsSync, mkdirSync, mkdtempSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
2+
import { existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, renameSync, rmSync, writeFileSync } from "node:fs";
33
import { tmpdir } from "node:os";
44
import { dirname, join } from "node:path";
55
import { NativeProfileManager } from "../src/codex/native-profile-manager";
6+
import { decryptNativeEnvelope, readNativeProfileVault } from "../src/codex/native-profile-store";
67
import { NativeProfileError, type NativeProfileKey, type NativeProfileKeyProvider } from "../src/codex/native-profile-types";
78

89
const roots: string[] = [];
@@ -70,6 +71,31 @@ async function enrolledFixture() {
7071
return { ...f, manager, sourceProfile: sourceProfile.profile, targetProfile: targetProfile.profile, stage };
7172
}
7273

74+
async function leavePendingJournal(f: Awaited<ReturnType<typeof enrolledFixture>>): Promise<NativeProfileManager> {
75+
const authPath = f.manager.context.authPath;
76+
const journalPath = f.manager.context.journalPath;
77+
let authWrites = 0;
78+
const interrupted = new NativeProfileManager({
79+
...f.options,
80+
atomicWrite: async (path, content) => {
81+
if (path === authPath) {
82+
authWrites += 1;
83+
if (authWrites > 1) throw new Error("injected restore failure");
84+
}
85+
if (path === journalPath && content.includes('"phase": "auth-replaced"')) {
86+
throw new Error("injected post-replacement failure");
87+
}
88+
return atomic(path, content);
89+
},
90+
});
91+
let caught: unknown;
92+
try { await interrupted.switch("work", true); } catch (error) { caught = error; }
93+
expect(caught).toBeInstanceOf(NativeProfileError);
94+
expect((caught as NativeProfileError).code).toBe("AUTH_RESTORE_FAILED");
95+
expect(existsSync(journalPath)).toBe(true);
96+
return interrupted;
97+
}
98+
7399
async function waitForPath(path: string): Promise<void> {
74100
const deadline = Date.now() + 5_000;
75101
while (!existsSync(path) && Date.now() < deadline) await Bun.sleep(10);
@@ -363,6 +389,122 @@ describe("native main profile transactions", () => {
363389
expect(existsSync(journalPath)).toBe(true);
364390
});
365391

392+
test("pending recovery blocks register before auth or vault mutation", async () => {
393+
const f = await enrolledFixture();
394+
await leavePendingJournal(f);
395+
const authBefore = readFileSync(f.manager.context.authPath, "utf8");
396+
const vaultBefore = readFileSync(f.manager.context.vaultPath, "utf8");
397+
const journalBefore = readFileSync(f.manager.context.journalPath, "utf8");
398+
399+
let caught: unknown;
400+
try { await f.manager.register("renamed"); } catch (error) { caught = error; }
401+
402+
expect(caught).toBeInstanceOf(NativeProfileError);
403+
expect((caught as NativeProfileError).code).toBe("RECOVERY_REQUIRED");
404+
expect((caught as NativeProfileError).message).toContain("ocx account main recover");
405+
expect(readFileSync(f.manager.context.authPath, "utf8")).toBe(authBefore);
406+
expect(readFileSync(f.manager.context.vaultPath, "utf8")).toBe(vaultBefore);
407+
expect(readFileSync(f.manager.context.journalPath, "utf8")).toBe(journalBefore);
408+
});
409+
410+
test("pending recovery blocks prepareStage before creating staging plaintext", async () => {
411+
const f = await enrolledFixture();
412+
await leavePendingJournal(f);
413+
const authBefore = readFileSync(f.manager.context.authPath, "utf8");
414+
const vaultBefore = readFileSync(f.manager.context.vaultPath, "utf8");
415+
const journalBefore = readFileSync(f.manager.context.journalPath, "utf8");
416+
const stagingBefore = readdirSync(f.manager.context.stagingRoot);
417+
418+
let caught: unknown;
419+
try { await f.manager.prepareStage(); } catch (error) { caught = error; }
420+
421+
expect(caught).toBeInstanceOf(NativeProfileError);
422+
expect((caught as NativeProfileError).code).toBe("RECOVERY_REQUIRED");
423+
expect(readdirSync(f.manager.context.stagingRoot)).toEqual(stagingBefore);
424+
expect(readFileSync(f.manager.context.authPath, "utf8")).toBe(authBefore);
425+
expect(readFileSync(f.manager.context.vaultPath, "utf8")).toBe(vaultBefore);
426+
expect(readFileSync(f.manager.context.journalPath, "utf8")).toBe(journalBefore);
427+
});
428+
429+
test("pending recovery blocks finishStage without deleting staged plaintext", async () => {
430+
const f = await enrolledFixture();
431+
const stage = await f.manager.prepareStage();
432+
const stagedEnvelope = envelope("account-third", "third");
433+
writeFileSync(join(stage.stagingCodexHome, "auth.json"), stagedEnvelope);
434+
await leavePendingJournal(f);
435+
const authBefore = readFileSync(f.manager.context.authPath, "utf8");
436+
const vaultBefore = readFileSync(f.manager.context.vaultPath, "utf8");
437+
const journalBefore = readFileSync(f.manager.context.journalPath, "utf8");
438+
439+
let caught: unknown;
440+
try { await f.manager.finishStage(stage.stageId, "third"); } catch (error) { caught = error; }
441+
442+
expect(caught).toBeInstanceOf(NativeProfileError);
443+
expect((caught as NativeProfileError).code).toBe("RECOVERY_REQUIRED");
444+
expect(readFileSync(join(stage.stagingCodexHome, "auth.json"), "utf8")).toBe(stagedEnvelope);
445+
expect(readFileSync(f.manager.context.authPath, "utf8")).toBe(authBefore);
446+
expect(readFileSync(f.manager.context.vaultPath, "utf8")).toBe(vaultBefore);
447+
expect(readFileSync(f.manager.context.journalPath, "utf8")).toBe(journalBefore);
448+
});
449+
450+
test("explicit rollback preserves a digest-changed target envelope before restoring source auth", async () => {
451+
const f = await enrolledFixture();
452+
await leavePendingJournal(f);
453+
const refreshedTarget = envelope("account-target", "target-refreshed");
454+
writeFileSync(f.manager.context.authPath, refreshedTarget);
455+
456+
const result = await f.manager.recover(true, true);
457+
458+
expect(result).toMatchObject({ recovered: true, action: "rollback-source", restartRequired: true });
459+
expect(readFileSync(f.manager.context.authPath, "utf8")).toBe(f.source);
460+
expect(existsSync(f.manager.context.journalPath)).toBe(false);
461+
const vaultText = readFileSync(f.manager.context.vaultPath, "utf8");
462+
expect(vaultText).not.toContain("target-refreshed");
463+
expect(vaultText).not.toContain("opaque-access-target-refreshed");
464+
expect(vaultText).not.toContain("opaque-refresh-target-refreshed");
465+
const vault = readNativeProfileVault(f.manager.context)!;
466+
expect(vault.activeProfileId).toBe(f.sourceProfile.id);
467+
const targetProfile = vault.profiles.find(profile => profile.id === f.targetProfile.id)!;
468+
expect(targetProfile.state).toBe("inactive");
469+
const key = await f.keyProvider.get(f.manager.context.homeId);
470+
expect(key).not.toBeNull();
471+
const decrypted = decryptNativeEnvelope(
472+
f.manager.context,
473+
targetProfile.id,
474+
targetProfile.identityHash,
475+
targetProfile.payload!,
476+
key!,
477+
);
478+
try { expect(decrypted.text).toBe(refreshedTarget); } finally { decrypted.raw.fill(0); key!.key.fill(0); }
479+
expect(f.transitions).toEqual(["account-target->account-source"]);
480+
});
481+
482+
test("rollback preservation failure leaves refreshed target auth untouched and journaled", async () => {
483+
const f = await enrolledFixture();
484+
await leavePendingJournal(f);
485+
const refreshedTarget = envelope("account-target", "target-refreshed-failure");
486+
writeFileSync(f.manager.context.authPath, refreshedTarget);
487+
const vaultBefore = readFileSync(f.manager.context.vaultPath, "utf8");
488+
const failing = new NativeProfileManager({
489+
...f.options,
490+
atomicWrite: async (path, content) => {
491+
if (path === f.manager.context.vaultPath) throw new Error("injected rollback vault failure");
492+
return atomic(path, content);
493+
},
494+
});
495+
496+
let caught: unknown;
497+
try { await failing.recover(true, true); } catch (error) { caught = error; }
498+
499+
expect(caught).toBeInstanceOf(Error);
500+
expect(readFileSync(f.manager.context.authPath, "utf8")).toBe(refreshedTarget);
501+
expect(readFileSync(f.manager.context.vaultPath, "utf8")).toBe(vaultBefore);
502+
expect(existsSync(f.manager.context.journalPath)).toBe(true);
503+
const journalText = readFileSync(f.manager.context.journalPath, "utf8");
504+
expect(journalText).not.toContain("target-refreshed-failure");
505+
expect(journalText).not.toContain("opaque-refresh-target-refreshed-failure");
506+
});
507+
366508
test("non-file Codex credential stores fail before vault or auth mutation", async () => {
367509
const f = fixture();
368510
writeFileSync(join(f.codexHome, "config.toml"), 'cli_auth_credentials_store = "auto"\n');

0 commit comments

Comments
 (0)