Skip to content

Commit 9cf74b6

Browse files
committed
fix(codex): harden native main refresh recovery
1 parent 34319ac commit 9cf74b6

9 files changed

Lines changed: 485 additions & 61 deletions

‎src/codex/main-account.ts‎

Lines changed: 30 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -56,10 +56,15 @@ export interface NativeMainRefreshDependencies {
5656
type NativeMainRefreshFlight = {
5757
controller: AbortController;
5858
deadline: ReturnType<typeof setTimeout>;
59-
waiters: number;
6059
promise: Promise<{ accessToken: string; chatgptAccountId: string }>;
6160
};
6261

62+
type NativeMainRefreshResolution = {
63+
dependencies: NativeMainRefreshDependencies;
64+
rejectedAccessToken: string | undefined;
65+
replacementAttempted: boolean;
66+
};
67+
6368
const nativeMainRefreshFlights = new Map<string, NativeMainRefreshFlight>();
6469

6570
export class MainAuthJsonChangedDuringRefreshError extends Error {
@@ -183,6 +188,7 @@ export function setMainAuthJsonBeforeRenameHookForTests(hook: (() => void) | nul
183188
async function resolveMainAccountToken(
184189
dependencies: NativeMainRefreshDependencies = {},
185190
rejectedAccessToken?: string,
191+
replacementAttempted = false,
186192
): Promise<{ accessToken: string; chatgptAccountId: string } | null> {
187193
const initial = readMainAuthJsonCredential();
188194
if (!initial) return null;
@@ -200,7 +206,8 @@ async function resolveMainAccountToken(
200206

201207
const context = resolveNativeProfileContext();
202208
const current = nativeMainRefreshFlights.get(context.homeId);
203-
if (current) return await waitForNativeMainRefresh(current, dependencies.signal);
209+
const resolution = { dependencies, rejectedAccessToken, replacementAttempted };
210+
if (current) return await resolveNativeMainRefreshFlight(context, current, resolution);
204211
if (nativeMainRefreshFlights.size >= MAX_NATIVE_MAIN_REFRESH_FLIGHTS) {
205212
throw new MainAccountTokenRefreshError("transient");
206213
}
@@ -209,15 +216,28 @@ async function resolveMainAccountToken(
209216
const flight: NativeMainRefreshFlight = {
210217
controller,
211218
deadline,
212-
waiters: 0,
213219
promise: runNativeMainRefreshFlight(context, dependencies, rejectedAccessToken, controller.signal),
214220
};
215221
nativeMainRefreshFlights.set(context.homeId, flight);
216222
flight.promise.finally(() => {
217223
clearTimeout(flight.deadline);
218224
if (nativeMainRefreshFlights.get(context.homeId) === flight) nativeMainRefreshFlights.delete(context.homeId);
219225
}).catch(() => undefined);
220-
return await waitForNativeMainRefresh(flight, dependencies.signal);
226+
return await resolveNativeMainRefreshFlight(context, flight, resolution);
227+
}
228+
229+
async function resolveNativeMainRefreshFlight(
230+
context: NativeProfileContext,
231+
flight: NativeMainRefreshFlight,
232+
resolution: NativeMainRefreshResolution,
233+
): Promise<{ accessToken: string; chatgptAccountId: string }> {
234+
const result = await waitForNativeMainRefresh(flight, resolution.dependencies.signal);
235+
if (resolution.rejectedAccessToken === undefined || result.accessToken !== resolution.rejectedAccessToken) return result;
236+
if (resolution.replacementAttempted) throw new MainAccountTokenRefreshError("transient");
237+
if (nativeMainRefreshFlights.get(context.homeId) === flight) nativeMainRefreshFlights.delete(context.homeId);
238+
const replacement = await resolveMainAccountToken(resolution.dependencies, resolution.rejectedAccessToken, true);
239+
if (!replacement) throw new MainAccountTokenRefreshError("transient");
240+
return replacement;
221241
}
222242

223243
function abortError(_signal: AbortSignal): MainAccountRefreshCancelledError {
@@ -228,18 +248,12 @@ async function waitForNativeMainRefresh(
228248
flight: NativeMainRefreshFlight,
229249
signal: AbortSignal | undefined,
230250
): Promise<{ accessToken: string; chatgptAccountId: string }> {
231-
flight.waiters += 1;
232-
try {
233-
if (!signal) return await flight.promise;
234-
if (signal.aborted) throw abortError(signal);
235-
return await Promise.race([
236-
flight.promise,
237-
new Promise<never>((_resolve, reject) => signal.addEventListener("abort", () => reject(abortError(signal)), { once: true })),
238-
]);
239-
} finally {
240-
flight.waiters -= 1;
241-
if (flight.waiters === 0) flight.controller.abort();
242-
}
251+
if (!signal) return await flight.promise;
252+
if (signal.aborted) throw abortError(signal);
253+
return await Promise.race([
254+
flight.promise,
255+
new Promise<never>((_resolve, reject) => signal.addEventListener("abort", () => reject(abortError(signal)), { once: true })),
256+
]);
243257
}
244258

245259
async function runNativeMainRefreshFlight(

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

Lines changed: 17 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -19,8 +19,8 @@ type Journal = {
1919
};
2020

2121
export class NativeMainRefreshPublicationError extends Error {
22-
constructor() {
23-
super("Native credential refresh could not be published.");
22+
constructor(options?: ErrorOptions) {
23+
super("Native credential refresh could not be published.", options);
2424
this.name = "NativeMainRefreshPublicationError";
2525
}
2626
}
@@ -30,7 +30,7 @@ function digest(value: string | Buffer): string {
3030
}
3131

3232
function fsync(path: string): void {
33-
const fd = openSync(path, "r");
33+
const fd = openSync(path, "r+");
3434
try { fsyncSync(fd); } finally { closeSync(fd); }
3535
}
3636

@@ -57,7 +57,7 @@ function readExact(path: string): Buffer | null {
5757
}
5858

5959
function removeExact(path: string): void {
60-
try { unlinkSync(path); } catch { throw new NativeMainRefreshPublicationError(); }
60+
try { unlinkSync(path); } catch (cause) { throw new NativeMainRefreshPublicationError({ cause }); }
6161
}
6262

6363
function journalPaths(context: NativeProfileContext, journal: Journal): { staged: string; previous: string } {
@@ -79,22 +79,23 @@ export function recoverNativeMainRefreshPublication(context: NativeProfileContex
7979
const path = journalPath(context);
8080
if (!existsSync(path)) return;
8181
let journal: Journal;
82-
try { journal = JSON.parse(readFileSync(path, "utf8")) as Journal; } catch { throw new NativeMainRefreshPublicationError(); }
82+
try { journal = JSON.parse(readFileSync(path, "utf8")) as Journal; } catch (cause) { throw new NativeMainRefreshPublicationError({ cause }); }
8383
if (!validJournal(journal)) throw new NativeMainRefreshPublicationError();
8484
const { staged, previous } = journalPaths(context, journal);
8585
const canonical = readExact(context.authPath);
8686
const stagedBytes = readExact(staged);
87-
const previousBytes = readExact(previous);
8887
if (!canonical) throw new NativeMainRefreshPublicationError();
8988
if (digest(canonical) === journal.expectedSha256 && stagedBytes && digest(stagedBytes) === journal.replacementSha256) {
90-
replaceFilePreservingTarget(staged, context.authPath, previous);
91-
cleanup(context, { ...journal, phase: "replaced" });
89+
try {
90+
replaceFilePreservingTarget(staged, context.authPath, previous);
91+
cleanup(context, { ...journal, phase: "replaced" });
92+
} catch (cause) {
93+
throw new NativeMainRefreshPublicationError({ cause });
94+
}
9295
return;
9396
}
94-
if (digest(canonical) === journal.replacementSha256
95-
&& ((stagedBytes && digest(stagedBytes) === journal.expectedSha256)
96-
|| (previousBytes && digest(previousBytes) === journal.expectedSha256))) {
97-
cleanup(context, journal);
97+
if (digest(canonical) === journal.replacementSha256) {
98+
try { cleanup(context, journal); } catch (cause) { throw new NativeMainRefreshPublicationError({ cause }); }
9899
return;
99100
}
100101
throw new NativeMainRefreshPublicationError();
@@ -144,11 +145,10 @@ export function publishNativeMainRefresh(
144145
}
145146
atomicWriteFile(journalPath(context), `${JSON.stringify({ ...journal, phase: "replaced" })}\n`);
146147
cleanup(context, journal);
147-
} catch (error) {
148-
if (error instanceof NativeMainRefreshPublicationError || error instanceof PreservingReplaceError) {
149-
throw new NativeMainRefreshPublicationError();
150-
}
151-
throw new NativeMainRefreshPublicationError();
148+
} catch (cause) {
149+
if (cause instanceof NativeMainRefreshPublicationError) throw cause;
150+
if (cause instanceof PreservingReplaceError) throw new NativeMainRefreshPublicationError({ cause });
151+
throw new NativeMainRefreshPublicationError({ cause });
152152
}
153153
}
154154

‎src/lib/atomic-file-preserving-replace.ts‎

Lines changed: 82 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -1,77 +1,135 @@
1-
import { dlopen, ptr } from "bun:ffi";
1+
import { dlopen, ptr, read } from "bun:ffi";
22

33
const AT_FDCWD = -100;
44
const RENAME_EXCHANGE = 2;
55
const RENAME_SWAP = 0x00000002;
66

7+
type ReplaceOperation = "renameat2" | "renamex_np" | "ReplaceFileW" | "unsupported";
8+
type NativeExchangeResult =
9+
| { ok: true }
10+
| { ok: false; nativeCode?: number; cause?: unknown };
11+
12+
type FailedReplacementDetails = {
13+
operation: ReplaceOperation;
14+
sourcePath: string;
15+
targetPath: string;
16+
backupPath: string;
17+
result: Extract<NativeExchangeResult, { ok: false }>;
18+
};
19+
720
export class PreservingReplaceError extends Error {
8-
constructor() {
9-
super("Native credential publication could not complete.");
21+
readonly operation: ReplaceOperation;
22+
readonly sourcePath: string;
23+
readonly targetPath: string;
24+
readonly backupPath: string;
25+
readonly platform: NodeJS.Platform;
26+
readonly nativeCode?: number;
27+
28+
constructor(details: {
29+
operation: ReplaceOperation;
30+
sourcePath: string;
31+
targetPath: string;
32+
backupPath: string;
33+
platform: NodeJS.Platform;
34+
nativeCode?: number;
35+
cause?: unknown;
36+
}) {
37+
super("Native credential publication could not complete.", details.cause === undefined ? undefined : { cause: details.cause });
1038
this.name = "PreservingReplaceError";
39+
this.operation = details.operation;
40+
this.sourcePath = details.sourcePath;
41+
this.targetPath = details.targetPath;
42+
this.backupPath = details.backupPath;
43+
this.platform = details.platform;
44+
this.nativeCode = details.nativeCode;
1145
}
1246
}
1347

14-
type Exchange = (source: string, target: string) => boolean;
15-
1648
function cString(value: string): Buffer {
1749
return Buffer.from(`${value}\0`);
1850
}
1951

20-
function unixExchange(symbol: "renameat2" | "renamex_np"): Exchange | null {
52+
function unixExchange(symbol: "renameat2" | "renamex_np"): (source: string, target: string) => NativeExchangeResult {
2153
try {
54+
const errnoSymbol = process.platform === "darwin" ? "__error" : "__errno_location";
2255
const library = dlopen(process.platform === "darwin" ? "/usr/lib/libSystem.B.dylib" : "libc.so.6", {
2356
[symbol]: {
2457
args: symbol === "renameat2" ? ["i32", "cstring", "i32", "cstring", "u32"] : ["cstring", "cstring", "u32"],
2558
returns: "i32",
2659
},
60+
[errnoSymbol]: { args: [], returns: "ptr" },
2761
});
2862
const call = library.symbols[symbol] as (...args: unknown[]) => number;
29-
return (source, target) => symbol === "renameat2"
30-
? call(AT_FDCWD, cString(source), AT_FDCWD, cString(target), RENAME_EXCHANGE) === 0
31-
: call(cString(source), cString(target), RENAME_SWAP) === 0;
32-
} catch {
33-
return null;
63+
const errnoLocation = library.symbols[errnoSymbol] as () => number;
64+
return (source, target) => {
65+
const status = symbol === "renameat2"
66+
? call(AT_FDCWD, cString(source), AT_FDCWD, cString(target), RENAME_EXCHANGE)
67+
: call(cString(source), cString(target), RENAME_SWAP);
68+
if (status === 0) return { ok: true };
69+
return { ok: false, nativeCode: read.i32(errnoLocation()) };
70+
};
71+
} catch (cause) {
72+
return () => ({ ok: false, cause });
3473
}
3574
}
3675

3776
function wide(value: string): Buffer {
3877
return Buffer.from(`${value}\0`, "utf16le");
3978
}
4079

41-
function windowsExchange(source: string, target: string, backup: string): boolean {
80+
function windowsExchange(source: string, target: string, backup: string): NativeExchangeResult {
4281
try {
4382
const library = dlopen("kernel32.dll", {
4483
ReplaceFileW: { args: ["ptr", "ptr", "ptr", "u32", "ptr", "ptr"], returns: "i32" },
84+
GetLastError: { args: [], returns: "u32" },
4585
});
4686
const replacement = wide(source);
4787
const replaced = wide(target);
4888
const privateBackup = wide(backup);
49-
return (library.symbols.ReplaceFileW as (...args: unknown[]) => number)(
89+
const status = (library.symbols.ReplaceFileW as (...args: unknown[]) => number)(
5090
ptr(replaced), ptr(replacement), ptr(privateBackup), 0, null, null,
51-
) !== 0;
52-
} catch {
53-
return false;
91+
);
92+
if (status !== 0) return { ok: true };
93+
return { ok: false, nativeCode: (library.symbols.GetLastError as () => number)() };
94+
} catch (cause) {
95+
return { ok: false, cause };
5496
}
5597
}
5698

99+
function failedReplacement(details: FailedReplacementDetails): PreservingReplaceError {
100+
return new PreservingReplaceError({
101+
operation: details.operation,
102+
sourcePath: details.sourcePath,
103+
targetPath: details.targetPath,
104+
backupPath: details.backupPath,
105+
platform: process.platform,
106+
...(details.result.nativeCode === undefined ? {} : { nativeCode: details.result.nativeCode }),
107+
...(details.result.cause === undefined ? {} : { cause: details.result.cause }),
108+
});
109+
}
110+
57111
/**
58112
* Exchange a staged file with an existing canonical file without a missing-target window.
59113
* On Unix the displaced entry remains at `source`; Windows places it at `backup`.
60114
*/
61115
export function replaceFilePreservingTarget(source: string, target: string, backup: string): void {
62116
if (process.platform === "linux") {
63-
const exchange = unixExchange("renameat2");
64-
if (exchange?.(source, target)) return;
65-
throw new PreservingReplaceError();
117+
const result = unixExchange("renameat2")(source, target);
118+
if (result.ok) return;
119+
throw failedReplacement({ operation: "renameat2", sourcePath: source, targetPath: target, backupPath: backup, result });
66120
}
67121
if (process.platform === "darwin") {
68-
const exchange = unixExchange("renamex_np");
69-
if (exchange?.(source, target)) return;
70-
throw new PreservingReplaceError();
122+
const result = unixExchange("renamex_np")(source, target);
123+
if (result.ok) return;
124+
throw failedReplacement({ operation: "renamex_np", sourcePath: source, targetPath: target, backupPath: backup, result });
125+
}
126+
if (process.platform === "win32") {
127+
const result = windowsExchange(source, target, backup);
128+
if (result.ok) return;
129+
throw failedReplacement({ operation: "ReplaceFileW", sourcePath: source, targetPath: target, backupPath: backup, result });
71130
}
72-
if (process.platform === "win32" && windowsExchange(source, target, backup)) return;
73131
// No rename fallback is safe: it can make auth.json absent between operations.
74-
throw new PreservingReplaceError();
132+
throw failedReplacement({ operation: "unsupported", sourcePath: source, targetPath: target, backupPath: backup, result: { ok: false } });
75133
}
76134

77135
/** Restore a verified displaced entry while preserving the canonical target. */

‎src/oauth/index.ts‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ import { loginXai, refreshXaiToken, XAI_LOCAL_CLI_DETACH_WARNING, XaiTokenReques
99
import { ANTHROPIC_OAUTH_BETA, AnthropicTokenError, loginAnthropic, refreshAnthropicToken } from "./anthropic";
1010
import { loginKimi, refreshKimiToken } from "./kimi";
1111
import { loginNous, NousTokenError, refreshNousToken, clearNousRefreshIntent, RefreshIntentIOError } from "./nous";
12-
import { loginChatGPT, refreshChatGPTToken } from "./chatgpt";
12+
import { ChatGPTTokenRefreshError, loginChatGPT, refreshChatGPTToken } from "./chatgpt";
1313
import { loginAntigravity, refreshAntigravityToken } from "./google-antigravity";
1414
import { loginCursor, refreshCursorToken } from "./cursor";
1515
import { loginGithubCopilot, refreshGithubCopilotToken, validateCopilotApiBaseUrl } from "./github-copilot";
@@ -556,6 +556,9 @@ function terminal(error:unknown):boolean{
556556
if(error instanceof AnthropicTokenError)return (error.httpStatus===400||error.httpStatus===401)&&["invalid_grant","refresh_token_reused","revoked","revoked_token","refresh_token_revoked"].includes(error.oauthError??"");
557557
if(error instanceof KiroTokenRefreshError)return (error.httpStatus===400||error.httpStatus===401)&&error.oauthError!==undefined;
558558
if(error instanceof NousTokenError)return error.terminal===true||["invalid_grant","refresh_token_reused","revoked","revoked_token","expired_token"].includes(error.oauthError??"");
559+
if (error instanceof ChatGPTTokenRefreshError) {
560+
return error.code === "invalid_grant" && (error.status === 400 || error.status === 401);
561+
}
559562
// Local durable-write/read/cleanup failures are operational, not credential
560563
// death: the provider credential was never rejected or consumed. Never mark
561564
// the account needsReauth for broken local persistence infrastructure.

‎tests/atomic-file-preserving-replace.test.ts‎

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ import { afterEach, describe, expect, test } from "bun:test";
22
import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
33
import { tmpdir } from "node:os";
44
import { join } from "node:path";
5-
import { replaceFilePreservingTarget } from "../src/lib/atomic-file-preserving-replace";
5+
import { PreservingReplaceError, replaceFilePreservingTarget } from "../src/lib/atomic-file-preserving-replace";
66

77
let directory = "";
88

@@ -26,4 +26,28 @@ describe("preserving file replacement", () => {
2626
expect(readFileSync(canonical, "utf8")).toBe("replacement");
2727
expect(readFileSync(process.platform === "win32" ? backup : staged, "utf8")).toBe("external-before");
2828
});
29+
30+
test("reports structured native details when the staged source is missing", () => {
31+
directory = mkdtempSync(join(tmpdir(), "ocx-preserving-replace-"));
32+
const staged = join(directory, ".missing-refresh.new");
33+
const canonical = join(directory, "auth.json");
34+
const backup = join(directory, ".refresh.previous");
35+
writeFileSync(canonical, "external-before");
36+
37+
let failure: unknown;
38+
try {
39+
replaceFilePreservingTarget(staged, canonical, backup);
40+
} catch (error) {
41+
failure = error;
42+
}
43+
44+
expect(failure).toBeInstanceOf(PreservingReplaceError);
45+
const structured = failure as PreservingReplaceError;
46+
expect(structured.operation).toBe(process.platform === "linux" ? "renameat2" : process.platform === "darwin" ? "renamex_np" : process.platform === "win32" ? "ReplaceFileW" : "unsupported");
47+
expect(structured.sourcePath).toBe(staged);
48+
expect(structured.targetPath).toBe(canonical);
49+
expect(structured.backupPath).toBe(backup);
50+
expect(structured.platform).toBe(process.platform);
51+
if (["linux", "darwin", "win32"].includes(process.platform)) expect(structured.nativeCode).toBe(2);
52+
});
2953
});

0 commit comments

Comments
 (0)