Skip to content

Commit 50f037b

Browse files
codexMarcTCruz
authored andcommitted
fix(codex): validate native refresh recovery journals
1 parent 6e457c9 commit 50f037b

3 files changed

Lines changed: 77 additions & 9 deletions

File tree

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

Lines changed: 12 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -6,8 +6,7 @@ import { PreservingReplaceError, replaceFilePreservingTarget, restoreFilePreserv
66
import type { NativeProfileContext } from "./native-profile-store";
77

88
const JOURNAL = ".opencodex-native-main-refresh.json";
9-
const NEW = /^\.opencodex-native-main-refresh\.[0-9a-f-]+\.new$/;
10-
const PREVIOUS = /^\.opencodex-native-main-refresh\.[0-9a-f-]+\.previous$/;
9+
const TRANSACTION_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;
1110

1211
type Journal = {
1312
version: 1;
@@ -42,13 +41,15 @@ function journalPath(context: NativeProfileContext): string {
4241
function validJournal(value: unknown): value is Journal {
4342
if (!value || typeof value !== "object" || Array.isArray(value)) return false;
4443
const item = value as Record<string, unknown>;
44+
const transactionId = typeof item.transactionId === "string" ? item.transactionId : "";
4545
return item.version === 1
46-
&& typeof item.transactionId === "string"
47-
&& NEW.test(String(item.stagedBasename))
48-
&& PREVIOUS.test(String(item.previousBasename))
46+
&& TRANSACTION_ID.test(transactionId)
47+
&& item.stagedBasename === `.opencodex-native-main-refresh.${transactionId}.new`
48+
&& item.previousBasename === `.opencodex-native-main-refresh.${transactionId}.previous`
4949
&& (item.phase === "prepared" || item.phase === "replaced")
5050
&& /^[0-9a-f]{64}$/.test(String(item.expectedSha256))
51-
&& /^[0-9a-f]{64}$/.test(String(item.replacementSha256));
51+
&& /^[0-9a-f]{64}$/.test(String(item.replacementSha256))
52+
&& item.expectedSha256 !== item.replacementSha256;
5253
}
5354

5455
function readExact(path: string): Buffer | null {
@@ -129,7 +130,11 @@ export function publishNativeMainRefresh(
129130
if (!displaced || digest(displaced) !== journal.expectedSha256) {
130131
const canonical = readExact(context.authPath);
131132
if (canonical && digest(canonical) === journal.replacementSha256) {
132-
restoreFilePreservingTarget(process.platform === "win32" ? previous : staged, context.authPath, previous);
133+
restoreFilePreservingTarget(
134+
process.platform === "win32" ? previous : staged,
135+
context.authPath,
136+
process.platform === "win32" ? staged : previous,
137+
);
133138
}
134139
throw new NativeMainRefreshPublicationError();
135140
}

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -74,7 +74,7 @@ export function replaceFilePreservingTarget(source: string, target: string, back
7474
throw new PreservingReplaceError();
7575
}
7676

77-
/** Used only to restore a verified displaced Unix entry. */
77+
/** Restore a verified displaced entry while preserving the canonical target. */
7878
export function restoreFilePreservingTarget(source: string, target: string, backup: string): void {
7979
replaceFilePreservingTarget(source, target, backup);
8080
}

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

Lines changed: 64 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import { afterEach, beforeEach, describe, expect, test } from "bun:test";
2-
import { mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from "node:fs";
2+
import { createHash } from "node:crypto";
3+
import { existsSync, mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from "node:fs";
34
import { tmpdir } from "node:os";
45
import { join } from "node:path";
56
import {
@@ -136,6 +137,68 @@ describe("native main token refresh", () => {
136137
expect((failure as MainAccountTokenRefreshError).reason).toBe("transient");
137138
});
138139

140+
test("rejects a recovery journal whose basenames do not belong to its transaction", async () => {
141+
const authPath = join(home, "auth.json");
142+
const original = JSON.stringify({ tokens: { refresh_token: "old-refresh", account_id: "account-main" } });
143+
const replacement = JSON.stringify({ tokens: { access_token: "new-access", refresh_token: "new-refresh" } });
144+
const fileTransactionId = "11111111-1111-4111-8111-111111111111";
145+
const stagedBasename = `.opencodex-native-main-refresh.${fileTransactionId}.new`;
146+
const journalPath = join(home, ".opencodex-native-main-refresh.json");
147+
const digest = (value: string) => createHash("sha256").update(value).digest("hex");
148+
writeFileSync(authPath, original);
149+
writeFileSync(join(home, stagedBasename), replacement);
150+
writeFileSync(journalPath, JSON.stringify({
151+
version: 1,
152+
transactionId: "22222222-2222-4222-8222-222222222222",
153+
stagedBasename,
154+
previousBasename: `.opencodex-native-main-refresh.${fileTransactionId}.previous`,
155+
phase: "prepared",
156+
expectedSha256: digest(original),
157+
replacementSha256: digest(replacement),
158+
}));
159+
let attempts = 0;
160+
161+
const failure = await getValidMainAccountToken({
162+
refreshToken: async () => {
163+
attempts += 1;
164+
throw new Error("must not refresh through malformed recovery state");
165+
},
166+
}).catch(error => error);
167+
168+
expect(failure).toBeInstanceOf(MainAccountTokenRefreshError);
169+
expect((failure as MainAccountTokenRefreshError).reason).toBe("transient");
170+
expect(attempts).toBe(0);
171+
expect(readFileSync(authPath, "utf8")).toBe(original);
172+
expect(existsSync(journalPath)).toBe(true);
173+
});
174+
175+
test("rejects hash-ambiguous recovery state without consuming it", async () => {
176+
const authPath = join(home, "auth.json");
177+
const original = JSON.stringify({ tokens: { refresh_token: "old-refresh", account_id: "account-main" } });
178+
const transactionId = "11111111-1111-4111-8111-111111111111";
179+
const stagedBasename = `.opencodex-native-main-refresh.${transactionId}.new`;
180+
const journalPath = join(home, ".opencodex-native-main-refresh.json");
181+
const hash = createHash("sha256").update(original).digest("hex");
182+
writeFileSync(authPath, original);
183+
writeFileSync(join(home, stagedBasename), original);
184+
writeFileSync(journalPath, JSON.stringify({
185+
version: 1,
186+
transactionId,
187+
stagedBasename,
188+
previousBasename: `.opencodex-native-main-refresh.${transactionId}.previous`,
189+
phase: "prepared",
190+
expectedSha256: hash,
191+
replacementSha256: hash,
192+
}));
193+
194+
const failure = await getValidMainAccountToken().catch(error => error);
195+
196+
expect(failure).toBeInstanceOf(MainAccountTokenRefreshError);
197+
expect((failure as MainAccountTokenRefreshError).reason).toBe("transient");
198+
expect(readFileSync(authPath, "utf8")).toBe(original);
199+
expect(existsSync(journalPath)).toBe(true);
200+
});
201+
139202
test("keeps a joiner alive when the refresh owner cancels", async () => {
140203
writeFileSync(join(home, "auth.json"), JSON.stringify({
141204
tokens: {

0 commit comments

Comments
 (0)