Skip to content

Commit ea8187d

Browse files
committed
fix(codex): preserve symlinked native auth targets
1 parent 9cf74b6 commit ea8187d

3 files changed

Lines changed: 208 additions & 19 deletions

File tree

‎src/codex/main-account.ts‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ import {
1111
import type { OAuthCredentials } from "../oauth/types";
1212
import { extractChatgptPlanType } from "./plan";
1313
import { MAIN_CODEX_ACCOUNT_ID } from "./account-id";
14+
import { resolveWriteTarget } from "../config/atomic-write";
1415
import { resolveCodexHomeDir } from "./home";
1516
import { assertNotRealCodexHomeUnderTest } from "../lib/test-home-guard";
1617
import { clearAccountNeedsReauth } from "./account-runtime-state";
@@ -95,7 +96,7 @@ function nonEmptyString(value: unknown): string | undefined {
9596
}
9697

9798
function readMainAuthJsonCredential(): MainAuthJsonCredential | null {
98-
const path = join(resolveCodexHomeDir(), "auth.json");
99+
const path = resolveWriteTarget(join(resolveCodexHomeDir(), "auth.json"));
99100
let raw: string;
100101
try {
101102
raw = readFileSync(path, "utf8");
@@ -177,7 +178,7 @@ function persistRefreshedMainAuthJson(
177178
beforeMainAuthJsonRenameForTests = null;
178179
hook?.();
179180
assertMainAuthJsonSnapshotUnchanged(expected);
180-
publishNativeMainRefresh(context, expected.raw, JSON.stringify({ ...expected.root, tokens }, null, 2) + "\n");
181+
publishNativeMainRefresh(context, expected.path, expected.raw, JSON.stringify({ ...expected.root, tokens }, null, 2) + "\n");
181182
return { accessToken, chatgptAccountId };
182183
}
183184

‎src/codex/native-main-refresh-publication.ts‎

Lines changed: 37 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import { createHash, randomUUID } from "node:crypto";
22
import { closeSync, existsSync, fsyncSync, openSync, readFileSync, unlinkSync } from "node:fs";
3-
import { basename, join } from "node:path";
4-
import { atomicWriteFile } from "../config/atomic-write";
3+
import { basename, dirname, join } from "node:path";
4+
import { atomicWriteFile, resolveWriteTarget } from "../config/atomic-write";
55
import { PreservingReplaceError, replaceFilePreservingTarget, restoreFilePreservingTarget } from "../lib/atomic-file-preserving-replace";
66
import type { NativeProfileContext } from "./native-profile-store";
77

@@ -11,6 +11,7 @@ const TRANSACTION_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-
1111
type Journal = {
1212
version: 1;
1313
transactionId: string;
14+
targetPath: string;
1415
stagedBasename: string;
1516
previousBasename: string;
1617
phase: "prepared" | "replaced";
@@ -44,6 +45,8 @@ function validJournal(value: unknown): value is Journal {
4445
const transactionId = typeof item.transactionId === "string" ? item.transactionId : "";
4546
return item.version === 1
4647
&& TRANSACTION_ID.test(transactionId)
48+
&& typeof item.targetPath === "string"
49+
&& item.targetPath.length > 0
4750
&& item.stagedBasename === `.opencodex-native-main-refresh.${transactionId}.new`
4851
&& item.previousBasename === `.opencodex-native-main-refresh.${transactionId}.previous`
4952
&& (item.phase === "prepared" || item.phase === "replaced")
@@ -60,15 +63,28 @@ function removeExact(path: string): void {
6063
try { unlinkSync(path); } catch (cause) { throw new NativeMainRefreshPublicationError({ cause }); }
6164
}
6265

63-
function journalPaths(context: NativeProfileContext, journal: Journal): { staged: string; previous: string } {
66+
function resolveAuthTarget(context: NativeProfileContext): string {
67+
try {
68+
return resolveWriteTarget(context.authPath);
69+
} catch (cause) {
70+
throw new NativeMainRefreshPublicationError({ cause });
71+
}
72+
}
73+
74+
function assertAuthTarget(context: NativeProfileContext, expectedTarget: string): void {
75+
if (resolveAuthTarget(context) !== expectedTarget) throw new NativeMainRefreshPublicationError();
76+
}
77+
78+
function journalPaths(journal: Journal): { staged: string; previous: string } {
79+
const targetDir = dirname(journal.targetPath);
6480
return {
65-
staged: join(context.codexHome, journal.stagedBasename),
66-
previous: join(context.codexHome, journal.previousBasename),
81+
staged: join(targetDir, journal.stagedBasename),
82+
previous: join(targetDir, journal.previousBasename),
6783
};
6884
}
6985

7086
function cleanup(context: NativeProfileContext, journal: Journal): void {
71-
const { staged, previous } = journalPaths(context, journal);
87+
const { staged, previous } = journalPaths(journal);
7288
for (const path of [staged, previous, journalPath(context)]) {
7389
if (existsSync(path)) removeExact(path);
7490
}
@@ -81,13 +97,14 @@ export function recoverNativeMainRefreshPublication(context: NativeProfileContex
8197
let journal: Journal;
8298
try { journal = JSON.parse(readFileSync(path, "utf8")) as Journal; } catch (cause) { throw new NativeMainRefreshPublicationError({ cause }); }
8399
if (!validJournal(journal)) throw new NativeMainRefreshPublicationError();
84-
const { staged, previous } = journalPaths(context, journal);
85-
const canonical = readExact(context.authPath);
100+
assertAuthTarget(context, journal.targetPath);
101+
const { staged, previous } = journalPaths(journal);
102+
const canonical = readExact(journal.targetPath);
86103
const stagedBytes = readExact(staged);
87104
if (!canonical) throw new NativeMainRefreshPublicationError();
88105
if (digest(canonical) === journal.expectedSha256 && stagedBytes && digest(stagedBytes) === journal.replacementSha256) {
89106
try {
90-
replaceFilePreservingTarget(staged, context.authPath, previous);
107+
replaceFilePreservingTarget(staged, journal.targetPath, previous);
91108
cleanup(context, { ...journal, phase: "replaced" });
92109
} catch (cause) {
93110
throw new NativeMainRefreshPublicationError({ cause });
@@ -104,6 +121,7 @@ export function recoverNativeMainRefreshPublication(context: NativeProfileContex
104121
/** The sole native-main auth.json publisher. */
105122
export function publishNativeMainRefresh(
106123
context: NativeProfileContext,
124+
targetPath: string,
107125
expected: string,
108126
replacement: string,
109127
): void {
@@ -113,33 +131,36 @@ export function publishNativeMainRefresh(
113131
const journal: Journal = {
114132
version: 1,
115133
transactionId: tx,
134+
targetPath,
116135
stagedBasename,
117136
previousBasename,
118137
phase: "prepared",
119138
expectedSha256: digest(expected),
120139
replacementSha256: digest(replacement),
121140
};
122-
const staged = join(context.codexHome, stagedBasename);
123-
const previous = join(context.codexHome, previousBasename);
141+
const { staged, previous } = journalPaths(journal);
124142
try {
125-
if (digest(readFileSync(context.authPath)) !== journal.expectedSha256) throw new NativeMainRefreshPublicationError();
143+
assertAuthTarget(context, targetPath);
144+
if (digest(readFileSync(targetPath)) !== journal.expectedSha256) throw new NativeMainRefreshPublicationError();
126145
atomicWriteFile(staged, replacement);
127146
fsync(staged);
128147
atomicWriteFile(journalPath(context), `${JSON.stringify(journal)}\n`);
129-
replaceFilePreservingTarget(staged, context.authPath, previous);
148+
assertAuthTarget(context, targetPath);
149+
if (digest(readFileSync(targetPath)) !== journal.expectedSha256) throw new NativeMainRefreshPublicationError();
150+
replaceFilePreservingTarget(staged, targetPath, previous);
130151
const displaced = readExact(process.platform === "win32" ? previous : staged);
131152
if (!displaced || digest(displaced) !== journal.expectedSha256) {
132-
const canonical = readExact(context.authPath);
153+
const canonical = readExact(targetPath);
133154
if (canonical && digest(canonical) === journal.replacementSha256) {
134155
restoreFilePreservingTarget(
135156
process.platform === "win32" ? previous : staged,
136-
context.authPath,
157+
targetPath,
137158
process.platform === "win32" ? staged : previous,
138159
);
139160
}
140161
throw new NativeMainRefreshPublicationError();
141162
}
142-
const canonical = readExact(context.authPath);
163+
const canonical = readExact(targetPath);
143164
if (!canonical || digest(canonical) !== journal.replacementSha256) {
144165
throw new NativeMainRefreshPublicationError();
145166
}

‎tests/codex-main-account-refresh.test.ts‎

Lines changed: 168 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,18 @@
11
import { afterEach, beforeEach, describe, expect, test } from "bun:test";
22
import { createHash } from "node:crypto";
3-
import { existsSync, mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from "node:fs";
3+
import {
4+
existsSync,
5+
lstatSync,
6+
mkdirSync,
7+
mkdtempSync,
8+
readFileSync,
9+
readdirSync,
10+
readlinkSync,
11+
rmSync,
12+
symlinkSync,
13+
unlinkSync,
14+
writeFileSync,
15+
} from "node:fs";
416
import { tmpdir } from "node:os";
517
import { join } from "node:path";
618
import {
@@ -16,6 +28,19 @@ import { resolveNativeProfileContext } from "../src/codex/native-profile-store";
1628
let home: string;
1729
let previousCodexHome: string | undefined;
1830

31+
const canSymlink = (() => {
32+
const dir = mkdtempSync(join(tmpdir(), "ocx-main-refresh-symlink-probe-"));
33+
try {
34+
symlinkSync(join(dir, "probe-target"), join(dir, "probe-link"));
35+
return true;
36+
} catch (error) {
37+
if ((error as NodeJS.ErrnoException).code === "EPERM") return false;
38+
throw error;
39+
} finally {
40+
rmSync(dir, { recursive: true, force: true });
41+
}
42+
})();
43+
1944
function expiredJwt(): string {
2045
const payload = Buffer.from(JSON.stringify({ exp: Math.floor(Date.now() / 1000) - 60 })).toString("base64url");
2146
return `header.${payload}.signature`;
@@ -78,6 +103,73 @@ describe("native main token refresh", () => {
78103
expect(readdirSync(home).filter(name => name.includes(".tmp"))).toEqual([]);
79104
});
80105

106+
test.skipIf(!canSymlink)("preserves a symlinked auth file and rotates its canonical target", async () => {
107+
const managedDir = join(home, "dotfiles");
108+
const targetPath = join(managedDir, "auth.json");
109+
const authPath = join(home, "auth.json");
110+
mkdirSync(managedDir);
111+
writeFileSync(targetPath, JSON.stringify({
112+
tokens: {
113+
access_token: expiredJwt(),
114+
refresh_token: "old-refresh",
115+
account_id: "account-main",
116+
},
117+
}));
118+
symlinkSync(targetPath, authPath);
119+
120+
await expect(getValidMainAccountToken({
121+
refreshToken: async () => ({
122+
access: "new-access",
123+
refresh: "rotated-refresh",
124+
expires: Date.now() + 3_600_000,
125+
accountId: "account-main",
126+
}),
127+
})).resolves.toEqual({ accessToken: "new-access", chatgptAccountId: "account-main" });
128+
129+
expect(lstatSync(authPath).isSymbolicLink()).toBe(true);
130+
expect(readlinkSync(authPath)).toBe(targetPath);
131+
expect(JSON.parse(readFileSync(targetPath, "utf8")).tokens).toMatchObject({
132+
access_token: "new-access",
133+
refresh_token: "rotated-refresh",
134+
});
135+
expect(readdirSync(managedDir).filter(name => name.startsWith(".opencodex-native-main-refresh."))).toEqual([]);
136+
});
137+
138+
test.skipIf(!canSymlink)("fails closed when the auth symlink is retargeted during refresh", async () => {
139+
const authPath = join(home, "auth.json");
140+
const firstTarget = join(home, "first-auth.json");
141+
const secondTarget = join(home, "second-auth.json");
142+
const original = JSON.stringify({
143+
tokens: {
144+
access_token: expiredJwt(),
145+
refresh_token: "old-refresh",
146+
account_id: "account-main",
147+
},
148+
});
149+
const external = JSON.stringify({ tokens: { access_token: "external-access" } });
150+
writeFileSync(firstTarget, original);
151+
writeFileSync(secondTarget, external);
152+
symlinkSync(firstTarget, authPath);
153+
setMainAuthJsonBeforeRenameHookForTests(() => {
154+
unlinkSync(authPath);
155+
symlinkSync(secondTarget, authPath);
156+
});
157+
158+
await expect(getValidMainAccountToken({
159+
refreshToken: async () => ({
160+
access: "new-access",
161+
refresh: "rotated-refresh",
162+
expires: Date.now() + 3_600_000,
163+
accountId: "account-main",
164+
}),
165+
})).rejects.toThrow("changed while its token was refreshing");
166+
167+
expect(lstatSync(authPath).isSymbolicLink()).toBe(true);
168+
expect(readlinkSync(authPath)).toBe(secondTarget);
169+
expect(readFileSync(firstTarget, "utf8")).toBe(original);
170+
expect(readFileSync(secondTarget, "utf8")).toBe(external);
171+
});
172+
81173
test("refuses to overwrite an external auth writer after refresh", async () => {
82174
const authPath = join(home, "auth.json");
83175
writeFileSync(authPath, JSON.stringify({
@@ -154,6 +246,7 @@ describe("native main token refresh", () => {
154246
writeFileSync(journalPath, JSON.stringify({
155247
version: 1,
156248
transactionId: "22222222-2222-4222-8222-222222222222",
249+
targetPath: authPath,
157250
stagedBasename,
158251
previousBasename: `.opencodex-native-main-refresh.${fileTransactionId}.previous`,
159252
phase: "prepared",
@@ -188,6 +281,7 @@ describe("native main token refresh", () => {
188281
writeFileSync(journalPath, JSON.stringify({
189282
version: 1,
190283
transactionId,
284+
targetPath: authPath,
191285
stagedBasename,
192286
previousBasename: `.opencodex-native-main-refresh.${transactionId}.previous`,
193287
phase: "prepared",
@@ -346,6 +440,78 @@ describe("native main token refresh", () => {
346440
expect(attempts).toBe(2);
347441
});
348442

443+
test.skipIf(!canSymlink)("recovers a prepared publication through the original symlink target", () => {
444+
const managedDir = join(home, "dotfiles-recovery");
445+
const targetPath = join(managedDir, "auth.json");
446+
const authPath = join(home, "auth.json");
447+
const transactionId = "11111111-1111-4111-8111-111111111111";
448+
const stagedBasename = `.opencodex-native-main-refresh.${transactionId}.new`;
449+
const previousBasename = `.opencodex-native-main-refresh.${transactionId}.previous`;
450+
const original = JSON.stringify({ tokens: { refresh_token: "old-refresh", account_id: "account-main" } });
451+
const replacement = JSON.stringify({ tokens: { access_token: "new-access", refresh_token: "new-refresh" } });
452+
const digest = (value: string) => createHash("sha256").update(value).digest("hex");
453+
mkdirSync(managedDir);
454+
writeFileSync(targetPath, original);
455+
symlinkSync(targetPath, authPath);
456+
writeFileSync(join(managedDir, stagedBasename), replacement);
457+
writeFileSync(join(home, ".opencodex-native-main-refresh.json"), JSON.stringify({
458+
version: 1,
459+
transactionId,
460+
targetPath,
461+
stagedBasename,
462+
previousBasename,
463+
phase: "prepared",
464+
expectedSha256: digest(original),
465+
replacementSha256: digest(replacement),
466+
}));
467+
468+
recoverNativeMainRefreshPublication(resolveNativeProfileContext());
469+
470+
expect(lstatSync(authPath).isSymbolicLink()).toBe(true);
471+
expect(readlinkSync(authPath)).toBe(targetPath);
472+
expect(readFileSync(targetPath, "utf8")).toBe(replacement);
473+
expect(readdirSync(managedDir)).toEqual(["auth.json"]);
474+
expect(existsSync(join(home, ".opencodex-native-main-refresh.json"))).toBe(false);
475+
});
476+
477+
test.skipIf(!canSymlink)("refuses recovery after the auth symlink target changes", () => {
478+
const authPath = join(home, "auth.json");
479+
const firstTarget = join(home, "first-auth.json");
480+
const secondTarget = join(home, "second-auth.json");
481+
const transactionId = "11111111-1111-4111-8111-111111111111";
482+
const stagedBasename = `.opencodex-native-main-refresh.${transactionId}.new`;
483+
const previousBasename = `.opencodex-native-main-refresh.${transactionId}.previous`;
484+
const journalPath = join(home, ".opencodex-native-main-refresh.json");
485+
const original = JSON.stringify({ tokens: { refresh_token: "old-refresh", account_id: "account-main" } });
486+
const replacement = JSON.stringify({ tokens: { access_token: "new-access", refresh_token: "new-refresh" } });
487+
const external = JSON.stringify({ tokens: { access_token: "external-access" } });
488+
const digest = (value: string) => createHash("sha256").update(value).digest("hex");
489+
writeFileSync(firstTarget, original);
490+
writeFileSync(secondTarget, external);
491+
symlinkSync(secondTarget, authPath);
492+
writeFileSync(join(home, stagedBasename), replacement);
493+
writeFileSync(journalPath, JSON.stringify({
494+
version: 1,
495+
transactionId,
496+
targetPath: firstTarget,
497+
stagedBasename,
498+
previousBasename,
499+
phase: "prepared",
500+
expectedSha256: digest(original),
501+
replacementSha256: digest(replacement),
502+
}));
503+
504+
expect(() => recoverNativeMainRefreshPublication(resolveNativeProfileContext())).toThrow(
505+
"Native credential refresh could not be published",
506+
);
507+
508+
expect(readlinkSync(authPath)).toBe(secondTarget);
509+
expect(readFileSync(firstTarget, "utf8")).toBe(original);
510+
expect(readFileSync(secondTarget, "utf8")).toBe(external);
511+
expect(existsSync(journalPath)).toBe(true);
512+
expect(existsSync(join(home, stagedBasename))).toBe(true);
513+
});
514+
349515
test("cleans committed recovery journals with zero, one, and multiple exact remnants", () => {
350516
const original = JSON.stringify({ tokens: { refresh_token: "old-refresh", account_id: "account-main" } });
351517
const replacement = JSON.stringify({ tokens: { access_token: "access-b", refresh_token: "refresh-b", account_id: "account-main" } });
@@ -363,6 +529,7 @@ describe("native main token refresh", () => {
363529
writeFileSync(journalPath, JSON.stringify({
364530
version: 1,
365531
transactionId: testCase.transactionId,
532+
targetPath: join(home, "auth.json"),
366533
stagedBasename: staged,
367534
previousBasename: previous,
368535
phase: "replaced",

0 commit comments

Comments
 (0)