Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(desktop): make shared Codex auth self-healing (#3653)

Chris Zhang5a595a25fffc
diff --git a/apps/desktop/src/main/__tests__/codexAuthLink.test.ts b/apps/desktop/src/main/__tests__/codexAuthLink.test.ts
index aadb7344c2..0a3d10d5e8 100644
--- a/apps/desktop/src/main/__tests__/codexAuthLink.test.ts
+++ b/apps/desktop/src/main/__tests__/codexAuthLink.test.ts
@@ -1,7 +1,7 @@
/**
* codex-auth-link 单测 — 真实 fs tmpdir fixture。
*
- * 这套测试守护 2026-06-18 线上踩坑的修复:reconcile 替换 codex auth.json 硬链时,固定 sidecar
+ * 这套测试守护 reconcile 替换 codex auth.json 共享链接时的原子性、自愈与并发安全。
* 名 + 无串行化导致并发撞 `EEXIST` / `ENOENT`,且 rename 失败会让用户的 auth.json 凭空消失。
* 覆盖:
* - 基本 link(myAuth 已存在 / 不存在)→ 'linked' 且与 systemAuth 同 inode、内容一致
@@ -10,12 +10,16 @@
* - recoverCodexAuth 兜底:systemAuth 在→重建成功;不在→失败
*/
-import { describe, it, expect, beforeEach, afterEach } from 'vitest';
+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
import * as fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
-import { relinkSharedCodexAuth, recoverCodexAuth } from '../maker-host/codex-auth-link';
+import {
+ inspectCodexAuthLink,
+ relinkSharedCodexAuth,
+ recoverCodexAuth,
+} from '../maker-host/codex-auth-link';
let tmpRoot: string;
let systemAuth: string;
@@ -34,10 +38,11 @@ beforeEach(() => {
});
afterEach(() => {
+ vi.restoreAllMocks();
fs.rmSync(tmpRoot, { recursive: true, force: true });
});
-/** 两个路径是否指向同一个 inode(硬链共享的判据)。 */
+/** 两个路径最终是否解析到同一个 inode。 */
function sameInode(a: string, b: string): boolean {
const sa = fs.statSync(a);
const sb = fs.statSync(b);
@@ -46,36 +51,86 @@ function sameInode(a: string, b: string): boolean {
/** 列出 myAuth 同目录下残留的 .linktmp sidecar 文件。 */
function leftoverSidecars(): string[] {
- return fs
- .readdirSync(path.dirname(myAuth))
- .filter((name) => name.includes('.linktmp'));
+ return fs.readdirSync(path.dirname(myAuth)).filter((name) => name.includes('.linktmp'));
}
describe('relinkSharedCodexAuth', () => {
- it('myAuth 已存在(不同内容)→ linked,共享 inode 且内容变为 systemAuth', async () => {
+ it('POSIX:myAuth 已存在→原子替换为 symlink', async () => {
fs.writeFileSync(systemAuth, SYSTEM_CONTENT);
fs.writeFileSync(myAuth, MY_CONTENT);
- const out = await relinkSharedCodexAuth(systemAuth, myAuth);
+ const out = await relinkSharedCodexAuth(systemAuth, myAuth, 'darwin');
expect(out.kind).toBe('linked');
+ expect(out.linkType).toBe('symlink');
expect(out.error).toBeUndefined();
+ expect(fs.lstatSync(myAuth).isSymbolicLink()).toBe(true);
expect(sameInode(systemAuth, myAuth)).toBe(true);
expect(fs.readFileSync(myAuth, 'utf-8')).toBe(SYSTEM_CONTENT);
expect(leftoverSidecars()).toEqual([]);
});
- it('myAuth 不存在 → linked,直接建出共享硬链', async () => {
+ it('POSIX:myAuth 不存在 → linked,直接建出 symlink', async () => {
fs.writeFileSync(systemAuth, SYSTEM_CONTENT);
- const out = await relinkSharedCodexAuth(systemAuth, myAuth);
+ const out = await relinkSharedCodexAuth(systemAuth, myAuth, 'darwin');
expect(out.kind).toBe('linked');
+ expect(out.linkType).toBe('symlink');
expect(fs.existsSync(myAuth)).toBe(true);
expect(sameInode(systemAuth, myAuth)).toBe(true);
expect(leftoverSidecars()).toEqual([]);
});
+ it('POSIX:系统 auth 原子替换后 symlink 自动跟随新 inode', async () => {
+ fs.writeFileSync(systemAuth, SYSTEM_CONTENT);
+ await relinkSharedCodexAuth(systemAuth, myAuth, 'darwin');
+ const oldInode = fs.statSync(myAuth).ino;
+ const replacement = `${systemAuth}.new`;
+ fs.writeFileSync(replacement, JSON.stringify({ tokens: { access_token: 'rotated' } }));
+
+ fs.renameSync(replacement, systemAuth);
+
+ expect(fs.lstatSync(myAuth).isSymbolicLink()).toBe(true);
+ expect(fs.statSync(myAuth).ino).not.toBe(oldInode);
+ expect(fs.readFileSync(myAuth, 'utf-8')).toContain('rotated');
+ });
+
+ it('Windows 策略保留 hardlink', async () => {
+ fs.writeFileSync(systemAuth, SYSTEM_CONTENT);
+
+ const out = await relinkSharedCodexAuth(systemAuth, myAuth, 'win32');
+
+ expect(out).toMatchObject({ kind: 'linked', linkType: 'hardlink' });
+ expect(fs.lstatSync(myAuth).isSymbolicLink()).toBe(false);
+ expect(sameInode(systemAuth, myAuth)).toBe(true);
+ });
+
+ it('Windows 跨分区 hardlink 失败时保留原凭证', async () => {
+ fs.writeFileSync(systemAuth, SYSTEM_CONTENT);
+ fs.writeFileSync(myAuth, MY_CONTENT);
+ vi.spyOn(fs.promises, 'link').mockRejectedValueOnce(
+ Object.assign(new Error('cross-device link'), { code: 'EXDEV' }),
+ );
+
+ const out = await relinkSharedCodexAuth(systemAuth, myAuth, 'win32');
+
+ expect(out.kind).toBe('link-unsupported');
+ expect(fs.readFileSync(myAuth, 'utf8')).toBe(MY_CONTENT);
+ expect(leftoverSidecars()).toEqual([]);
+ });
+
+ it('POSIX 会原子替换 dangling symlink', async () => {
+ fs.writeFileSync(systemAuth, SYSTEM_CONTENT);
+ fs.symlinkSync(path.join(tmpRoot, 'missing-auth.json'), myAuth);
+
+ const out = await relinkSharedCodexAuth(systemAuth, myAuth, 'darwin');
+
+ expect(out).toMatchObject({ kind: 'linked', linkType: 'symlink' });
+ expect(fs.readFileSync(myAuth, 'utf8')).toBe(SYSTEM_CONTENT);
+ expect(leftoverSidecars()).toEqual([]);
+ });
+
it('systemAuth 不存在 → link-unsupported,myAuth 一字未动', async () => {
fs.writeFileSync(myAuth, MY_CONTENT);
@@ -100,7 +155,7 @@ describe('relinkSharedCodexAuth', () => {
// 没有任何一次把 auth.json 弄丢。
expect(outcomes.some((o) => o.kind === 'lost')).toBe(false);
- // 至少有人成功建立了共享硬链。
+ // 至少有人成功建立了共享链接。
expect(outcomes.some((o) => o.kind === 'linked')).toBe(true);
// 终态:myAuth 存在、内容是 systemAuth、与 systemAuth 同 inode、无残留 sidecar。
expect(fs.existsSync(myAuth)).toBe(true);
@@ -109,7 +164,7 @@ describe('relinkSharedCodexAuth', () => {
expect(leftoverSidecars()).toEqual([]);
});
- it('幂等:对已是硬链的 myAuth 再 relink 仍 linked、仍共享', async () => {
+ it('幂等:对已是 symlink 的 myAuth 再 relink 仍 linked、仍共享', async () => {
fs.writeFileSync(systemAuth, SYSTEM_CONTENT);
const first = await relinkSharedCodexAuth(systemAuth, myAuth);
@@ -140,4 +195,66 @@ describe('recoverCodexAuth', () => {
expect(ok).toBe(false);
expect(fs.existsSync(myAuth)).toBe(false);
});
+
+ it('Windows recovery hardlink 失败时不复制 token 副本', async () => {
+ fs.writeFileSync(systemAuth, SYSTEM_CONTENT);
+ vi.spyOn(fs.promises, 'link').mockRejectedValueOnce(
+ Object.assign(new Error('cross-device link'), { code: 'EXDEV' }),
+ );
+
+ await expect(recoverCodexAuth(systemAuth, myAuth, 'win32')).resolves.toBe(false);
+ expect(fs.existsSync(myAuth)).toBe(false);
+ });
+});
+
+describe('inspectCodexAuthLink', () => {
+ it('本地缺失时仍返回系统权威文件元数据', async () => {
+ fs.writeFileSync(systemAuth, SYSTEM_CONTENT);
+
+ await expect(inspectCodexAuthLink(systemAuth, myAuth)).resolves.toMatchObject({
+ linkType: 'missing',
+ healthy: false,
+ systemAuthMtimeMs: expect.any(Number),
+ systemAuthLinkCount: 1,
+ });
+ });
+
+ it('返回 symlink 健康度与权威文件元数据', async () => {
+ fs.writeFileSync(systemAuth, SYSTEM_CONTENT);
+ await relinkSharedCodexAuth(systemAuth, myAuth, 'darwin');
+
+ const diagnostics = await inspectCodexAuthLink(systemAuth, myAuth);
+
+ expect(diagnostics).toMatchObject({ linkType: 'symlink', healthy: true });
+ expect(diagnostics.systemAuthMtimeMs).toEqual(expect.any(Number));
+ expect(diagnostics.systemAuthLinkCount).toBe(1);
+ });
+
+ it('识别 dangling symlink', async () => {
+ fs.symlinkSync(systemAuth, myAuth);
+
+ await expect(inspectCodexAuthLink(systemAuth, myAuth)).resolves.toEqual({
+ linkType: 'dangling-symlink',
+ healthy: false,
+ });
+ });
+
+ it('识别无 provenance 普通文件为不健康', async () => {
+ fs.writeFileSync(systemAuth, SYSTEM_CONTENT);
+ fs.writeFileSync(myAuth, MY_CONTENT);
+
+ await expect(inspectCodexAuthLink(systemAuth, myAuth)).resolves.toMatchObject({
+ linkType: 'file',
+ healthy: false,
+ });
+ });
+
+ it('系统权威文件缺失时仍识别本地普通文件', async () => {
+ fs.writeFileSync(myAuth, MY_CONTENT);
+
+ await expect(inspectCodexAuthLink(systemAuth, myAuth)).resolves.toEqual({
+ linkType: 'file',
+ healthy: false,
+ });
+ });
});
diff --git a/apps/desktop/src/main/maker-host/__tests__/codexAuthInvalidation.test.ts b/apps/desktop/src/main/maker-host/__tests__/codexAuthInvalidation.test.ts
index 4bdd09a22c..ae543cc044 100644
--- a/apps/desktop/src/main/maker-host/__tests__/codexAuthInvalidation.test.ts
+++ b/apps/desktop/src/main/maker-host/__tests__/codexAuthInvalidation.test.ts
@@ -5,6 +5,7 @@ import { afterEach, describe, expect, it, vi } from 'vitest';
import {
CODEX_USER_DISCONNECT_REASON,
+ currentCodexAuthFileFingerprint,
getCodexAuthInvalidationMarkerPath,
getActiveInvalidatedSystemCodexAuthMarker,
readInvalidatedSystemCodexAuthMarker,
@@ -15,6 +16,7 @@ import {
} from '../codex-auth-invalidation.js';
const dirs: string[] = [];
+const expectedSharedLinkType = process.platform === 'win32' ? 'hardlink' : 'symlink';
const h = vi.hoisted(() => ({
userDataDir: '',
dataOwnerId: null as string | null,
@@ -74,6 +76,16 @@ function deferred<T = void>() {
return { promise, resolve };
}
+function expectPlatformSharedLink(systemAuth: string, localAuth: string): void {
+ expect(fs.lstatSync(localAuth).isSymbolicLink()).toBe(process.platform !== 'win32');
+ const systemStat = fs.statSync(systemAuth);
+ const localStat = fs.statSync(localAuth);
+ expect({ dev: localStat.dev, ino: localStat.ino }).toEqual({
+ dev: systemStat.dev,
+ ino: systemStat.ino,
+ });
+}
+
it('compares Codex hard-link identities without Windows number precision collisions', async () => {
const { haveSameStableFileIdentity } = await import('../auth-adapters.js');
expect(
@@ -182,7 +194,10 @@ describe('Codex system credential suppression marker', () => {
resolveWindowsAclPrincipal({ USERDOMAIN: 'WORKSTATION', USERNAME: 'alex' }, 'fallback'),
).toBe('WORKSTATION\\alex');
expect(
- resolveWindowsAclPrincipal({ USERDOMAIN: 'WORKSTATION', USERNAME: 'DOMAIN\\alex' }, 'fallback'),
+ resolveWindowsAclPrincipal(
+ { USERDOMAIN: 'WORKSTATION', USERNAME: 'DOMAIN\\alex' },
+ 'fallback',
+ ),
).toBe('DOMAIN\\alex');
expect(resolveWindowsAclPrincipal({}, 'fallback')).toBe('fallback');
});
@@ -512,6 +527,65 @@ describe('Codex system credential suppression marker', () => {
});
});
+ it('persists first explicit login provenance before reconciling a different system account', async () => {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'xdt-codex-first-explicit-login-'));
+ dirs.push(root);
+ h.userDataDir = path.join(root, 'user-data');
+ h.dataOwnerId = 'owner-a';
+ const home = path.join(root, 'home');
+ const systemAuth = path.join(home, '.codex', 'auth.json');
+ const codexHome = path.join(h.userDataDir, 'codex-home');
+ const localAuth = path.join(codexHome, 'auth.json');
+ const bindingFile = path.join(h.userDataDir, 'native-provider-auth.json');
+ vi.spyOn(os, 'homedir').mockReturnValue(home);
+ fs.mkdirSync(path.dirname(systemAuth), { recursive: true });
+ fs.mkdirSync(codexHome, { recursive: true });
+ fs.writeFileSync(
+ systemAuth,
+ JSON.stringify({
+ account: { email: '[email protected]' },
+ tokens: { access_token: 'system-a-token', account_id: 'account-a' },
+ }),
+ );
+ fs.writeFileSync(
+ localAuth,
+ JSON.stringify({
+ account: { email: '[email protected]' },
+ tokens: { access_token: 'cindy-b-token', account_id: 'account-b' },
+ }),
+ );
+
+ const { DesktopCodexAuthAdapter } = await import('../auth-adapters.js');
+ const adapter = new DesktopCodexAuthAdapter();
+ const finishSuccessfulCodexLogin = (
+ adapter as unknown as {
+ finishSuccessfulCodexLogin(): Promise<{
+ authenticated: boolean;
+ credentialScope?: string;
+ }>;
+ }
+ ).finishSuccessfulCodexLogin.bind(adapter);
+
+ await expect(finishSuccessfulCodexLogin()).resolves.toMatchObject({
+ authenticated: true,
+ credentialScope: 'instance-isolated',
+ });
+ expect(JSON.parse(fs.readFileSync(localAuth, 'utf8'))).toMatchObject({
+ account: { email: '[email protected]' },
+ tokens: { access_token: 'cindy-b-token', account_id: 'account-b' },
+ });
+ expect(JSON.parse(fs.readFileSync(systemAuth, 'utf8'))).toMatchObject({
+ account: { email: '[email protected]' },
+ tokens: { access_token: 'system-a-token', account_id: 'account-a' },
+ });
+ expect(JSON.parse(fs.readFileSync(bindingFile, 'utf8'))).toMatchObject({
+ openai: 'owner-a',
+ selfAuthorized: { openai: 'owner-a' },
+ sources: { openai: 'explicit-provider-oauth' },
+ instanceIsolatedCredential: { openai: 'owner-a' },
+ });
+ });
+
it('reclassifies a shared invalidation as isolated after an explicit Cindy login', async () => {
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'xdt-codex-shared-to-isolated-'));
dirs.push(root);
@@ -928,10 +1002,9 @@ describe('Codex system credential suppression marker', () => {
dirs.push(root);
h.userDataDir = path.join(root, 'user-data');
h.dataOwnerId = 'owner-a';
- fs.mkdirSync(
- path.join(h.userDataDir, 'native-provider-auth.json.mutation-lock.db'),
- { recursive: true },
- );
+ fs.mkdirSync(path.join(h.userDataDir, 'native-provider-auth.json.mutation-lock.db'), {
+ recursive: true,
+ });
const { DesktopCodexAuthAdapter } = await import('../auth-adapters.js');
const adapter = new DesktopCodexAuthAdapter();
@@ -1100,6 +1173,237 @@ describe('Codex system credential suppression marker', () => {
expect(readCodexOneShotCreds()).toBeNull();
});
+ it('persists unproven child suppression without modifying shared F2', async () => {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'xdt-codex-unproven-child-'));
+ dirs.push(root);
+ h.userDataDir = path.join(root, 'user-data');
+ h.dataOwnerId = 'owner-a';
+ const home = path.join(root, 'home');
+ const systemAuth = path.join(home, '.codex', 'auth.json');
+ const codexHome = path.join(h.userDataDir, 'codex-home');
+ const localAuth = path.join(codexHome, 'auth.json');
+ const markerPath = getCodexAuthInvalidationMarkerPath(codexHome);
+ vi.spyOn(os, 'homedir').mockReturnValue(home);
+ fs.mkdirSync(path.dirname(systemAuth), { recursive: true });
+ fs.mkdirSync(codexHome, { recursive: true });
+ fs.writeFileSync(
+ systemAuth,
+ JSON.stringify({ tokens: { access_token: 'system-f2-token', account_id: 'acct-1' } }),
+ { mode: 0o600 },
+ );
+ if (process.platform === 'win32') fs.linkSync(systemAuth, localAuth);
+ else fs.symlinkSync(systemAuth, localAuth);
+ fs.writeFileSync(
+ path.join(h.userDataDir, 'native-provider-auth.json'),
+ JSON.stringify({
+ openai: 'owner-a',
+ sharedSystemCredential: { openai: 'owner-a' },
+ }),
+ );
+ const f2Bytes = fs.readFileSync(systemAuth);
+ const f2Stat = fs.statSync(systemAuth);
+ const rmSpy = vi.spyOn(fs.promises, 'rm');
+ const chmodSpy = vi.spyOn(fs.promises, 'chmod');
+ const { DesktopCodexAuthAdapter } = await import('../auth-adapters.js');
+ const adapter = new DesktopCodexAuthAdapter();
+ const onLogoutSuccess = vi.fn().mockResolvedValue(undefined);
+ const broadcast = vi.fn().mockResolvedValue(undefined);
+ adapter.setOnLogoutSuccess(onLogoutSuccess);
+ adapter.setOnInvalidatedBroadcast(broadcast);
+
+ await expect(
+ adapter.invalidate('child_auth_rejected', { credentialAttribution: 'unproven' }),
+ ).resolves.toBeUndefined();
+
+ expect(onLogoutSuccess).not.toHaveBeenCalled();
+ expect(broadcast).toHaveBeenCalledWith('child_auth_rejected', 'system-shared', false);
+ expect(readInvalidatedSystemCodexAuthMarker(codexHome)).toMatchObject({
+ reason: 'child_auth_rejected',
+ credentialScope: 'system-shared',
+ recoveryOwnerId: 'owner-a',
+ unprovenCredentialAttribution: true,
+ });
+ expect(rmSpy).not.toHaveBeenCalled();
+ expect(chmodSpy).not.toHaveBeenCalled();
+ expect(fs.readFileSync(systemAuth)).toEqual(f2Bytes);
+ expect(fs.readFileSync(localAuth)).toEqual(f2Bytes);
+ expect(fs.statSync(systemAuth)).toMatchObject({ ino: f2Stat.ino, mode: f2Stat.mode });
+ await expect(adapter.getState({ credentialMode: 'oauth-bearer' })).resolves.toMatchObject({
+ authenticated: false,
+ errorReason: 'child_auth_rejected',
+ credentialScope: 'system-shared',
+ });
+
+ const restartedAdapter = new DesktopCodexAuthAdapter();
+ await expect(
+ restartedAdapter.getState({ credentialMode: 'oauth-bearer' }),
+ ).resolves.toMatchObject({
+ authenticated: false,
+ errorReason: 'child_auth_rejected',
+ credentialScope: 'system-shared',
+ });
+ expect(fs.readFileSync(systemAuth)).toEqual(f2Bytes);
+ expect(fs.readFileSync(localAuth)).toEqual(f2Bytes);
+
+ rmSpy.mockRestore();
+ const replacement = path.join(path.dirname(systemAuth), 'auth.f3.json');
+ fs.writeFileSync(
+ replacement,
+ JSON.stringify({ tokens: { access_token: 'system-f3-token', account_id: 'acct-1' } }),
+ { mode: 0o600 },
+ );
+ fs.renameSync(replacement, systemAuth);
+ await expect(
+ restartedAdapter.getState({ credentialMode: 'oauth-bearer' }),
+ ).resolves.toMatchObject({
+ authenticated: true,
+ credentialScope: 'system-shared',
+ recoveryRequiredReason: 'child_auth_rejected',
+ });
+ await expect(restartedAdapter.getAccessToken()).resolves.toBe('system-f3-token');
+ await restartedAdapter.verifyRecoveryWithAccountRpc(async () => undefined);
+ expect(fs.existsSync(markerPath)).toBe(false);
+ expect(chmodSpy).not.toHaveBeenCalled();
+ });
+
+ it('keeps unproven shared suppression across restart when marker commit fails', async () => {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'xdt-codex-unproven-marker-fail-'));
+ dirs.push(root);
+ h.userDataDir = path.join(root, 'user-data');
+ h.dataOwnerId = 'owner-a';
+ const home = path.join(root, 'home');
+ const systemAuth = path.join(home, '.codex', 'auth.json');
+ const codexHome = path.join(h.userDataDir, 'codex-home');
+ const localAuth = path.join(codexHome, 'auth.json');
+ const markerPath = getCodexAuthInvalidationMarkerPath(codexHome);
+ const bindingPath = path.join(h.userDataDir, 'native-provider-auth.json');
+ vi.spyOn(os, 'homedir').mockReturnValue(home);
+ fs.mkdirSync(path.dirname(systemAuth), { recursive: true });
+ fs.mkdirSync(codexHome, { recursive: true });
+ fs.writeFileSync(
+ systemAuth,
+ JSON.stringify({ tokens: { access_token: 'system-f2-token', account_id: 'acct-1' } }),
+ { mode: 0o600 },
+ );
+ if (process.platform === 'win32') fs.linkSync(systemAuth, localAuth);
+ else fs.symlinkSync(systemAuth, localAuth);
+ fs.writeFileSync(
+ bindingPath,
+ JSON.stringify({
+ openai: 'owner-a',
+ sharedSystemCredential: { openai: 'owner-a' },
+ sources: { openai: 'native-harness-inherited' },
+ }),
+ );
+ const f2Bytes = fs.readFileSync(systemAuth);
+ const f2Stat = fs.statSync(systemAuth);
+ const realRenameSync = fs.renameSync.bind(fs);
+ vi.spyOn(fs, 'renameSync').mockImplementation((from, to) => {
+ if (String(to) === markerPath) throw new Error('EIO: marker rename failed');
+ return realRenameSync(from, to);
+ });
+ const rm = vi.spyOn(fs.promises, 'rm');
+ const chmod = vi.spyOn(fs.promises, 'chmod');
+ const { DesktopCodexAuthAdapter, readCodexOneShotCreds } = await import('../auth-adapters.js');
+ const adapter = new DesktopCodexAuthAdapter();
+ const broadcast = vi.fn();
+ adapter.setOnInvalidatedBroadcast(broadcast);
+
+ await adapter.invalidate('child_auth_rejected', { credentialAttribution: 'unproven' });
+
+ expect(broadcast).toHaveBeenCalledWith('child_auth_rejected', 'unknown', false);
+ expect(fs.existsSync(markerPath)).toBe(false);
+ expect(JSON.parse(fs.readFileSync(bindingPath, 'utf8'))).toMatchObject({
+ revoked: { openai: 'owner-a' },
+ });
+ expect(fs.readFileSync(systemAuth)).toEqual(f2Bytes);
+ expect(fs.readFileSync(localAuth)).toEqual(f2Bytes);
+ expect(fs.statSync(systemAuth)).toMatchObject({ ino: f2Stat.ino, mode: f2Stat.mode });
+ expect(rm).not.toHaveBeenCalled();
+ expect(chmod).not.toHaveBeenCalled();
+
+ const restartedAdapter = new DesktopCodexAuthAdapter();
+ await expect(
+ restartedAdapter.getState({ credentialMode: 'oauth-bearer' }),
+ ).resolves.toMatchObject({ authenticated: false });
+ await expect(restartedAdapter.getAccessToken()).resolves.toBeNull();
+ expect(readCodexOneShotCreds(restartedAdapter)).toBeNull();
+ expect(JSON.parse(fs.readFileSync(bindingPath, 'utf8'))).toMatchObject({
+ revoked: { openai: 'owner-a' },
+ });
+ expect(fs.readFileSync(systemAuth)).toEqual(f2Bytes);
+ expect(fs.readFileSync(localAuth)).toEqual(f2Bytes);
+ expect(rm).not.toHaveBeenCalled();
+ expect(chmod).not.toHaveBeenCalled();
+ });
+
+ it('keeps an unproven isolated boundary until the local credential changes', async () => {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'xdt-codex-unproven-isolated-'));
+ dirs.push(root);
+ h.userDataDir = path.join(root, 'user-data');
+ h.dataOwnerId = 'owner-a';
+ const home = path.join(root, 'home');
+ const systemAuth = path.join(home, '.codex', 'auth.json');
+ const codexHome = path.join(h.userDataDir, 'codex-home');
+ const localAuth = path.join(codexHome, 'auth.json');
+ vi.spyOn(os, 'homedir').mockReturnValue(home);
+ fs.mkdirSync(path.dirname(systemAuth), { recursive: true });
+ fs.mkdirSync(codexHome, { recursive: true });
+ fs.writeFileSync(
+ systemAuth,
+ JSON.stringify({ tokens: { access_token: 'system-token', account_id: 'acct-system' } }),
+ );
+ const localF2 = JSON.stringify({
+ tokens: { access_token: 'isolated-f2-token', account_id: 'acct-local' },
+ });
+ fs.writeFileSync(localAuth, localF2);
+ fs.writeFileSync(
+ path.join(h.userDataDir, 'native-provider-auth.json'),
+ JSON.stringify({
+ openai: 'owner-a',
+ selfAuthorized: { openai: 'owner-a' },
+ sources: { openai: 'explicit-provider-oauth' },
+ instanceIsolatedCredential: { openai: 'owner-a' },
+ }),
+ );
+ const { DesktopCodexAuthAdapter } = await import('../auth-adapters.js');
+ const adapter = new DesktopCodexAuthAdapter();
+ await adapter.invalidate('isolated_child_auth_rejected', {
+ credentialAttribution: 'unproven',
+ });
+ expect(readInvalidatedSystemCodexAuthMarker(codexHome)).toMatchObject({
+ reason: 'isolated_child_auth_rejected',
+ credentialScope: 'instance-isolated',
+ unprovenCredentialAttribution: true,
+ });
+
+ const restartedAdapter = new DesktopCodexAuthAdapter();
+ await expect(
+ restartedAdapter.getState({ credentialMode: 'oauth-bearer' }),
+ ).resolves.toMatchObject({ authenticated: false, errorReason: 'isolated_child_auth_rejected' });
+
+ fs.writeFileSync(
+ systemAuth,
+ JSON.stringify({ tokens: { access_token: 'system-f3-token', account_id: 'acct-system' } }),
+ );
+ await expect(
+ restartedAdapter.getState({ credentialMode: 'oauth-bearer' }),
+ ).resolves.toMatchObject({ authenticated: false, errorReason: 'isolated_child_auth_rejected' });
+ expect(fs.readFileSync(localAuth, 'utf8')).toBe(localF2);
+
+ fs.writeFileSync(
+ localAuth,
+ JSON.stringify({ tokens: { access_token: 'isolated-f3-token', account_id: 'acct-local' } }),
+ );
+ await expect(
+ restartedAdapter.getState({ credentialMode: 'oauth-bearer' }),
+ ).resolves.toMatchObject({
+ authenticated: true,
+ credentialScope: 'instance-isolated',
+ recoveryRequiredReason: 'isolated_child_auth_rejected',
+ });
+ });
+
it('fails closed when the invalidation marker cannot be committed and restores suppression after login', async () => {
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'xdt-codex-invalidation-marker-fail-'));
dirs.push(root);
@@ -1392,6 +1696,9 @@ describe('Codex system credential suppression marker', () => {
authSource: 'oauth',
credentialScope: 'system-shared',
});
+ const expiredGeneration = adapter.captureCredentialGeneration();
+ expect(expiredGeneration).not.toBeNull();
+ expectPlatformSharedLink(systemAuth, localAuth);
const replacement = path.join(path.dirname(systemAuth), 'auth.replacement.json');
fs.writeFileSync(
@@ -1402,45 +1709,948 @@ describe('Codex system credential suppression marker', () => {
}),
);
fs.renameSync(replacement, systemAuth);
- expect(fs.readFileSync(localAuth, 'utf8')).not.toBe(fs.readFileSync(systemAuth, 'utf8'));
+ if (process.platform === 'win32') {
+ expect(fs.readFileSync(localAuth, 'utf8')).not.toBe(fs.readFileSync(systemAuth, 'utf8'));
+ } else {
+ expect(fs.readFileSync(localAuth, 'utf8')).toBe(fs.readFileSync(systemAuth, 'utf8'));
+ }
const broadcast = vi.fn();
adapter.setOnInvalidatedBroadcast(broadcast);
- await expect(adapter.invalidate('token_revoked')).resolves.toBeUndefined();
- expect(broadcast).toHaveBeenCalledWith('token_revoked', 'system-shared');
+ await expect(
+ adapter.invalidate('token_revoked', { credentialGeneration: expiredGeneration }),
+ ).resolves.toBeUndefined();
+ expect(JSON.parse(fs.readFileSync(bindingFile, 'utf8'))).not.toHaveProperty('revoked.openai');
+ const restartedAdapter = new DesktopCodexAuthAdapter();
+ if (process.platform === 'win32') {
+ // Windows local 仍是 F1 旧 hardlink,generation 匹配;清掉 F1 后从 system F2 恢复。
+ expect(broadcast).toHaveBeenCalledWith('token_revoked', 'system-shared');
+ expect(readInvalidatedSystemCodexAuthMarker(codexHome)).toMatchObject({
+ credentialScope: 'system-shared',
+ recoveryOwnerId: 'owner-b',
+ });
+ await expect(
+ restartedAdapter.getState({ credentialMode: 'oauth-bearer' }),
+ ).resolves.toMatchObject({
+ authenticated: true,
+ authSource: 'oauth',
+ credentialScope: 'system-shared',
+ recoveryRequiredReason: 'token_revoked',
+ });
+ await restartedAdapter.verifyRecoveryWithAccountRpc(async () => undefined);
+ expect(readInvalidatedSystemCodexAuthMarker(codexHome)).toBeNull();
+ } else {
+ // POSIX symlink 已跟到 F2;F1 迟到 invalidation 不能碰当前凭证或制造恢复态。
+ expect(broadcast).not.toHaveBeenCalled();
+ expect(readInvalidatedSystemCodexAuthMarker(codexHome)).toBeNull();
+ await expect(
+ restartedAdapter.getState({ credentialMode: 'oauth-bearer' }),
+ ).resolves.toMatchObject({
+ authenticated: true,
+ authSource: 'oauth',
+ credentialScope: 'system-shared',
+ });
+ }
+ await expect(restartedAdapter.getAccessToken()).resolves.toBe('renewed-system-token');
+ expect(JSON.parse(fs.readFileSync(bindingFile, 'utf8'))).toMatchObject({
+ legacyClaimOwner: 'owner-a',
+ openai: 'owner-b',
+ });
+ });
+
+ it('repairs a pre-upgrade Windows hardlink rotated before provenance migration', async () => {
+ const originalPlatform = process.platform;
+ Object.defineProperty(process, 'platform', { value: 'win32', configurable: true });
+ try {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'xdt-codex-windows-shared-rotation-'));
+ dirs.push(root);
+ h.userDataDir = path.join(root, 'user-data');
+ h.dataOwnerId = 'owner-a';
+ const home = path.join(root, 'home');
+ const systemAuth = path.join(home, '.codex', 'auth.json');
+ const codexHome = path.join(h.userDataDir, 'codex-home');
+ const localAuth = path.join(codexHome, 'auth.json');
+ const bindingFile = path.join(h.userDataDir, 'native-provider-auth.json');
+ vi.spyOn(os, 'homedir').mockReturnValue(home);
+ const chmodSpy = vi.spyOn(fs.promises, 'chmod');
+ fs.mkdirSync(path.dirname(systemAuth), { recursive: true });
+ fs.mkdirSync(codexHome, { recursive: true });
+ fs.writeFileSync(
+ systemAuth,
+ JSON.stringify({ tokens: { access_token: 'system-f1-token', account_id: 'acct-1' } }),
+ { mode: 0o600 },
+ );
+ fs.linkSync(systemAuth, localAuth);
+ fs.mkdirSync(h.userDataDir, { recursive: true });
+ fs.writeFileSync(
+ bindingFile,
+ JSON.stringify({
+ openai: 'owner-a',
+ selfAuthorized: { openai: 'owner-a' },
+ sources: { openai: 'explicit-provider-oauth' },
+ }),
+ );
+
+ const replacement = path.join(path.dirname(systemAuth), 'auth.f2.json');
+ fs.writeFileSync(
+ replacement,
+ JSON.stringify({ tokens: { access_token: 'system-f2-token', account_id: 'acct-1' } }),
+ { mode: 0o600 },
+ );
+ fs.renameSync(replacement, systemAuth);
+ expect(fs.readFileSync(localAuth, 'utf8')).toContain('system-f1-token');
+ const systemBeforeReconcile = fs.readFileSync(systemAuth);
+ const systemStatBeforeReconcile = fs.statSync(systemAuth);
+
+ const { DesktopCodexAuthAdapter } = await import('../auth-adapters.js');
+ await expect(
+ new DesktopCodexAuthAdapter().getState({ credentialMode: 'oauth-bearer' }),
+ ).resolves.toMatchObject({
+ authenticated: true,
+ credentialScope: 'system-shared',
+ credentialDiagnostics: {
+ linkType: 'hardlink',
+ healthy: true,
+ orphanRepair: 'relinked',
+ },
+ });
+
+ expect(fs.readFileSync(localAuth, 'utf8')).toContain('system-f2-token');
+ expect(fs.readFileSync(localAuth, 'utf8')).not.toContain('system-f1-token');
+ const localStat = fs.statSync(localAuth);
+ const systemStatAfterReconcile = fs.statSync(systemAuth);
+ expect({ dev: localStat.dev, ino: localStat.ino }).toEqual({
+ dev: systemStatAfterReconcile.dev,
+ ino: systemStatAfterReconcile.ino,
+ });
+ expect(fs.readFileSync(systemAuth)).toEqual(systemBeforeReconcile);
+ expect({
+ dev: systemStatAfterReconcile.dev,
+ ino: systemStatAfterReconcile.ino,
+ mode: systemStatAfterReconcile.mode,
+ }).toEqual({
+ dev: systemStatBeforeReconcile.dev,
+ ino: systemStatBeforeReconcile.ino,
+ mode: systemStatBeforeReconcile.mode,
+ });
+ expect(chmodSpy).not.toHaveBeenCalled();
+ } finally {
+ Object.defineProperty(process, 'platform', {
+ value: originalPlatform,
+ configurable: true,
+ });
+ }
+ });
+
+ it('repairs a pre-upgrade POSIX hardlink rotated before provenance migration', async () => {
+ const originalPlatform = process.platform;
+ Object.defineProperty(process, 'platform', { value: 'darwin', configurable: true });
+ try {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'xdt-codex-posix-shared-rotation-'));
+ dirs.push(root);
+ h.userDataDir = path.join(root, 'user-data');
+ h.dataOwnerId = 'owner-a';
+ const home = path.join(root, 'home');
+ const systemAuth = path.join(home, '.codex', 'auth.json');
+ const localAuth = path.join(h.userDataDir, 'codex-home', 'auth.json');
+ vi.spyOn(os, 'homedir').mockReturnValue(home);
+ const chmodSpy = vi.spyOn(fs.promises, 'chmod');
+ fs.mkdirSync(path.dirname(systemAuth), { recursive: true });
+ fs.mkdirSync(path.dirname(localAuth), { recursive: true });
+ fs.writeFileSync(
+ systemAuth,
+ JSON.stringify({ tokens: { access_token: 'system-f1-token', account_id: 'acct-1' } }),
+ { mode: 0o600 },
+ );
+ fs.linkSync(systemAuth, localAuth);
+ fs.writeFileSync(
+ path.join(h.userDataDir, 'native-provider-auth.json'),
+ JSON.stringify({
+ openai: 'owner-a',
+ selfAuthorized: { openai: 'owner-a' },
+ sources: { openai: 'explicit-provider-oauth' },
+ }),
+ );
+
+ const replacement = path.join(path.dirname(systemAuth), 'auth.f2.json');
+ fs.writeFileSync(
+ replacement,
+ JSON.stringify({ tokens: { access_token: 'system-f2-token', account_id: 'acct-1' } }),
+ { mode: 0o600 },
+ );
+ fs.renameSync(replacement, systemAuth);
+ expect(fs.readFileSync(localAuth, 'utf8')).toContain('system-f1-token');
+ const systemBeforeReconcile = fs.readFileSync(systemAuth);
+ const systemStatBeforeReconcile = fs.statSync(systemAuth);
+
+ const { DesktopCodexAuthAdapter } = await import('../auth-adapters.js');
+ await expect(
+ new DesktopCodexAuthAdapter().getState({ credentialMode: 'oauth-bearer' }),
+ ).resolves.toMatchObject({
+ authenticated: true,
+ credentialScope: 'system-shared',
+ credentialDiagnostics: { linkType: 'symlink', healthy: true, orphanRepair: 'relinked' },
+ });
+
+ expect(fs.lstatSync(localAuth).isSymbolicLink()).toBe(true);
+ expect(fs.readFileSync(localAuth, 'utf8')).toContain('system-f2-token');
+ expect(fs.readFileSync(localAuth, 'utf8')).not.toContain('system-f1-token');
+ expect(fs.readFileSync(systemAuth)).toEqual(systemBeforeReconcile);
+ expect(fs.statSync(systemAuth)).toMatchObject({
+ ino: systemStatBeforeReconcile.ino,
+ mode: systemStatBeforeReconcile.mode,
+ });
+ expect(chmodSpy).not.toHaveBeenCalled();
+ } finally {
+ Object.defineProperty(process, 'platform', {
+ value: originalPlatform,
+ configurable: true,
+ });
+ }
+ });
+
+ it.each([
+ { platform: 'darwin', label: 'POSIX' },
+ { platform: 'win32', label: 'Windows' },
+ ])('preserves a parent-version explicit isolated account on $label', async ({ platform }) => {
+ const originalPlatform = process.platform;
+ Object.defineProperty(process, 'platform', { value: platform, configurable: true });
+ try {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'xdt-codex-legacy-explicit-'));
+ dirs.push(root);
+ h.userDataDir = path.join(root, 'user-data');
+ h.dataOwnerId = 'owner-a';
+ const home = path.join(root, 'home');
+ const systemAuth = path.join(home, '.codex', 'auth.json');
+ const localAuth = path.join(h.userDataDir, 'codex-home', 'auth.json');
+ const bindingFile = path.join(h.userDataDir, 'native-provider-auth.json');
+ vi.spyOn(os, 'homedir').mockReturnValue(home);
+ const chmodSpy = vi.spyOn(fs.promises, 'chmod');
+ fs.mkdirSync(path.dirname(systemAuth), { recursive: true });
+ fs.mkdirSync(path.dirname(localAuth), { recursive: true });
+ fs.writeFileSync(
+ systemAuth,
+ JSON.stringify({ tokens: { access_token: 'system-a-token', account_id: 'account-a' } }),
+ { mode: 0o600 },
+ );
+ fs.writeFileSync(
+ localAuth,
+ JSON.stringify({ tokens: { access_token: 'cindy-b-token', account_id: 'account-b' } }),
+ { mode: 0o600 },
+ );
+ fs.writeFileSync(
+ bindingFile,
+ JSON.stringify({
+ openai: 'owner-a',
+ selfAuthorized: { openai: 'owner-a' },
+ sources: { openai: 'explicit-provider-oauth' },
+ }),
+ );
+ const localBefore = fs.readFileSync(localAuth);
+ const localStatBefore = fs.statSync(localAuth);
+ const systemBefore = fs.readFileSync(systemAuth);
+ const systemStatBefore = fs.statSync(systemAuth);
+
+ const { DesktopCodexAuthAdapter } = await import('../auth-adapters.js');
+ const adapter = new DesktopCodexAuthAdapter();
+ await expect(adapter.getState({ credentialMode: 'oauth-bearer' })).resolves.toMatchObject({
+ authenticated: true,
+ credentialScope: 'instance-isolated',
+ });
+ await expect(adapter.getAccessToken()).resolves.toBe('cindy-b-token');
+
+ expect(fs.readFileSync(localAuth)).toEqual(localBefore);
+ expect(fs.statSync(localAuth)).toMatchObject({
+ ino: localStatBefore.ino,
+ mode: localStatBefore.mode,
+ });
+ expect(fs.readFileSync(systemAuth)).toEqual(systemBefore);
+ expect(fs.statSync(systemAuth)).toMatchObject({
+ ino: systemStatBefore.ino,
+ mode: systemStatBefore.mode,
+ });
+ expect(JSON.parse(fs.readFileSync(bindingFile, 'utf8'))).toMatchObject({
+ openai: 'owner-a',
+ selfAuthorized: { openai: 'owner-a' },
+ sources: { openai: 'explicit-provider-oauth' },
+ instanceIsolatedCredential: { openai: 'owner-a' },
+ });
+ expect(chmodSpy).not.toHaveBeenCalled();
+ } finally {
+ Object.defineProperty(process, 'platform', {
+ value: originalPlatform,
+ configurable: true,
+ });
+ }
+ });
+
+ it.each([
+ { platform: 'darwin', label: 'POSIX' },
+ { platform: 'win32', label: 'Windows' },
+ ])('attributes a detached shared F1 invalidation on $label', async ({ platform }) => {
+ const originalPlatform = process.platform;
+ Object.defineProperty(process, 'platform', { value: platform, configurable: true });
+ try {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'xdt-codex-shared-provenance-'));
+ dirs.push(root);
+ h.userDataDir = path.join(root, 'user-data');
+ h.dataOwnerId = 'owner-a';
+ const home = path.join(root, 'home');
+ const systemAuth = path.join(home, '.codex', 'auth.json');
+ const codexHome = path.join(h.userDataDir, 'codex-home');
+ const localAuth = path.join(codexHome, 'auth.json');
+ const bindingFile = path.join(h.userDataDir, 'native-provider-auth.json');
+ vi.spyOn(os, 'homedir').mockReturnValue(home);
+ const chmodSpy = vi.spyOn(fs.promises, 'chmod');
+ fs.mkdirSync(path.dirname(systemAuth), { recursive: true });
+ fs.mkdirSync(codexHome, { recursive: true });
+ fs.writeFileSync(
+ systemAuth,
+ JSON.stringify({ tokens: { access_token: 'system-f1-token', account_id: 'acct-1' } }),
+ { mode: 0o600 },
+ );
+ fs.linkSync(systemAuth, localAuth);
+ fs.writeFileSync(
+ bindingFile,
+ JSON.stringify({
+ openai: 'owner-a',
+ selfAuthorized: { openai: 'owner-a' },
+ sources: { openai: 'explicit-provider-oauth' },
+ sharedSystemCredential: { openai: 'owner-a' },
+ }),
+ );
+
+ const { DesktopCodexAuthAdapter } = await import('../auth-adapters.js');
+ const adapter = new DesktopCodexAuthAdapter();
+ const f1Fingerprint = currentCodexAuthFileFingerprint(localAuth);
+ const f1Generation = adapter.captureCredentialGeneration();
+ expect(f1Fingerprint).not.toBeNull();
+ expect(f1Generation).not.toBeNull();
+
+ const replacement = path.join(path.dirname(systemAuth), 'auth.f2.json');
+ fs.writeFileSync(
+ replacement,
+ JSON.stringify({ tokens: { access_token: 'system-f2-token', account_id: 'acct-1' } }),
+ { mode: 0o600 },
+ );
+ fs.renameSync(replacement, systemAuth);
+ const systemF2Before = fs.readFileSync(systemAuth);
+ const systemF2StatBefore = fs.statSync(systemAuth);
+ const onLogoutSuccess = vi.fn().mockResolvedValue(undefined);
+ const broadcast = vi.fn().mockResolvedValue(undefined);
+ adapter.setOnLogoutSuccess(onLogoutSuccess);
+ adapter.setOnInvalidatedBroadcast(broadcast);
+
+ await expect(
+ adapter.invalidate('late_f1_401', { credentialGeneration: f1Generation }),
+ ).resolves.toBeUndefined();
+
+ expect(readInvalidatedSystemCodexAuthMarker(codexHome)).toMatchObject({
+ reason: 'late_f1_401',
+ credentialScope: 'system-shared',
+ recoveryOwnerId: 'owner-a',
+ sha256: f1Fingerprint!.sha256,
+ });
+ expect(onLogoutSuccess).toHaveBeenCalledOnce();
+ expect(broadcast).toHaveBeenCalledWith('late_f1_401', 'system-shared');
+ expect(fs.readFileSync(systemAuth)).toEqual(systemF2Before);
+ expect(fs.statSync(systemAuth)).toMatchObject({
+ ino: systemF2StatBefore.ino,
+ mode: systemF2StatBefore.mode,
+ });
+
+ const restartedAdapter = new DesktopCodexAuthAdapter();
+ await expect(
+ restartedAdapter.getState({ credentialMode: 'oauth-bearer' }),
+ ).resolves.toMatchObject({
+ authenticated: true,
+ credentialScope: 'system-shared',
+ recoveryRequiredReason: 'late_f1_401',
+ });
+ expectPlatformSharedLink(systemAuth, localAuth);
+ await expect(restartedAdapter.getAccessToken()).resolves.toBe('system-f2-token');
+ await restartedAdapter.verifyRecoveryWithAccountRpc(async () => undefined);
+ expect(readInvalidatedSystemCodexAuthMarker(codexHome)).toBeNull();
+ expect(fs.readFileSync(systemAuth)).toEqual(systemF2Before);
+ expect(chmodSpy).not.toHaveBeenCalled();
+ } finally {
+ Object.defineProperty(process, 'platform', {
+ value: originalPlatform,
+ configurable: true,
+ });
+ }
+ });
+
+ it('tracks a consumed symlink target generation until a later system replacement', async () => {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'xdt-codex-shared-generation-'));
+ dirs.push(root);
+ h.userDataDir = path.join(root, 'user-data');
+ h.dataOwnerId = 'owner-b';
+ const home = path.join(root, 'home');
+ const systemAuth = path.join(home, '.codex', 'auth.json');
+ const codexHome = path.join(h.userDataDir, 'codex-home');
+ const localAuth = path.join(codexHome, 'auth.json');
+ const bindingFile = path.join(h.userDataDir, 'native-provider-auth.json');
+ vi.spyOn(os, 'homedir').mockReturnValue(home);
+ fs.mkdirSync(path.dirname(systemAuth), { recursive: true });
+ fs.mkdirSync(codexHome, { recursive: true });
+ fs.writeFileSync(
+ systemAuth,
+ JSON.stringify({
+ account: { email: '[email protected]' },
+ tokens: { access_token: 'system-f1-token', account_id: 'acct-1' },
+ }),
+ );
+ fs.linkSync(systemAuth, localAuth);
+ fs.mkdirSync(h.userDataDir, { recursive: true });
+ fs.writeFileSync(bindingFile, JSON.stringify({ openai: 'owner-b' }));
+
+ const { DesktopCodexAuthAdapter } = await import('../auth-adapters.js');
+ const adapter = new DesktopCodexAuthAdapter();
+ await expect(adapter.getAccessToken()).resolves.toBe('system-f1-token');
+ expectPlatformSharedLink(systemAuth, localAuth);
+
+ const f2Replacement = path.join(path.dirname(systemAuth), 'auth.f2.json');
+ fs.writeFileSync(
+ f2Replacement,
+ JSON.stringify({
+ account: { email: '[email protected]' },
+ tokens: { access_token: 'system-f2-token', account_id: 'acct-1' },
+ }),
+ );
+ fs.renameSync(f2Replacement, systemAuth);
+ // Crossing the healthy shared reconcile boundary proves F2 is now the consumed generation.
+ await expect(adapter.getAccessToken()).resolves.toBe('system-f2-token');
+ const f2Fingerprint = currentCodexAuthFileFingerprint(systemAuth);
+ const f2Generation = adapter.captureCredentialGeneration();
+ expect(f2Fingerprint).not.toBeNull();
+ expect(f2Generation).not.toBeNull();
+
+ await expect(
+ adapter.invalidate('token_revoked', { credentialGeneration: f2Generation }),
+ ).resolves.toBeUndefined();
expect(readInvalidatedSystemCodexAuthMarker(codexHome)).toMatchObject({
credentialScope: 'system-shared',
- recoveryOwnerId: 'owner-b',
+ sha256: f2Fingerprint!.sha256,
});
- expect(JSON.parse(fs.readFileSync(bindingFile, 'utf8'))).not.toHaveProperty('revoked.openai');
+ expect(getActiveInvalidatedSystemCodexAuthMarker(codexHome, systemAuth)).not.toBeNull();
+ await expect(adapter.getState({ credentialMode: 'oauth-bearer' })).resolves.toMatchObject({
+ authenticated: false,
+ errorReason: 'token_revoked',
+ credentialScope: 'system-shared',
+ });
+ await expect(adapter.getAccessToken()).resolves.toBeNull();
+ const f3Replacement = path.join(path.dirname(systemAuth), 'auth.f3.json');
+ fs.writeFileSync(
+ f3Replacement,
+ JSON.stringify({
+ account: { email: '[email protected]' },
+ tokens: { access_token: 'system-f3-token', account_id: 'acct-1' },
+ }),
+ );
+ fs.renameSync(f3Replacement, systemAuth);
await expect(adapter.getState({ credentialMode: 'oauth-bearer' })).resolves.toMatchObject({
authenticated: true,
authSource: 'oauth',
credentialScope: 'system-shared',
recoveryRequiredReason: 'token_revoked',
});
- await expect(adapter.getAccessToken()).resolves.toBe('renewed-system-token');
+ await expect(adapter.getAccessToken()).resolves.toBe('system-f3-token');
+ });
- const restartedAdapter = new DesktopCodexAuthAdapter();
+ it('ignores a late shared-host invalidation across lossless Windows file IDs', async () => {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'xdt-codex-host-generation-'));
+ dirs.push(root);
+ h.userDataDir = path.join(root, 'user-data');
+ h.dataOwnerId = 'owner-b';
+ const home = path.join(root, 'home');
+ const systemAuth = path.join(home, '.codex', 'auth.json');
+ const codexHome = path.join(h.userDataDir, 'codex-home');
+ const localAuth = path.join(codexHome, 'auth.json');
+ const bindingFile = path.join(h.userDataDir, 'native-provider-auth.json');
+ vi.spyOn(os, 'homedir').mockReturnValue(home);
+ fs.mkdirSync(path.dirname(systemAuth), { recursive: true });
+ fs.mkdirSync(codexHome, { recursive: true });
+ fs.writeFileSync(
+ systemAuth,
+ JSON.stringify({ tokens: { access_token: 'system-f1-token', account_id: 'acct-1' } }),
+ );
+ fs.linkSync(systemAuth, localAuth);
+ fs.mkdirSync(h.userDataDir, { recursive: true });
+ fs.writeFileSync(bindingFile, JSON.stringify({ openai: 'owner-b' }));
+
+ const realFstatSync = fs.fstatSync.bind(fs);
+ const realStatSync = fs.statSync.bind(fs);
+ let exactIno = 9_007_199_254_740_992n;
+ vi.spyOn(fs, 'fstatSync').mockImplementation(((fd: number) => ({
+ ...realFstatSync(fd, { bigint: true }),
+ ino: exactIno,
+ })) as typeof fs.fstatSync);
+ vi.spyOn(fs, 'statSync').mockImplementation(((target: fs.PathLike, options?: unknown) => {
+ if (
+ typeof options === 'object' &&
+ options !== null &&
+ 'bigint' in options &&
+ (options as { bigint?: boolean }).bigint
+ ) {
+ return realStatSync(target, { bigint: true });
+ }
+ const stat = realStatSync(target);
+ return path.resolve(String(target)) === path.resolve(localAuth)
+ ? { ...stat, ino: Number(exactIno) }
+ : stat;
+ }) as typeof fs.statSync);
+
+ const { DesktopCodexAuthAdapter } = await import('../auth-adapters.js');
+ const adapter = new DesktopCodexAuthAdapter();
+ await expect(adapter.getAccessToken()).resolves.toBe('system-f1-token');
+ const f1Fingerprint = currentCodexAuthFileFingerprint(localAuth);
+ const f1Generation = adapter.captureCredentialGeneration();
+ expect(f1Fingerprint).not.toBeNull();
+ expect(f1Generation).not.toBeNull();
+ expect(JSON.parse(f1Generation!).ino).toBe('9007199254740992');
+
+ const f2Replacement = path.join(path.dirname(systemAuth), 'auth.f2.json');
+ fs.writeFileSync(
+ f2Replacement,
+ JSON.stringify({ tokens: { access_token: 'system-f2-token', account_id: 'acct-1' } }),
+ );
+ fs.renameSync(f2Replacement, systemAuth);
+ exactIno = 9_007_199_254_740_993n;
+ expect(Number(9_007_199_254_740_992n)).toBe(Number(exactIno));
+ const f2Before = fs.readFileSync(systemAuth);
+ const f2StatBefore = fs.statSync(systemAuth);
+ const onLogoutSuccess = vi.fn().mockResolvedValue(undefined);
+ const broadcast = vi.fn().mockResolvedValue(undefined);
+ adapter.setOnLogoutSuccess(onLogoutSuccess);
+ adapter.setOnInvalidatedBroadcast(broadcast);
+
+ await Promise.all([
+ adapter.getState({ credentialMode: 'oauth-bearer' }),
+ adapter.getAccessToken(),
+ ]);
await expect(
- restartedAdapter.getState({ credentialMode: 'oauth-bearer' }),
- ).resolves.toMatchObject({
+ adapter.invalidate('late_f1_401', { credentialGeneration: f1Generation }),
+ ).resolves.toBeUndefined();
+
+ expect(readInvalidatedSystemCodexAuthMarker(codexHome)).toBeNull();
+ expect(getActiveInvalidatedSystemCodexAuthMarker(codexHome, systemAuth)).toBeNull();
+ expect(onLogoutSuccess).not.toHaveBeenCalled();
+ expect(broadcast).not.toHaveBeenCalled();
+ await expect(adapter.getState({ credentialMode: 'oauth-bearer' })).resolves.toMatchObject({
authenticated: true,
- authSource: 'oauth',
credentialScope: 'system-shared',
- recoveryRequiredReason: 'token_revoked',
});
+ await expect(adapter.getAccessToken()).resolves.toBe('system-f2-token');
+ expect(fs.readFileSync(systemAuth)).toEqual(f2Before);
+ const f2StatAfter = fs.statSync(systemAuth);
+ expect({ dev: f2StatAfter.dev, ino: f2StatAfter.ino, mode: f2StatAfter.mode }).toEqual({
+ dev: f2StatBefore.dev,
+ ino: f2StatBefore.ino,
+ mode: f2StatBefore.mode,
+ });
+ });
+
+ it.each([
+ { identity: 'same inode', zeroInode: false },
+ { identity: 'zero inode', zeroInode: true },
+ ])('fails closed when a host credential rotates in place with $identity', async ({
+ zeroInode,
+ }) => {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'xdt-codex-in-place-generation-'));
+ dirs.push(root);
+ h.userDataDir = path.join(root, 'user-data');
+ h.dataOwnerId = 'owner-b';
+ const home = path.join(root, 'home');
+ const systemAuth = path.join(home, '.codex', 'auth.json');
+ const codexHome = path.join(h.userDataDir, 'codex-home');
+ const localAuth = path.join(codexHome, 'auth.json');
+ const bindingFile = path.join(h.userDataDir, 'native-provider-auth.json');
+ vi.spyOn(os, 'homedir').mockReturnValue(home);
+ fs.mkdirSync(path.dirname(systemAuth), { recursive: true });
+ fs.mkdirSync(codexHome, { recursive: true });
+ fs.writeFileSync(
+ systemAuth,
+ JSON.stringify({ tokens: { access_token: 'system-f1-token', account_id: 'acct-1' } }),
+ );
+ fs.linkSync(systemAuth, localAuth);
+ fs.mkdirSync(h.userDataDir, { recursive: true });
+ fs.writeFileSync(bindingFile, JSON.stringify({ openai: 'owner-b' }));
+
+ if (zeroInode) {
+ const realFstatSync = fs.fstatSync.bind(fs);
+ vi.spyOn(fs, 'fstatSync').mockImplementation(((fd: number) => ({
+ ...realFstatSync(fd, { bigint: true }),
+ ino: 0n,
+ })) as typeof fs.fstatSync);
+ }
+
+ const { DesktopCodexAuthAdapter } = await import('../auth-adapters.js');
+ const adapter = new DesktopCodexAuthAdapter();
+ const f1Generation = adapter.captureCredentialGeneration();
+ const f1Stat = fs.statSync(systemAuth);
+ expect(f1Generation).not.toBeNull();
+ if (zeroInode) expect(JSON.parse(f1Generation!).ino).toBe('0');
+
+ fs.writeFileSync(
+ systemAuth,
+ JSON.stringify({ tokens: { access_token: 'system-f2-token', account_id: 'acct-1' } }),
+ );
+ const f2Bytes = fs.readFileSync(systemAuth);
+ const f2Stat = fs.statSync(systemAuth);
+ expect({ dev: f2Stat.dev, ino: f2Stat.ino }).toEqual({ dev: f1Stat.dev, ino: f1Stat.ino });
+ const onLogoutSuccess = vi.fn().mockResolvedValue(undefined);
+ const broadcast = vi.fn().mockResolvedValue(undefined);
+ adapter.setOnLogoutSuccess(onLogoutSuccess);
+ adapter.setOnInvalidatedBroadcast(broadcast);
+
+ await adapter.invalidate('f2_token_revoked', { credentialGeneration: f1Generation });
+
expect(readInvalidatedSystemCodexAuthMarker(codexHome)).toMatchObject({
- recoveryOwnerId: 'owner-b',
+ reason: 'f2_token_revoked',
+ credentialScope: 'unknown',
+ });
+ expect(onLogoutSuccess).toHaveBeenCalledOnce();
+ expect(broadcast).toHaveBeenCalledWith('f2_token_revoked', 'unknown');
+ expect(fs.existsSync(localAuth)).toBe(false);
+ expect(fs.readFileSync(systemAuth)).toEqual(f2Bytes);
+ const systemAfter = fs.statSync(systemAuth);
+ expect({ dev: systemAfter.dev, ino: systemAfter.ino, mode: systemAfter.mode }).toEqual({
+ dev: f2Stat.dev,
+ ino: f2Stat.ino,
+ mode: f2Stat.mode,
+ });
+ await expect(adapter.getState({ credentialMode: 'oauth-bearer' })).resolves.toMatchObject({
+ authenticated: false,
+ errorReason: 'f2_token_revoked',
+ credentialScope: 'unknown',
});
+ await expect(adapter.getAccessToken()).resolves.toBeNull();
+ });
- await restartedAdapter.verifyRecoveryWithAccountRpc(async () => undefined);
+ it('preserves an in-flight Cindy F2 login when an F1 host reports a late invalidation', async () => {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'xdt-codex-stale-host-login-'));
+ dirs.push(root);
+ h.userDataDir = path.join(root, 'user-data');
+ h.dataOwnerId = 'owner-a';
+ const home = path.join(root, 'home');
+ const codexHome = path.join(h.userDataDir, 'codex-home');
+ const localAuth = path.join(codexHome, 'auth.json');
+ const bindingFile = path.join(h.userDataDir, 'native-provider-auth.json');
+ const cachePath = path.join(codexHome, 'models_cache.json');
+ vi.spyOn(os, 'homedir').mockReturnValue(home);
+ fs.mkdirSync(codexHome, { recursive: true });
+ fs.mkdirSync(h.userDataDir, { recursive: true });
+ fs.writeFileSync(
+ localAuth,
+ JSON.stringify({ tokens: { access_token: 'host-f1-token', account_id: 'acct-1' } }),
+ );
+ fs.writeFileSync(bindingFile, JSON.stringify({ openai: 'owner-a' }));
+
+ const { DesktopCodexAuthAdapter } = await import('../auth-adapters.js');
+ const adapter = new DesktopCodexAuthAdapter();
+ const f1Generation = adapter.captureCredentialGeneration();
+ expect(f1Generation).not.toBeNull();
+
+ fs.writeFileSync(
+ localAuth,
+ JSON.stringify({ tokens: { access_token: 'cindy-f2-token', account_id: 'acct-2' } }),
+ );
+ const loginFinalizeGate = deferred();
+ const onLoginSuccess = vi.fn(() => loginFinalizeGate.promise);
+ const onLogoutSuccess = vi.fn().mockResolvedValue(undefined);
+ const broadcast = vi.fn().mockResolvedValue(undefined);
+ adapter.setOnLoginSuccess(onLoginSuccess);
+ adapter.setOnLogoutSuccess(onLogoutSuccess);
+ adapter.setOnInvalidatedBroadcast(broadcast);
+ const finishSuccessfulCodexLogin = (
+ adapter as unknown as {
+ finishSuccessfulCodexLogin(): Promise<{ authenticated: boolean; credentialScope?: string }>;
+ }
+ ).finishSuccessfulCodexLogin.bind(adapter);
+ (adapter as unknown as { loginCancellationOpen: boolean }).loginCancellationOpen = true;
+ const loginFinalization = finishSuccessfulCodexLogin();
+ await vi.waitFor(() => expect(onLoginSuccess).toHaveBeenCalledOnce());
+ fs.writeFileSync(cachePath, JSON.stringify({ models: [{ slug: 'f2-model' }] }));
+ const f2Before = fs.readFileSync(localAuth);
+
+ await expect(
+ adapter.invalidate('late_f1_401', { credentialGeneration: f1Generation }),
+ ).resolves.toBeUndefined();
+
+ expect(fs.readFileSync(localAuth)).toEqual(f2Before);
+ expect(fs.existsSync(cachePath)).toBe(true);
expect(readInvalidatedSystemCodexAuthMarker(codexHome)).toBeNull();
+ expect(onLogoutSuccess).not.toHaveBeenCalled();
+ expect(broadcast).not.toHaveBeenCalled();
expect(JSON.parse(fs.readFileSync(bindingFile, 'utf8'))).toMatchObject({
- legacyClaimOwner: 'owner-a',
- openai: 'owner-b',
+ openai: 'owner-a',
+ selfAuthorized: { openai: 'owner-a' },
+ sources: { openai: 'explicit-provider-oauth' },
+ });
+
+ loginFinalizeGate.resolve();
+ await expect(loginFinalization).resolves.toMatchObject({
+ authenticated: true,
+ credentialScope: 'instance-isolated',
+ });
+ await expect(adapter.getAccessToken()).resolves.toBe('cindy-f2-token');
+ });
+
+ it.each([
+ { platform: 'darwin', label: 'POSIX' },
+ { platform: 'win32', label: 'Windows' },
+ ])('preserves a tracked login when an F1 host fails during the $label cleanup window', async ({
+ platform,
+ }) => {
+ const originalPlatform = process.platform;
+ Object.defineProperty(process, 'platform', { value: platform, configurable: true });
+ try {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'xdt-codex-login-cleanup-race-'));
+ dirs.push(root);
+ h.userDataDir = path.join(root, 'user-data');
+ h.dataOwnerId = 'owner-a';
+ const codexHome = path.join(h.userDataDir, 'codex-home');
+ const localAuth = path.join(codexHome, 'auth.json');
+ const bindingFile = path.join(h.userDataDir, 'native-provider-auth.json');
+ fs.mkdirSync(codexHome, { recursive: true });
+ fs.mkdirSync(h.userDataDir, { recursive: true });
+ fs.writeFileSync(
+ localAuth,
+ JSON.stringify({ tokens: { access_token: 'host-f1-token', account_id: 'acct-1' } }),
+ );
+ fs.writeFileSync(bindingFile, JSON.stringify({ openai: 'owner-a' }));
+
+ const { clearCodexAuthBoundaryStateBeforeLogin, DesktopCodexAuthAdapter } = await import(
+ '../auth-adapters.js'
+ );
+ const adapter = new DesktopCodexAuthAdapter();
+ const f1Generation = adapter.captureCredentialGeneration();
+ expect(f1Generation).not.toBeNull();
+ await expect(
+ clearCodexAuthBoundaryStateBeforeLogin(codexHome, { forceRemoveAuth: true }),
+ ).resolves.toBe(true);
+ expect(fs.existsSync(localAuth)).toBe(false);
+
+ const loginGate = deferred<{ authenticated: boolean }>();
+ const trackedLogin = { promise: loginGate.promise, cancelled: false };
+ const privateState = adapter as unknown as {
+ pendingLogin: typeof trackedLogin | null;
+ loginCancellationOpen: boolean;
+ };
+ privateState.pendingLogin = trackedLogin;
+ privateState.loginCancellationOpen = true;
+ const onLogoutSuccess = vi.fn().mockResolvedValue(undefined);
+ const broadcast = vi.fn().mockResolvedValue(undefined);
+ const chmodSpy = vi.spyOn(fs.promises, 'chmod');
+ adapter.setOnLogoutSuccess(onLogoutSuccess);
+ adapter.setOnInvalidatedBroadcast(broadcast);
+
+ const invalidation = adapter.invalidate('late_f1_401', {
+ credentialGeneration: f1Generation,
+ });
+ const f2Bytes = Buffer.from(
+ JSON.stringify({ tokens: { access_token: 'cindy-f2-token', account_id: 'acct-2' } }),
+ );
+ fs.writeFileSync(localAuth, f2Bytes);
+ loginGate.resolve({ authenticated: true });
+ await expect(invalidation).resolves.toBeUndefined();
+
+ expect(trackedLogin.cancelled).toBe(false);
+ expect(fs.readFileSync(localAuth)).toEqual(f2Bytes);
+ expect(readInvalidatedSystemCodexAuthMarker(codexHome)).toBeNull();
+ expect(onLogoutSuccess).not.toHaveBeenCalled();
+ expect(broadcast).not.toHaveBeenCalled();
+ expect(chmodSpy).not.toHaveBeenCalled();
+ expect(JSON.parse(fs.readFileSync(bindingFile, 'utf8'))).toMatchObject({
+ openai: 'owner-a',
+ });
+ } finally {
+ Object.defineProperty(process, 'platform', {
+ value: originalPlatform,
+ configurable: true,
+ });
+ }
+ });
+
+ it('does not apply a stale orphan reconcile after a login writes local auth', async () => {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'xdt-codex-login-reconcile-race-'));
+ dirs.push(root);
+ h.userDataDir = path.join(root, 'user-data');
+ h.dataOwnerId = 'owner-a';
+ const home = path.join(root, 'home');
+ const systemAuth = path.join(home, '.codex', 'auth.json');
+ const localAuth = path.join(h.userDataDir, 'codex-home', 'auth.json');
+ vi.spyOn(os, 'homedir').mockReturnValue(home);
+ fs.mkdirSync(path.dirname(systemAuth), { recursive: true });
+ fs.mkdirSync(path.dirname(localAuth), { recursive: true });
+ fs.writeFileSync(
+ systemAuth,
+ JSON.stringify({ tokens: { access_token: 'system-a-token', account_id: 'acct-a' } }),
+ );
+
+ const originalReadFile = fs.promises.readFile;
+ const systemReadStarted = deferred();
+ const continueSystemRead = deferred();
+ let heldSystemRead = false;
+ vi.spyOn(fs.promises, 'readFile').mockImplementation(((target: unknown, ...rest: unknown[]) => {
+ if (!heldSystemRead && path.resolve(String(target)) === path.resolve(systemAuth)) {
+ heldSystemRead = true;
+ systemReadStarted.resolve();
+ return continueSystemRead.promise.then(() =>
+ (originalReadFile as (...args: unknown[]) => unknown)(target, ...rest),
+ );
+ }
+ return (originalReadFile as (...args: unknown[]) => unknown)(target, ...rest);
+ }) as typeof fs.promises.readFile);
+
+ const { DesktopCodexAuthAdapter } = await import('../auth-adapters.js');
+ const adapter = new DesktopCodexAuthAdapter();
+ const reconcile = (
+ adapter as unknown as { reconcileWithSystemCodex(): Promise<void> }
+ ).reconcileWithSystemCodex.bind(adapter);
+ const inFlightReconcile = reconcile();
+ await systemReadStarted.promise;
+
+ (adapter as unknown as { loginCancellationOpen: boolean }).loginCancellationOpen = true;
+ fs.writeFileSync(
+ localAuth,
+ JSON.stringify({ tokens: { access_token: 'cindy-b-token', account_id: 'acct-b' } }),
+ );
+ const localBeforeResume = fs.readFileSync(localAuth);
+ const systemBeforeResume = fs.readFileSync(systemAuth);
+ continueSystemRead.resolve();
+ await inFlightReconcile;
+
+ expect(fs.readFileSync(localAuth)).toEqual(localBeforeResume);
+ expect(fs.readFileSync(systemAuth)).toEqual(systemBeforeResume);
+ expect(fs.lstatSync(localAuth).isSymbolicLink()).toBe(false);
+ expect(fs.existsSync(path.join(h.userDataDir, 'native-provider-auth.json'))).toBe(false);
+ });
+
+ it('repairs an unproven local auth orphan instead of preserving its refresh token', async () => {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'xdt-codex-orphan-repair-'));
+ dirs.push(root);
+ h.userDataDir = path.join(root, 'user-data');
+ h.dataOwnerId = 'owner-a';
+ const home = path.join(root, 'home');
+ const systemAuth = path.join(home, '.codex', 'auth.json');
+ const localAuth = path.join(h.userDataDir, 'codex-home', 'auth.json');
+ vi.spyOn(os, 'homedir').mockReturnValue(home);
+ fs.mkdirSync(path.dirname(systemAuth), { recursive: true });
+ fs.mkdirSync(path.dirname(localAuth), { recursive: true });
+ fs.writeFileSync(
+ systemAuth,
+ JSON.stringify({ tokens: { access_token: 'system-token', account_id: 'system-account' } }),
+ );
+ fs.writeFileSync(
+ localAuth,
+ JSON.stringify({ tokens: { access_token: 'orphan-token', account_id: 'old-account' } }),
+ );
+ fs.writeFileSync(
+ path.join(h.userDataDir, 'native-provider-auth.json'),
+ JSON.stringify({
+ openai: 'owner-a',
+ sources: { openai: 'native-harness-inherited' },
+ }),
+ );
+
+ const { DesktopCodexAuthAdapter } = await import('../auth-adapters.js');
+ const state = await new DesktopCodexAuthAdapter().getState({ credentialMode: 'oauth-bearer' });
+
+ expect(state).toMatchObject({
+ authenticated: true,
+ credentialScope: 'system-shared',
+ credentialDiagnostics: {
+ linkType: expectedSharedLinkType,
+ healthy: true,
+ orphanRepair: 'relinked',
+ },
+ });
+ expectPlatformSharedLink(systemAuth, localAuth);
+ expect(fs.readFileSync(localAuth, 'utf8')).toContain('system-token');
+ });
+
+ it('preserves explicit isolated auth across owner A to B to A without exposing it to B', async () => {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'xdt-codex-isolated-preserve-'));
+ dirs.push(root);
+ h.userDataDir = path.join(root, 'user-data');
+ h.dataOwnerId = 'owner-a';
+ const home = path.join(root, 'home');
+ const systemAuth = path.join(home, '.codex', 'auth.json');
+ const localAuth = path.join(h.userDataDir, 'codex-home', 'auth.json');
+ vi.spyOn(os, 'homedir').mockReturnValue(home);
+ fs.mkdirSync(path.dirname(systemAuth), { recursive: true });
+ fs.mkdirSync(path.dirname(localAuth), { recursive: true });
+ fs.writeFileSync(
+ systemAuth,
+ JSON.stringify({ tokens: { access_token: 'system-token', account_id: 'system-account' } }),
+ );
+ fs.writeFileSync(
+ localAuth,
+ JSON.stringify({ tokens: { access_token: 'isolated-token', account_id: 'other-account' } }),
+ );
+ fs.writeFileSync(
+ path.join(h.userDataDir, 'native-provider-auth.json'),
+ JSON.stringify({
+ openai: 'owner-a',
+ selfAuthorized: { openai: 'owner-a' },
+ sources: { openai: 'explicit-provider-oauth' },
+ instanceIsolatedCredential: { openai: 'owner-a' },
+ }),
+ );
+
+ const bindingFile = path.join(h.userDataDir, 'native-provider-auth.json');
+ const { DesktopCodexAuthAdapter } = await import('../auth-adapters.js');
+ const ownerAAdapter = new DesktopCodexAuthAdapter();
+ const state = await ownerAAdapter.getState({ credentialMode: 'oauth-bearer' });
+
+ expect(state).toMatchObject({
+ authenticated: true,
+ credentialScope: 'instance-isolated',
+ credentialDiagnostics: {
+ linkType: 'file',
+ healthy: true,
+ orphanRepair: 'none',
+ },
+ });
+ expect(fs.lstatSync(localAuth).isSymbolicLink()).toBe(false);
+ expect(fs.readFileSync(localAuth, 'utf8')).toContain('isolated-token');
+ await expect(ownerAAdapter.getAccessToken()).resolves.toBe('isolated-token');
+
+ const localBeforeSwitch = fs.readFileSync(localAuth);
+ const systemBeforeSwitch = fs.readFileSync(systemAuth);
+ const systemStatBeforeSwitch = fs.statSync(systemAuth);
+ h.dataOwnerId = 'owner-b';
+ h.sessionGeneration += 1;
+ const ownerBAdapter = new DesktopCodexAuthAdapter();
+
+ await expect(ownerBAdapter.getState()).resolves.toEqual({
+ authenticated: false,
+ errorReason: 'oauth_not_bound',
+ });
+ await expect(ownerBAdapter.getAccessToken()).resolves.toBeNull();
+ expect(fs.readFileSync(localAuth)).toEqual(localBeforeSwitch);
+ expect(fs.readFileSync(systemAuth)).toEqual(systemBeforeSwitch);
+ expect(fs.statSync(systemAuth).ino).toBe(systemStatBeforeSwitch.ino);
+ expect(JSON.parse(fs.readFileSync(bindingFile, 'utf8'))).toMatchObject({
+ openai: 'owner-a',
+ selfAuthorized: { openai: 'owner-a' },
+ sources: { openai: 'explicit-provider-oauth' },
+ });
+
+ h.dataOwnerId = 'owner-a';
+ h.sessionGeneration += 1;
+ const restoredOwnerAAdapter = new DesktopCodexAuthAdapter();
+ await expect(
+ restoredOwnerAAdapter.getState({ credentialMode: 'oauth-bearer' }),
+ ).resolves.toMatchObject({
+ authenticated: true,
+ credentialScope: 'instance-isolated',
});
+ await expect(restoredOwnerAAdapter.getAccessToken()).resolves.toBe('isolated-token');
+ expect(fs.readFileSync(localAuth)).toEqual(localBeforeSwitch);
});
it('real token invalidation still surfaces its reason when no replacement local credential exists', () => {
diff --git a/apps/desktop/src/main/maker-host/__tests__/codexAuthIsolatedSandbox.test.ts b/apps/desktop/src/main/maker-host/__tests__/codexAuthIsolatedSandbox.test.ts
index f2e193bdc0..9145b8dec7 100644
--- a/apps/desktop/src/main/maker-host/__tests__/codexAuthIsolatedSandbox.test.ts
+++ b/apps/desktop/src/main/maker-host/__tests__/codexAuthIsolatedSandbox.test.ts
@@ -30,6 +30,11 @@ vi.mock('electron', () => ({
vi.mock('@cindy/maker-core', () => ({}));
+vi.mock('../../agent-binaries/index.js', () => ({
+ getCachedBinaryStatus: () => ({ binaryReady: false, binaryPath: null }),
+ isVettedAgentBinaryPath: () => false,
+}));
+
vi.mock('../../appSessionState.js', async (importOriginal) => {
const actual = await importOriginal<typeof import('../../appSessionState.js')>();
return {
@@ -125,6 +130,36 @@ describe('dev 沙箱凭证隔离(XDT_ISOLATED_AUTH)', () => {
);
});
+ it.runIf(process.platform !== 'win32')(
+ '开关开:系统凭证缺失时清除悬空共享软链,恢复后仍保持隔离',
+ async () => {
+ const { codexHome, localAuth, systemAuth } = fixture();
+ fs.mkdirSync(codexHome, { recursive: true });
+ fs.rmSync(systemAuth);
+ fs.symlinkSync(systemAuth, localAuth);
+ expect(fs.lstatSync(localAuth).isSymbolicLink()).toBe(true);
+ expect(fs.existsSync(localAuth)).toBe(false);
+
+ trustIsolatedAuthSandbox();
+ h.dataOwnerId = 'owner-a';
+ const { DesktopCodexAuthAdapter } = await import('../auth-adapters.js');
+ const adapter = new DesktopCodexAuthAdapter();
+ await expect(adapter.getState()).resolves.toMatchObject({ authenticated: false });
+ expect(() => fs.lstatSync(localAuth)).toThrow();
+
+ fs.writeFileSync(
+ systemAuth,
+ JSON.stringify({
+ account: { email: '[email protected]' },
+ tokens: { access_token: 'restored-system-token', account_id: 'acct-restored' },
+ }),
+ );
+ expect(fs.existsSync(localAuth)).toBe(false);
+ await expect(adapter.getState()).resolves.toMatchObject({ authenticated: false });
+ expect(fs.existsSync(localAuth)).toBe(false);
+ },
+ );
+
it('开关开:旧的独立凭证孤岛也会被清空', async () => {
const { codexHome, localAuth, systemAuth } = fixture();
fs.mkdirSync(codexHome, { recursive: true });
@@ -217,6 +252,56 @@ describe('dev 沙箱凭证隔离(XDT_ISOLATED_AUTH)', () => {
expect(fs.existsSync(getCodexAuthInvalidationMarkerPath(codexHome))).toBe(false);
});
+ it('dev 默认只读的 unproven 失效只保留内存边界', async () => {
+ const { codexHome, localAuth, systemAuth } = fixture();
+ h.dataOwnerId = 'owner-a';
+ const { DesktopCodexAuthAdapter, readCodexOneShotCreds } = await import('../auth-adapters.js');
+ const adapter = new DesktopCodexAuthAdapter();
+ const onInvalidated = vi.fn();
+ adapter.setOnInvalidatedBroadcast(onInvalidated);
+
+ await expect(adapter.getState({ credentialMode: 'oauth-bearer' })).resolves.toMatchObject({
+ authenticated: true,
+ credentialScope: 'system-shared',
+ oauthWritesBlocked: true,
+ });
+ const systemBytes = fs.readFileSync(systemAuth);
+ const localBytes = fs.readFileSync(localAuth);
+ const systemStat = fs.statSync(systemAuth);
+ const localStat = fs.statSync(localAuth);
+ const rm = vi.spyOn(fs.promises, 'rm');
+ const chmod = vi.spyOn(fs.promises, 'chmod');
+
+ await adapter.invalidate('child_auth_rejected', { credentialAttribution: 'unproven' });
+
+ expect(onInvalidated).toHaveBeenCalledWith('child_auth_rejected', 'system-shared', true);
+ await expect(adapter.getState({ credentialMode: 'oauth-bearer' })).resolves.toMatchObject({
+ authenticated: false,
+ errorReason: 'child_auth_rejected',
+ credentialScope: 'system-shared',
+ oauthWritesBlocked: true,
+ });
+ await expect(adapter.getAccessToken()).resolves.toBeNull();
+ await expect(adapter.getAccountId()).resolves.toBeNull();
+ expect(readCodexOneShotCreds(adapter)).toBeNull();
+ expect(fs.existsSync(getCodexAuthInvalidationMarkerPath(codexHome))).toBe(false);
+ expect(fs.readFileSync(systemAuth)).toEqual(systemBytes);
+ expect(fs.readFileSync(localAuth)).toEqual(localBytes);
+ expect(fs.statSync(systemAuth)).toMatchObject({ ino: systemStat.ino, mode: systemStat.mode });
+ expect(fs.statSync(localAuth)).toMatchObject({ ino: localStat.ino, mode: localStat.mode });
+ expect(rm).not.toHaveBeenCalled();
+ expect(chmod).not.toHaveBeenCalled();
+
+ await expect(
+ new DesktopCodexAuthAdapter().getState({ credentialMode: 'oauth-bearer' }),
+ ).resolves.toMatchObject({
+ authenticated: true,
+ credentialScope: 'system-shared',
+ oauthWritesBlocked: true,
+ });
+ expect(fs.existsSync(getCodexAuthInvalidationMarkerPath(codexHome))).toBe(false);
+ });
+
it('dev 只读失效以内存指纹等待系统凭证换代,不泄漏旧 token 或写共享文件', async () => {
const { codexHome, localAuth, systemAuth } = fixture();
h.dataOwnerId = 'owner-a';
@@ -302,6 +387,8 @@ describe('dev 沙箱凭证隔离(XDT_ISOLATED_AUTH)', () => {
credentialScope: 'system-shared',
oauthWritesBlocked: true,
});
+ const oldGeneration = adapter.captureCredentialGeneration();
+ expect(oldGeneration).not.toBeNull();
const oldLocalBytes = fs.readFileSync(localAuth);
const originalMode = fs.statSync(systemAuth).mode;
@@ -317,11 +404,15 @@ describe('dev 沙箱凭证隔离(XDT_ISOLATED_AUTH)', () => {
fs.renameSync(replacement, systemAuth);
const renewedSystemBytes = fs.readFileSync(systemAuth);
const renewedSystemStat = fs.statSync(systemAuth);
- expect(fs.readFileSync(localAuth)).toEqual(oldLocalBytes);
- expect(fs.readFileSync(localAuth)).not.toEqual(renewedSystemBytes);
+ if (process.platform === 'win32') {
+ expect(fs.readFileSync(localAuth)).toEqual(oldLocalBytes);
+ expect(fs.readFileSync(localAuth)).not.toEqual(renewedSystemBytes);
+ } else {
+ expect(fs.readFileSync(localAuth)).toEqual(renewedSystemBytes);
+ }
const chmod = vi.spyOn(fs.promises, 'chmod');
- await adapter.invalidate('late_host_401');
+ await adapter.invalidate('late_host_401', { credentialGeneration: oldGeneration });
expect(readCodexOneShotCreds(adapter)).toBeNull();
expect(fs.existsSync(getCodexAuthInvalidationMarkerPath(codexHome))).toBe(false);
@@ -432,6 +523,44 @@ describe('dev 沙箱凭证隔离(XDT_ISOLATED_AUTH)', () => {
).toBe(false);
});
+ it('排队登录在 logout barrier 后执行自己的 isolated-auth 清理', async () => {
+ const { codexHome, localAuth, systemAuth } = fixture();
+ fs.mkdirSync(codexHome, { recursive: true });
+ fs.writeFileSync(localAuth, JSON.stringify({ tokens: { access_token: 'stale-sandbox-token' } }));
+ const systemBytes = fs.readFileSync(systemAuth);
+ trustIsolatedAuthSandbox();
+ h.dataOwnerId = 'owner-a';
+ const { DesktopCodexAuthAdapter } = await import('../auth-adapters.js');
+ const adapter = new DesktopCodexAuthAdapter();
+ let finishLogout!: () => void;
+ const logoutOperation = new Promise<void>((resolve) => {
+ finishLogout = resolve;
+ });
+ const privateState = adapter as unknown as {
+ logoutOperation: Promise<void> | null;
+ isolatedAuthSanitized: boolean;
+ pendingLogin: unknown;
+ };
+ privateState.logoutOperation = logoutOperation;
+
+ const login = adapter.triggerLogin({ mode: 'device-code' });
+ await Promise.resolve();
+ expect(fs.existsSync(localAuth)).toBe(true);
+ expect(privateState.isolatedAuthSanitized).toBe(false);
+
+ privateState.logoutOperation = null;
+ finishLogout();
+ await expect(login).resolves.toMatchObject({
+ authenticated: false,
+ errorReason: 'codex_binary_missing',
+ });
+
+ expect(fs.existsSync(localAuth)).toBe(false);
+ expect(privateState.isolatedAuthSanitized).toBe(true);
+ expect(privateState.pendingLogin).toBeNull();
+ expect(fs.readFileSync(systemAuth)).toEqual(systemBytes);
+ });
+
it('proof 绑定其它 userData 时保持只读且不消费凭证', async () => {
const { localAuth, systemAuth } = fixture();
fs.mkdirSync(path.dirname(localAuth), { recursive: true });
diff --git a/apps/desktop/src/main/maker-host/__tests__/nativeProviderAuthBinding.test.ts b/apps/desktop/src/main/maker-host/__tests__/nativeProviderAuthBinding.test.ts
index 9ce065abd6..7440dcf456 100644
--- a/apps/desktop/src/main/maker-host/__tests__/nativeProviderAuthBinding.test.ts
+++ b/apps/desktop/src/main/maker-host/__tests__/nativeProviderAuthBinding.test.ts
@@ -29,8 +29,11 @@ import {
isNativeProviderAuthBound,
isNativeProviderAuthRevoked,
isNativeProviderAuthSelfAuthorized,
+ isNativeProviderAuthSharedSystemCredential,
+ markNativeProviderAuthSharedSystemCredential,
migrateLocalNativeProviderAuthBindings,
migrateLegacyNativeProviderAuthBindings,
+ readExplicitNativeProviderAuthOwner,
readLegacyNativeProviderAuthOwner,
recoverPendingLegacyNativeProviderAuthOwner,
reserveCommittedLegacyNativeProviderAuthOwner,
@@ -142,6 +145,37 @@ describe('local → cloud native provider binding migration', () => {
expect(fsyncSpy).toHaveBeenCalled();
});
+ it('keeps directory durability bound to the real host when link tests spoof the platform', () => {
+ const hostPlatform = process.platform;
+ const realFsync = fs.fsyncSync.bind(fs);
+ vi.spyOn(fs, 'fsyncSync').mockImplementation((fd) => {
+ if (fs.fstatSync(fd).isDirectory()) {
+ throw Object.assign(new Error('directory fsync is unsupported'), { code: 'EPERM' });
+ }
+ realFsync(fd);
+ });
+ Object.defineProperty(process, 'platform', {
+ value: hostPlatform === 'win32' ? 'darwin' : 'win32',
+ configurable: true,
+ });
+
+ try {
+ if (hostPlatform === 'win32') {
+ expect(reserveLegacyNativeProviderAuthOwner('owner-a')).toBe('claimed');
+ expect(JSON.parse(fs.readFileSync(bindingFile, 'utf8'))).toMatchObject({
+ legacyClaimOwner: 'owner-a',
+ });
+ } else {
+ expect(reserveLegacyNativeProviderAuthOwner('owner-a')).toBe('failed');
+ }
+ } finally {
+ Object.defineProperty(process, 'platform', {
+ value: hostPlatform,
+ configurable: true,
+ });
+ }
+ });
+
it('retries transient Windows-style binding publication locks', () => {
expect(reserveLegacyNativeProviderAuthOwner('owner-a')).toBe('claimed');
const originalRenameSync = fs.renameSync.bind(fs);
@@ -805,6 +839,42 @@ describe('凭证来路(selfAuthorized)—— 显式授权 vs 自动继承', () =
expect(isNativeProviderAuthSelfAuthorized('openai')).toBe(false);
});
+ it('新显式授权和登出都会清除旧的系统共享 provenance', () => {
+ bindNativeProviderAuth('openai');
+ expect(markNativeProviderAuthSharedSystemCredential('openai')).toBe(true);
+ expect(isNativeProviderAuthSharedSystemCredential('openai')).toBe(true);
+
+ bindNativeProviderAuth('openai');
+ expect(isNativeProviderAuthSharedSystemCredential('openai')).toBe(false);
+
+ expect(markNativeProviderAuthSharedSystemCredential('openai')).toBe(true);
+ unbindNativeProviderAuth('openai');
+ expect(isNativeProviderAuthSharedSystemCredential('openai')).toBe(false);
+ });
+
+ it('只有登录收尾证明的当前隔离凭证才可阻止 orphan repair', () => {
+ fs.mkdirSync(userDataDir, { recursive: true });
+ fs.writeFileSync(
+ bindingFile,
+ JSON.stringify({
+ openai: 'owner-a',
+ selfAuthorized: { openai: 'owner-a' },
+ sources: { openai: 'explicit-provider-oauth' },
+ }),
+ );
+
+ expect(readExplicitNativeProviderAuthOwner('openai')).toBeNull();
+
+ bindNativeProviderAuth('openai', { instanceIsolated: true });
+ expect(readExplicitNativeProviderAuthOwner('openai')).toBe('owner-a');
+ expect(JSON.parse(fs.readFileSync(bindingFile, 'utf8'))).toMatchObject({
+ instanceIsolatedCredential: { openai: 'owner-a' },
+ });
+
+ expect(markNativeProviderAuthSharedSystemCredential('openai')).toBe(true);
+ expect(readExplicitNativeProviderAuthOwner('openai')).toBeNull();
+ });
+
it('从没绑定过的 provider 不算自己授权过', () => {
expect(isNativeProviderAuthSelfAuthorized('xai')).toBe(false);
});
@@ -814,4 +884,23 @@ describe('凭证来路(selfAuthorized)—— 显式授权 vs 自动继承', () =
fs.writeFileSync(bindingFile, '{ this is not json');
expect(isNativeProviderAuthSelfAuthorized('anthropic')).toBe(true);
});
+
+ it.each([
+ ['provider owner', { openai: 42, selfAuthorized: { openai: 'owner-a' } }],
+ ['self-authorized owner', { openai: 'owner-a', selfAuthorized: { openai: 42 } }],
+ [
+ 'isolated credential owner',
+ { openai: 'owner-a', instanceIsolatedCredential: { openai: 42 } },
+ ],
+ ])('treats a non-string %s as unproven without rewriting the binding', (_case, value) => {
+ fs.mkdirSync(userDataDir, { recursive: true });
+ fs.writeFileSync(bindingFile, JSON.stringify(value));
+ const before = fs.readFileSync(bindingFile);
+
+ expect(() => readExplicitNativeProviderAuthOwner('openai')).not.toThrow();
+ expect(readExplicitNativeProviderAuthOwner('openai')).toBeNull();
+ expect(isNativeProviderAuthBound('openai')).toBe(false);
+ expect(claimDetectedNativeProviderAuth('openai', () => true)).toBe(false);
+ expect(fs.readFileSync(bindingFile)).toEqual(before);
+ });
});
diff --git a/apps/desktop/src/main/maker-host/auth-adapters.ts b/apps/desktop/src/main/maker-host/auth-adapters.ts
index 79d524a753..cbf078c23c 100644
--- a/apps/desktop/src/main/maker-host/auth-adapters.ts
+++ b/apps/desktop/src/main/maker-host/auth-adapters.ts
@@ -36,7 +36,7 @@ import { prepareCodexGlobalRulesCopy } from './codex-global-rules.js';
import { prepareCodexGlobalPluginsBridge } from './codex-global-plugins.js';
import { DESKTOP_CAPABILITY_ROUTING_POLICY } from './capability-routing.js';
import { prepareSharedGlobalSkillLinks } from './shared-global-skills.js';
-import { relinkSharedCodexAuth } from './codex-auth-link.js';
+import { inspectCodexAuthLink, relinkSharedCodexAuth } from './codex-auth-link.js';
import { claudeOAuthSpawnEnv } from './claude-oauth-spawn-env.js';
import {
CODEX_USER_DISCONNECT_REASON,
@@ -52,6 +52,8 @@ import {
shouldSuppressLocalCodexAuth,
updateInvalidatedSystemCodexAuthMarkerCredentialScope,
writeInvalidatedSystemCodexAuthMarker,
+ writeUnprovenCodexAuthSuppressionMarker,
+ type CodexAuthFileFingerprint,
type InvalidatedSystemCodexAuthMarker,
} from './codex-auth-invalidation.js';
import {
@@ -98,6 +100,11 @@ import {
isNativeProviderAuthBound,
isNativeProviderAuthRevoked,
isNativeProviderAuthSelfAuthorized,
+ isNativeProviderAuthSharedSystemCredential,
+ markNativeProviderAuthSharedSystemCredential,
+ migrateLegacyExplicitNativeProviderAuthToInstanceIsolated,
+ readExplicitNativeProviderAuthOwner,
+ readLegacyExplicitNativeProviderAuthOwner,
restoreNativeProviderAuthForRecovery,
unbindNativeProviderAuth,
} from './nativeProviderAuthBinding.js';
@@ -318,6 +325,68 @@ function pathsReferToSameFileSync(left: string, right: string): boolean {
);
}
+type CodexCredentialGeneration = {
+ dev: string;
+ ino: string;
+ size: number;
+ mtimeMs: number;
+ sha256: string;
+};
+
+const DECIMAL_FILE_ID_RE = /^(0|[1-9]\d*)$/;
+
+function currentCodexCredentialGeneration(authPath: string): CodexCredentialGeneration | null {
+ let fd: number | null = null;
+ try {
+ fd = fs.openSync(authPath, 'r');
+ const stat = fs.fstatSync(fd, { bigint: true });
+ const bytes = fs.readFileSync(fd);
+ return {
+ dev: stat.dev.toString(),
+ ino: stat.ino.toString(),
+ size: Number(stat.size),
+ mtimeMs: Number(stat.mtimeMs),
+ sha256: createHash('sha256').update(bytes).digest('hex'),
+ };
+ } catch {
+ return null;
+ } finally {
+ if (fd !== null) fs.closeSync(fd);
+ }
+}
+
+function parseCodexCredentialGeneration(
+ value: string | null | undefined,
+): CodexCredentialGeneration | null {
+ if (!value) return null;
+ try {
+ const parsed = JSON.parse(value) as Partial<Record<keyof CodexCredentialGeneration, unknown>>;
+ const parseFileId = (candidate: unknown): string | null => {
+ if (typeof candidate === 'string' && DECIMAL_FILE_ID_RE.test(candidate)) return candidate;
+ if (typeof candidate === 'number' && Number.isSafeInteger(candidate) && candidate >= 0) {
+ return String(candidate);
+ }
+ return null;
+ };
+ const dev = parseFileId(parsed.dev);
+ const ino = parseFileId(parsed.ino);
+ if (
+ dev === null ||
+ ino === null ||
+ typeof parsed.size !== 'number' ||
+ !Number.isFinite(parsed.size) ||
+ typeof parsed.mtimeMs !== 'number' ||
+ !Number.isFinite(parsed.mtimeMs) ||
+ typeof parsed.sha256 !== 'string' ||
+ !/^[0-9a-f]{64}$/i.test(parsed.sha256)
+ )
+ return null;
+ return { dev, ino, size: parsed.size, mtimeMs: parsed.mtimeMs, sha256: parsed.sha256 };
+ } catch {
+ return null;
+ }
+}
+
async function pathsReferToSameFile(left: string, right: string): Promise<boolean> {
const [leftStat, rightStat] = await Promise.all([
fsp.stat(left, { bigint: true }),
@@ -341,8 +410,9 @@ function detectCodexCredentialScope(codexHome: string): NonNullable<AuthState['c
if (existsSync(systemAuth) && pathsReferToSameFileSync(localAuth, systemAuth)) {
return 'system-shared';
}
- if (isNativeProviderAuthBound('openai') && isNativeProviderAuthSelfAuthorized('openai')) {
- return 'instance-isolated';
+ if (isNativeProviderAuthBound('openai')) {
+ if (isNativeProviderAuthSharedSystemCredential('openai')) return 'system-shared';
+ if (isNativeProviderAuthSelfAuthorized('openai')) return 'instance-isolated';
}
return 'unknown';
} catch {
@@ -535,8 +605,7 @@ export class DesktopClaudeAuthAdapter implements AuthAdapter {
const ownerId = getActiveAppSession().dataOwnerId;
const result = await withSharedGlobalSkillProjectionMutation(ownerId, () =>
prepareSharedGlobalSkillLinks({
- assertOwnerStable: () =>
- assertGhostSkillProjectionBoundaryStableForOwner(ownerId),
+ assertOwnerStable: () => assertGhostSkillProjectionBoundaryStableForOwner(ownerId),
}),
);
for (const warning of result.warnings) {
@@ -848,9 +917,11 @@ export class DesktopCodexAuthAdapter implements AuthAdapter {
private oauthRecoveryRequiredReason: string | null = null;
private oauthRecoveryCredentialScope: AuthState['credentialScope'] = undefined;
private suppressSystemCodexReconcile = false;
+ private lastOrphanRepair: NonNullable<AuthState['credentialDiagnostics']>['orphanRepair'] =
+ 'none';
private devReadOnlyDetached = false;
- /** Dev read-only invalidation fingerprint; memory-only so shared credentials stay untouched. */
- private devReadOnlyInvalidatedSystemCredential: InvalidatedSystemCodexAuthMarker | null = null;
+ /** Runtime-only invalidation baseline used when shared credentials must stay untouched. */
+ private memoryOnlyInvalidatedSystemCredential: InvalidatedSystemCodexAuthMarker | null = null;
private devOAuthWriteOverrideWarned = false;
private isolatedAuthSanitized = false;
private isolatedAuthLaunchProofTrusted: boolean | null = null;
@@ -984,7 +1055,12 @@ export class DesktopCodexAuthAdapter implements AuthAdapter {
*
* dedup 包装: 并发调用复用同一次在途 reconcile (见 pendingReconcile 字段)。
*/
- private reconcileWithSystemCodex(): Promise<void> {
+ private reconcileWithSystemCodex(options?: { allowCurrentLogin?: boolean }): Promise<void> {
+ // 登录流程会直接改写 auth.json;此时任何预热/getState reconcile 都不能依据旧拓扑
+ // 启动 orphan repair。登录完成后的显式 provenance 会决定下一轮 reconcile。
+ if (!options?.allowCurrentLogin && (this.pendingLogin || this.loginCancellationOpen)) {
+ return Promise.resolve();
+ }
if (this.pendingReconcile) return this.pendingReconcile;
// 发起时刻固定会话快照:reconcile 是异步的,期间可能发生账号切换;绑定自愈
// 只允许写给「发起时与完成时都是同一个已提交会话」的 owner(见 claim 内校验)。
@@ -1018,6 +1094,7 @@ export class DesktopCodexAuthAdapter implements AuthAdapter {
* reconcile 会带着自己的快照重试,自愈不丢,只是绝不把 A 时代发起的认领写到 B 名下。
*/
private claimDetectedCodexOAuthBinding(sessionAtStart: ActiveAppSession): void {
+ if (this.pendingLogin || this.loginCancellationOpen) return;
const session = getActiveAppSession();
if (isAppSessionBoundaryPending()) return;
if (
@@ -1042,8 +1119,11 @@ export class DesktopCodexAuthAdapter implements AuthAdapter {
// invalidation time. Never let generic legacy auto-claim hand it to a different Cindy
// owner, but also do not let an older legacyClaimOwner strand the original owner.
if (
- getActiveInvalidatedSystemCodexAuthMarker(this.codexHome, getSystemCodexAuthPath()) !==
- null
+ getActiveInvalidatedSystemCodexAuthMarker(
+ this.codexHome,
+ getSystemCodexAuthPath(),
+ path.join(this.codexHome, 'auth.json'),
+ ) !== null
) {
return;
}
@@ -1082,9 +1162,9 @@ export class DesktopCodexAuthAdapter implements AuthAdapter {
}
/**
- * 登录成功后专用: 先等在途的 reconcile 结束, 再保证用刚写好的 auth.json 重新跑一遍。
- * 否则 dedup 可能把这次"必须基于最新 auth.json"的 reconcile 合并到一个用登录前状态
- * 启动的在途调用上, 导致刚登录的凭证没被正确共享 (规则 9: 用代码而非侥幸保证确定性)。
+ * 登录成功后专用:先等登录前的 reconcile 结束。新 reconcile 在 pending login 期间会被
+ * 门禁延后到登录 Promise 收口后的下一次读取;此时显式 provenance 已持久化,不会再把
+ * 刚写入的 auth.json 当成孤岛覆盖。
*/
private async reconcileWithSystemCodexAfterLogin(): Promise<void> {
const inflight = this.pendingReconcile;
@@ -1121,7 +1201,13 @@ export class DesktopCodexAuthAdapter implements AuthAdapter {
const marker = readInvalidatedSystemCodexAuthMarker(this.codexHome);
// marker 丢失时保持本进程 fail-closed;磁盘写失败不能变成下一次调用立刻回灌坏 token。
if (!marker) return;
- if (getActiveInvalidatedSystemCodexAuthMarker(this.codexHome, getSystemCodexAuthPath())) {
+ if (
+ getActiveInvalidatedSystemCodexAuthMarker(
+ this.codexHome,
+ getSystemCodexAuthPath(),
+ path.join(this.codexHome, 'auth.json'),
+ )
+ ) {
return;
}
this.suppressSystemCodexReconcile = false;
@@ -1136,46 +1222,80 @@ export class DesktopCodexAuthAdapter implements AuthAdapter {
if (!existsSync(systemAuth)) return;
- // 热路径: 已经是同 inode 直接返回
- if (existsSync(myAuth)) {
- try {
- if (await pathsReferToSameFile(systemAuth, myAuth)) {
- this.lastKnownCodexCredentialScope = 'system-shared';
- return;
- }
- } catch {
- /* stat 失败走完整流程 */
- }
+ const topology = await inspectCodexAuthLink(systemAuth, myAuth);
+ if (topology.healthy && topology.linkType === 'hardlink') {
+ markNativeProviderAuthSharedSystemCredential('openai');
+ }
+ if (topology.healthy && (process.platform === 'win32' || topology.linkType === 'symlink')) {
+ this.lastKnownCodexCredentialScope = 'system-shared';
+ return;
+ }
+
+ const hasLocalEntry = topology.linkType !== 'missing';
+ const wasSharedLegacyCredential =
+ topology.linkType === 'file' &&
+ isNativeProviderAuthSharedSystemCredential('openai');
+ const explicitIsolatedOwner =
+ topology.linkType === 'file' && !wasSharedLegacyCredential
+ ? readExplicitNativeProviderAuthOwner('openai')
+ : null;
+ const legacyExplicitOwner =
+ topology.linkType === 'file' && !wasSharedLegacyCredential && !explicitIsolatedOwner
+ ? readLegacyExplicitNativeProviderAuthOwner('openai')
+ : null;
+ if (explicitIsolatedOwner) {
+ log.info('keeping explicitly authorized instance-isolated Codex auth', {
+ ownerMatchesActive: explicitIsolatedOwner === getActiveAppSession().dataOwnerId,
+ });
+ return;
}
const sysAccount = await readCodexAccountId(systemAuth);
if (!sysAccount) return; // 本机 auth.json 解析不出 account, 保守不动
- if (existsSync(myAuth)) {
- const myAccount = await readCodexAccountId(myAuth);
- // 解析得出且不同 → 不同账号, 各管各
- if (myAccount && myAccount !== sysAccount) {
- log.info('system codex logged in as different account, keeping isolated auth');
- return;
- }
- // myAccount === sysAccount, 或 myAccount 解析不出 (可能是损坏/旧 schema): 都按"可合并"处理
+ const myAccount = hasLocalEntry ? await readCodexAccountId(myAuth) : null;
+ if (legacyExplicitOwner && myAccount && myAccount !== sysAccount) {
+ const migrated = migrateLegacyExplicitNativeProviderAuthToInstanceIsolated(
+ 'openai',
+ legacyExplicitOwner,
+ );
+ log.info('keeping account-distinct legacy explicit Codex auth', {
+ provenanceMigrated: migrated,
+ ownerMatchesActive: legacyExplicitOwner === getActiveAppSession().dataOwnerId,
+ });
+ return;
}
- // 同账号 (或 xdt-maker 没登过): 用本机的, 通过硬链共享, refresh 写回两端同步。
+ if (hasLocalEntry) {
+ credPathLog.warn('unproven Codex auth is an orphan repair candidate', {
+ linkType: topology.linkType,
+ accountMatch: myAccount ? myAccount === sysAccount : 'unknown',
+ dryRunCandidate: true,
+ });
+ }
+
+ // topology/account reads above cross await boundaries. A login may have started and written a
+ // new local credential since that snapshot; never replace it using the stale orphan decision.
+ if (this.pendingLogin || this.loginCancellationOpen) return;
+
+ // 无显式隔离 provenance 时使用本机凭证:POSIX symlink / Windows hardlink。
// 安全替换 (唯一 sidecar + 失败重建) 见 codex-auth-link.ts —— 避免并发撞临时文件、
// 以及"myAuth 删了又建不回去导致用户被迫重登"的空窗。
- // 硬链前幂等确保 codexHome 目录存在: 首启时 assets 预热可能尚未建好目录, ENOENT
+ // 建共享链接前幂等确保 codexHome 目录存在: 首启时 assets 预热可能尚未建好目录, ENOENT
// 会让 relink 走 link-unsupported 回退, splash 后首次 auth 查询短暂误报未登录。
await fsp.mkdir(this.codexHome, { recursive: true }).catch(() => undefined);
- const { kind, error } = await relinkSharedCodexAuth(systemAuth, myAuth);
+ const { kind, error, linkType } = await relinkSharedCodexAuth(systemAuth, myAuth);
+ if (hasLocalEntry && !topology.healthy) {
+ this.lastOrphanRepair = kind === 'linked' ? 'relinked' : 'failed';
+ }
switch (kind) {
case 'linked':
this.lastKnownCodexCredentialScope = 'system-shared';
- log.info('codex auth.json linked with ~/.codex (shared)');
+ log.info('codex auth.json linked with ~/.codex (shared)', { linkType });
break;
case 'link-unsupported':
- // 跨分区 / 权限 → 建不出硬链, myAuth 一字未动, xdt-maker 继续走自己的隔离 auth。
- credPathLog.warn('hardlink to ~/.codex failed, fallback to isolated auth', {
+ // 共享链接不支持时 myAuth 一字未动。
+ credPathLog.warn('shared link to ~/.codex failed, auth.json left intact', {
error: error?.message,
});
break;
@@ -1212,8 +1332,7 @@ export class DesktopCodexAuthAdapter implements AuthAdapter {
const ownerId = getActiveAppSession().dataOwnerId;
const sharedOutcome = await withSharedGlobalSkillProjectionMutation(ownerId, () =>
prepareSharedGlobalSkillLinks({
- assertOwnerStable: () =>
- assertGhostSkillProjectionBoundaryStableForOwner(ownerId),
+ assertOwnerStable: () => assertGhostSkillProjectionBoundaryStableForOwner(ownerId),
}),
).then(
(r) => ({ ok: true as const, label: 'shared-skills' as const, warnings: r.warnings }),
@@ -1304,7 +1423,25 @@ export class DesktopCodexAuthAdapter implements AuthAdapter {
async getState(options?: AuthAdapterOptions): Promise<AuthState> {
const state = await this.readState({ credentialMode: options?.credentialMode });
- return this.devOAuthWritesBlocked() ? { ...state, oauthWritesBlocked: true } : state;
+ const stateWithWritePolicy = this.devOAuthWritesBlocked()
+ ? { ...state, oauthWritesBlocked: true }
+ : state;
+ if (!state.credentialScope && state.authSource !== 'oauth') return stateWithWritePolicy;
+ const diagnostics = await inspectCodexAuthLink(
+ getSystemCodexAuthPath(),
+ path.join(this.codexHome, 'auth.json'),
+ );
+ return {
+ ...stateWithWritePolicy,
+ credentialDiagnostics: {
+ ...diagnostics,
+ healthy:
+ diagnostics.healthy ||
+ (state.credentialScope === 'instance-isolated' && diagnostics.linkType === 'file'),
+ devReadOnly: this.devOAuthWritesBlocked(),
+ orphanRepair: this.lastOrphanRepair,
+ },
+ };
}
private async readState(options?: {
@@ -1398,14 +1535,23 @@ export class DesktopCodexAuthAdapter implements AuthAdapter {
private async clearStaleInvalidationIfSystemCodexChanged(): Promise<void> {
if (!this.oauthInvalidatedReason) return;
const persistedMarker = readInvalidatedSystemCodexAuthMarker(this.codexHome);
- const marker = persistedMarker ?? this.devReadOnlyInvalidatedSystemCredential;
+ const marker = persistedMarker ?? this.memoryOnlyInvalidatedSystemCredential;
if (!marker) return;
const systemAuthPath = getSystemCodexAuthPath();
if (persistedMarker) {
- if (getActiveInvalidatedSystemCodexAuthMarker(this.codexHome, systemAuthPath)) return;
+ if (
+ getActiveInvalidatedSystemCodexAuthMarker(
+ this.codexHome,
+ systemAuthPath,
+ path.join(this.codexHome, 'auth.json'),
+ )
+ ) {
+ return;
+ }
} else {
- // Dev read-only mode cannot persist a marker. Keep the old credential detached until a
- // present system auth has a different fingerprint; deletion alone is not recovery.
+ // Memory-only invalidation cannot persist a marker. Keep the rejected/ambiguous credential
+ // detached until a present system auth has a different fingerprint; deletion alone is not
+ // recovery.
if (!currentSystemCodexAuthMarker(systemAuthPath, marker.reason)) return;
if (markerMatchesCurrentSystemCodexAuth(marker, systemAuthPath)) return;
}
@@ -1451,7 +1597,7 @@ export class DesktopCodexAuthAdapter implements AuthAdapter {
return null;
}
const persistedMarker = readInvalidatedSystemCodexAuthMarker(this.codexHome);
- const marker = persistedMarker ?? this.devReadOnlyInvalidatedSystemCredential;
+ const marker = persistedMarker ?? this.memoryOnlyInvalidatedSystemCredential;
const credential = readCodexRecoveryCredentialProof(path.join(this.codexHome, 'auth.json'));
if (!marker || !credential) return null;
const credentialScope =
@@ -1500,12 +1646,17 @@ export class DesktopCodexAuthAdapter implements AuthAdapter {
}
this.suppressSystemCodexReconcile = true;
}
- this.devReadOnlyInvalidatedSystemCredential = null;
+ this.memoryOnlyInvalidatedSystemCredential = null;
this.oauthRecoveryRequiredReason = null;
this.oauthRecoveryCredentialScope = undefined;
return true;
}
+ captureCredentialGeneration(): string | null {
+ const fingerprint = currentCodexCredentialGeneration(path.join(this.codexHome, 'auth.json'));
+ return fingerprint ? JSON.stringify(fingerprint) : null;
+ }
+
/** Bracket one account-level RPC with compare-and-commit recovery confirmation. */
async verifyRecoveryWithAccountRpc<T>(read: () => Promise<T>): Promise<T> {
const proof = this.captureRecoveryVerificationProof();
@@ -1576,7 +1727,7 @@ export class DesktopCodexAuthAdapter implements AuthAdapter {
}
this.warnDevOAuthWriteOverride('login');
this.devReadOnlyDetached = false;
- this.devReadOnlyInvalidatedSystemCredential = null;
+ this.memoryOnlyInvalidatedSystemCredential = null;
const mode = opts?.mode ?? 'browser';
if (this.pendingLogin) {
if (this.pendingLogin.mode === mode && !this.pendingLogin.cancelled) {
@@ -1655,15 +1806,28 @@ export class DesktopCodexAuthAdapter implements AuthAdapter {
opts?: AuthLoginOptions,
isCancelled: () => boolean = () => false,
): Promise<AuthState> {
+ this.ensureInvalidationMarkerLoaded();
+ this.loginAborted = false;
+ this.loginCancellationOpen = true;
+ // A reconcile that started before triggerLogin may already be inside the relink primitive.
+ // Let it finish before cleanup/spawn; the open login gate prevents any successor from starting.
+ const inflightReconcile = this.pendingReconcile;
+ if (inflightReconcile) await inflightReconcile.catch(() => undefined);
+ if (this.loginAborted || isCancelled()) {
+ return { authenticated: false, errorReason: 'login_cancelled' };
+ }
if (!app.isPackaged && process.env.XDT_ISOLATED_AUTH === '1' && !this.isolatedAuthSanitized) {
- await this.reconcileWithSystemCodex();
+ // This tracked login is itself the owner of the pending-login gate. After its logout barrier
+ // has settled, allow only its trusted isolated-auth cleanup through that gate; ordinary
+ // warmup/state reconciles remain blocked until the login finishes.
+ await this.reconcileWithSystemCodex({ allowCurrentLogin: true });
+ if (this.loginAborted || isCancelled()) {
+ return { authenticated: false, errorReason: 'login_cancelled' };
+ }
if (!this.isolatedAuthSanitized) {
return { authenticated: false, errorReason: 'isolated_auth_cleanup_failed' };
}
}
- this.ensureInvalidationMarkerLoaded();
- this.loginAborted = false;
- this.loginCancellationOpen = true;
await this.ensureGlobalCodexAssets();
// Binary 必须在应用启动时就绪 (bootstrap-electron 的 ready 钩子会阻塞预下载)。
@@ -1871,8 +2035,15 @@ export class DesktopCodexAuthAdapter implements AuthAdapter {
const { keepSuppressed } = settleInvalidationMarkerAfterLogin(
this.codexHome,
getSystemCodexAuthPath(),
+ path.join(this.codexHome, 'auth.json'),
);
this.suppressSystemCodexReconcile = keepSuppressed || missingMarkerFailClosed;
+ // `codex login` 的成功已经由刚写入的真实 access_token 证明。先持久化显式来源,
+ // 再允许 reconcile 检查本地普通文件;否则首次登录会被当成无 provenance 孤岛,
+ // 用系统账号覆盖后才把错误的系统凭证标成 Cindy 显式授权。
+ bindNativeProviderAuth('openai', {
+ instanceIsolated: finalizedCredentialScope === 'instance-isolated',
+ });
if (this.suppressSystemCodexReconcile) {
log.warn(
'system codex auth.json marker still active; keeping reconcile suppressed after login',
@@ -1882,8 +2053,6 @@ export class DesktopCodexAuthAdapter implements AuthAdapter {
}
const cancelledAfterReconcile = cancelFinalization();
if (cancelledAfterReconcile) return cancelledAfterReconcile;
- // `codex login` 的成功必须由真实 access_token 证明;绝不能被 XD Gateway fallback 冒充。
- bindNativeProviderAuth('openai');
const state = requireCodexOAuthLoginState(
await this.readState({ skipReconcile: true, credentialMode: 'oauth-bearer' }),
);
@@ -1945,7 +2114,7 @@ export class DesktopCodexAuthAdapter implements AuthAdapter {
this.oauthInvalidatedCredentialScope = undefined;
this.oauthRecoveryRequiredReason = null;
this.oauthRecoveryCredentialScope = undefined;
- this.devReadOnlyInvalidatedSystemCredential = null;
+ this.memoryOnlyInvalidatedSystemCredential = null;
return this.logoutOperation;
}
// runLogout 的 async cleanup 已经结束,但 Promise.finally 还没清掉 operation。此时
@@ -2010,7 +2179,7 @@ export class DesktopCodexAuthAdapter implements AuthAdapter {
this.oauthInvalidatedCredentialScope = undefined;
this.oauthRecoveryRequiredReason = null;
this.oauthRecoveryCredentialScope = undefined;
- this.devReadOnlyInvalidatedSystemCredential = null;
+ this.memoryOnlyInvalidatedSystemCredential = null;
}
if (this.onLogoutSuccess) {
try {
@@ -2027,7 +2196,7 @@ export class DesktopCodexAuthAdapter implements AuthAdapter {
this.oauthInvalidatedCredentialScope = undefined;
this.oauthRecoveryRequiredReason = null;
this.oauthRecoveryCredentialScope = undefined;
- this.devReadOnlyInvalidatedSystemCredential = null;
+ this.memoryOnlyInvalidatedSystemCredential = null;
}
log.info('dev read-only Codex auth detached in memory; durable credentials unchanged');
}
@@ -2273,7 +2442,14 @@ export class DesktopCodexAuthAdapter implements AuthAdapter {
* 等价于 logout() + 主动 push auth state 让 renderer 立刻显示 "请重新登录",
* 否则错误只会反复埋进后台日志, 用户全程无感。
*/
- async invalidate(reason: string): Promise<void> {
+ async invalidate(
+ reason: string,
+ context?: {
+ credentialGeneration?: string | null;
+ credentialAttribution?: 'unproven';
+ },
+ ): Promise<void> {
+ const capturedFingerprint = parseCodexCredentialGeneration(context?.credentialGeneration);
if (this.devOAuthWritesBlocked()) {
log.warn('codex auth invalidated in dev read-only mode; durable credentials unchanged', {
reason,
@@ -2283,9 +2459,19 @@ export class DesktopCodexAuthAdapter implements AuthAdapter {
// A late 401 belongs to the credential actually consumed by the old host. The system path
// may already contain its replacement; if local evidence is unreadable, keep failing closed
// instead of guessing that the current system credential is the invalidated generation.
- this.devReadOnlyInvalidatedSystemCredential =
+ this.memoryOnlyInvalidatedSystemCredential =
credentialScope === 'system-shared'
- ? currentCodexAuthMarker(localAuthPath, reason, credentialScope)
+ ? capturedFingerprint
+ ? {
+ reason,
+ credentialScope,
+ dev: Number(capturedFingerprint.dev),
+ ino: Number(capturedFingerprint.ino),
+ size: capturedFingerprint.size,
+ mtimeMs: capturedFingerprint.mtimeMs,
+ sha256: capturedFingerprint.sha256,
+ }
+ : currentCodexAuthMarker(localAuthPath, reason, credentialScope)
: null;
this.oauthInvalidatedReason = reason;
this.oauthInvalidatedCredentialScope = credentialScope;
@@ -2308,6 +2494,87 @@ export class DesktopCodexAuthAdapter implements AuthAdapter {
}
return;
}
+ if (context?.credentialAttribution === 'unproven') {
+ this.ensureInvalidationMarkerLoaded();
+ const existingMarker = readInvalidatedSystemCodexAuthMarker(this.codexHome);
+ if (existingMarker && isDurableDisconnectMarker(existingMarker)) {
+ log.info('ignoring unproven Codex invalidation after explicit disconnect', { reason });
+ return;
+ }
+ if (this.pendingLogin || this.loginCancellationOpen) {
+ log.info('ignoring unproven Codex invalidation while a tracked login is active', { reason });
+ return;
+ }
+ const credentialScope = this.readCodexCredentialScope();
+ const localAuthPath = path.join(this.codexHome, 'auth.json');
+ // A structured 401 proves this child is bad, but the protocol does not identify whether it
+ // loaded F1 or an atomically published F2. Keep the current credential byte-for-byte intact,
+ // block new hosts in memory, and use the current shared generation only as a replacement
+ // baseline. A later F3 can recover in-process without treating F2 as the failed child fact.
+ const activeOwnerId = getActiveAppSession().dataOwnerId;
+ const recoveryOwnerId =
+ credentialScope === 'system-shared' && activeOwnerId && isNativeProviderAuthBound('openai')
+ ? activeOwnerId
+ : undefined;
+ const markerCommitted = writeUnprovenCodexAuthSuppressionMarker(
+ this.codexHome,
+ getSystemCodexAuthPath(),
+ localAuthPath,
+ reason,
+ credentialScope,
+ recoveryOwnerId,
+ );
+ let durableFallbackCommitted = false;
+ let effectiveCredentialScope = credentialScope;
+ if (!markerCommitted) {
+ log.error('failed to persist unproven Codex suppression marker; revoking provider claim', {
+ reason,
+ credentialScope,
+ });
+ try {
+ // The child generation is unknown, so this revokes only Cindy's provider claim. Keep
+ // auth.json byte-for-byte intact; a later explicit Cindy login proves the replacement
+ // credential and clears this coarse cross-restart boundary.
+ unbindNativeProviderAuth('openai', { revoked: true });
+ durableFallbackCommitted = isNativeProviderAuthRevoked('openai');
+ if (durableFallbackCommitted) effectiveCredentialScope = 'unknown';
+ } catch (err) {
+ log.error('failed to persist fallback Codex provider revocation', {
+ error: err instanceof Error ? err.message : String(err),
+ });
+ }
+ }
+ this.memoryOnlyInvalidatedSystemCredential = markerCommitted
+ ? null
+ : credentialScope === 'system-shared'
+ ? currentCodexAuthMarker(localAuthPath, reason, credentialScope)
+ : null;
+ this.oauthInvalidatedReason = reason;
+ this.oauthInvalidatedCredentialScope = effectiveCredentialScope;
+ this.oauthRecoveryRequiredReason = null;
+ this.oauthRecoveryCredentialScope = undefined;
+ this.suppressSystemCodexReconcile = true;
+ log.warn('codex child auth invalidated without credential attribution; preserving auth.json', {
+ reason,
+ credentialScope,
+ markerCommitted,
+ durableFallbackCommitted,
+ });
+ if (this.onInvalidatedBroadcast) {
+ try {
+ await this.onInvalidatedBroadcast(
+ reason,
+ effectiveCredentialScope,
+ this.devOAuthWritesBlocked(),
+ );
+ } catch (error) {
+ log.warn('onInvalidatedBroadcast threw', {
+ error: error instanceof Error ? error.message : String(error),
+ });
+ }
+ }
+ return;
+ }
this.warnDevOAuthWriteOverride('invalidation');
this.ensureInvalidationMarkerLoaded();
log.warn('codex auth invalidated', { reason });
@@ -2326,7 +2593,65 @@ export class DesktopCodexAuthAdapter implements AuthAdapter {
}
// 服务端已经明确判定 OAuth 凭证失效时, 不能再从 ~/.codex 自动 reconcile 回来。
// 否则 app-server 会拿同一份坏 token 继续 spawn/retry, 用户也看不到明确的重登录入口。
- const credentialScope = this.readCodexCredentialScope();
+ const currentLocalFingerprint = currentCodexCredentialGeneration(localAuthPath);
+ const loginCleanupOwnsMissingCredential = Boolean(
+ this.pendingLogin &&
+ this.loginCancellationOpen &&
+ capturedFingerprint &&
+ !currentLocalFingerprint,
+ );
+ if (loginCleanupOwnsMissingCredential) {
+ // Login preflight deliberately removes F1 before the CLI can publish F2. A late F1 host
+ // failure in that empty window may retire that host, but must not cancel the tracked login
+ // or race its eventual F2 write with destructive logout cleanup.
+ log.info('ignoring stale Codex invalidation during login credential cleanup', { reason });
+ return;
+ }
+ const credentialContentChanged = Boolean(
+ capturedFingerprint &&
+ currentLocalFingerprint &&
+ capturedFingerprint.sha256 !== currentLocalFingerprint.sha256,
+ );
+ const credentialIdentityChanged = Boolean(
+ credentialContentChanged &&
+ capturedFingerprint &&
+ currentLocalFingerprint &&
+ capturedFingerprint.ino !== '0' &&
+ currentLocalFingerprint.ino !== '0' &&
+ (capturedFingerprint.dev !== currentLocalFingerprint.dev ||
+ capturedFingerprint.ino !== currentLocalFingerprint.ino),
+ );
+ if (credentialContentChanged && (credentialIdentityChanged || this.loginCancellationOpen)) {
+ // A different file identity proves an external atomic replacement. An open login
+ // cancellation window means Cindy is still finalizing the replacement selected by the
+ // active login. In either case the old host may be retired, but must not delete it.
+ log.info('ignoring stale Codex invalidation from an older credential generation', {
+ reason,
+ });
+ return;
+ }
+ // Same-inode content rotation or unavailable file identity is ambiguous: the app-server may
+ // have refreshed in place and then failed with F2, or another trusted process may have advanced
+ // the shared file while this host still held F1. The protocol exposes no refresh-adopted
+ // generation, so fail closed without attributing F1 to F2; the unknown marker blocks respawning
+ // the rejected current credential.
+ const invalidatedFingerprint: CodexAuthFileFingerprint | null =
+ credentialContentChanged || !capturedFingerprint
+ ? null
+ : {
+ dev: Number(capturedFingerprint.dev),
+ ino: Number(capturedFingerprint.ino),
+ size: capturedFingerprint.size,
+ mtimeMs: capturedFingerprint.mtimeMs,
+ sha256: capturedFingerprint.sha256,
+ };
+ const detectedCredentialScope = this.readCodexCredentialScope();
+ // A host-bound invalidation without a valid spawn generation is ambiguous. Keep it fail-closed
+ // instead of fingerprinting whichever system credential happens to be current now.
+ const credentialScope =
+ context && detectedCredentialScope === 'system-shared' && !invalidatedFingerprint
+ ? 'unknown'
+ : detectedCredentialScope;
const activeOwnerId = getActiveAppSession().dataOwnerId;
const recoveryOwnerId =
credentialScope === 'system-shared' && activeOwnerId && isNativeProviderAuthBound('openai')
@@ -2344,6 +2669,7 @@ export class DesktopCodexAuthAdapter implements AuthAdapter {
localAuthPath,
credentialScope,
recoveryOwnerId,
+ invalidatedFingerprint ?? undefined,
);
let durableFallbackCommitted = false;
let effectiveCredentialScope = credentialScope;
diff --git a/apps/desktop/src/main/maker-host/codex-auth-invalidation.ts b/apps/desktop/src/main/maker-host/codex-auth-invalidation.ts
index 712503a9fb..3f0e80b569 100644
--- a/apps/desktop/src/main/maker-host/codex-auth-invalidation.ts
+++ b/apps/desktop/src/main/maker-host/codex-auth-invalidation.ts
@@ -32,6 +32,12 @@ export const CODEX_USER_DISCONNECT_REASON = 'user_disconnected';
/** 失效标记文件内容: 失效原因 + 当时 ~/.codex/auth.json 的文件指纹。 */
export type InvalidatedSystemCodexAuthMarker = {
reason: string;
+ /**
+ * The child reported an auth failure without identifying the generation it loaded. In this
+ * mode the fingerprint is only a suppression/replacement baseline, not proof that these bytes
+ * were rejected. It must never authorize credential deletion.
+ */
+ unprovenCredentialAttribution?: true;
/** 失效前 Cindy 使用的是系统共享凭证、实例隔离凭证,还是无法判断。 */
credentialScope?: CodexCredentialScope;
/** 系统共享凭证失效时所属的 Cindy data owner;只允许该 owner 恢复原绑定。 */
@@ -80,6 +86,9 @@ export function readInvalidatedSystemCodexAuthMarker(
(parsed.localSha256 === undefined || typeof parsed.localSha256 === 'string'));
const validDurableDisconnect =
parsed.durableDisconnect === undefined || typeof parsed.durableDisconnect === 'boolean';
+ const validUnprovenCredentialAttribution =
+ parsed.unprovenCredentialAttribution === undefined ||
+ parsed.unprovenCredentialAttribution === true;
const validCredentialScope =
parsed.credentialScope === undefined ||
parsed.credentialScope === 'system-shared' ||
@@ -90,6 +99,7 @@ export function readInvalidatedSystemCodexAuthMarker(
if (
typeof parsed.reason === 'string' &&
validDurableDisconnect &&
+ validUnprovenCredentialAttribution &&
validCredentialScope &&
validRecoveryOwnerId &&
typeof parsed.dev === 'number' &&
@@ -112,18 +122,48 @@ export function readInvalidatedSystemCodexAuthMarker(
return null;
}
+/**
+ * Persist a non-destructive boundary for a child auth failure whose credential generation is
+ * unknown. The fingerprint is the credential a replacement child would currently observe; it is
+ * used only to keep that generation suppressed across restart and detect a later replacement.
+ */
+export function writeUnprovenCodexAuthSuppressionMarker(
+ codexHome: string,
+ systemAuthPath: string,
+ localAuthPath: string,
+ reason: string,
+ credentialScope: CodexCredentialScope,
+ recoveryOwnerId?: string,
+): boolean {
+ const previous = readInvalidatedSystemCodexAuthMarker(codexHome);
+ if (previous && isDurableDisconnectMarker(previous)) return false;
+ const baseline =
+ currentCodexAuthFileFingerprint(localAuthPath) ??
+ currentCodexAuthFileFingerprint(systemAuthPath);
+ if (!baseline) return false;
+ return persistInvalidatedSystemCodexAuthMarker(codexHome, {
+ reason,
+ credentialScope,
+ ...(credentialScope === 'system-shared' && recoveryOwnerId ? { recoveryOwnerId } : {}),
+ unprovenCredentialAttribution: true,
+ ...baseline,
+ });
+}
+
/** 兼容最初只靠 reason 表示的 user_disconnected marker。 */
export function isDurableDisconnectMarker(marker: InvalidatedSystemCodexAuthMarker): boolean {
return marker.reason === CODEX_USER_DISCONNECT_REASON || marker.durableDisconnect === true;
}
-function currentAuthFileFingerprint(authPath: string): {
+export interface CodexAuthFileFingerprint {
dev: number;
ino: number;
size: number;
mtimeMs: number;
sha256: string;
-} | null {
+}
+
+export function currentCodexAuthFileFingerprint(authPath: string): CodexAuthFileFingerprint | null {
try {
const stat = fs.statSync(authPath);
const bytes = fs.readFileSync(authPath);
@@ -145,7 +185,7 @@ export function currentCodexAuthMarker(
reason: string,
credentialScope?: CodexCredentialScope,
): InvalidatedSystemCodexAuthMarker | null {
- const fingerprint = currentAuthFileFingerprint(authPath);
+ const fingerprint = currentCodexAuthFileFingerprint(authPath);
if (!fingerprint) return null;
return { reason, ...(credentialScope ? { credentialScope } : {}), ...fingerprint };
}
@@ -156,7 +196,9 @@ export function currentSystemCodexAuthMarker(
reason: string,
credentialScope?: CodexCredentialScope,
): InvalidatedSystemCodexAuthMarker | null {
- return currentCodexAuthMarker(systemAuthPath, reason, credentialScope);
+ const fingerprint = currentCodexAuthFileFingerprint(systemAuthPath);
+ if (!fingerprint) return null;
+ return { reason, ...(credentialScope ? { credentialScope } : {}), ...fingerprint };
}
function persistInvalidatedSystemCodexAuthMarker(
@@ -207,7 +249,7 @@ function localFileMatchesInvalidatedMarker(
localAuthPath: string,
): boolean {
if (marker.localSha256) {
- return currentAuthFileFingerprint(localAuthPath)?.sha256 === marker.localSha256;
+ return currentCodexAuthFileFingerprint(localAuthPath)?.sha256 === marker.localSha256;
}
if (
marker.localDev == null ||
@@ -254,9 +296,18 @@ export function markerMatchesCurrentSystemCodexAuth(
export function getActiveInvalidatedSystemCodexAuthMarker(
codexHome: string,
systemAuthPath: string,
+ localAuthPath?: string,
): InvalidatedSystemCodexAuthMarker | null {
const marker = readInvalidatedSystemCodexAuthMarker(codexHome);
if (!marker) return null;
+ if (marker.unprovenCredentialAttribution) {
+ const baselinePath =
+ marker.credentialScope === 'system-shared' ? systemAuthPath : localAuthPath;
+ // Absence cannot prove replacement. For isolated/unknown credentials the caller must provide
+ // the local path; otherwise preserve the boundary rather than release it optimistically.
+ if (!baselinePath || currentCodexAuthFileFingerprint(baselinePath) === null) return marker;
+ return fileMatchesInvalidatedMarker(marker, baselinePath) ? marker : null;
+ }
// 实例隔离或来源不明的凭证都不能靠 ~/.codex 变化证明已经恢复;UI 会引导用户在 Cindy
// 重新登录。新的 local auth 不再匹配坏凭证 fingerprint,但 marker 仍负责抑制系统回灌。
if (marker.credentialScope === 'instance-isolated' || marker.credentialScope === 'unknown') {
@@ -266,7 +317,7 @@ export function getActiveInvalidatedSystemCodexAuthMarker(
// 指引,直到 App/CLI 写入一份与坏 token 不同的新 auth.json。
if (
marker.credentialScope === 'system-shared' &&
- currentAuthFileFingerprint(systemAuthPath) === null
+ currentCodexAuthFileFingerprint(systemAuthPath) === null
) {
return marker;
}
@@ -288,12 +339,13 @@ export function writeInvalidatedSystemCodexAuthMarker(
localAuthPath?: string,
credentialScope?: CodexCredentialScope,
recoveryOwnerId?: string,
+ invalidatedFingerprint?: CodexAuthFileFingerprint,
): boolean {
const previous = readInvalidatedSystemCodexAuthMarker(codexHome);
const durableDisconnect =
reason === CODEX_USER_DISCONNECT_REASON ||
(previous !== null && isDurableDisconnectMarker(previous));
- const localFingerprint = localAuthPath ? currentAuthFileFingerprint(localAuthPath) : null;
+ const localFingerprint = localAuthPath ? currentCodexAuthFileFingerprint(localAuthPath) : null;
// 主动断开不依赖系统文件当前是否存在,也不随其指纹变化失效;零值只是兼容既有 marker schema
// 的 durable sentinel。已有 durable sentinel 后的普通 token invalidation 也继承该属性,
// 即使系统文件暂时不存在也要把新的失败原因落盘,不能退回可自动 reconcile 的普通 marker。
@@ -301,15 +353,11 @@ export function writeInvalidatedSystemCodexAuthMarker(
// 被服务端判坏的是 local 指向的旧 inode,不是系统路径上已经换新的凭证;优先记录 local
// 指纹,让下一次检测能立即认出系统登录已经更新并安全 relink。
const sharedInvalidatedCredential: InvalidatedSystemCodexAuthMarker | null =
- credentialScope === 'system-shared' && localFingerprint
+ credentialScope === 'system-shared' && (invalidatedFingerprint ?? localFingerprint)
? {
reason,
credentialScope,
- dev: localFingerprint.dev,
- ino: localFingerprint.ino,
- size: localFingerprint.size,
- mtimeMs: localFingerprint.mtimeMs,
- sha256: localFingerprint.sha256,
+ ...(invalidatedFingerprint ?? localFingerprint)!,
}
: null;
const marker: InvalidatedSystemCodexAuthMarker | null =
@@ -339,12 +387,13 @@ export function writeInvalidatedSystemCodexAuthMarker(
marker.recoveryOwnerId = recoveryOwnerId;
}
if (durableDisconnect) marker.durableDisconnect = true;
- if (localFingerprint) {
- marker.localDev = localFingerprint.dev;
- marker.localIno = localFingerprint.ino;
- marker.localSize = localFingerprint.size;
- marker.localMtimeMs = localFingerprint.mtimeMs;
- marker.localSha256 = localFingerprint.sha256;
+ const invalidatedLocalFingerprint = invalidatedFingerprint ?? localFingerprint;
+ if (invalidatedLocalFingerprint) {
+ marker.localDev = invalidatedLocalFingerprint.dev;
+ marker.localIno = invalidatedLocalFingerprint.ino;
+ marker.localSize = invalidatedLocalFingerprint.size;
+ marker.localMtimeMs = invalidatedLocalFingerprint.mtimeMs;
+ marker.localSha256 = invalidatedLocalFingerprint.sha256;
}
return persistInvalidatedSystemCodexAuthMarker(codexHome, marker);
}
@@ -364,8 +413,8 @@ export function shouldSuppressLocalCodexAuth(codexHome: string, localAuthPath: s
const marker = readInvalidatedSystemCodexAuthMarker(codexHome);
return Boolean(
marker &&
- (localFileMatchesInvalidatedMarker(marker, localAuthPath) ||
- fileMatchesInvalidatedMarker(marker, localAuthPath)),
+ (localFileMatchesInvalidatedMarker(marker, localAuthPath) ||
+ fileMatchesInvalidatedMarker(marker, localAuthPath)),
);
}
@@ -393,6 +442,7 @@ export function clearInvalidatedSystemCodexAuthMarker(codexHome: string): boolea
export function settleInvalidationMarkerAfterLogin(
codexHome: string,
systemAuthPath: string,
+ localAuthPath?: string,
): { keepSuppressed: boolean } {
const marker = readInvalidatedSystemCodexAuthMarker(codexHome);
if (marker?.credentialScope === 'instance-isolated' || marker?.credentialScope === 'unknown') {
@@ -404,7 +454,8 @@ export function settleInvalidationMarkerAfterLogin(
return { keepSuppressed: true };
}
return {
- keepSuppressed: getActiveInvalidatedSystemCodexAuthMarker(codexHome, systemAuthPath) != null,
+ keepSuppressed:
+ getActiveInvalidatedSystemCodexAuthMarker(codexHome, systemAuthPath, localAuthPath) != null,
};
}
@@ -434,7 +485,11 @@ export function restoreInvalidationStateOnStartup(
if (!persistedMarker) {
return { suppressReconcile: false, invalidatedReason: null };
}
- const marker = getActiveInvalidatedSystemCodexAuthMarker(codexHome, systemAuthPath);
+ const marker = getActiveInvalidatedSystemCodexAuthMarker(
+ codexHome,
+ systemAuthPath,
+ localAuthPath,
+ );
if (!marker) {
// A changed system auth.json is only a recovery candidate. Reconcile may consume it, but the
// renderer must perform an account RPC before replacing the actionable invalidation prompt.
@@ -467,9 +522,7 @@ export function restoreInvalidationStateOnStartup(
!fileMatchesInvalidatedMarker(marker, localAuthPath) &&
!localFileMatchesInvalidatedMarker(marker, localAuthPath);
const recoveryRequiredReason =
- !isDurableDisconnectMarker(marker) && hasReplacementLocalCredential
- ? marker.reason
- : undefined;
+ !isDurableDisconnectMarker(marker) && hasReplacementLocalCredential ? marker.reason : undefined;
return {
suppressReconcile: true,
...(marker.credentialScope ? { credentialScope: marker.credentialScope } : {}),
diff --git a/apps/desktop/src/main/maker-host/codex-auth-link.ts b/apps/desktop/src/main/maker-host/codex-auth-link.ts
index 54bed9d42e..c1cd38f3a5 100644
--- a/apps/desktop/src/main/maker-host/codex-auth-link.ts
+++ b/apps/desktop/src/main/maker-host/codex-auth-link.ts
@@ -1,7 +1,7 @@
/**
* apps/desktop/src/main/maker-host/codex-auth-link.ts
*
- * Codex auth.json 共享硬链的"安全替换"原语 —— 从 auth-adapters 的 reconcile 流程里拆出来,
+ * Codex auth.json 共享链接的"安全替换"原语 —— 从 auth-adapters 的 reconcile 流程里拆出来,
* 不依赖 Electron, 可单测。
*
* 背景 (2026-06-18 线上踩坑):
@@ -22,34 +22,38 @@
* 注意: 本模块只管"安全替换"这一件事, 不做账号比对 / inode 短路 / suppress 标记等判定 ——
* 那些仍由 auth-adapters 的 reconcile 主流程负责。
*/
-import { promises as fsp, existsSync } from 'node:fs';
+import { promises as fsp } from 'node:fs';
/**
* relinkSharedCodexAuth 的结果分类:
- * - linked 成功: myAuth 现在和 systemAuth 同 inode (硬链共享, refresh 写回两端生效)
- * - link-unsupported 连 sidecar 硬链都建不出 (跨分区 / 权限) → myAuth 一字未动, 安全回落隔离模式
+ * - linked 成功:POSIX symlink / Windows hardlink 指向 systemAuth
+ * - link-unsupported 连 sidecar 共享链接都建不出 → myAuth 一字未动
* - swap-failed-intact 替换失败但 myAuth 仍在 (多半是并发的另一次 reconcile 已抢先放好)
- * - recovered 替换中途 myAuth 一度丢失, 已从 systemAuth 重建 (硬链或独立拷贝)
+ * - recovered 替换中途 myAuth 一度丢失, 已从 systemAuth 重建共享链接
* - lost 替换失败且无法重建 (systemAuth 也读不了) → 需要用户重新登录
*/
export type RelinkResultKind =
- | 'linked'
- | 'link-unsupported'
- | 'swap-failed-intact'
- | 'recovered'
- | 'lost';
+ 'linked' | 'link-unsupported' | 'swap-failed-intact' | 'recovered' | 'lost';
export interface RelinkOutcome {
kind: RelinkResultKind;
+ linkType?: 'symlink' | 'hardlink';
/** 失败路径上的底层错误, 供调用方打日志; linked 时为 undefined。 */
error?: Error;
}
+export interface CodexAuthLinkDiagnostics {
+ linkType: 'symlink' | 'hardlink' | 'file' | 'missing' | 'dangling-symlink' | 'unknown';
+ healthy: boolean;
+ systemAuthMtimeMs?: number;
+ systemAuthLinkCount?: number;
+}
+
/** 同进程内自增, 保证并发调用拿到互不相同的 sidecar 路径。 */
let sidecarCounter = 0;
/**
- * 原子地把 myAuth 替换成指向 systemAuth 的硬链。
+ * 原子地把 myAuth 替换成指向 systemAuth 的共享链接。
*
* 调用方需自行保证 systemAuth 存在、且两边是同账号 (本函数不做账号比对)。
* 并发安全: 每次调用使用唯一 sidecar, 不会和同进程内其它调用撞同名临时文件。
@@ -57,56 +61,115 @@ let sidecarCounter = 0;
export async function relinkSharedCodexAuth(
systemAuth: string,
myAuth: string,
+ platform: NodeJS.Platform = process.platform,
): Promise<RelinkOutcome> {
// 唯一 sidecar 名 (pid + 自增计数): 同进程内并发 reconcile 各用各的, 不再撞 EEXIST / ENOENT。
const sidecar = `${myAuth}.${process.pid}.${sidecarCounter++}.linktmp`;
- // 1. 先把 sidecar 硬链建出来 —— 失败 (跨分区 / 权限) 时 myAuth 完全没动, 安全回落。
+ const linkType = platform === 'win32' ? 'hardlink' : 'symlink';
+ // Codex 0.145.0 实测会原位写 auth.json:POSIX symlink 会保留并穿透写目标。
+ // Windows 普通用户无法稳定创建 symlink,继续用 hardlink。
try {
- await fsp.link(systemAuth, sidecar);
+ await fsp.stat(systemAuth);
+ if (linkType === 'symlink') await fsp.symlink(systemAuth, sidecar, 'file');
+ else await fsp.link(systemAuth, sidecar);
} catch (error) {
return { kind: 'link-unsupported', error: error as Error };
}
- // 2. 用 sidecar 覆盖 myAuth。Windows 的 rename 不能覆盖已存在目标, 所以先删 myAuth 再 rename。
+ // POSIX rename 可原子覆盖旧文件,没有“先删后建”空窗。Windows 仍需先删目标。
try {
- await fsp.rm(myAuth, { force: true });
+ if (platform === 'win32') await fsp.rm(myAuth, { force: true });
await fsp.rename(sidecar, myAuth);
- // POSIX 上若 sidecar 与 myAuth 已是同一 inode (并发的另一次替换已把 myAuth 建成共享硬链),
- // rename 是成功的 no-op、不会移走 sidecar —— 顺手清掉, 避免并发下 .linktmp 残留堆积。
+ // 顺手清掉可能残留的 sidecar,避免并发下 .linktmp 堆积。
await fsp.rm(sidecar, { force: true }).catch(() => undefined);
- return { kind: 'linked' };
+ return { kind: 'linked', linkType };
} catch (error) {
// 替换失败: 先清掉 sidecar, 再判断 myAuth 是否还在。
await fsp.rm(sidecar, { force: true }).catch(() => undefined);
- if (existsSync(myAuth)) {
+ if (await pathEntryExists(myAuth)) {
// 危险窗口没真正发生 (myAuth 还在) —— 多半是并发的另一次替换已抢先放好, 无需补救。
return { kind: 'swap-failed-intact', error: error as Error };
}
// myAuth 被删却没换上 → 绝不能让用户凭空丢登录态, 尽力从 systemAuth 重建。
- const recovered = await recoverCodexAuth(systemAuth, myAuth);
+ const recovered = await recoverCodexAuth(systemAuth, myAuth, platform);
return { kind: recovered ? 'recovered' : 'lost', error: error as Error };
}
}
/**
- * myAuth 在替换中途丢失时的兜底重建:
- * - 先试硬链 (保持和 systemAuth 共享, refresh 写回仍两端生效)
- * - 跨分区 / 权限导致硬链失败时, 退化为独立拷贝 (等价隔离模式, 仍可正常登录使用)
+ * myAuth 在替换中途丢失时的兜底重建。只重建共享链接,绝不复制 token。
*
* @returns 是否成功让 myAuth 重新存在
*/
-export async function recoverCodexAuth(systemAuth: string, myAuth: string): Promise<boolean> {
+export async function recoverCodexAuth(
+ systemAuth: string,
+ myAuth: string,
+ platform: NodeJS.Platform = process.platform,
+): Promise<boolean> {
try {
- await fsp.link(systemAuth, myAuth);
+ await fsp.stat(systemAuth);
+ if (platform === 'win32') await fsp.link(systemAuth, myAuth);
+ else await fsp.symlink(systemAuth, myAuth, 'file');
return true;
} catch {
- /* 跨分区 / 权限 → 退化为独立拷贝 */
+ // 不再 copy token 兜底:可写副本会变成 refresh-token 孤岛。
+ return false;
}
+}
+
+async function pathEntryExists(file: string): Promise<boolean> {
try {
- await fsp.copyFile(systemAuth, myAuth);
+ await fsp.lstat(file);
return true;
} catch {
return false;
}
}
+
+export async function inspectCodexAuthLink(
+ systemAuth: string,
+ myAuth: string,
+): Promise<CodexAuthLinkDiagnostics> {
+ let system;
+ try {
+ system = await fsp.stat(systemAuth, { bigint: true });
+ } catch {
+ system = null;
+ }
+ const base = system
+ ? {
+ systemAuthMtimeMs: Number(system.mtimeMs),
+ systemAuthLinkCount: Number(system.nlink),
+ }
+ : {};
+ let local;
+ try {
+ local = await fsp.lstat(myAuth, { bigint: true });
+ } catch {
+ return { ...base, linkType: 'missing', healthy: false };
+ }
+ if (!system) {
+ return {
+ linkType: local.isSymbolicLink() ? 'dangling-symlink' : local.isFile() ? 'file' : 'unknown',
+ healthy: false,
+ };
+ }
+ let resolved;
+ try {
+ resolved = await fsp.stat(myAuth, { bigint: true });
+ } catch {
+ return { ...base, linkType: 'dangling-symlink', healthy: false };
+ }
+ const same =
+ resolved.ino !== 0n &&
+ system.ino !== 0n &&
+ resolved.dev === system.dev &&
+ resolved.ino === system.ino;
+ const linkType = local.isSymbolicLink()
+ ? 'symlink'
+ : same && local.nlink > 1n
+ ? 'hardlink'
+ : 'file';
+ return { ...base, linkType, healthy: same };
+}
diff --git a/apps/desktop/src/main/maker-host/nativeProviderAuthBinding.ts b/apps/desktop/src/main/maker-host/nativeProviderAuthBinding.ts
index 4ea3d7cc9c..96cc244c8f 100644
--- a/apps/desktop/src/main/maker-host/nativeProviderAuthBinding.ts
+++ b/apps/desktop/src/main/maker-host/nativeProviderAuthBinding.ts
@@ -1,6 +1,7 @@
import { app } from 'electron';
import { randomUUID } from 'node:crypto';
import fs from 'node:fs';
+import { platform as hostPlatform } from 'node:os';
import path from 'node:path';
import {
@@ -18,6 +19,11 @@ import {
} from './model-discovery/connection-source.js';
import { atomicWriteFileSync, readAtomicFileSync } from '../utils/atomicWriteFile.js';
+// Link-reconciliation tests override process.platform to exercise POSIX and
+// Windows topology semantics. Durability capabilities belong to the actual
+// host filesystem, so capture them before any such override can occur.
+const NATIVE_BINDING_HOST_PLATFORM = hostPlatform();
+
const NATIVE_PROVIDER_IDS = [
'anthropic',
'openai',
@@ -53,12 +59,46 @@ type BindingFile = Partial<Record<NativeProviderId, string>> & {
selfAuthorized?: Partial<Record<NativeProviderId, string>>;
/** 授权来源审计;旧文件缺失时继续由 selfAuthorized / provider 迁移语义兼容。 */
sources?: Partial<Record<NativeProviderId, ConnectionSourceKind>>;
+ /**
+ * 已当场验证为系统共享凭证的 owner。存量 POSIX 与 Windows hardlink 在系统 auth.json
+ * 原子换代后都会退化成普通 file;这份独立 provenance 让下次启动仍能把旧 inode 迁回
+ * 系统新凭证,且不覆盖 sources 里真实的「最初由 Cindy 显式授权」来路。
+ */
+ sharedSystemCredential?: Partial<Record<NativeProviderId, string>>;
+ /**
+ * 已在登录收尾当场确认是实例隔离普通文件的 owner。旧 selfAuthorized / sources 只证明
+ * owner 曾显式授权,不能证明眼前文件没有先被共享成 hardlink 再因系统换代而断链。
+ */
+ instanceIsolatedCredential?: Partial<Record<NativeProviderId, string>>;
};
+function sharedSystemCredentialOwners(
+ bindings: BindingFile,
+): Partial<Record<NativeProviderId, string>> {
+ const value = bindings.sharedSystemCredential;
+ return value && typeof value === 'object' && !Array.isArray(value) ? { ...value } : {};
+}
+
+function instanceIsolatedCredentialOwners(
+ bindings: BindingFile,
+): Partial<Record<NativeProviderId, string>> {
+ const value = bindings.instanceIsolatedCredential;
+ return value && typeof value === 'object' && !Array.isArray(value) ? { ...value } : {};
+}
+
function bindingPath(): string {
return path.join(app.getPath('userData'), 'native-provider-auth.json');
}
+function hasInvalidProviderOwnerSlot(value: unknown): boolean {
+ if (value === undefined) return false;
+ if (!value || typeof value !== 'object' || Array.isArray(value)) return true;
+ const owners = value as Record<string, unknown>;
+ return NATIVE_PROVIDER_IDS.some(
+ (provider) => provider in owners && typeof owners[provider] !== 'string',
+ );
+}
+
/**
* 读绑定文件,**区分「确实还没有这个文件」与「有但读不出来」**。
*
@@ -110,6 +150,21 @@ function readBindingsOrFail(): BindingRead {
if (!value || typeof value !== 'object' || Array.isArray(value)) {
return { ok: false, reason: 'unreadable' };
}
+ const ownerFields = value as {
+ selfAuthorized?: unknown;
+ sharedSystemCredential?: unknown;
+ instanceIsolatedCredential?: unknown;
+ };
+ if (
+ hasInvalidProviderOwnerSlot(value) ||
+ hasInvalidProviderOwnerSlot(ownerFields.selfAuthorized) ||
+ hasInvalidProviderOwnerSlot(ownerFields.sharedSystemCredential) ||
+ hasInvalidProviderOwnerSlot(ownerFields.instanceIsolatedCredential)
+ ) {
+ // Owner provenance is an authorization boundary. A syntactically valid JSON value with
+ // the wrong runtime type is not proof and must never reach downstream string operations.
+ return { ok: false, reason: 'unreadable' };
+ }
// revoked 也要验型:下游用 `provider in bindings.revoked` 判定,而 `in` 的右操作数是
// 原始值时直接抛 TypeError —— 一个被手工修坏的字段会让认领、迁移、登出乃至重新授权
// 全部炸在这里(PR #548 review)。
@@ -123,7 +178,8 @@ function readBindingsOrFail(): BindingRead {
revoked !== undefined &&
(typeof revoked !== 'object' || revoked === null || Array.isArray(revoked))
) {
- const { revoked: _bad, ...rest } = value as BindingFile;
+ const rest = { ...(value as BindingFile) };
+ delete rest.revoked;
return { ok: false, reason: 'badRevoked', bindings: rest };
}
return { ok: true, bindings: value as BindingFile };
@@ -162,7 +218,7 @@ function syncParentDirectory(file: string): void {
// final-file FlushFileBuffers above remains the fallback durability
// barrier in that case; do not turn a successful binding commit into a
// logout merely because directory fsync is unavailable.
- if (process.platform !== 'win32') throw error;
+ if (NATIVE_BINDING_HOST_PLATFORM !== 'win32') throw error;
} finally {
if (dirHandle !== undefined) fs.closeSync(dirHandle);
}
@@ -414,13 +470,21 @@ export function isNativeProviderAuthRevoked(provider: NativeProviderId): boolean
}
/** Bind newly completed native OAuth to the current data owner. */
-export function bindNativeProviderAuth(provider: NativeProviderId): void {
+export function bindNativeProviderAuth(
+ provider: NativeProviderId,
+ opts?: { instanceIsolated?: boolean },
+): void {
const owner = getActiveAppSession().dataOwnerId;
if (!owner) throw new Error('cannot bind native provider auth without an active data owner');
const written = withNativeBindingMutationLock(false, () => {
const read = readBindingsOrFail();
if (read.ok) {
const bindings = read.bindings;
+ const sharedSystemCredential = sharedSystemCredentialOwners(bindings);
+ delete sharedSystemCredential[provider];
+ const instanceIsolatedCredential = instanceIsolatedCredentialOwners(bindings);
+ if (opts?.instanceIsolated) instanceIsolatedCredential[provider] = owner;
+ else delete instanceIsolatedCredential[provider];
// 显式授权 = 用户重新表达了「我要连它」,撤销标记就此作废。
if (bindings.revoked && provider in bindings.revoked) {
const revoked = { ...bindings.revoked };
@@ -435,6 +499,8 @@ export function bindNativeProviderAuth(provider: NativeProviderId): void {
...bindings.sources,
[provider]: 'explicit-provider-oauth',
},
+ sharedSystemCredential,
+ instanceIsolatedCredential,
[provider]: owner,
});
return true;
@@ -452,6 +518,11 @@ export function bindNativeProviderAuth(provider: NativeProviderId): void {
// 就此关闭 —— 无从得知谁被撤销过时,丢弃标记等于给所有残留凭证放行。用户对它们各自显式
// 授权即可恢复。
const salvaged = read.reason === 'badRevoked' ? read.bindings : {};
+ const sharedSystemCredential = sharedSystemCredentialOwners(salvaged);
+ delete sharedSystemCredential[provider];
+ const instanceIsolatedCredential = instanceIsolatedCredentialOwners(salvaged);
+ if (opts?.instanceIsolated) instanceIsolatedCredential[provider] = owner;
+ else delete instanceIsolatedCredential[provider];
const suppressed: Partial<Record<NativeProviderId, string>> = {};
for (const other of NATIVE_PROVIDER_IDS) {
if (other !== provider) suppressed[other] = owner;
@@ -464,6 +535,8 @@ export function bindNativeProviderAuth(provider: NativeProviderId): void {
...salvaged.sources,
[provider]: 'explicit-provider-oauth',
},
+ sharedSystemCredential,
+ instanceIsolatedCredential,
[provider]: owner,
});
return true;
@@ -485,6 +558,117 @@ export function isNativeProviderAuthSelfAuthorized(provider: NativeProviderId):
);
}
+function explicitNativeProviderAuthOwner(
+ bindings: BindingFile,
+ provider: NativeProviderId,
+): string | null {
+ const boundOwner = bindings[provider]?.trim();
+ if (!boundOwner) return null;
+ const source = bindings.sources?.[provider];
+ const selfAuthorizedOwner = bindings.selfAuthorized?.[provider]?.trim();
+ if (source !== undefined && source !== 'explicit-provider-oauth') return null;
+ if (selfAuthorizedOwner !== undefined && selfAuthorizedOwner !== boundOwner) return null;
+ return source === 'explicit-provider-oauth' || selfAuthorizedOwner === boundOwner
+ ? boundOwner
+ : null;
+}
+
+/**
+ * Return the proven owner of a Cindy-explicit OAuth credential without applying the active-owner
+ * binding gate. This is intentionally stricter than isNativeProviderAuthSelfAuthorized(): unreadable
+ * or contradictory provenance must not turn an unproven local credential into an isolated one.
+ */
+export function readExplicitNativeProviderAuthOwner(
+ provider: NativeProviderId,
+): string | null {
+ const read = readBindingsOrFail();
+ if (!read.ok) return null;
+ const boundOwner = explicitNativeProviderAuthOwner(read.bindings, provider);
+ if (!boundOwner) return null;
+ const isolatedOwner = instanceIsolatedCredentialOwners(read.bindings)[provider]?.trim();
+ return isolatedOwner === boundOwner ? boundOwner : null;
+}
+
+/** Return a parent-version explicit owner only when neither current provenance marker exists. */
+export function readLegacyExplicitNativeProviderAuthOwner(
+ provider: NativeProviderId,
+): string | null {
+ const read = readBindingsOrFail();
+ if (!read.ok) return null;
+ const owner = explicitNativeProviderAuthOwner(read.bindings, provider);
+ if (!owner) return null;
+ if (sharedSystemCredentialOwners(read.bindings)[provider] !== undefined) return null;
+ if (instanceIsolatedCredentialOwners(read.bindings)[provider] !== undefined) return null;
+ return owner;
+}
+
+/** Promote an account-distinct parent-version explicit credential without rebinding its owner. */
+export function migrateLegacyExplicitNativeProviderAuthToInstanceIsolated(
+ provider: NativeProviderId,
+ expectedOwner: string,
+): boolean {
+ return withNativeBindingMutationLock(false, () => {
+ const read = readBindingsOrFail();
+ if (!read.ok) return false;
+ if (explicitNativeProviderAuthOwner(read.bindings, provider) !== expectedOwner) return false;
+ if (sharedSystemCredentialOwners(read.bindings)[provider] !== undefined) return false;
+ const isolated = instanceIsolatedCredentialOwners(read.bindings);
+ if (isolated[provider] !== undefined && isolated[provider] !== expectedOwner) return false;
+ if (isolated[provider] === expectedOwner) return true;
+ writeBindings({
+ ...read.bindings,
+ instanceIsolatedCredential: { ...isolated, [provider]: expectedOwner },
+ });
+ return true;
+ });
+}
+
+/** Persist that this owner's credential was observed as a healthy system-shared hardlink inode. */
+export function markNativeProviderAuthSharedSystemCredential(
+ provider: NativeProviderId,
+): boolean {
+ const snapshot = readBindingsOrFail();
+ if (!snapshot.ok) return false;
+ const snapshotOwner = snapshot.bindings[provider]?.trim();
+ if (!snapshotOwner) return false;
+ if (
+ sharedSystemCredentialOwners(snapshot.bindings)[provider]?.trim() === snapshotOwner &&
+ instanceIsolatedCredentialOwners(snapshot.bindings)[provider] === undefined
+ ) {
+ return true;
+ }
+ return withNativeBindingMutationLock(false, () => {
+ const read = readBindingsOrFail();
+ if (!read.ok) return false;
+ const owner = read.bindings[provider]?.trim();
+ if (!owner) return false;
+ const sharedSystemCredential = sharedSystemCredentialOwners(read.bindings);
+ const instanceIsolatedCredential = instanceIsolatedCredentialOwners(read.bindings);
+ if (
+ sharedSystemCredential[provider]?.trim() === owner &&
+ instanceIsolatedCredential[provider] === undefined
+ )
+ return true;
+ delete instanceIsolatedCredential[provider];
+ writeBindings({
+ ...read.bindings,
+ sharedSystemCredential: { ...sharedSystemCredential, [provider]: owner },
+ instanceIsolatedCredential,
+ });
+ return true;
+ });
+}
+
+/** Whether the current binding carries owner-consistent proof of a previously shared system inode. */
+export function isNativeProviderAuthSharedSystemCredential(provider: NativeProviderId): boolean {
+ const read = readBindingsOrFail();
+ if (!read.ok) return false;
+ const owner = read.bindings[provider]?.trim();
+ return Boolean(
+ owner && sharedSystemCredentialOwners(read.bindings)[provider]?.trim() === owner,
+ );
+}
+
/** 返回当前 owner 绑定的授权来源;归属不明或旧文件未记录时返回 null。 */
export function getNativeProviderAuthSource(
provider: NativeProviderId,
@@ -526,7 +710,18 @@ export function unbindNativeProviderAuth(
const bindings = snapshot.bindings;
const hasSelfAuthorized = bindings.selfAuthorized?.[provider] !== undefined;
const hasSource = bindings.sources?.[provider] !== undefined;
- if (!(provider in bindings) && !hasSelfAuthorized && !hasSource) return;
+ const hasSharedSystemCredential =
+ sharedSystemCredentialOwners(bindings)[provider] !== undefined;
+ const hasInstanceIsolatedCredential =
+ instanceIsolatedCredentialOwners(bindings)[provider] !== undefined;
+ if (
+ !(provider in bindings) &&
+ !hasSelfAuthorized &&
+ !hasSource &&
+ !hasSharedSystemCredential &&
+ !hasInstanceIsolatedCredential
+ )
+ return;
}
}
withRequiredNativeBindingMutationLock(() => {
@@ -537,7 +732,19 @@ export function unbindNativeProviderAuth(
const marking = opts?.revoked === true && !!owner;
const hadSelfAuthorized = bindings.selfAuthorized?.[provider] !== undefined;
const hadSource = bindings.sources?.[provider] !== undefined;
- if (!(provider in bindings) && !marking && !hadSelfAuthorized && !hadSource) return;
+ const sharedSystemCredential = sharedSystemCredentialOwners(bindings);
+ const hadSharedSystemCredential = sharedSystemCredential[provider] !== undefined;
+ const instanceIsolatedCredential = instanceIsolatedCredentialOwners(bindings);
+ const hadInstanceIsolatedCredential = instanceIsolatedCredential[provider] !== undefined;
+ if (
+ !(provider in bindings) &&
+ !marking &&
+ !hadSelfAuthorized &&
+ !hadSource &&
+ !hadSharedSystemCredential &&
+ !hadInstanceIsolatedCredential
+ )
+ return;
delete bindings[provider];
// 授权来路随绑定一起作废:登出之后这份凭证若还在本机,它对 Cindy 就重新是「外部已有的
// 凭证」,继承语义(及其文案)重新成立。
@@ -551,6 +758,14 @@ export function unbindNativeProviderAuth(
delete sources[provider];
bindings.sources = sources;
}
+ if (hadSharedSystemCredential) {
+ delete sharedSystemCredential[provider];
+ bindings.sharedSystemCredential = sharedSystemCredential;
+ }
+ if (hadInstanceIsolatedCredential) {
+ delete instanceIsolatedCredential[provider];
+ bindings.instanceIsolatedCredential = instanceIsolatedCredential;
+ }
if (marking) bindings.revoked = { ...(bindings.revoked ?? {}), [provider]: owner as string };
writeBindings(bindings);
});
diff --git a/apps/desktop/src/renderer/hooks/__tests__/useCodexAuth.test.ts b/apps/desktop/src/renderer/hooks/__tests__/useCodexAuth.test.ts
index 28e567a63d..350188db00 100644
--- a/apps/desktop/src/renderer/hooks/__tests__/useCodexAuth.test.ts
+++ b/apps/desktop/src/renderer/hooks/__tests__/useCodexAuth.test.ts
@@ -22,6 +22,12 @@ type TestAuthState = {
oauthWritesBlocked?: boolean;
credentialScope?: 'system-shared' | 'instance-isolated' | 'unknown';
recoveryRequiredReason?: string;
+ credentialDiagnostics?: {
+ linkType: 'symlink';
+ healthy: boolean;
+ devReadOnly: boolean;
+ systemAuthLinkCount?: number;
+ };
};
function deferred<T>() {
@@ -96,6 +102,34 @@ describe('useCodexAuth lifecycle', () => {
delete (window as unknown as { electronAPI?: unknown }).electronAPI;
});
+ it('projects structured Codex credential diagnostics into renderer state', async () => {
+ const auth = installAuthApi(async () => undefined);
+ auth.getState.mockResolvedValueOnce({
+ authenticated: true,
+ identity: '[email protected]',
+ authSource: 'oauth',
+ credentialScope: 'system-shared',
+ credentialDiagnostics: {
+ linkType: 'symlink',
+ healthy: true,
+ devReadOnly: true,
+ systemAuthLinkCount: 1,
+ },
+ });
+
+ const { result } = renderHook(() => useCodexAuth());
+
+ await waitFor(() => expect(result.current.state.kind).toBe('authenticated'));
+ expect(result.current.state).toMatchObject({
+ credentialDiagnostics: {
+ linkType: 'symlink',
+ healthy: true,
+ devReadOnly: true,
+ systemAuthLinkCount: 1,
+ },
+ });
+ });
+
it('keeps the authenticated UI when durable disconnect was not committed', async () => {
const auth = installAuthApi(async () => {
throw new Error('[INTERNAL] failed to persist Codex disconnect state');
diff --git a/apps/desktop/src/renderer/hooks/codexAuthLogin.ts b/apps/desktop/src/renderer/hooks/codexAuthLogin.ts
index 0a989d68c2..87c0a20a69 100644
--- a/apps/desktop/src/renderer/hooks/codexAuthLogin.ts
+++ b/apps/desktop/src/renderer/hooks/codexAuthLogin.ts
@@ -3,6 +3,15 @@ import { createLogger } from '@/lib/logger';
const log = createLogger('codexAuthLogin');
+export type CodexCredentialDiagnostics = {
+ linkType: 'symlink' | 'hardlink' | 'file' | 'missing' | 'dangling-symlink' | 'unknown';
+ healthy: boolean;
+ devReadOnly: boolean;
+ systemAuthMtimeMs?: number;
+ systemAuthLinkCount?: number;
+ orphanRepair?: 'none' | 'relinked' | 'failed';
+};
+
export type CodexLoginResult = {
authenticated: boolean;
identity?: string;
@@ -11,6 +20,7 @@ export type CodexLoginResult = {
authSource?: 'oauth' | 'api-key';
oauthWritesBlocked?: boolean;
credentialScope?: 'system-shared' | 'instance-isolated' | 'unknown';
+ credentialDiagnostics?: CodexCredentialDiagnostics;
recoveryRequiredReason?: string;
};
diff --git a/apps/desktop/src/renderer/hooks/useCodexAuth.ts b/apps/desktop/src/renderer/hooks/useCodexAuth.ts
index 84901075e6..203d7db07e 100644
--- a/apps/desktop/src/renderer/hooks/useCodexAuth.ts
+++ b/apps/desktop/src/renderer/hooks/useCodexAuth.ts
@@ -16,6 +16,7 @@ import {
onCodexLoginStarted,
type CodexLoginLease,
type CodexLoginResult,
+ type CodexCredentialDiagnostics,
} from './codexAuthLogin';
import { isCodexOAuthReconnectRequired } from './codexAuthRecovery';
@@ -40,7 +41,10 @@ export type CodexUiState = (
credentialScope?: 'system-shared' | 'instance-isolated' | 'unknown';
}
| { kind: 'error'; message: string }
-) & { oauthWritesBlocked?: boolean };
+) & {
+ credentialDiagnostics?: CodexCredentialDiagnostics;
+ oauthWritesBlocked?: boolean;
+};
export type CodexLoginOutcome = 'authenticated' | 'cancelled' | 'blocked' | 'failed' | 'unverified';
export type CodexRecoveryCheck = 'idle' | 'checking' | 'failed';
@@ -92,9 +96,13 @@ function createInitialMachineState(): CodexAuthMachineState {
}
function toCodexUiState(raw: CodexLoginResult, preserveGenericError = false): CodexUiState {
+ const diagnostics = raw.credentialDiagnostics
+ ? { credentialDiagnostics: raw.credentialDiagnostics }
+ : {};
const writePolicy = raw.oauthWritesBlocked ? { oauthWritesBlocked: true } : {};
if (raw.authenticated && raw.recoveryRequiredReason) {
return {
+ ...diagnostics,
kind: 'reconnect-required',
reason: raw.recoveryRequiredReason,
...writePolicy,
@@ -103,6 +111,7 @@ function toCodexUiState(raw: CodexLoginResult, preserveGenericError = false): Co
}
if (raw.authenticated) {
return {
+ ...diagnostics,
kind: 'authenticated',
identity: raw.identity,
expiresAt: raw.expiresAt,
@@ -114,6 +123,7 @@ function toCodexUiState(raw: CodexLoginResult, preserveGenericError = false): Co
const reason = raw.errorReason;
if (reason && isCodexOAuthReconnectRequired(reason)) {
return {
+ ...diagnostics,
kind: 'reconnect-required',
reason,
...writePolicy,
@@ -121,9 +131,9 @@ function toCodexUiState(raw: CodexLoginResult, preserveGenericError = false): Co
};
}
if (preserveGenericError && reason) {
- return { kind: 'error', message: reason, ...writePolicy };
+ return { kind: 'error', message: reason, ...diagnostics, ...writePolicy };
}
- return { kind: 'unauthenticated', ...writePolicy };
+ return { kind: 'unauthenticated', ...diagnostics, ...writePolicy };
}
function replaceUi(
diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.ts
index dadb86f7a2..50cb4692bc 100644
--- a/apps/desktop/src/renderer/vite-env.d.ts
+++ b/apps/desktop/src/renderer/vite-env.d.ts
@@ -646,6 +646,14 @@ interface CodexAuthState {
authSource?: 'oauth' | 'api-key';
oauthWritesBlocked?: boolean;
credentialScope?: 'system-shared' | 'instance-isolated' | 'unknown';
+ credentialDiagnostics?: {
+ linkType: 'symlink' | 'hardlink' | 'file' | 'missing' | 'dangling-symlink' | 'unknown';
+ healthy: boolean;
+ devReadOnly: boolean;
+ systemAuthMtimeMs?: number;
+ systemAuthLinkCount?: number;
+ orphanRepair?: 'none' | 'relinked' | 'failed';
+ };
recoveryRequiredReason?: string;
}
diff --git a/packages/maker-core/src/agents/codex/app-server/client.ts b/packages/maker-core/src/agents/codex/app-server/client.ts
index c66ec6064f..4cf01d6ac7 100644
--- a/packages/maker-core/src/agents/codex/app-server/client.ts
+++ b/packages/maker-core/src/agents/codex/app-server/client.ts
@@ -188,7 +188,15 @@ export interface AppServerClientOptions {
* 关联中的 JSON-RPC response 明确返回 cloudRequirements Auth/relogin 时调用一次。
* 任意 stderr 与工具输出均不得触发;上层 (CodexAgent) 用它注销旧凭证并通知 UI 重登。
*/
- onAuthInvalidated?: (reason: string) => void;
+ onAuthInvalidated?: (
+ reason: string,
+ context?: { credentialGeneration?: string | null },
+ ) => void;
+ /**
+ * Return the generation frozen for this concrete transport. It must not resnapshot mutable
+ * credential storage; the client binds the returned host fact to each correlated request id.
+ */
+ captureCredentialGeneration?: () => string | null;
}
export type NotificationHandler = (params: unknown) => void | Promise<void>;
@@ -201,6 +209,7 @@ interface PendingRequest {
resolve: (value: unknown) => void;
reject: (err: Error) => void;
method: string;
+ credentialGeneration?: string | null;
timeoutId: ReturnType<typeof setTimeout> | null;
}
@@ -211,7 +220,8 @@ export class AppServerClient {
private readonly logger: Logger;
private readonly maxLineBytes: number;
private readonly onTransportError?: (err: Error) => void;
- private readonly onAuthInvalidated?: (reason: string) => void;
+ private readonly onAuthInvalidated?: AppServerClientOptions['onAuthInvalidated'];
+ private readonly captureCredentialGeneration?: () => string | null;
/** 单次 latch — 结构化鉴权失败只通知一次, 防 cloud_requirements 周期性 retry 刷屏。 */
private authInvalidatedFired = false;
@@ -226,7 +236,10 @@ export class AppServerClient {
* the request. Preserve only the request id/method so a late structured auth
* error remains correlated without keeping the already-rejected Promise.
*/
- private readonly writeFailureTombstones = new Map<JsonRpcId, string>();
+ private readonly writeFailureTombstones = new Map<
+ JsonRpcId,
+ { method: string; credentialGeneration?: string | null }
+ >();
private readonly notificationHandlers = new Map<string, NotificationHandler>();
private readonly requestHandlers = new Map<string, ServerRequestHandler>();
@@ -243,6 +256,7 @@ export class AppServerClient {
this.maxLineBytes = opts.maxLineBytes ?? DEFAULT_MAX_LINE_BYTES;
this.onTransportError = opts.onTransportError;
this.onAuthInvalidated = opts.onAuthInvalidated;
+ this.captureCredentialGeneration = opts.captureCredentialGeneration;
}
/**
@@ -346,6 +360,15 @@ export class AppServerClient {
const transport = this.transport;
const id = this.nextId++;
const payload = JSON.stringify({ id, method, params });
+ let credentialGeneration: string | null | undefined;
+ try {
+ credentialGeneration = this.captureCredentialGeneration?.();
+ } catch (error) {
+ credentialGeneration = null;
+ this.logger.warn('credential generation capture failed', {
+ message: error instanceof Error ? error.message : String(error),
+ });
+ }
const timeoutMs = opts?.timeoutMs;
if (
timeoutMs !== undefined &&
@@ -360,6 +383,7 @@ export class AppServerClient {
resolve: resolve as (v: unknown) => void,
reject,
method,
+ credentialGeneration,
timeoutId: null,
};
this.pending.set(id, pending);
@@ -378,7 +402,7 @@ export class AppServerClient {
if (this.pending.get(id) !== pending) return;
this.pending.delete(id);
if (pending.timeoutId) clearTimeout(pending.timeoutId);
- this.rememberWriteFailure(id, method);
+ this.rememberWriteFailure(id, method, credentialGeneration);
reject(err);
});
});
@@ -470,15 +494,21 @@ export class AppServerClient {
private dispatchResponse(id: JsonRpcId, result: unknown, error: JsonRpcErrorObject | null): void {
const pending = this.pending.get(id);
if (!pending) {
- const failedWriteMethod = this.writeFailureTombstones.get(id);
- if (failedWriteMethod !== undefined) {
+ const failedWrite = this.writeFailureTombstones.get(id);
+ if (failedWrite !== undefined) {
this.writeFailureTombstones.delete(id);
this.logger.warn('late response for request with failed write', {
id,
- method: failedWriteMethod,
+ method: failedWrite.method,
hasError: error !== null,
});
- if (error) this.notifyAuthInvalidated(error, failedWriteMethod);
+ if (error) {
+ this.notifyAuthInvalidated(
+ error,
+ failedWrite.method,
+ failedWrite.credentialGeneration,
+ );
+ }
return;
}
this.logger.warn('response for unknown id', { id });
@@ -487,7 +517,7 @@ export class AppServerClient {
this.pending.delete(id);
if (pending.timeoutId) clearTimeout(pending.timeoutId);
if (error) {
- this.notifyAuthInvalidated(error, pending.method);
+ this.notifyAuthInvalidated(error, pending.method, pending.credentialGeneration);
const err = new Error(`codex app-server ${pending.method} error ${error.code}: ${error.message}`);
// 把 code/data 挂上, 上层想区分 OVERLOADED 等可以判 (err as any).code。
Object.assign(err, { code: error.code, data: error.data });
@@ -498,8 +528,12 @@ export class AppServerClient {
}
/** Keep write-failure correlation bounded; oldest ids are least useful. */
- private rememberWriteFailure(id: JsonRpcId, method: string): void {
- this.writeFailureTombstones.set(id, method);
+ private rememberWriteFailure(
+ id: JsonRpcId,
+ method: string,
+ credentialGeneration?: string | null,
+ ): void {
+ this.writeFailureTombstones.set(id, { method, credentialGeneration });
while (this.writeFailureTombstones.size > MAX_WRITE_FAILURE_TOMBSTONES) {
const oldestId = this.writeFailureTombstones.keys().next().value as JsonRpcId | undefined;
if (oldestId === undefined) break;
@@ -508,12 +542,20 @@ export class AppServerClient {
}
/** Notify the host once, but only after the caller has correlated the response. */
- private notifyAuthInvalidated(error: JsonRpcErrorObject, method?: string): void {
+ private notifyAuthInvalidated(
+ error: JsonRpcErrorObject,
+ method?: string,
+ credentialGeneration?: string | null,
+ ): void {
const authInvalidationReason = detectAuthInvalidationReason(error, method);
if (this.authInvalidatedFired || !this.onAuthInvalidated || !authInvalidationReason) return;
this.authInvalidatedFired = true;
try {
- this.onAuthInvalidated(authInvalidationReason);
+ if (credentialGeneration === undefined) {
+ this.onAuthInvalidated(authInvalidationReason);
+ } else {
+ this.onAuthInvalidated(authInvalidationReason, { credentialGeneration });
+ }
} catch (e) {
this.logger.warn('onAuthInvalidated handler threw', { message: (e as Error).message });
}
diff --git a/packages/maker-core/src/agents/codex/app-server/host.ts b/packages/maker-core/src/agents/codex/app-server/host.ts
index 649817d3d9..f8cf6ffe05 100644
--- a/packages/maker-core/src/agents/codex/app-server/host.ts
+++ b/packages/maker-core/src/agents/codex/app-server/host.ts
@@ -255,7 +255,12 @@ export interface AppServerHostOptions {
* 关联中的 JSON-RPC response 明确返回 cloudRequirements Auth/relogin 时调用一次
* (单次 latch 在 client 内)。stderr 始终只作为诊断日志。
*/
- onAuthInvalidated?: (reason: string) => void;
+ onAuthInvalidated?: (
+ reason: string,
+ context?: { credentialGeneration?: string | null },
+ ) => void;
+ /** Returns the credential generation frozen for the current concrete transport. */
+ captureCredentialGeneration?: () => string | null;
/**
* Host 创建时冻结的事实:该 app-server 的 model_provider.base_url 是否走
* 本机 codex proxy。session 级 prompt gate 只读这个值,不再 live 读取全局状态。
@@ -532,6 +537,7 @@ export class AppServerHost {
logger: this.opts.logger,
onTransportError: (err) => this.handleTransportError(err),
onAuthInvalidated: this.opts.onAuthInvalidated,
+ captureCredentialGeneration: this.opts.captureCredentialGeneration,
});
this.client = client;
diff --git a/packages/maker-core/src/agents/codex/index.test.ts b/packages/maker-core/src/agents/codex/index.test.ts
index f8d2a23563..9800faa2cb 100644
--- a/packages/maker-core/src/agents/codex/index.test.ts
+++ b/packages/maker-core/src/agents/codex/index.test.ts
@@ -39,6 +39,7 @@ const { MockCodexTransport, createdTransports, createdStdioOptions } = vi.hoiste
static dropThreadUnsubscribe = false;
static dropModelList = false;
static dropInitialize = false;
+ static beforeInitializeResponse: (() => Promise<void> | void) | null = null;
static beforeThreadStartResponse: ((transport: MockCodexTransport) => Promise<void> | void) | null = null;
static beforeSkillsListResponse: ((transport: MockCodexTransport) => Promise<void> | void) | null = null;
static onCreate: ((transport: MockCodexTransport) => void) | null = null;
@@ -70,6 +71,7 @@ const { MockCodexTransport, createdTransports, createdStdioOptions } = vi.hoiste
}
if (req.method === 'initialize') {
if (MockCodexTransport.dropInitialize) return;
+ await MockCodexTransport.beforeInitializeResponse?.();
this.emitLine({
id: req.id,
result: {
@@ -273,6 +275,7 @@ beforeEach(() => {
MockCodexTransport.dropThreadUnsubscribe = false;
MockCodexTransport.dropModelList = false;
MockCodexTransport.dropInitialize = false;
+ MockCodexTransport.beforeInitializeResponse = null;
MockCodexTransport.beforeThreadStartResponse = null;
MockCodexTransport.beforeSkillsListResponse = null;
MockCodexTransport.onCreate = null;
@@ -6040,6 +6043,7 @@ describe('CodexAgent MCP thread context hooks', () => {
it('retires only the local host when local Codex auth is invalidated', async () => {
const invalidate = vi.fn(async () => undefined);
+ const captureCredentialGeneration = vi.fn(() => 'host-f1-generation');
const auth: AuthAdapter = {
async getState() {
return { authenticated: true };
@@ -6051,6 +6055,7 @@ describe('CodexAgent MCP thread context hooks', () => {
async getAuthEnv() {
return {};
},
+ captureCredentialGeneration,
invalidate,
};
const getRemoteCodexTransport = vi.fn(() => {
@@ -6092,7 +6097,10 @@ describe('CodexAgent MCP thread context hooks', () => {
await waitForExpectation(() => {
expect(createdTransports[0].closed).toBe(true);
});
- expect(invalidate).toHaveBeenCalledWith('refresh_token_reused');
+ expect(captureCredentialGeneration).not.toHaveBeenCalled();
+ expect(invalidate).toHaveBeenCalledWith('refresh_token_reused', {
+ credentialAttribution: 'unproven',
+ });
expect(createdTransports[1].closed).toBe(false);
await remoteHandle.send({ type: 'user', content: 'still remote' });
@@ -6101,6 +6109,60 @@ describe('CodexAgent MCP thread context hooks', () => {
await agent.dispose();
});
+ it('does not attribute a child F2 failure to a parent F1 snapshot across spawn', async () => {
+ let credentialGeneration = 'host-f1-generation';
+ const captureCredentialGeneration = vi.fn(() => credentialGeneration);
+ const invalidate = vi.fn(async () => undefined);
+ const agent = new CodexAgent(createDeps({}, {
+ auth: {
+ async getState() { return { authenticated: true }; },
+ async triggerLogin() { return { authenticated: true }; },
+ async logout() {},
+ async getAuthEnv() { return {}; },
+ captureCredentialGeneration,
+ invalidate,
+ },
+ }));
+
+ MockCodexTransport.beforeInitializeResponse = () => {
+ // The child can first load auth.json after spawn but before initialize returns. The parent
+ // cannot prove whether this transport consumed F1 or the atomically published F2.
+ credentialGeneration = 'disk-f2-generation';
+ };
+ const handle = await agent.startSession({
+ sessionId: 'session-frozen-host-generation',
+ model: 'gpt-5.4',
+ workingDir: '/repo-local',
+ });
+ expect(credentialGeneration).toBe('disk-f2-generation');
+ expect(captureCredentialGeneration).not.toHaveBeenCalled();
+ createdTransports[0].setMockResponse(Method.TurnStart, {
+ error: {
+ code: -32000,
+ message: 'OAuth refresh token was already used',
+ data: { reason: 'cloudRequirements', errorCode: 'Auth' },
+ },
+ });
+ await expect(
+ handle.send(
+ { type: 'user', content: 'child still uses cached F1 after disk rotates' },
+ { throwOnStartFailure: true },
+ ),
+ ).rejects.toThrow(/refresh token was already used/i);
+ await waitForExpectation(() => {
+ expect(invalidate).toHaveBeenCalledWith('refresh_token_reused', {
+ credentialAttribution: 'unproven',
+ });
+ });
+ expect(captureCredentialGeneration).not.toHaveBeenCalled();
+ await waitForExpectation(() => {
+ expect(createdTransports[0].closed).toBe(true);
+ });
+
+ await handle.close();
+ await agent.dispose();
+ });
+
it('retires only the remote host when remote Codex auth is invalidated', async () => {
const invalidate = vi.fn(async () => undefined);
const auth: AuthAdapter = {
diff --git a/packages/maker-core/src/agents/codex/index.ts b/packages/maker-core/src/agents/codex/index.ts
index efae7c6f2a..4bac6adeff 100644
--- a/packages/maker-core/src/agents/codex/index.ts
+++ b/packages/maker-core/src/agents/codex/index.ts
@@ -2723,14 +2723,15 @@ export class CodexAgent extends BaseAgent {
binaryPath,
env,
extraArgs,
- onProcessSpawned: (pid) =>
+ onProcessSpawned: (pid) => {
this.deps.registerLocalCodexAppServerProcess?.({
pid,
role:
hostPurpose === 'control-plane'
? 'control-plane-service'
: 'task-host',
- }),
+ });
+ },
});
}
@@ -2760,13 +2761,18 @@ export class CodexAgent extends BaseAgent {
this.deps.logger.warn('codex auth invalidated', {
reason,
key,
- localAuthWillInvalidate: usesLocalAuth,
+ localAuthWillEnterUnprovenRecovery: usesLocalAuth,
});
Promise.resolve()
.then(async () => {
if (usesLocalAuth) {
try {
- await this.deps.auth.invalidate?.(reason);
+ // The app-server protocol does not expose which auth.json generation the child
+ // loaded. Parent-side snapshots before spawn, after initialize, or per request can
+ // all race that read, so they cannot authorize credential deletion or logout.
+ await this.deps.auth.invalidate?.(reason, {
+ credentialAttribution: 'unproven',
+ });
} catch (e) {
this.deps.logger.error('auth.invalidate threw', { message: (e as Error).message });
}
diff --git a/packages/maker-core/src/interfaces/auth-adapter.ts b/packages/maker-core/src/interfaces/auth-adapter.ts
index 93b975d7f2..0fe61a5b7a 100644
--- a/packages/maker-core/src/interfaces/auth-adapter.ts
+++ b/packages/maker-core/src/interfaces/auth-adapter.ts
@@ -89,6 +89,12 @@ export interface AuthAdapter {
*/
cancelLogin?(): void;
+ /**
+ * Capture an opaque credential generation at agent-host spawn time. The runtime must only carry
+ * this value back to invalidate(); it must not inspect or persist its contents.
+ */
+ captureCredentialGeneration?(): string | null;
+
/**
* agent runtime 检测到当前凭证已被服务端作废 (e.g. OAuth refresh token 已被旋转,
* 401 reauth_required 等) 时调用一次。实现侧应等价于 logout() + 通知 UI 重登,
@@ -97,5 +103,12 @@ export interface AuthAdapter {
* 可选 — 没实现时 runtime 至少会自己 dispose 当前 agent host 防御性收尾,
* 但 UI 端不会自动跳出 "请重新登录" 的提示。
*/
- invalidate?(reason: string): Promise<void>;
+ invalidate?(
+ reason: string,
+ context?: {
+ credentialGeneration?: string | null;
+ /** The child reported auth failure, but the protocol did not identify its credential. */
+ credentialAttribution?: 'unproven';
+ },
+ ): Promise<void>;
}
diff --git a/packages/maker-core/src/types/common.ts b/packages/maker-core/src/types/common.ts
index e74fad7f81..46dd432444 100644
--- a/packages/maker-core/src/types/common.ts
+++ b/packages/maker-core/src/types/common.ts
@@ -79,6 +79,15 @@ export interface AuthState {
* 其它 agent 不返回该字段。
*/
credentialScope?: 'system-shared' | 'instance-isolated' | 'unknown';
+ /** Local-only Codex credential topology. Additive; older renderers may ignore it. */
+ credentialDiagnostics?: {
+ linkType: 'symlink' | 'hardlink' | 'file' | 'missing' | 'dangling-symlink' | 'unknown';
+ healthy: boolean;
+ devReadOnly: boolean;
+ systemAuthMtimeMs?: number;
+ systemAuthLinkCount?: number;
+ orphanRepair?: 'none' | 'relinked' | 'failed';
+ };
/**
* A replacement Codex OAuth credential exists locally but must pass an account-level RPC before
* UI may declare the previous invalidation recovered.