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): protect shared Codex OAuth credentials (#3651)

Chris Zhang2d176b7fedef
diff --git a/apps/desktop/src/main/__tests__/devKeychainMarkerIo.test.ts b/apps/desktop/src/main/__tests__/devKeychainMarkerIo.test.ts
index 0c806b0792..9beeabe35b 100644
--- a/apps/desktop/src/main/__tests__/devKeychainMarkerIo.test.ts
+++ b/apps/desktop/src/main/__tests__/devKeychainMarkerIo.test.ts
@@ -11,7 +11,11 @@ import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { createKeychainMarkerIo } from '../devKeychainMarkerIo';
-import { KEYCHAIN_IDENTITY_MARKER_FILE } from '../devKeychainName';
+import {
+ ISOLATED_AUTH_LAUNCH_PROOF_FILE,
+ KEYCHAIN_IDENTITY_MARKER_FILE,
+ resolveDevKeychainDecision,
+} from '../devKeychainName';
// Windows 上创建 symlink 需要管理员或开发者模式;拿不到权限时(EPERM)按仓内
@@ -178,4 +182,24 @@ describe('createKeychainMarkerIo', () => {
fs.writeFileSync(join(profileDir, 'config.json'), '{}');
expect(io.profileHasData()).toBe(true);
});
+
+ it('proof-only isolated-auth profile 仍认领 CindyDev 身份', () => {
+ fs.writeFileSync(join(profileDir, ISOLATED_AUTH_LAUNCH_PROOF_FILE), '{}\n');
+ fs.writeFileSync(
+ join(profileDir, `${ISOLATED_AUTH_LAUNCH_PROOF_FILE}.123-${'b'.repeat(64)}.tmp`),
+ '{}\n',
+ );
+ const io = makeIo();
+
+ expect(io.profileHasData()).toBe(false);
+ expect(
+ resolveDevKeychainDecision({
+ isPackaged: false,
+ isolated: true,
+ hasDirOverride: true,
+ io,
+ }),
+ ).toEqual({ kind: 'rename', appName: 'CindyDev' });
+ expect(io.readMarker()).toEqual({ kind: 'present', value: 'CindyDev\n' });
+ });
});
diff --git a/apps/desktop/src/main/__tests__/devKeychainName.test.ts b/apps/desktop/src/main/__tests__/devKeychainName.test.ts
index 8f6c0c1444..7dd077578c 100644
--- a/apps/desktop/src/main/__tests__/devKeychainName.test.ts
+++ b/apps/desktop/src/main/__tests__/devKeychainName.test.ts
@@ -16,6 +16,8 @@
import { describe, expect, it, vi } from 'vitest';
import {
+ ISOLATED_AUTH_LAUNCH_PROOF_FILE,
+ isDevProfileFreshnessArtifact,
isKeychainIdentityMarkerArtifact,
resolveDevKeychainDecision,
type KeychainIdentityIo,
@@ -321,4 +323,12 @@ describe('isKeychainIdentityMarkerArtifact', () => {
expect(isKeychainIdentityMarkerArtifact('safe-storage')).toBe(false);
expect(isKeychainIdentityMarkerArtifact('keychain-identity-notes.txt')).toBe(false);
});
+
+ it('launch proof 与原子临时文件不构成 profile 存量数据', () => {
+ expect(isDevProfileFreshnessArtifact(ISOLATED_AUTH_LAUNCH_PROOF_FILE)).toBe(true);
+ expect(
+ isDevProfileFreshnessArtifact(`${ISOLATED_AUTH_LAUNCH_PROOF_FILE}.123-${'a'.repeat(64)}.tmp`),
+ ).toBe(true);
+ expect(isDevProfileFreshnessArtifact(`${ISOLATED_AUTH_LAUNCH_PROOF_FILE}.notes`)).toBe(false);
+ });
});
diff --git a/apps/desktop/src/main/devKeychainMarkerIo.ts b/apps/desktop/src/main/devKeychainMarkerIo.ts
index 52c4c436ab..a91329b92e 100644
--- a/apps/desktop/src/main/devKeychainMarkerIo.ts
+++ b/apps/desktop/src/main/devKeychainMarkerIo.ts
@@ -13,7 +13,7 @@
import { randomUUID } from 'node:crypto';
import fs from 'node:fs';
-import { isKeychainIdentityMarkerArtifact, type KeychainIdentityIo } from './devKeychainName.js';
+import { isDevProfileFreshnessArtifact, type KeychainIdentityIo } from './devKeychainName.js';
export interface KeychainMarkerIoDeps {
/** 身份标记文件的绝对路径(profileDir 下的 KEYCHAIN_IDENTITY_MARKER_FILE)。 */
@@ -258,8 +258,9 @@ export function createKeychainMarkerIo(deps: KeychainMarkerIoDeps): KeychainIden
},
profileHasData: () => {
try {
- // 排除标记文件与其 .tmp 半成品:它们是本机制自身产物,不构成旧沙箱证据。
- return fs.readdirSync(profileDir).some((entry) => !isKeychainIdentityMarkerArtifact(entry));
+ // 排除身份标记、launch proof 与各自的 .tmp 半成品:它们是 dev 启动机制
+ // 自身产物,不能把本轮刚创建的空隔离沙箱误判成旧 profile。
+ return fs.readdirSync(profileDir).some((entry) => !isDevProfileFreshnessArtifact(entry));
} catch (err) {
// 读失败(非 ENOENT)按「有数据」处理:误判方向安全,保持改动前行为。
return (err as NodeJS.ErrnoException)?.code !== 'ENOENT';
diff --git a/apps/desktop/src/main/devKeychainName.ts b/apps/desktop/src/main/devKeychainName.ts
index 6ff5842e28..a91c23a8e9 100644
--- a/apps/desktop/src/main/devKeychainName.ts
+++ b/apps/desktop/src/main/devKeychainName.ts
@@ -48,6 +48,7 @@ import { BRAND_IDENTITY } from '@cindy/maker-shared/brand-identity';
* 词表 = 'CindyDev' | 默认身份名 'Cindy',其它内容一律视为身份不确定)。
*/
export const KEYCHAIN_IDENTITY_MARKER_FILE = 'keychain-identity';
+export const ISOLATED_AUTH_LAUNCH_PROOF_FILE = '.isolated-auth-launch-proof.json';
/** 该目录项是否属于身份标记机制自己的产物(最终标记 或 `<marker>.<pid>-<uuid>.tmp` 半成品)。 */
export function isKeychainIdentityMarkerArtifact(entryName: string): boolean {
@@ -57,6 +58,15 @@ export function isKeychainIdentityMarkerArtifact(entryName: string): boolean {
);
}
+/** 该目录项是否只属于 dev profile 启动/身份认领机制,不构成存量用户数据。 */
+export function isDevProfileFreshnessArtifact(entryName: string): boolean {
+ if (isKeychainIdentityMarkerArtifact(entryName)) return true;
+ if (entryName === ISOLATED_AUTH_LAUNCH_PROOF_FILE) return true;
+ return (
+ entryName.startsWith(`${ISOLATED_AUTH_LAUNCH_PROOF_FILE}.`) && entryName.endsWith('.tmp')
+ );
+}
+
/**
* 标记读取三态:absent 仅代表确证的 ENOENT;其它 IO 错一律 unreadable。
* present.value 必须是**原始文件内容**(不 trim):完整性(终止换行)由 resolver
@@ -95,7 +105,7 @@ export interface KeychainIdentityIo {
claimMarker(name: string): 'claimed' | 'exists' | 'error';
/**
* profile 目录是否已有**真实数据**(读失败按 true,方向安全)。实现必须用
- * isKeychainIdentityMarkerArtifact 排除标记文件与其 .tmp 半成品。
+ * isDevProfileFreshnessArtifact 排除身份标记、launch proof 与它们的 .tmp 半成品。
*/
profileHasData(): boolean;
/**
diff --git a/apps/desktop/src/main/maker-host/__tests__/codexAuthBindingClaim.test.ts b/apps/desktop/src/main/maker-host/__tests__/codexAuthBindingClaim.test.ts
index 06cffb1cb5..7b00b55abc 100644
--- a/apps/desktop/src/main/maker-host/__tests__/codexAuthBindingClaim.test.ts
+++ b/apps/desktop/src/main/maker-host/__tests__/codexAuthBindingClaim.test.ts
@@ -22,7 +22,7 @@ vi.mock('electron', () => ({
app: {
getPath: () => h.userDataDir,
getAppPath: () => h.userDataDir,
- isPackaged: false,
+ isPackaged: true,
},
safeStorage: { isEncryptionAvailable: () => 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 a44e63241d..4bdd09a22c 100644
--- a/apps/desktop/src/main/maker-host/__tests__/codexAuthInvalidation.test.ts
+++ b/apps/desktop/src/main/maker-host/__tests__/codexAuthInvalidation.test.ts
@@ -20,13 +20,16 @@ const h = vi.hoisted(() => ({
dataOwnerId: null as string | null,
sessionGeneration: 1,
sessionBoundaryPending: false,
+ isPackaged: true,
}));
vi.mock('electron', () => ({
app: {
getPath: () => h.userDataDir,
getAppPath: () => h.userDataDir,
- isPackaged: false,
+ get isPackaged() {
+ return h.isPackaged;
+ },
},
safeStorage: { isEncryptionAvailable: () => false },
}));
@@ -83,6 +86,37 @@ it('compares Codex hard-link identities without Windows number precision collisi
expect(haveSameStableFileIdentity({ dev: 7n, ino: 11n }, { dev: 7n, ino: 11n })).toBe(true);
});
+it('does not chmod a system-shared auth file while finalizing login', async () => {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'xdt-codex-shared-mode-'));
+ 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: 'shared-token', account_id: 'acct-1' } }),
+ );
+ fs.linkSync(systemAuth, localAuth);
+ const chmod = vi.spyOn(fs.promises, 'chmod');
+ const { DesktopCodexAuthAdapter } = await import('../auth-adapters.js');
+ const adapter = new DesktopCodexAuthAdapter();
+ const finishSuccessfulCodexLogin = (
+ adapter as unknown as {
+ finishSuccessfulCodexLogin(): Promise<{ authenticated: boolean }>;
+ }
+ ).finishSuccessfulCodexLogin.bind(adapter);
+
+ await expect(finishSuccessfulCodexLogin()).resolves.toMatchObject({ authenticated: true });
+ expect(chmod).not.toHaveBeenCalled();
+ expect(fs.statSync(systemAuth).ino).toBe(fs.statSync(localAuth).ino);
+});
+
async function createRecoveryCandidate(
credentialScope: 'system-shared' | 'instance-isolated' | 'unknown',
) {
@@ -136,6 +170,7 @@ afterEach(() => {
h.dataOwnerId = null;
h.sessionGeneration = 1;
h.sessionBoundaryPending = false;
+ h.isPackaged = true;
for (const dir of dirs.splice(0)) fs.rmSync(dir, { recursive: true, force: true });
});
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 00ef08c0d9..f2e193bdc0 100644
--- a/apps/desktop/src/main/maker-host/__tests__/codexAuthIsolatedSandbox.test.ts
+++ b/apps/desktop/src/main/maker-host/__tests__/codexAuthIsolatedSandbox.test.ts
@@ -5,8 +5,8 @@
* 隔离沙箱里做 OAuth 登录/登出会改写正式实例与本机 CLI 共用的凭证文件 ——
* 2026-08-13 Chris 实测:沙箱一登录,本机 OAuth 全部被退登。
*
- * 期望:置 XDT_ISOLATED_AUTH=1(仅非 packaged)后,reconcile
- * 1) 不再新建共享硬链(本地无 auth.json 时保持无,登录后写独立文件);
+ * 期望:restart 脚本提供完整可信 isolated-auth 信号(仅非 packaged)后,reconcile
+ * 1) 启动时清空旧 auth,之后显式允许的测试登录可写独立文件且不会被再次清掉;
* 2) 已存在的共享硬链解除本沙箱一端(unlink 本地链),系统文件原样保留;
* 3) 开关关闭时行为不变(既有 reconcile 测试覆盖,这里锁默认关)。
*/
@@ -14,6 +14,7 @@ import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { afterEach, describe, expect, it, vi } from 'vitest';
+import { getCodexAuthInvalidationMarkerPath } from '../codex-auth-invalidation.js';
const dirs: string[] = [];
const h = vi.hoisted(() => ({ userDataDir: '', dataOwnerId: null as string | null }));
@@ -61,6 +62,30 @@ function fixture(): { codexHome: string; systemAuth: string; localAuth: string }
return { codexHome, systemAuth, localAuth: path.join(codexHome, 'auth.json') };
}
+function trustIsolatedAuthSandbox(): void {
+ const nonce = 'a'.repeat(64);
+ const now = Date.now();
+ fs.writeFileSync(
+ path.join(h.userDataDir, '.isolated-auth-launch-proof.json'),
+ `${JSON.stringify({
+ version: 1,
+ nonce,
+ userDataDir: fs.realpathSync.native(h.userDataDir),
+ profileKind: 'isolated-sandbox',
+ epoch: 1,
+ isolationName: '',
+ issuedAtMs: now,
+ expiresAtMs: now + 60_000,
+ })}\n`,
+ { mode: 0o600 },
+ );
+ vi.stubEnv('XDT_ISOLATED', '1');
+ vi.stubEnv('XDT_ISOLATED_AUTH', '1');
+ vi.stubEnv('XDT_USER_DATA_DIR_EPOCH', '1');
+ vi.stubEnv('XDT_ALLOW_DEV_OAUTH_WRITE', '1');
+ vi.stubEnv('XDT_ISOLATED_AUTH_PROOF', nonce);
+}
+
afterEach(() => {
vi.restoreAllMocks();
vi.unstubAllEnvs();
@@ -71,7 +96,7 @@ afterEach(() => {
describe('dev 沙箱凭证隔离(XDT_ISOLATED_AUTH)', () => {
it('开关开:不建共享硬链,本地保持无凭证(登录后走独立文件)', async () => {
const { localAuth, systemAuth } = fixture();
- vi.stubEnv('XDT_ISOLATED_AUTH', '1');
+ trustIsolatedAuthSandbox();
h.dataOwnerId = 'owner-a';
const { DesktopCodexAuthAdapter } = await import('../auth-adapters.js');
const adapter = new DesktopCodexAuthAdapter();
@@ -87,7 +112,7 @@ describe('dev 沙箱凭证隔离(XDT_ISOLATED_AUTH)', () => {
fs.mkdirSync(codexHome, { recursive: true });
fs.linkSync(systemAuth, localAuth);
expect(fs.statSync(systemAuth).nlink).toBe(2);
- vi.stubEnv('XDT_ISOLATED_AUTH', '1');
+ trustIsolatedAuthSandbox();
h.dataOwnerId = 'owner-a';
const { DesktopCodexAuthAdapter } = await import('../auth-adapters.js');
const adapter = new DesktopCodexAuthAdapter();
@@ -100,6 +125,31 @@ describe('dev 沙箱凭证隔离(XDT_ISOLATED_AUTH)', () => {
);
});
+ it('开关开:旧的独立凭证孤岛也会被清空', async () => {
+ const { codexHome, localAuth, systemAuth } = fixture();
+ fs.mkdirSync(codexHome, { recursive: true });
+ fs.writeFileSync(localAuth, JSON.stringify({ tokens: { access_token: 'orphan-token' } }));
+ trustIsolatedAuthSandbox();
+ h.dataOwnerId = 'owner-a';
+ const { DesktopCodexAuthAdapter } = await import('../auth-adapters.js');
+ const adapter = new DesktopCodexAuthAdapter();
+
+ await adapter.getState();
+
+ expect(fs.existsSync(localAuth)).toBe(false);
+ fs.writeFileSync(localAuth, JSON.stringify({ tokens: { access_token: 'fresh-test-token' } }));
+ const reconcile = (
+ adapter as unknown as { reconcileWithSystemCodex(): Promise<void> }
+ ).reconcileWithSystemCodex.bind(adapter);
+ await reconcile();
+ expect(JSON.parse(fs.readFileSync(localAuth, 'utf8')).tokens.access_token).toBe(
+ 'fresh-test-token',
+ );
+ expect(JSON.parse(fs.readFileSync(systemAuth, 'utf8')).tokens.access_token).toBe(
+ 'system-token',
+ );
+ });
+
it('开关关(默认):reconcile 照常建共享硬链', async () => {
const { localAuth, systemAuth } = fixture();
h.dataOwnerId = 'owner-a';
@@ -110,4 +160,298 @@ describe('dev 沙箱凭证隔离(XDT_ISOLATED_AUTH)', () => {
const myStat = fs.statSync(localAuth);
expect(sysStat.ino).toBe(myStat.ino);
});
+
+ it('dev 默认只读共享:登录、登出和失效都不改持久凭证', async () => {
+ const { codexHome, localAuth, systemAuth } = fixture();
+ h.dataOwnerId = 'owner-a';
+ const { DesktopCodexAuthAdapter, readCodexOneShotCreds } = await import('../auth-adapters.js');
+ const adapter = new DesktopCodexAuthAdapter();
+ const onLogout = vi.fn();
+ const onInvalidated = vi.fn();
+ adapter.setOnLogoutSuccess(onLogout);
+ adapter.setOnInvalidatedBroadcast(onInvalidated);
+
+ await expect(adapter.getState()).resolves.toMatchObject({
+ authenticated: true,
+ oauthWritesBlocked: true,
+ });
+ expect(readCodexOneShotCreds(adapter)).toEqual({
+ accessToken: 'system-token',
+ accountId: 'acct-1',
+ });
+ const beforeSystem = fs.readFileSync(systemAuth, 'utf8');
+ const beforeLocal = fs.readFileSync(localAuth, 'utf8');
+ const beforeSystemStat = fs.statSync(systemAuth);
+ const beforeLocalStat = fs.statSync(localAuth);
+
+ await expect(adapter.triggerLogin()).resolves.toEqual({
+ authenticated: false,
+ errorReason: 'dev_oauth_write_blocked',
+ oauthWritesBlocked: true,
+ });
+ await adapter.logout();
+ await expect(adapter.getState()).resolves.toMatchObject({
+ authenticated: false,
+ oauthWritesBlocked: true,
+ });
+ await expect(adapter.getAccessToken()).resolves.toBeNull();
+ await expect(adapter.getAccountId()).resolves.toBeNull();
+ expect(readCodexOneShotCreds(adapter)).toBeNull();
+ expect(onLogout).toHaveBeenCalledOnce();
+ expect(fs.readFileSync(systemAuth, 'utf8')).toBe(beforeSystem);
+ expect(fs.readFileSync(localAuth, 'utf8')).toBe(beforeLocal);
+ expect(fs.statSync(systemAuth).ino).toBe(beforeSystemStat.ino);
+ expect(fs.statSync(localAuth).ino).toBe(beforeLocalStat.ino);
+ expect(fs.existsSync(getCodexAuthInvalidationMarkerPath(codexHome))).toBe(false);
+
+ const invalidatedAdapter = new DesktopCodexAuthAdapter();
+ invalidatedAdapter.setOnInvalidatedBroadcast(onInvalidated);
+ await invalidatedAdapter.invalidate('refresh_token_reused');
+ expect(onInvalidated).toHaveBeenCalledWith(
+ 'refresh_token_reused',
+ 'system-shared',
+ true,
+ );
+ expect(fs.readFileSync(systemAuth, 'utf8')).toBe(beforeSystem);
+ expect(fs.readFileSync(localAuth, 'utf8')).toBe(beforeLocal);
+ expect(fs.existsSync(getCodexAuthInvalidationMarkerPath(codexHome))).toBe(false);
+ });
+
+ it('dev 只读失效以内存指纹等待系统凭证换代,不泄漏旧 token 或写共享文件', async () => {
+ const { codexHome, localAuth, systemAuth } = fixture();
+ h.dataOwnerId = 'owner-a';
+ const { DesktopCodexAuthAdapter, readCodexOneShotCreds } = await import('../auth-adapters.js');
+ const adapter = new DesktopCodexAuthAdapter();
+
+ await expect(adapter.getState({ credentialMode: 'oauth-bearer' })).resolves.toMatchObject({
+ authenticated: true,
+ credentialScope: 'system-shared',
+ oauthWritesBlocked: true,
+ });
+ const invalidatedSystemBytes = fs.readFileSync(systemAuth);
+ const invalidatedSystemMode = fs.statSync(systemAuth).mode;
+
+ await adapter.invalidate('refresh_token_reused');
+
+ await expect(adapter.getAccessToken()).resolves.toBeNull();
+ await expect(adapter.getAccountId()).resolves.toBeNull();
+ expect(readCodexOneShotCreds(adapter)).toBeNull();
+ expect(fs.readFileSync(systemAuth)).toEqual(invalidatedSystemBytes);
+ expect(fs.readFileSync(localAuth)).toEqual(invalidatedSystemBytes);
+ expect(fs.statSync(systemAuth).mode).toBe(invalidatedSystemMode);
+ expect(fs.existsSync(getCodexAuthInvalidationMarkerPath(codexHome))).toBe(false);
+
+ const replacement = path.join(path.dirname(systemAuth), 'auth.replacement.json');
+ fs.writeFileSync(
+ replacement,
+ JSON.stringify({
+ account: { email: '[email protected]' },
+ tokens: { access_token: 'renewed-system-token', account_id: 'acct-1' },
+ }),
+ { mode: invalidatedSystemMode },
+ );
+ fs.renameSync(replacement, systemAuth);
+ const renewedSystemBytes = fs.readFileSync(systemAuth);
+ const renewedSystemMode = fs.statSync(systemAuth).mode;
+ expect(readCodexOneShotCreds(adapter)).toBeNull();
+
+ await expect(adapter.getState({ credentialMode: 'oauth-bearer' })).resolves.toMatchObject({
+ authenticated: true,
+ credentialScope: 'system-shared',
+ recoveryRequiredReason: 'refresh_token_reused',
+ oauthWritesBlocked: true,
+ });
+ await expect(adapter.getAccessToken()).resolves.toBe('renewed-system-token');
+ await expect(adapter.getAccountId()).resolves.toBe('acct-1');
+ expect(readCodexOneShotCreds(adapter)).toEqual({
+ accessToken: 'renewed-system-token',
+ accountId: 'acct-1',
+ });
+ expect(fs.readFileSync(systemAuth)).toEqual(renewedSystemBytes);
+ expect(fs.statSync(systemAuth).mode).toBe(renewedSystemMode);
+ expect(fs.existsSync(getCodexAuthInvalidationMarkerPath(codexHome))).toBe(false);
+
+ const renewedSystemStat = fs.statSync(systemAuth);
+ const renewedLocalStat = fs.statSync(localAuth);
+ await expect(adapter.verifyRecoveryWithAccountRpc(async () => 'account-ok')).resolves.toBe(
+ 'account-ok',
+ );
+ const recoveredState = await adapter.getState({ credentialMode: 'oauth-bearer' });
+ expect(recoveredState).toMatchObject({
+ authenticated: true,
+ credentialScope: 'system-shared',
+ oauthWritesBlocked: true,
+ });
+ expect(recoveredState).not.toHaveProperty('recoveryRequiredReason');
+ expect(fs.readFileSync(systemAuth)).toEqual(renewedSystemBytes);
+ expect(fs.readFileSync(localAuth)).toEqual(renewedSystemBytes);
+ expect(fs.statSync(systemAuth).mode).toBe(renewedSystemMode);
+ expect(fs.statSync(systemAuth).ino).toBe(renewedSystemStat.ino);
+ expect(fs.statSync(localAuth).ino).toBe(renewedLocalStat.ino);
+ expect(fs.existsSync(getCodexAuthInvalidationMarkerPath(codexHome))).toBe(false);
+ });
+
+ it('dev 只读系统换代先于迟到失效时记录本地旧代并恢复系统新代', async () => {
+ const { codexHome, localAuth, systemAuth } = fixture();
+ h.dataOwnerId = 'owner-a';
+ const { DesktopCodexAuthAdapter, readCodexOneShotCreds } = await import('../auth-adapters.js');
+ const adapter = new DesktopCodexAuthAdapter();
+
+ await expect(adapter.getState({ credentialMode: 'oauth-bearer' })).resolves.toMatchObject({
+ authenticated: true,
+ credentialScope: 'system-shared',
+ oauthWritesBlocked: true,
+ });
+ const oldLocalBytes = fs.readFileSync(localAuth);
+ const originalMode = fs.statSync(systemAuth).mode;
+
+ const replacement = path.join(path.dirname(systemAuth), 'auth.before-late-401.json');
+ fs.writeFileSync(
+ replacement,
+ JSON.stringify({
+ account: { email: '[email protected]' },
+ tokens: { access_token: 'preexisting-renewed-token', account_id: 'acct-1' },
+ }),
+ { mode: originalMode },
+ );
+ 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);
+
+ const chmod = vi.spyOn(fs.promises, 'chmod');
+ await adapter.invalidate('late_host_401');
+
+ expect(readCodexOneShotCreds(adapter)).toBeNull();
+ expect(fs.existsSync(getCodexAuthInvalidationMarkerPath(codexHome))).toBe(false);
+ await expect(adapter.getState({ credentialMode: 'oauth-bearer' })).resolves.toMatchObject({
+ authenticated: true,
+ credentialScope: 'system-shared',
+ recoveryRequiredReason: 'late_host_401',
+ oauthWritesBlocked: true,
+ });
+ await expect(adapter.getAccessToken()).resolves.toBe('preexisting-renewed-token');
+ await adapter.verifyRecoveryWithAccountRpc(async () => undefined);
+ const recoveredState = await adapter.getState({ credentialMode: 'oauth-bearer' });
+ expect(recoveredState).toMatchObject({
+ authenticated: true,
+ credentialScope: 'system-shared',
+ oauthWritesBlocked: true,
+ });
+ expect(recoveredState).not.toHaveProperty('recoveryRequiredReason');
+ expect(fs.readFileSync(systemAuth)).toEqual(renewedSystemBytes);
+ expect(fs.readFileSync(localAuth)).toEqual(renewedSystemBytes);
+ expect(fs.statSync(systemAuth).mode).toBe(renewedSystemStat.mode);
+ expect(fs.statSync(systemAuth).ino).toBe(renewedSystemStat.ino);
+ expect(chmod).not.toHaveBeenCalled();
+ expect(fs.existsSync(getCodexAuthInvalidationMarkerPath(codexHome))).toBe(false);
+ });
+
+ it('普通 isolated 的写开关不能绕过只读门禁或改写共享凭证', async () => {
+ const { localAuth, systemAuth } = fixture();
+ const systemBytes = fs.readFileSync(systemAuth);
+ const systemStat = fs.statSync(systemAuth);
+ vi.stubEnv('XDT_ISOLATED', '1');
+ vi.stubEnv('XDT_ALLOW_DEV_OAUTH_WRITE', '1');
+ h.dataOwnerId = 'owner-a';
+ const chmod = vi.spyOn(fs.promises, 'chmod');
+ const { DesktopCodexAuthAdapter } = await import('../auth-adapters.js');
+ const adapter = new DesktopCodexAuthAdapter();
+
+ await expect(adapter.getState()).resolves.toMatchObject({
+ authenticated: true,
+ oauthWritesBlocked: true,
+ });
+ expect(fs.readFileSync(localAuth)).toEqual(systemBytes);
+ expect(fs.readFileSync(systemAuth)).toEqual(systemBytes);
+ expect(fs.statSync(systemAuth).mode).toBe(systemStat.mode);
+ expect(fs.statSync(systemAuth).ino).toBe(systemStat.ino);
+ expect(chmod).not.toHaveBeenCalled();
+ });
+
+ it('ambient 四变量与任意 userData 不能伪造 proof 或改写凭证', async () => {
+ const { codexHome, localAuth, systemAuth } = fixture();
+ fs.mkdirSync(codexHome, { recursive: true });
+ fs.writeFileSync(
+ localAuth,
+ JSON.stringify({ tokens: { access_token: 'instance-token', account_id: 'acct-local' } }),
+ { mode: 0o600 },
+ );
+ const localBytes = fs.readFileSync(localAuth);
+ const localStat = fs.statSync(localAuth);
+ const systemBytes = fs.readFileSync(systemAuth);
+ const systemStat = fs.statSync(systemAuth);
+ vi.stubEnv('XDT_USER_DATA_DIR', h.userDataDir);
+ vi.stubEnv('XDT_ISOLATED', '1');
+ vi.stubEnv('XDT_ISOLATED_AUTH', '1');
+ vi.stubEnv('XDT_USER_DATA_DIR_EPOCH', '1');
+ vi.stubEnv('XDT_ALLOW_DEV_OAUTH_WRITE', '1');
+ h.dataOwnerId = 'owner-a';
+ const chmod = vi.spyOn(fs.promises, 'chmod');
+ const { DesktopCodexAuthAdapter } = await import('../auth-adapters.js');
+ const adapter = new DesktopCodexAuthAdapter();
+
+ await expect(adapter.getState()).resolves.toMatchObject({
+ authenticated: true,
+ oauthWritesBlocked: true,
+ });
+ await expect(adapter.triggerLogin()).resolves.toMatchObject({
+ authenticated: false,
+ errorReason: 'dev_oauth_write_blocked',
+ oauthWritesBlocked: true,
+ });
+ expect(fs.readFileSync(localAuth)).toEqual(localBytes);
+ expect(fs.statSync(localAuth).ino).toBe(localStat.ino);
+ expect(fs.statSync(localAuth).mode).toBe(localStat.mode);
+ expect(fs.readFileSync(systemAuth)).toEqual(systemBytes);
+ expect(fs.statSync(systemAuth).ino).toBe(systemStat.ino);
+ expect(fs.statSync(systemAuth).mode).toBe(systemStat.mode);
+ expect(chmod).not.toHaveBeenCalled();
+ });
+
+ it('受信 isolated-auth 沙箱可从空凭证启动并解除写门禁', async () => {
+ const { localAuth, systemAuth } = fixture();
+ const systemBytes = fs.readFileSync(systemAuth);
+ const systemStat = fs.statSync(systemAuth);
+ trustIsolatedAuthSandbox();
+ h.dataOwnerId = 'owner-a';
+ const chmod = vi.spyOn(fs.promises, 'chmod');
+ const { DesktopCodexAuthAdapter } = await import('../auth-adapters.js');
+
+ const state = await new DesktopCodexAuthAdapter().getState();
+ expect(state).toMatchObject({ authenticated: false });
+ expect(state).not.toHaveProperty('oauthWritesBlocked');
+ expect(fs.existsSync(localAuth)).toBe(false);
+ expect(fs.readFileSync(systemAuth)).toEqual(systemBytes);
+ expect(fs.statSync(systemAuth).ino).toBe(systemStat.ino);
+ expect(fs.statSync(systemAuth).mode).toBe(systemStat.mode);
+ expect(chmod).not.toHaveBeenCalled();
+ expect(
+ fs.existsSync(path.join(h.userDataDir, '.isolated-auth-launch-proof.json')),
+ ).toBe(false);
+ });
+
+ it('proof 绑定其它 userData 时保持只读且不消费凭证', async () => {
+ const { localAuth, systemAuth } = fixture();
+ fs.mkdirSync(path.dirname(localAuth), { recursive: true });
+ fs.writeFileSync(localAuth, JSON.stringify({ tokens: { access_token: 'instance-token' } }));
+ const localBytes = fs.readFileSync(localAuth);
+ const systemBytes = fs.readFileSync(systemAuth);
+ trustIsolatedAuthSandbox();
+ const proofPath = path.join(h.userDataDir, '.isolated-auth-launch-proof.json');
+ const proof = JSON.parse(fs.readFileSync(proofPath, 'utf8'));
+ proof.userDataDir = path.join(path.dirname(h.userDataDir), 'another-profile');
+ fs.writeFileSync(proofPath, `${JSON.stringify(proof)}\n`, { mode: 0o600 });
+ h.dataOwnerId = 'owner-a';
+ const chmod = vi.spyOn(fs.promises, 'chmod');
+ const { DesktopCodexAuthAdapter } = await import('../auth-adapters.js');
+
+ await expect(new DesktopCodexAuthAdapter().getState()).resolves.toMatchObject({
+ oauthWritesBlocked: true,
+ });
+ expect(fs.readFileSync(localAuth)).toEqual(localBytes);
+ expect(fs.readFileSync(systemAuth)).toEqual(systemBytes);
+ expect(chmod).not.toHaveBeenCalled();
+ });
});
diff --git a/apps/desktop/src/main/maker-host/__tests__/codexAuthLoginConcurrency.test.ts b/apps/desktop/src/main/maker-host/__tests__/codexAuthLoginConcurrency.test.ts
index 8b34d9e1a3..67632b7b1c 100644
--- a/apps/desktop/src/main/maker-host/__tests__/codexAuthLoginConcurrency.test.ts
+++ b/apps/desktop/src/main/maker-host/__tests__/codexAuthLoginConcurrency.test.ts
@@ -7,7 +7,7 @@ vi.mock('electron', () => ({
app: {
getPath: () => h.userDataDir,
getAppPath: () => h.userDataDir,
- isPackaged: false,
+ isPackaged: true,
},
safeStorage: { isEncryptionAvailable: () => false },
}));
diff --git a/apps/desktop/src/main/maker-host/auth-adapters.ts b/apps/desktop/src/main/maker-host/auth-adapters.ts
index 747a33ad1e..79d524a753 100644
--- a/apps/desktop/src/main/maker-host/auth-adapters.ts
+++ b/apps/desktop/src/main/maker-host/auth-adapters.ts
@@ -14,7 +14,7 @@
*/
import { app, safeStorage } from 'electron';
-import { createHash } from 'node:crypto';
+import { createHash, timingSafeEqual } from 'node:crypto';
import os from 'node:os';
import path from 'node:path';
import fs from 'node:fs';
@@ -41,14 +41,18 @@ import { claudeOAuthSpawnEnv } from './claude-oauth-spawn-env.js';
import {
CODEX_USER_DISCONNECT_REASON,
clearInvalidatedSystemCodexAuthMarker,
+ currentCodexAuthMarker,
+ currentSystemCodexAuthMarker,
getActiveInvalidatedSystemCodexAuthMarker,
isDurableDisconnectMarker,
+ markerMatchesCurrentSystemCodexAuth,
readInvalidatedSystemCodexAuthMarker,
restoreInvalidationStateOnStartup,
settleInvalidationMarkerAfterLogin,
shouldSuppressLocalCodexAuth,
updateInvalidatedSystemCodexAuthMarkerCredentialScope,
writeInvalidatedSystemCodexAuthMarker,
+ type InvalidatedSystemCodexAuthMarker,
} from './codex-auth-invalidation.js';
import {
codexLoginArgs,
@@ -177,6 +181,7 @@ type CodexRecoveryVerificationProof = {
ownerScopeKey: string;
reason: string;
credentialScope: NonNullable<AuthState['credentialScope']>;
+ markerPersistence: 'persisted' | 'memory-only';
markerFingerprint: string;
credentialSha256: string;
accountId: string | null;
@@ -241,7 +246,7 @@ export function chatgptAccountIdFromIdToken(idToken: string): string | null {
* app-server / CLI 负责(本函数只读当下值);文件缺失 / 非 chatgpt 模式 / 解析失败 → null
* (调用方据此跳过 codex 这条标题来源,不抛)。
*/
-export function readCodexOneShotCreds(): { accessToken: string; accountId: string } | null {
+function readCodexOneShotCredsFromDisk(): { accessToken: string; accountId: string } | null {
if (!isNativeProviderAuthBound('openai')) return null;
try {
const codexHome = getCodexHome();
@@ -724,9 +729,66 @@ type CodexDisconnectIntent = {
explicitBoundaryCommitted: boolean;
/** async cleanup 完成后关闭合并窗口;迟到意图会同步重申最终边界,不能改坏 settle 结果。 */
acceptingIntent: boolean;
+ devReadOnly: boolean;
};
const MAX_COALESCED_LOGIN_PROGRESS_CHARS = 64 * 1024;
+const ISOLATED_AUTH_LAUNCH_PROOF_FILE = '.isolated-auth-launch-proof.json';
+const MAX_ISOLATED_AUTH_PROOF_BYTES = 4096;
+const MAX_ISOLATED_AUTH_PROOF_TTL_MS = 10 * 60_000;
+
+function canonicalizeIsolatedAuthProofDir(dir: string): string {
+ try {
+ return fs.realpathSync.native(dir);
+ } catch {
+ return path.resolve(dir);
+ }
+}
+
+function consumeIsolatedAuthLaunchProof(): boolean {
+ const expectedNonce = process.env.XDT_ISOLATED_AUTH_PROOF;
+ delete process.env.XDT_ISOLATED_AUTH_PROOF;
+ if (!expectedNonce || !/^[a-f0-9]{64}$/.test(expectedNonce)) return false;
+ const userDataDir = app.getPath('userData');
+ const proofPath = path.join(userDataDir, ISOLATED_AUTH_LAUNCH_PROOF_FILE);
+ try {
+ const stat = fs.lstatSync(proofPath);
+ if (!stat.isFile() || stat.isSymbolicLink() || stat.size > MAX_ISOLATED_AUTH_PROOF_BYTES) {
+ return false;
+ }
+ if (process.platform !== 'win32' && (stat.mode & 0o077) !== 0) return false;
+ if (process.getuid && stat.uid !== process.getuid()) return false;
+ const proof = JSON.parse(fs.readFileSync(proofPath, 'utf8')) as Record<string, unknown>;
+ const nonce = typeof proof.nonce === 'string' ? proof.nonce : '';
+ const expected = Buffer.from(expectedNonce, 'hex');
+ const actual = /^[a-f0-9]{64}$/.test(nonce) ? Buffer.from(nonce, 'hex') : Buffer.alloc(0);
+ const now = Date.now();
+ return (
+ actual.length === expected.length &&
+ timingSafeEqual(actual, expected) &&
+ proof.version === 1 &&
+ proof.profileKind === 'isolated-sandbox' &&
+ proof.epoch === 1 &&
+ proof.isolationName === (process.env.XDT_ISOLATED_NAME ?? '') &&
+ typeof proof.userDataDir === 'string' &&
+ canonicalizeIsolatedAuthProofDir(proof.userDataDir) ===
+ canonicalizeIsolatedAuthProofDir(userDataDir) &&
+ typeof proof.issuedAtMs === 'number' &&
+ typeof proof.expiresAtMs === 'number' &&
+ proof.issuedAtMs <= now &&
+ proof.expiresAtMs >= now &&
+ proof.expiresAtMs - proof.issuedAtMs <= MAX_ISOLATED_AUTH_PROOF_TTL_MS
+ );
+ } catch {
+ return false;
+ } finally {
+ try {
+ fs.unlinkSync(proofPath);
+ } catch {
+ // Missing/locked proof is already fail-closed.
+ }
+ }
+}
export class DesktopCodexAuthAdapter implements AuthAdapter {
private currentLoginProc: ChildProcess | null = null;
@@ -767,6 +829,7 @@ export class DesktopCodexAuthAdapter implements AuthAdapter {
private onInvalidatedBroadcast?: (
reason: string,
credentialScope: NonNullable<AuthState['credentialScope']>,
+ oauthWritesBlocked?: boolean,
) => void | Promise<void>;
/**
@@ -785,6 +848,12 @@ export class DesktopCodexAuthAdapter implements AuthAdapter {
private oauthRecoveryRequiredReason: string | null = null;
private oauthRecoveryCredentialScope: AuthState['credentialScope'] = undefined;
private suppressSystemCodexReconcile = false;
+ private devReadOnlyDetached = false;
+ /** Dev read-only invalidation fingerprint; memory-only so shared credentials stay untouched. */
+ private devReadOnlyInvalidatedSystemCredential: InvalidatedSystemCodexAuthMarker | null = null;
+ private devOAuthWriteOverrideWarned = false;
+ private isolatedAuthSanitized = false;
+ private isolatedAuthLaunchProofTrusted: boolean | null = null;
/** 运行期最近一次能够被文件/授权记录明确证明的来源,兜住系统 auth 原子替换后的旧硬链。 */
private lastKnownCodexCredentialScope: AuthState['credentialScope'] = undefined;
@@ -826,6 +895,29 @@ export class DesktopCodexAuthAdapter implements AuthAdapter {
return getCodexHome();
}
+ private trustedDevOAuthWriteOverride(): boolean {
+ const declared =
+ !app.isPackaged &&
+ process.env.XDT_ISOLATED === '1' &&
+ process.env.XDT_ISOLATED_AUTH === '1' &&
+ process.env.XDT_USER_DATA_DIR_EPOCH === '1' &&
+ process.env.XDT_ALLOW_DEV_OAUTH_WRITE === '1';
+ if (!declared) return false;
+ this.isolatedAuthLaunchProofTrusted ??= consumeIsolatedAuthLaunchProof();
+ return this.isolatedAuthLaunchProofTrusted;
+ }
+
+ private devOAuthWritesBlocked(): boolean {
+ return !app.isPackaged && !this.trustedDevOAuthWriteOverride();
+ }
+
+ private warnDevOAuthWriteOverride(action: string): void {
+ if (!this.trustedDevOAuthWriteOverride()) return;
+ if (this.devOAuthWriteOverrideWarned) return;
+ this.devOAuthWriteOverrideWarned = true;
+ log.warn(`DEV OAUTH WRITE OVERRIDE ENABLED (${action}): local ChatGPT/Codex login can change`);
+ }
+
/**
* 惰性加载「系统 codex 凭证已被服务端作废」marker(原构造函数逻辑)。
* 所有消费 oauthInvalidatedReason / suppressSystemCodexReconcile 的入口先过这里,
@@ -1002,24 +1094,23 @@ export class DesktopCodexAuthAdapter implements AuthAdapter {
/** reconcile 真正的执行体 —— 只经由 reconcileWithSystemCodex(AfterLogin) 调用, 不直接对外。 */
private async runReconcileWithSystemCodex(): Promise<void> {
- // dev 沙箱凭证隔离(XDT_ISOLATED_AUTH=1,仅非 packaged 生效):完全不与本机
- // ~/.codex 协调 —— 不建共享硬链;当前 auth.json 若已是与系统文件同 inode 的
- // 硬链,解除本沙箱这一端(系统文件与其它实例的链接不受影响),让沙箱回到
- // 未登录、之后的登录写独立文件。背景:共享硬链下沙箱内登录/登出会改写
- // 正式实例与本机 CLI 共用的凭证(2026-08-13 Chris 实测:沙箱一登录,本机
- // OAuth 全被退登),隔离沙箱要可安全测登录必须掐掉这条共享。
if (!app.isPackaged && process.env.XDT_ISOLATED_AUTH === '1') {
+ // XDT_ISOLATED_AUTH 可能被 shell / IDE 环境继承;单一 flag 不是删除凭证的授权。
+ // 与 OAuth 写门禁复用同一完整信任谓词,确保只有 restart 脚本本轮派生的
+ // isolated-auth 沙箱能清理自己的 auth.json。信号不完整时保持磁盘原样并返回,
+ // 既不删除普通实例文件,也不把它送入下方共享链接替换流程。
+ if (!this.trustedDevOAuthWriteOverride()) {
+ log.warn('isolated-auth: ignored untrusted cleanup request');
+ return;
+ }
+ if (this.isolatedAuthSanitized) return;
const isolatedMyAuth = path.join(this.codexHome, 'auth.json');
- const isolatedSystemAuth = getSystemCodexAuthPath();
try {
- if (existsSync(isolatedMyAuth) && existsSync(isolatedSystemAuth)) {
- if (await pathsReferToSameFile(isolatedSystemAuth, isolatedMyAuth)) {
- await fsp.unlink(isolatedMyAuth);
- log.info('isolated-auth: detached shared codex auth hardlink for this sandbox');
- }
- }
+ await fsp.rm(isolatedMyAuth, { force: true });
+ this.isolatedAuthSanitized = true;
+ log.info('isolated-auth: removed local Codex auth so sandbox starts clean');
} catch (err) {
- log.warn('isolated-auth: failed to detach shared codex auth hardlink', {
+ log.warn('isolated-auth: failed to remove local Codex auth', {
error: err instanceof Error ? err.message : String(err),
});
}
@@ -1197,6 +1288,7 @@ export class DesktopCodexAuthAdapter implements AuthAdapter {
cb: (
reason: string,
credentialScope: NonNullable<AuthState['credentialScope']>,
+ oauthWritesBlocked?: boolean,
) => void | Promise<void>,
): void {
this.onInvalidatedBroadcast = cb;
@@ -1211,7 +1303,8 @@ export class DesktopCodexAuthAdapter implements AuthAdapter {
}
async getState(options?: AuthAdapterOptions): Promise<AuthState> {
- return this.readState({ credentialMode: options?.credentialMode });
+ const state = await this.readState({ credentialMode: options?.credentialMode });
+ return this.devOAuthWritesBlocked() ? { ...state, oauthWritesBlocked: true } : state;
}
private async readState(options?: {
@@ -1304,15 +1397,23 @@ export class DesktopCodexAuthAdapter implements AuthAdapter {
private async clearStaleInvalidationIfSystemCodexChanged(): Promise<void> {
if (!this.oauthInvalidatedReason) return;
- const marker = readInvalidatedSystemCodexAuthMarker(this.codexHome);
+ const persistedMarker = readInvalidatedSystemCodexAuthMarker(this.codexHome);
+ const marker = persistedMarker ?? this.devReadOnlyInvalidatedSystemCredential;
if (!marker) return;
- if (getActiveInvalidatedSystemCodexAuthMarker(this.codexHome, getSystemCodexAuthPath())) {
- return;
+ const systemAuthPath = getSystemCodexAuthPath();
+ if (persistedMarker) {
+ if (getActiveInvalidatedSystemCodexAuthMarker(this.codexHome, systemAuthPath)) 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.
+ if (!currentSystemCodexAuthMarker(systemAuthPath, marker.reason)) return;
+ if (markerMatchesCurrentSystemCodexAuth(marker, systemAuthPath)) return;
}
this.oauthInvalidatedReason = null;
this.oauthInvalidatedCredentialScope = undefined;
this.oauthRecoveryRequiredReason = marker.reason;
this.oauthRecoveryCredentialScope = marker.credentialScope ?? 'unknown';
+ this.devReadOnlyDetached = false;
this.suppressSystemCodexReconcile = false;
await this.reconcileWithSystemCodex();
}
@@ -1349,7 +1450,8 @@ export class DesktopCodexAuthAdapter implements AuthAdapter {
) {
return null;
}
- const marker = readInvalidatedSystemCodexAuthMarker(this.codexHome);
+ const persistedMarker = readInvalidatedSystemCodexAuthMarker(this.codexHome);
+ const marker = persistedMarker ?? this.devReadOnlyInvalidatedSystemCredential;
const credential = readCodexRecoveryCredentialProof(path.join(this.codexHome, 'auth.json'));
if (!marker || !credential) return null;
const credentialScope =
@@ -1358,6 +1460,7 @@ export class DesktopCodexAuthAdapter implements AuthAdapter {
ownerScopeKey: activeOwnerScopeKey(),
reason: this.oauthRecoveryRequiredReason,
credentialScope,
+ markerPersistence: persistedMarker ? 'persisted' : 'memory-only',
markerFingerprint: JSON.stringify(marker),
...credential,
};
@@ -1365,16 +1468,19 @@ export class DesktopCodexAuthAdapter implements AuthAdapter {
/**
* A successful account-level RPC proves only the credential captured before that RPC. Compare
- * the proof again before mutating the durable recovery boundary so a late response cannot clear
- * a newer login, invalidation or Cindy owner. Persistence failures are fail-soft for the usage
- * read but fail-closed for recovery: the pending reason remains authoritative.
+ * the proof again before mutating the recovery boundary so a late response cannot clear a newer
+ * login, invalidation or Cindy owner. Persistence failures are fail-soft for the usage read but
+ * fail-closed for recovery: the pending reason remains authoritative.
*/
private confirmRecoveryVerified(proof: CodexRecoveryVerificationProof): boolean {
const current = this.captureRecoveryVerificationProof();
if (!current || JSON.stringify(current) !== JSON.stringify(proof)) return false;
const credentialScope = proof.credentialScope;
- if (credentialScope === 'system-shared') {
+ if (proof.markerPersistence === 'memory-only') {
+ if (credentialScope !== 'system-shared') return false;
+ this.suppressSystemCodexReconcile = false;
+ } else if (credentialScope === 'system-shared') {
if (!clearInvalidatedSystemCodexAuthMarker(this.codexHome)) {
log.error('failed to clear verified Codex recovery marker');
return false;
@@ -1394,6 +1500,7 @@ export class DesktopCodexAuthAdapter implements AuthAdapter {
}
this.suppressSystemCodexReconcile = true;
}
+ this.devReadOnlyInvalidatedSystemCredential = null;
this.oauthRecoveryRequiredReason = null;
this.oauthRecoveryCredentialScope = undefined;
return true;
@@ -1424,6 +1531,7 @@ export class DesktopCodexAuthAdapter implements AuthAdapter {
}
private async readLocalCodexAuthState(): Promise<AuthState> {
+ if (this.devReadOnlyDetached) return { authenticated: false };
const authPath = path.join(this.codexHome, 'auth.json');
if (!existsSync(authPath)) return { authenticated: false };
// logout 的 marker 先于 unlink 落盘;崩溃 / 文件锁导致旧 auth 残留时也不能复活账号。
@@ -1459,6 +1567,16 @@ export class DesktopCodexAuthAdapter implements AuthAdapter {
}
triggerLogin(opts?: AuthLoginOptions): Promise<AuthState> {
+ if (this.devOAuthWritesBlocked()) {
+ return Promise.resolve({
+ authenticated: false,
+ errorReason: 'dev_oauth_write_blocked',
+ oauthWritesBlocked: true,
+ });
+ }
+ this.warnDevOAuthWriteOverride('login');
+ this.devReadOnlyDetached = false;
+ this.devReadOnlyInvalidatedSystemCredential = null;
const mode = opts?.mode ?? 'browser';
if (this.pendingLogin) {
if (this.pendingLogin.mode === mode && !this.pendingLogin.cancelled) {
@@ -1537,6 +1655,12 @@ export class DesktopCodexAuthAdapter implements AuthAdapter {
opts?: AuthLoginOptions,
isCancelled: () => boolean = () => false,
): Promise<AuthState> {
+ if (!app.isPackaged && process.env.XDT_ISOLATED_AUTH === '1' && !this.isolatedAuthSanitized) {
+ await this.reconcileWithSystemCodex();
+ if (!this.isolatedAuthSanitized) {
+ return { authenticated: false, errorReason: 'isolated_auth_cleanup_failed' };
+ }
+ }
this.ensureInvalidationMarkerLoaded();
this.loginAborted = false;
this.loginCancellationOpen = true;
@@ -1671,7 +1795,7 @@ export class DesktopCodexAuthAdapter implements AuthAdapter {
// 收紧 auth.json 权限 (fail-soft: 失败只打日志, 不阻塞登录成功)。
// Win 上 chmod 0o600 在 NTFS 是 no-op,走 icacls;POSIX 用标准 0o600。
const authPath = path.join(this.codexHome, 'auth.json');
- if (existsSync(authPath)) {
+ if (existsSync(authPath) && detectCodexCredentialScope(this.codexHome) !== 'system-shared') {
if (process.platform === 'win32') {
await tightenAclWindows(authPath).catch((e: unknown) => {
credPathLog.warn('icacls auth.json failed', { error: String(e) });
@@ -1816,6 +1940,14 @@ export class DesktopCodexAuthAdapter implements AuthAdapter {
}
}
if (!this.logoutIntent.acceptingIntent && this.logoutIntent.explicitRequested) {
+ if (this.logoutIntent.devReadOnly) {
+ this.oauthInvalidatedReason = null;
+ this.oauthInvalidatedCredentialScope = undefined;
+ this.oauthRecoveryRequiredReason = null;
+ this.oauthRecoveryCredentialScope = undefined;
+ this.devReadOnlyInvalidatedSystemCredential = null;
+ return this.logoutOperation;
+ }
// runLogout 的 async cleanup 已经结束,但 Promise.finally 还没清掉 operation。此时
// 迟到的 invalidation 可能刚改写 marker;同步重申 durable 边界,避免微任务顺序让
// server reason 覆盖已经完成的用户显式退出。
@@ -1837,9 +1969,14 @@ export class DesktopCodexAuthAdapter implements AuthAdapter {
invalidationMarkerCommitted: opts?.invalidationMarkerCommitted === true,
explicitBoundaryCommitted: false,
acceptingIntent: true,
+ devReadOnly: this.devOAuthWritesBlocked(),
};
this.logoutIntent = intent;
- const run = this.runLogout(intent).finally(() => {
+ if (!intent.devReadOnly) this.warnDevOAuthWriteOverride('logout');
+ const operation = intent.devReadOnly
+ ? this.runDevReadOnlyLogout(intent)
+ : this.runLogout(intent);
+ const run = operation.finally(() => {
if (this.logoutOperation === run) {
this.logoutOperation = null;
this.logoutIntent = null;
@@ -1860,6 +1997,41 @@ export class DesktopCodexAuthAdapter implements AuthAdapter {
await this.disconnectCodexOAuth(intent);
}
+ private async runDevReadOnlyLogout(intent: CodexDisconnectIntent): Promise<void> {
+ const pendingLogin = this.pendingLogin?.promise;
+ if (pendingLogin) {
+ this.cancelLogin();
+ await pendingLogin.catch(() => undefined);
+ }
+ this.devReadOnlyDetached = true;
+ this.suppressSystemCodexReconcile = true;
+ if (intent.explicitRequested) {
+ this.oauthInvalidatedReason = null;
+ this.oauthInvalidatedCredentialScope = undefined;
+ this.oauthRecoveryRequiredReason = null;
+ this.oauthRecoveryCredentialScope = undefined;
+ this.devReadOnlyInvalidatedSystemCredential = null;
+ }
+ if (this.onLogoutSuccess) {
+ try {
+ await this.onLogoutSuccess();
+ } catch (error) {
+ log.warn('onLogoutSuccess threw during dev read-only detach', {
+ error: error instanceof Error ? error.message : String(error),
+ });
+ }
+ }
+ intent.acceptingIntent = false;
+ if (intent.explicitRequested) {
+ this.oauthInvalidatedReason = null;
+ this.oauthInvalidatedCredentialScope = undefined;
+ this.oauthRecoveryRequiredReason = null;
+ this.oauthRecoveryCredentialScope = undefined;
+ this.devReadOnlyInvalidatedSystemCredential = null;
+ }
+ log.info('dev read-only Codex auth detached in memory; durable credentials unchanged');
+ }
+
private commitExplicitCodexDisconnectBoundary(intent: CodexDisconnectIntent): boolean {
if (!intent.explicitRequested || intent.explicitBoundaryCommitted) return false;
const persisted = writeInvalidatedSystemCodexAuthMarker(
@@ -1892,6 +2064,7 @@ export class DesktopCodexAuthAdapter implements AuthAdapter {
invalidationMarkerCommitted: false,
explicitBoundaryCommitted: false,
acceptingIntent: true,
+ devReadOnly: false,
};
this.commitExplicitCodexDisconnectBoundary(activeIntent);
const authPath = path.join(this.codexHome, 'auth.json');
@@ -2011,6 +2184,7 @@ export class DesktopCodexAuthAdapter implements AuthAdapter {
* 返回 false;差别仅在于「本来会被这次 reconcile 补上的绑定」这里看不到,于是显示未连接。
*/
hasCodexOAuthLoginReadOnly(): boolean {
+ if (this.devReadOnlyDetached) return false;
if (this.oauthInvalidatedReason) return false;
if (!isNativeProviderAuthBound('openai')) return false;
const authPath = path.join(this.codexHome, 'auth.json');
@@ -2020,6 +2194,7 @@ export class DesktopCodexAuthAdapter implements AuthAdapter {
/** Legacy upgrade probe; only used while claiming the first verified owner. */
hasCodexOAuthLoginUnbound(): boolean {
+ if (this.devReadOnlyDetached) return false;
try {
const raw = fs.readFileSync(path.join(this.codexHome, 'auth.json'), 'utf-8');
const parsed = JSON.parse(raw) as { tokens?: { access_token?: unknown } };
@@ -2031,6 +2206,11 @@ export class DesktopCodexAuthAdapter implements AuthAdapter {
}
}
+ readOneShotCreds(): { accessToken: string; accountId: string } | null {
+ if (this.devReadOnlyDetached) return null;
+ return readCodexOneShotCredsFromDisk();
+ }
+
/**
* Return the Codex OAuth access token for host-owned integrations.
*
@@ -2043,6 +2223,7 @@ export class DesktopCodexAuthAdapter implements AuthAdapter {
if (this.oauthInvalidatedReason) {
await this.clearStaleInvalidationIfSystemCodexChanged();
}
+ if (this.devReadOnlyDetached) return null;
if (this.oauthInvalidatedReason) return null;
// 绑定校验放在 reconcile 之后:reconcile 收口会为首个 owner 补绑定
// (claimDetectedCodexOAuthBinding),同一次调用内即可生效;校验仍在 token
@@ -2077,6 +2258,7 @@ export class DesktopCodexAuthAdapter implements AuthAdapter {
if (this.oauthInvalidatedReason) {
await this.clearStaleInvalidationIfSystemCodexChanged();
}
+ if (this.devReadOnlyDetached) return null;
if (this.oauthInvalidatedReason) return null;
// 同 getAccessToken:绑定校验在 reconcile(含首个 owner 补绑定)之后、读取之前。
await this.reconcileWithSystemCodex();
@@ -2092,6 +2274,41 @@ export class DesktopCodexAuthAdapter implements AuthAdapter {
* 否则错误只会反复埋进后台日志, 用户全程无感。
*/
async invalidate(reason: string): Promise<void> {
+ if (this.devOAuthWritesBlocked()) {
+ log.warn('codex auth invalidated in dev read-only mode; durable credentials unchanged', {
+ reason,
+ });
+ const credentialScope = this.readCodexCredentialScope();
+ const localAuthPath = path.join(this.codexHome, 'auth.json');
+ // 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 =
+ credentialScope === 'system-shared'
+ ? currentCodexAuthMarker(localAuthPath, reason, credentialScope)
+ : null;
+ this.oauthInvalidatedReason = reason;
+ this.oauthInvalidatedCredentialScope = credentialScope;
+ this.oauthRecoveryRequiredReason = null;
+ this.oauthRecoveryCredentialScope = undefined;
+ this.suppressSystemCodexReconcile = true;
+ await this.logout({ preserveInvalidatedReason: true });
+ if (
+ this.oauthInvalidatedReason === reason &&
+ this.oauthInvalidatedCredentialScope === credentialScope &&
+ this.onInvalidatedBroadcast
+ ) {
+ try {
+ await this.onInvalidatedBroadcast(reason, credentialScope, true);
+ } 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 });
const localAuthPath = path.join(this.codexHome, 'auth.json');
@@ -2192,3 +2409,9 @@ export class DesktopCodexAuthAdapter implements AuthAdapter {
// 单例 (与现有 host 消费者保持一致)
export const desktopClaudeAuthAdapter = new DesktopClaudeAuthAdapter();
export const desktopCodexAuthAdapter = new DesktopCodexAuthAdapter();
+
+export function readCodexOneShotCreds(
+ adapter: DesktopCodexAuthAdapter = desktopCodexAuthAdapter,
+): { accessToken: string; accountId: string } | null {
+ return adapter.readOneShotCreds();
+}
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 c691f6a261..712503a9fb 100644
--- a/apps/desktop/src/main/maker-host/codex-auth-invalidation.ts
+++ b/apps/desktop/src/main/maker-host/codex-auth-invalidation.ts
@@ -139,15 +139,24 @@ function currentAuthFileFingerprint(authPath: string): {
}
}
+/** 取指定 auth.json 的指纹; 文件不存在 / stat 失败返回 null。 */
+export function currentCodexAuthMarker(
+ authPath: string,
+ reason: string,
+ credentialScope?: CodexCredentialScope,
+): InvalidatedSystemCodexAuthMarker | null {
+ const fingerprint = currentAuthFileFingerprint(authPath);
+ if (!fingerprint) return null;
+ return { reason, ...(credentialScope ? { credentialScope } : {}), ...fingerprint };
+}
+
/** 取当前系统 auth.json 的指纹; 文件不存在 / stat 失败返回 null。 */
export function currentSystemCodexAuthMarker(
systemAuthPath: string,
reason: string,
credentialScope?: CodexCredentialScope,
): InvalidatedSystemCodexAuthMarker | null {
- const fingerprint = currentAuthFileFingerprint(systemAuthPath);
- if (!fingerprint) return null;
- return { reason, ...(credentialScope ? { credentialScope } : {}), ...fingerprint };
+ return currentCodexAuthMarker(systemAuthPath, reason, credentialScope);
}
function persistInvalidatedSystemCodexAuthMarker(
diff --git a/apps/desktop/src/main/maker-host/index.ts b/apps/desktop/src/main/maker-host/index.ts
index d9032ca40c..7cbbb99ed2 100644
--- a/apps/desktop/src/main/maker-host/index.ts
+++ b/apps/desktop/src/main/maker-host/index.ts
@@ -1731,7 +1731,11 @@ export function getMaker(): Maker {
// logout + 这里这个 broadcast, 让 useCodexAuth hook 立刻进 'unauthenticated' 状态,
// UI 弹 "请重新登录" — 否则错误只会反复埋在后台日志里。payload 字段对齐
// maker-ipc/auth.ts logout handler 的 broadcast 形态。
- desktopCodexAuthAdapter.setOnInvalidatedBroadcast(async (reason, credentialScope) => {
+ desktopCodexAuthAdapter.setOnInvalidatedBroadcast(async (
+ reason,
+ credentialScope,
+ oauthWritesBlocked,
+ ) => {
resetProviderModelAutoRefreshCooldowns('openai');
resetCodexModelBackfillState();
// 运行中 401/token invalidation 不经过 maker:auth:logout IPC,必须在这里做同一套
@@ -1760,6 +1764,7 @@ export function getMaker(): Maker {
authenticated: false,
errorReason: reason,
credentialScope,
+ ...(oauthWritesBlocked ? { oauthWritesBlocked: true } : {}),
};
for (const win of BrowserWindow.getAllWindows()) {
if (win.isDestroyed()) continue;
diff --git a/apps/desktop/src/renderer/__tests__/providersSectionDeepLink.test.tsx b/apps/desktop/src/renderer/__tests__/providersSectionDeepLink.test.tsx
index 7025527e0e..5a3eb1b4a5 100644
--- a/apps/desktop/src/renderer/__tests__/providersSectionDeepLink.test.tsx
+++ b/apps/desktop/src/renderer/__tests__/providersSectionDeepLink.test.tsx
@@ -20,6 +20,7 @@ const {
providersState,
codexAuthState,
codexAuthActions,
+ promptCodexSessionExpired,
toastError,
setModelVisibilitiesSpy,
} = vi.hoisted(
@@ -37,6 +38,7 @@ const {
cancelLogin: vi.fn(async () => undefined),
logout: vi.fn(async () => undefined),
},
+ promptCodexSessionExpired: vi.fn(() => true),
toastError: vi.fn(),
setModelVisibilitiesSpy: vi.fn(() => true),
}),
@@ -68,6 +70,10 @@ vi.mock('@/hooks/useCodexAuth', () => ({
}),
}));
+vi.mock('@/hooks/useCodexSessionExpiredPrompt', () => ({
+ useCodexSessionExpiredPrompt: () => promptCodexSessionExpired,
+}));
+
vi.mock('@/hooks/useApiKey', () => ({
useApiKey: () => ({ key: '', hasSavedKey: false, clearKey: vi.fn() }),
}));
@@ -186,7 +192,7 @@ afterEach(() => {
});
describe('ProvidersSection — 深链定位', () => {
- it('ChatGPT 系统共享登录失效时显示来源说明并在 Cindy 中重新登录', async () => {
+ it('ChatGPT 系统共享登录失效时显示来源说明并进入受保护恢复流程', async () => {
codexAuthState.state = {
kind: 'reconnect-required',
reason: 'token_revoked',
@@ -209,9 +215,10 @@ describe('ProvidersSection — 深链定位', () => {
'var(--remote-status-failed)',
);
expect(await screen.findByText('chatgptAuthRecovery.systemSharedInvalidated')).not.toBeNull();
- fireEvent.click(screen.getByRole('button', { name: 'chatgptAuthRecovery.relogin' }));
+ fireEvent.click(screen.getByRole('button', { name: 'chatgptAuthRecovery.recheck' }));
- await waitFor(() => expect(codexAuthActions.triggerLogin).toHaveBeenCalledOnce());
+ await waitFor(() => expect(promptCodexSessionExpired).toHaveBeenCalledWith('token_revoked'));
+ expect(codexAuthActions.triggerLogin).not.toHaveBeenCalled();
expect(window.electronAPI.openChatGPTApp).not.toHaveBeenCalled();
});
@@ -230,14 +237,13 @@ describe('ProvidersSection — 深链定位', () => {
models: { codex: [], 'claude-code': [] },
}),
];
- codexAuthActions.triggerLogin.mockResolvedValueOnce('cancelled');
renderAt('?tab=providers&connect=openai');
- fireEvent.click(await screen.findByRole('button', { name: 'chatgptAuthRecovery.relogin' }));
+ fireEvent.click(await screen.findByRole('button', { name: 'chatgptAuthRecovery.recheck' }));
- await waitFor(() => expect(codexAuthActions.triggerLogin).toHaveBeenCalledOnce());
+ await waitFor(() => expect(promptCodexSessionExpired).toHaveBeenCalledWith('token_revoked'));
expect(toastError).not.toHaveBeenCalled();
- expect(screen.getByRole('button', { name: 'chatgptAuthRecovery.relogin' })).not.toBeNull();
+ expect(screen.getByRole('button', { name: 'chatgptAuthRecovery.recheck' })).not.toBeNull();
expect(window.electronAPI.openChatGPTApp).not.toHaveBeenCalled();
});
diff --git a/apps/desktop/src/renderer/components/chat/ErrorBanner.tsx b/apps/desktop/src/renderer/components/chat/ErrorBanner.tsx
index 3cc780e954..f130dba2fa 100644
--- a/apps/desktop/src/renderer/components/chat/ErrorBanner.tsx
+++ b/apps/desktop/src/renderer/components/chat/ErrorBanner.tsx
@@ -147,8 +147,8 @@ export function ErrorBanner({
const { t, i18n } = useTranslation();
const { confirm } = useConfirmDialog();
const promptCodexSessionExpired = useCodexSessionExpiredPrompt({
- // 横幅已说明影响范围;用户点击“重新连接 ChatGPT”后直接进入浏览器连接流程,
- // 不再叠一层重复确认弹窗。
+ // 非共享凭证已有横幅说明,可直接重连;system-shared 始终由 hook 强制走
+ // “打开 ChatGPT App / 风险确认后由 Cindy 登录”的保护分支。
confirmBeforeLogin: false,
});
// SSH 与 device-link 是两种互斥的远端来源,但都不能读取或修复控制端本机认证。
@@ -632,8 +632,8 @@ export function ErrorBanner({
)}
</div>
{openAiReconnectRequired && (
- // 所有凭证来源都由 Cindy 启动可产生新 Codex 凭据的登录流程;登录候选出现后
- // 先走账号级服务端探测,探测成功前继续隐藏请求 Retry。
+ // 先走账号级服务端探测;共享凭证由恢复弹窗优先引导到 ChatGPT App,
+ // 不直接产生第二条可 refresh 的 OAuth 凭证链。
<button
type="button"
onClick={() => void handleOpenAiRecovery()}
@@ -649,7 +649,9 @@ export function ErrorBanner({
? 'chatgptAuthRecovery.recheck'
: openAiRecoveryBusy
? 'chatgptAuthRecovery.checking'
- : 'chatgptAuthRecovery.relogin',
+ : openAiCredentialScope === 'system-shared'
+ ? 'chatgptAuthRecovery.recheck'
+ : 'chatgptAuthRecovery.relogin',
)}
>
<Spinner icon={RefreshCw} size={12} spinning={openAiRecoveryBusy} />
@@ -658,7 +660,9 @@ export function ErrorBanner({
? 'chatgptAuthRecovery.checking'
: openAiRecoveryCheck === 'failed'
? 'chatgptAuthRecovery.recheck'
- : 'chatgptAuthRecovery.relogin',
+ : openAiCredentialScope === 'system-shared'
+ ? 'chatgptAuthRecovery.recheck'
+ : 'chatgptAuthRecovery.relogin',
)}
</button>
)}
diff --git a/apps/desktop/src/renderer/components/chat/__tests__/ErrorBannerCodexOAuth.test.tsx b/apps/desktop/src/renderer/components/chat/__tests__/ErrorBannerCodexOAuth.test.tsx
index d8b9724996..ed43ad5558 100644
--- a/apps/desktop/src/renderer/components/chat/__tests__/ErrorBannerCodexOAuth.test.tsx
+++ b/apps/desktop/src/renderer/components/chat/__tests__/ErrorBannerCodexOAuth.test.tsx
@@ -26,6 +26,7 @@ type AuthStateChangedPayload = {
const mocks = vi.hoisted(() => ({
confirm: vi.fn(),
+ confirmThree: vi.fn(),
getState: vi.fn(),
triggerLogin: vi.fn(),
cancelLogin: vi.fn(),
@@ -59,7 +60,7 @@ vi.mock('react-i18next', () => ({
}));
vi.mock('@/components/ui/confirm-dialog-provider', () => ({
- useConfirmDialog: () => ({ confirm: mocks.confirm }),
+ useConfirmDialog: () => ({ confirm: mocks.confirm, confirmThree: mocks.confirmThree }),
}));
vi.mock('@/hooks/useCodexRuntimeRoute', () => ({
@@ -76,6 +77,8 @@ describe('ErrorBanner OpenAI connection recovery', () => {
beforeEach(() => {
vi.clearAllMocks();
mocks.stateChangedListeners.clear();
+ mocks.confirm.mockResolvedValue(true);
+ mocks.confirmThree.mockResolvedValue('tertiary');
mocks.getState.mockResolvedValue({
authenticated: false,
errorReason: 'refresh_token_reused',
@@ -144,12 +147,13 @@ describe('ErrorBanner OpenAI connection recovery', () => {
expect(screen.queryByText(error)).toBeNull();
});
- it('starts Cindy login for an invalidated system-shared login', async () => {
+ it('opens ChatGPT App without starting Cindy OAuth for an invalidated system-shared login', async () => {
mocks.getState.mockResolvedValue({
authenticated: false,
errorReason: 'token_revoked',
credentialScope: 'system-shared',
});
+ mocks.confirmThree.mockResolvedValueOnce('confirm');
render(
<ErrorBanner
error="token_revoked"
@@ -162,12 +166,11 @@ describe('ErrorBanner OpenAI connection recovery', () => {
);
expect(await screen.findByText('chatgptAuthRecovery.systemSharedInvalidated')).toBeTruthy();
- fireEvent.click(screen.getByRole('button', { name: 'chatgptAuthRecovery.relogin' }));
+ fireEvent.click(screen.getByRole('button', { name: 'chatgptAuthRecovery.recheck' }));
- await waitFor(() => expect(mocks.triggerLogin).toHaveBeenCalledOnce());
- expect(mocks.openChatGPTApp).not.toHaveBeenCalled();
- expect(await screen.findByText('chatgptAuthRecovery.recovered')).toBeTruthy();
- expect(screen.getByRole('button', { name: 'chat.errorBanner.retry' })).toBeTruthy();
+ await waitFor(() => expect(mocks.openChatGPTApp).toHaveBeenCalledOnce());
+ expect(mocks.triggerLogin).not.toHaveBeenCalled();
+ expect(screen.queryByRole('button', { name: 'chat.errorBanner.retry' })).toBeNull();
});
it('keeps the recovery action disabled until the credential source is known', async () => {
@@ -201,7 +204,7 @@ describe('ErrorBanner OpenAI connection recovery', () => {
});
await initialState.promise;
});
- expect(await screen.findByRole('button', { name: 'chatgptAuthRecovery.relogin' })).toBeTruthy();
+ expect(await screen.findByRole('button', { name: 'chatgptAuthRecovery.recheck' })).toBeTruthy();
});
it('does not restore retry on a fresh mount until the replacement account probe succeeds', async () => {
@@ -265,12 +268,12 @@ describe('ErrorBanner OpenAI connection recovery', () => {
/>,
);
- fireEvent.click(await screen.findByRole('button', { name: 'chatgptAuthRecovery.relogin' }));
+ fireEvent.click(await screen.findByRole('button', { name: 'chatgptAuthRecovery.recheck' }));
await waitFor(() => expect(mocks.triggerLogin).toHaveBeenCalledOnce());
expect(mocks.toastError).not.toHaveBeenCalled();
expect(mocks.openChatGPTApp).not.toHaveBeenCalled();
- expect(screen.getByRole('button', { name: 'chatgptAuthRecovery.relogin' })).toBeTruthy();
+ expect(screen.getByRole('button', { name: 'chatgptAuthRecovery.recheck' })).toBeTruthy();
expect(screen.queryByRole('button', { name: 'chat.errorBanner.retry' })).toBeNull();
});
@@ -295,14 +298,14 @@ describe('ErrorBanner OpenAI connection recovery', () => {
/>,
);
- fireEvent.click(await screen.findByRole('button', { name: 'chatgptAuthRecovery.relogin' }));
+ fireEvent.click(await screen.findByRole('button', { name: 'chatgptAuthRecovery.recheck' }));
await waitFor(() => {
expect(mocks.toastError).toHaveBeenCalledWith('settings.connections.codex.toast.loginFailed');
});
expect(mocks.triggerLogin).toHaveBeenCalledOnce();
expect(mocks.openChatGPTApp).not.toHaveBeenCalled();
- expect(screen.getByRole('button', { name: 'chatgptAuthRecovery.relogin' })).toBeTruthy();
+ expect(screen.getByRole('button', { name: 'chatgptAuthRecovery.recheck' })).toBeTruthy();
expect(screen.queryByRole('button', { name: 'chat.errorBanner.retry' })).toBeNull();
});
@@ -731,13 +734,12 @@ describe('ErrorBanner OpenAI connection recovery', () => {
expect(mocks.cancelLogin).not.toHaveBeenCalled();
});
- it('uses the system-shared voice recovery copy and starts Cindy login', async () => {
+ it('requires a second risk confirmation before system-shared voice recovery starts Cindy login', async () => {
mocks.getState.mockResolvedValue({
authenticated: false,
errorReason: 'token_revoked',
credentialScope: 'system-shared',
});
- mocks.confirm.mockResolvedValueOnce(true);
const prompt = renderHook(() => useCodexSessionExpiredPrompt());
act(() => {
@@ -745,18 +747,44 @@ describe('ErrorBanner OpenAI connection recovery', () => {
});
await waitFor(() =>
- expect(mocks.confirm).toHaveBeenCalledWith({
+ expect(mocks.confirmThree).toHaveBeenCalledWith({
title: 'chatgptAuthRecovery.title',
description: 'chatgptAuthRecovery.systemSharedInvalidated',
- confirmText: 'chatgptAuthRecovery.relogin',
+ confirmText: 'chatgptAuthRecovery.openApp',
+ tertiaryText: 'chatgptAuthRecovery.relogin',
cancelText: 'chatgptAuthRecovery.later',
autoFocusConfirm: true,
}),
);
+ expect(mocks.confirm).toHaveBeenCalledWith({
+ title: 'chatgptAuthRecovery.reloginRiskTitle',
+ description: 'chatgptAuthRecovery.reloginRiskDescription',
+ confirmText: 'chatgptAuthRecovery.reloginRiskConfirm',
+ cancelText: 'chatgptAuthRecovery.later',
+ confirmVariant: 'destructive',
+ });
await waitFor(() => expect(mocks.triggerLogin).toHaveBeenCalledOnce());
expect(mocks.openChatGPTApp).not.toHaveBeenCalled();
});
+ it('offers only the ChatGPT App when dev policy blocks OAuth writes', async () => {
+ mocks.getState.mockResolvedValue({
+ authenticated: false,
+ errorReason: 'token_revoked',
+ credentialScope: 'system-shared',
+ oauthWritesBlocked: true,
+ });
+ const prompt = renderHook(() => useCodexSessionExpiredPrompt());
+
+ act(() => {
+ expect(prompt.result.current('token_revoked')).toBe(true);
+ });
+
+ await waitFor(() => expect(mocks.openChatGPTApp).toHaveBeenCalledOnce());
+ expect(mocks.confirmThree).not.toHaveBeenCalled();
+ expect(mocks.triggerLogin).not.toHaveBeenCalled();
+ });
+
it('starts Cindy login when an authenticated system-shared hint cannot be verified', async () => {
mocks.getState.mockResolvedValue({
authenticated: true,
@@ -765,7 +793,6 @@ describe('ErrorBanner OpenAI connection recovery', () => {
credentialScope: 'system-shared',
});
mocks.getCodexRateLimits.mockRejectedValueOnce(new Error('network unavailable'));
- mocks.confirm.mockResolvedValueOnce(true);
const prompt = renderHook(() => useCodexSessionExpiredPrompt());
act(() => {
@@ -773,10 +800,11 @@ describe('ErrorBanner OpenAI connection recovery', () => {
});
await waitFor(() =>
- expect(mocks.confirm).toHaveBeenCalledWith({
+ expect(mocks.confirmThree).toHaveBeenCalledWith({
title: 'chatgptAuthRecovery.title',
description: 'chatgptAuthRecovery.systemSharedInvalidated',
- confirmText: 'chatgptAuthRecovery.relogin',
+ confirmText: 'chatgptAuthRecovery.openApp',
+ tertiaryText: 'chatgptAuthRecovery.relogin',
cancelText: 'chatgptAuthRecovery.later',
autoFocusConfirm: true,
}),
@@ -904,9 +932,7 @@ describe('ErrorBanner OpenAI connection recovery', () => {
);
expect(screen.getByText('chat.errorBanner.codexOrganizationUsageLimit')).toBeTruthy();
- expect(
- screen.queryByText('chat.errorBanner.codexOrganizationUsageLimitWithReset'),
- ).toBeNull();
+ expect(screen.queryByText('chat.errorBanner.codexOrganizationUsageLimitWithReset')).toBeNull();
});
it('keeps a transient Codex 429 on its normal rate-limit path', () => {
diff --git a/apps/desktop/src/renderer/components/settings/AddProviderWizard.tsx b/apps/desktop/src/renderer/components/settings/AddProviderWizard.tsx
index d98dc09ea6..aece90bf9c 100644
--- a/apps/desktop/src/renderer/components/settings/AddProviderWizard.tsx
+++ b/apps/desktop/src/renderer/components/settings/AddProviderWizard.tsx
@@ -689,6 +689,10 @@ export function AddProviderWizard({
}
if (!r.ok && r.reason === 'login_cancelled') return;
} else if (id === 'openai') {
+ if (codexAuth.state.oauthWritesBlocked) {
+ toast.error(t('chatgptAuthRecovery.devWriteBlocked'));
+ return;
+ }
openaiLoginStartedRef.current = true;
const outcome = await codexAuth.triggerLogin(mode);
ok = outcome === 'authenticated';
@@ -1586,7 +1590,10 @@ export function AddProviderWizard({
<button
type="button"
onClick={() => void handleAuthorize('browser')}
- className="flex h-9 items-center justify-center rounded-full border px-6 text-13 font-medium transition-colors hover:bg-[var(--surface-hover)]"
+ disabled={
+ sel.provider.id === 'openai' && codexAuth.state.oauthWritesBlocked === true
+ }
+ className="flex h-9 items-center justify-center rounded-full border px-6 text-13 font-medium transition-colors hover:bg-[var(--surface-hover)] disabled:cursor-not-allowed disabled:opacity-50"
style={{
backgroundColor: 'var(--settings-btn-secondary-bg)',
borderColor: 'var(--settings-btn-secondary-border)',
@@ -1594,18 +1601,21 @@ export function AddProviderWizard({
}}
>
{t(
- sel.provider.id === 'openai'
- ? 'settings.providers.wizard.authorizeInBrowser'
- : sel.provider.auth.oauth?.flow === 'device-code'
- ? 'settings.providers.wizard.authorizeWithDeviceCode'
- : 'settings.providers.button.authorize',
+ sel.provider.id === 'openai' && codexAuth.state.oauthWritesBlocked
+ ? 'chatgptAuthRecovery.devReadOnly'
+ : sel.provider.id === 'openai'
+ ? 'settings.providers.wizard.authorizeInBrowser'
+ : sel.provider.auth.oauth?.flow === 'device-code'
+ ? 'settings.providers.wizard.authorizeWithDeviceCode'
+ : 'settings.providers.button.authorize',
)}
</button>
{sel.provider.id === 'openai' && (
<button
type="button"
onClick={() => void handleAuthorize('device-code')}
- className="flex h-9 items-center justify-center rounded-full border px-6 text-13 font-medium transition-colors hover:bg-[var(--surface-hover)]"
+ disabled={codexAuth.state.oauthWritesBlocked === true}
+ className="flex h-9 items-center justify-center rounded-full border px-6 text-13 font-medium transition-colors hover:bg-[var(--surface-hover)] disabled:cursor-not-allowed disabled:opacity-50"
style={{
backgroundColor: 'transparent',
borderColor: 'var(--settings-btn-secondary-border)',
diff --git a/apps/desktop/src/renderer/components/settings/ProvidersSection.tsx b/apps/desktop/src/renderer/components/settings/ProvidersSection.tsx
index 509438469f..cbab6b7481 100644
--- a/apps/desktop/src/renderer/components/settings/ProvidersSection.tsx
+++ b/apps/desktop/src/renderer/components/settings/ProvidersSection.tsx
@@ -37,6 +37,7 @@ import {
import { cn } from '@/lib/utils';
import { useProviders } from '@/hooks/useProviders';
import { isChatGptConnectionConnected, useCodexAuth } from '@/hooks/useCodexAuth';
+import { useCodexSessionExpiredPrompt } from '@/hooks/useCodexSessionExpiredPrompt';
import { useApiKey } from '@/hooks/useApiKey';
import { extractIpcError } from '@/utils/ipcError';
import { useModelAccessStatus } from '@/hooks/useModelAccessStatus';
@@ -585,6 +586,11 @@ function OpenAiHeader({ provider, onChanged }: { provider?: ProviderView; onChan
const credentialScope = reconnectRequired
? (state.credentialScope ?? 'unknown')
: (reconnectCredentialScope ?? 'unknown');
+ const oauthWritesBlocked = state.oauthWritesBlocked === true;
+ const promptCodexSessionExpired = useCodexSessionExpiredPrompt({
+ onAuthenticated: () => onChanged(),
+ confirmBeforeLogin: false,
+ });
const handleLogout = useCallback(async () => {
const confirmed = await confirm({
@@ -610,6 +616,8 @@ function OpenAiHeader({ provider, onChanged }: { provider?: ProviderView; onChan
onChanged();
} else if (outcome === 'unverified') {
toast.error(t('chatgptAuthRecovery.verificationFailed'));
+ } else if (outcome === 'blocked') {
+ toast.error(t('chatgptAuthRecovery.devWriteBlocked'));
} else if (outcome === 'failed') {
toast.error(t('settings.connections.codex.toast.loginFailed'));
}
@@ -621,8 +629,8 @@ function OpenAiHeader({ provider, onChanged }: { provider?: ProviderView; onChan
await refresh();
return;
}
- await handleLogin();
- }, [handleLogin, loggingIn, recoveryCheck, refresh]);
+ if (reconnectRequired) promptCodexSessionExpired(state.reason);
+ }, [loggingIn, promptCodexSessionExpired, reconnectRequired, recoveryCheck, refresh, state]);
const recoveryDetail = reconnectRequired ? (
<p className="text-12 leading-relaxed text-[var(--settings-integration-subtitle)]">
@@ -653,19 +661,28 @@ function OpenAiHeader({ provider, onChanged }: { provider?: ProviderView; onChan
? 'chatgptAuthRecovery.checking'
: recoveryCheck === 'failed'
? 'chatgptAuthRecovery.recheck'
- : 'chatgptAuthRecovery.relogin',
+ : credentialScope === 'system-shared'
+ ? 'chatgptAuthRecovery.recheck'
+ : 'chatgptAuthRecovery.relogin',
)}
onClick={() => void handleRecovery()}
- disabled={recoveryCheck === 'checking' || loggingIn}
+ disabled={
+ recoveryCheck === 'checking' ||
+ loggingIn ||
+ (oauthWritesBlocked && credentialScope !== 'system-shared')
+ }
/>
</div>
) : (
<PillButton
label={
- loggingIn
- ? t('settings.providers.openai.cancelConnect')
- : t('settings.providers.openai.connect')
+ oauthWritesBlocked
+ ? t('chatgptAuthRecovery.devReadOnly')
+ : loggingIn
+ ? t('settings.providers.openai.cancelConnect')
+ : t('settings.providers.openai.connect')
}
+ disabled={oauthWritesBlocked}
onClick={() => {
if (loggingIn) void cancelLogin();
else void handleLogin();
diff --git a/apps/desktop/src/renderer/hooks/__tests__/useCodexAuth.test.ts b/apps/desktop/src/renderer/hooks/__tests__/useCodexAuth.test.ts
index 59a4eb4e7a..28e567a63d 100644
--- a/apps/desktop/src/renderer/hooks/__tests__/useCodexAuth.test.ts
+++ b/apps/desktop/src/renderer/hooks/__tests__/useCodexAuth.test.ts
@@ -19,6 +19,7 @@ type TestAuthState = {
identity?: string;
errorReason?: string;
authSource?: 'oauth' | 'api-key';
+ oauthWritesBlocked?: boolean;
credentialScope?: 'system-shared' | 'instance-isolated' | 'unknown';
recoveryRequiredReason?: string;
};
@@ -119,7 +120,42 @@ describe('useCodexAuth lifecycle', () => {
await result.current.logout();
});
- expect(result.current.state.kind).toBe('unauthenticated');
+ expect(result.current.state).toEqual({ kind: 'unauthenticated' });
+ });
+
+ it('keeps dev write policy authoritative across logout and its state broadcast', async () => {
+ const auth = installAuthApi(async () => undefined);
+ auth.getState.mockResolvedValueOnce({
+ authenticated: true,
+ identity: '[email protected]',
+ authSource: 'oauth',
+ oauthWritesBlocked: true,
+ });
+ const { result } = renderHook(() => useCodexAuth());
+
+ await waitFor(() =>
+ expect(result.current.state).toMatchObject({
+ kind: 'authenticated',
+ oauthWritesBlocked: true,
+ }),
+ );
+ await act(async () => {
+ await result.current.logout();
+ });
+ expect(result.current.state).toEqual({
+ kind: 'unauthenticated',
+ oauthWritesBlocked: true,
+ });
+
+ act(() => {
+ stateChangedListener(auth)({ agentKind: 'codex', authenticated: false });
+ });
+ expect(result.current.state).toEqual({
+ kind: 'unauthenticated',
+ oauthWritesBlocked: true,
+ });
+ await expect(result.current.triggerLogin()).resolves.toBe('blocked');
+ expect(auth.triggerLogin).not.toHaveBeenCalled();
});
it('refreshes to disconnected when cleanup fails after the marker committed', async () => {
@@ -189,6 +225,36 @@ describe('useCodexAuth lifecycle', () => {
expect(result.current.state).toEqual({ kind: 'error', message: 'login_timeout' });
});
+ it('surfaces the dev read-only policy and reports blocked without hiding it', async () => {
+ const auth = installAuthApi(async () => undefined);
+ auth.getState.mockResolvedValueOnce({
+ authenticated: false,
+ oauthWritesBlocked: true,
+ });
+ auth.triggerLogin.mockResolvedValue({
+ authenticated: false,
+ errorReason: 'dev_oauth_write_blocked',
+ oauthWritesBlocked: true,
+ });
+ const { result } = renderHook(() => useCodexAuth());
+
+ await waitFor(() =>
+ expect(result.current.state).toEqual({
+ kind: 'unauthenticated',
+ oauthWritesBlocked: true,
+ }),
+ );
+ await act(async () => {
+ await expect(result.current.triggerLogin()).resolves.toBe('blocked');
+ });
+
+ expect(result.current.state).toEqual({
+ kind: 'unauthenticated',
+ oauthWritesBlocked: true,
+ });
+ expect(auth.triggerLogin).not.toHaveBeenCalled();
+ });
+
it('restores reconnect-required from a persisted OAuth invalidation', async () => {
const auth = installAuthApi(async () => undefined);
auth.getState.mockResolvedValueOnce({
diff --git a/apps/desktop/src/renderer/hooks/codexAuthLogin.ts b/apps/desktop/src/renderer/hooks/codexAuthLogin.ts
index 728154e489..0a989d68c2 100644
--- a/apps/desktop/src/renderer/hooks/codexAuthLogin.ts
+++ b/apps/desktop/src/renderer/hooks/codexAuthLogin.ts
@@ -9,6 +9,7 @@ export type CodexLoginResult = {
expiresAt?: number;
errorReason?: string;
authSource?: 'oauth' | 'api-key';
+ oauthWritesBlocked?: boolean;
credentialScope?: 'system-shared' | 'instance-isolated' | 'unknown';
recoveryRequiredReason?: string;
};
diff --git a/apps/desktop/src/renderer/hooks/useCodexAuth.ts b/apps/desktop/src/renderer/hooks/useCodexAuth.ts
index ca4e874e33..84901075e6 100644
--- a/apps/desktop/src/renderer/hooks/useCodexAuth.ts
+++ b/apps/desktop/src/renderer/hooks/useCodexAuth.ts
@@ -19,7 +19,7 @@ import {
} from './codexAuthLogin';
import { isCodexOAuthReconnectRequired } from './codexAuthRecovery';
-export type CodexUiState =
+export type CodexUiState = (
| { kind: 'loading' }
| { kind: 'unauthenticated' }
| {
@@ -39,9 +39,10 @@ export type CodexUiState =
reason: string;
credentialScope?: 'system-shared' | 'instance-isolated' | 'unknown';
}
- | { kind: 'error'; message: string };
+ | { kind: 'error'; message: string }
+) & { oauthWritesBlocked?: boolean };
-export type CodexLoginOutcome = 'authenticated' | 'cancelled' | 'failed' | 'unverified';
+export type CodexLoginOutcome = 'authenticated' | 'cancelled' | 'blocked' | 'failed' | 'unverified';
export type CodexRecoveryCheck = 'idle' | 'checking' | 'failed';
type CodexAuthMachineState = {
@@ -91,10 +92,12 @@ function createInitialMachineState(): CodexAuthMachineState {
}
function toCodexUiState(raw: CodexLoginResult, preserveGenericError = false): CodexUiState {
+ const writePolicy = raw.oauthWritesBlocked ? { oauthWritesBlocked: true } : {};
if (raw.authenticated && raw.recoveryRequiredReason) {
return {
kind: 'reconnect-required',
reason: raw.recoveryRequiredReason,
+ ...writePolicy,
...(raw.credentialScope ? { credentialScope: raw.credentialScope } : {}),
};
}
@@ -104,6 +107,7 @@ function toCodexUiState(raw: CodexLoginResult, preserveGenericError = false): Co
identity: raw.identity,
expiresAt: raw.expiresAt,
authSource: raw.authSource,
+ ...writePolicy,
...(raw.credentialScope ? { credentialScope: raw.credentialScope } : {}),
};
}
@@ -112,13 +116,14 @@ function toCodexUiState(raw: CodexLoginResult, preserveGenericError = false): Co
return {
kind: 'reconnect-required',
reason,
+ ...writePolicy,
...(raw.credentialScope ? { credentialScope: raw.credentialScope } : {}),
};
}
if (preserveGenericError && reason) {
- return { kind: 'error', message: reason };
+ return { kind: 'error', message: reason, ...writePolicy };
}
- return { kind: 'unauthenticated' };
+ return { kind: 'unauthenticated', ...writePolicy };
}
function replaceUi(
@@ -126,19 +131,24 @@ function replaceUi(
ui: CodexUiState,
revision: 'snapshot' | 'event' | 'auth',
): CodexAuthMachineState {
+ // Main's dev write policy is process-wide. Logout broadcasts intentionally omit it, so once
+ // observed it must remain authoritative across local/event state replacements.
+ const nextUi: CodexUiState = machine.ui.oauthWritesBlocked
+ ? { ...ui, oauthWritesBlocked: true }
+ : ui;
let reconnectReason = machine.reconnectReason;
let reconnectCredentialScope = machine.reconnectCredentialScope;
- if (ui.kind === 'reconnect-required') {
- reconnectReason = ui.reason;
- reconnectCredentialScope = ui.credentialScope;
+ if (nextUi.kind === 'reconnect-required') {
+ reconnectReason = nextUi.reason;
+ reconnectCredentialScope = nextUi.credentialScope;
}
- if (ui.kind === 'authenticated' || ui.kind === 'unauthenticated') {
+ if (nextUi.kind === 'authenticated' || nextUi.kind === 'unauthenticated') {
reconnectReason = null;
reconnectCredentialScope = undefined;
}
return {
- ui,
+ ui: nextUi,
reconnectReason,
...(reconnectCredentialScope ? { reconnectCredentialScope } : {}),
authRevision: machine.authRevision + (revision === 'auth' ? 1 : 0),
@@ -156,6 +166,7 @@ function restoreReconnectOr(
? {
kind: 'reconnect-required',
reason: machine.reconnectReason,
+ ...(fallback.oauthWritesBlocked ? { oauthWritesBlocked: true } : {}),
...(machine.reconnectCredentialScope
? { credentialScope: machine.reconnectCredentialScope }
: {}),
@@ -759,6 +770,7 @@ export function useCodexAuth(options?: {
async (mode: 'browser' | 'device-code' = 'browser'): Promise<CodexLoginOutcome> => {
const observerEpoch = observerEpochRef.current;
if (!isObserverActive(observerEpoch)) return 'cancelled';
+ if (machineRef.current.ui.oauthWritesBlocked) return 'blocked';
transition({ type: 'login-pending', mode });
try {
const result = await triggerOwnedLogin(mode);
@@ -778,7 +790,8 @@ export function useCodexAuth(options?: {
return 'authenticated';
}
transition({ type: 'login-result', result });
- return result.errorReason === 'login_cancelled' ? 'cancelled' : 'failed';
+ if (result.errorReason === 'login_cancelled') return 'cancelled';
+ return result.errorReason === 'dev_oauth_write_blocked' ? 'blocked' : 'failed';
} catch (error) {
if (!isObserverActive(observerEpoch)) return 'cancelled';
const message = error instanceof Error ? error.message : 'login_failed';
diff --git a/apps/desktop/src/renderer/hooks/useCodexSessionExpiredPrompt.ts b/apps/desktop/src/renderer/hooks/useCodexSessionExpiredPrompt.ts
index d4dcf3bfc9..ec6b22b2f0 100644
--- a/apps/desktop/src/renderer/hooks/useCodexSessionExpiredPrompt.ts
+++ b/apps/desktop/src/renderer/hooks/useCodexSessionExpiredPrompt.ts
@@ -18,7 +18,7 @@ function reconnectCopyForScope(scope: CodexCredentialScope): {
if (scope === 'system-shared') {
return {
description: 'chatgptAuthRecovery.systemSharedInvalidated',
- confirmText: 'chatgptAuthRecovery.relogin',
+ confirmText: 'chatgptAuthRecovery.openApp',
};
}
return {
@@ -37,7 +37,7 @@ export function useCodexSessionExpiredPrompt(options?: {
confirmBeforeLogin?: boolean;
}): (error: string) => boolean {
const { t } = useTranslation();
- const { confirm } = useConfirmDialog();
+ const { confirm, confirmThree } = useConfirmDialog();
const triggerOwnedLogin = useOwnedCodexLogin();
const promptedForErrorRef = useRef<string | null>(null);
const promptActiveRef = useRef(false);
@@ -71,8 +71,10 @@ export function useCodexSessionExpiredPrompt(options?: {
void (async () => {
let credentialScope: CodexCredentialScope = 'unknown';
+ let oauthWritesBlocked = false;
try {
const state = (await window.electronAPI.maker.auth.getState('codex')) as CodexLoginResult;
+ oauthWritesBlocked = state.oauthWritesBlocked === true;
if (!mountedRef.current) return;
if (state.authenticated) {
const verification = await verifyCodexAuthRecovery(state);
@@ -98,7 +100,67 @@ export function useCodexSessionExpiredPrompt(options?: {
// 无法读取来源时按 unknown 引导,避免误称沿用了系统登录。
}
const copy = reconnectCopyForScope(credentialScope);
- if (options?.confirmBeforeLogin !== false) {
+ const openChatGptAppAndClose = async () => {
+ try {
+ const opened = await window.electronAPI.openChatGPTApp();
+ if (!opened.success) toast.error(t('chatgptAuthRecovery.openAppFailed'));
+ } catch {
+ toast.error(t('chatgptAuthRecovery.openAppFailed'));
+ }
+ if (mountedRef.current) closePrompt();
+ };
+ if (credentialScope === 'system-shared') {
+ if (oauthWritesBlocked) {
+ const shouldOpenApp = await confirm({
+ title: t('chatgptAuthRecovery.title'),
+ description: t(copy.description),
+ confirmText: t('chatgptAuthRecovery.openApp'),
+ cancelText: t('chatgptAuthRecovery.later'),
+ autoFocusConfirm: true,
+ });
+ if (!mountedRef.current) return;
+ if (!shouldOpenApp) {
+ closePrompt();
+ return;
+ }
+ await openChatGptAppAndClose();
+ return;
+ }
+ const recoveryAction = await confirmThree({
+ title: t('chatgptAuthRecovery.title'),
+ description: t(copy.description),
+ confirmText: t(copy.confirmText),
+ tertiaryText: t('chatgptAuthRecovery.relogin'),
+ cancelText: t('chatgptAuthRecovery.later'),
+ autoFocusConfirm: true,
+ });
+ if (!mountedRef.current) return;
+ if (recoveryAction === 'cancel') {
+ closePrompt();
+ return;
+ }
+ if (recoveryAction === 'confirm') {
+ await openChatGptAppAndClose();
+ return;
+ }
+
+ const acceptsSignOutRisk = await confirm({
+ title: t('chatgptAuthRecovery.reloginRiskTitle'),
+ description: t('chatgptAuthRecovery.reloginRiskDescription'),
+ confirmText: t('chatgptAuthRecovery.reloginRiskConfirm'),
+ cancelText: t('chatgptAuthRecovery.later'),
+ confirmVariant: 'destructive',
+ });
+ if (!mountedRef.current) return;
+ if (!acceptsSignOutRisk) {
+ closePrompt();
+ return;
+ }
+ } else if (oauthWritesBlocked) {
+ toast.error(t('chatgptAuthRecovery.devWriteBlocked'));
+ closePrompt();
+ return;
+ } else if (options?.confirmBeforeLogin !== false) {
const shouldReconnect = await confirm({
title: t('chatgptAuthRecovery.title'),
description: t(copy.description),
@@ -128,7 +190,13 @@ export function useCodexSessionExpiredPrompt(options?: {
toast.error(t('settings.connections.codex.toast.loginFailed'));
}
} else if (result.errorReason !== 'login_cancelled') {
- toast.error(t('settings.connections.codex.toast.loginFailed'));
+ toast.error(
+ t(
+ result.errorReason === 'dev_oauth_write_blocked'
+ ? 'chatgptAuthRecovery.devWriteBlocked'
+ : 'settings.connections.codex.toast.loginFailed',
+ ),
+ );
}
} catch {
if (mountedRef.current) {
@@ -140,6 +208,6 @@ export function useCodexSessionExpiredPrompt(options?: {
})();
return true;
},
- [confirm, options?.confirmBeforeLogin, t, triggerOwnedLogin],
+ [confirm, confirmThree, options?.confirmBeforeLogin, t, triggerOwnedLogin],
);
}
diff --git a/apps/desktop/src/renderer/i18n/__tests__/devOAuthWritePolicy.test.ts b/apps/desktop/src/renderer/i18n/__tests__/devOAuthWritePolicy.test.ts
new file mode 100644
index 0000000000..d5b588e10b
--- /dev/null
+++ b/apps/desktop/src/renderer/i18n/__tests__/devOAuthWritePolicy.test.ts
@@ -0,0 +1,18 @@
+import { afterEach, describe, expect, it } from 'vitest';
+
+import i18n, { DEFAULT_LOCALE, SUPPORTED_LOCALES } from '../index';
+
+afterEach(async () => {
+ await i18n.changeLanguage(DEFAULT_LOCALE);
+});
+
+describe('dev OAuth write recovery guidance', () => {
+ it.each(SUPPORTED_LOCALES)('%s only points to the trusted isolated-auth command', async (locale) => {
+ await i18n.changeLanguage(locale);
+ const message = i18n.t('chatgptAuthRecovery.devWriteBlocked');
+
+ expect(message).toContain('pnpm restart:desktop:remote -- --isolated-auth --isolated');
+ expect(message).not.toContain('--isolated[');
+ expect(message).not.toContain('XDT_ALLOW_DEV_OAUTH_WRITE');
+ });
+});
diff --git a/apps/desktop/src/renderer/i18n/index.ts b/apps/desktop/src/renderer/i18n/index.ts
index 9bfc7bd881..7d704c96a0 100644
--- a/apps/desktop/src/renderer/i18n/index.ts
+++ b/apps/desktop/src/renderer/i18n/index.ts
@@ -34,12 +34,59 @@ export {
} from '../../shared/locale';
export type { LocalePreference, SupportedLocale } from '../../shared/locale';
+// 凭证写入逃生口必须在五语里共用同一条安全命令;集中覆盖防止某个 locale 又退回
+// “手动设置环境变量”的危险指引。对应跨 locale 契约由 devOAuthWritePolicy.test 锁住。
const resources = {
- en: { common: enCommon, aiRename: enAiRename },
- 'zh-CN': { common: zhCNCommon, aiRename: zhCNAiRename },
- 'zh-TW': { common: zhTWCommon, aiRename: zhTWAIName },
- ja: { common: jaCommon, aiRename: jaAiRename },
- ko: { common: koCommon, aiRename: koAiRename },
+ en: {
+ common: {
+ ...enCommon,
+ chatgptAuthRecovery: {
+ ...enCommon.chatgptAuthRecovery,
+ devWriteBlocked: 'Development builds use this computer’s ChatGPT sign-in read-only by default and cannot start OAuth or change its credentials. To test OAuth, run: pnpm restart:desktop:remote -- --isolated-auth --isolated. The restart script enables writes only after verifying the sandbox.',
+ },
+ },
+ aiRename: enAiRename,
+ },
+ 'zh-CN': {
+ common: {
+ ...zhCNCommon,
+ chatgptAuthRecovery: {
+ ...zhCNCommon.chatgptAuthRecovery,
+ devWriteBlocked: '开发环境默认只读共享本机 ChatGPT 登录,不能发起登录或改写凭证。测试 OAuth 只能运行:pnpm restart:desktop:remote -- --isolated-auth --isolated。脚本验证独立沙箱后会自动开放写入,无需手动设置环境变量。',
+ },
+ },
+ aiRename: zhCNAiRename,
+ },
+ 'zh-TW': {
+ common: {
+ ...zhTWCommon,
+ chatgptAuthRecovery: {
+ ...zhTWCommon.chatgptAuthRecovery,
+ devWriteBlocked: '開發環境預設以唯讀方式共用本機 ChatGPT 登入,不能發起登入或改寫憑證。測試 OAuth 只能執行:pnpm restart:desktop:remote -- --isolated-auth --isolated。指令碼驗證獨立沙箱後會自動開放寫入,無需手動設定環境變數。',
+ },
+ },
+ aiRename: zhTWAIName,
+ },
+ ja: {
+ common: {
+ ...jaCommon,
+ chatgptAuthRecovery: {
+ ...jaCommon.chatgptAuthRecovery,
+ devWriteBlocked: '開発環境では、このコンピューターの ChatGPT ログインを既定で読み取り専用として共有するため、OAuth の開始や認証情報の変更はできません。OAuth をテストする場合は、pnpm restart:desktop:remote -- --isolated-auth --isolated を実行してください。スクリプトはサンドボックスを検証した後にのみ書き込みを許可します。環境変数を手動で設定する必要はありません。',
+ },
+ },
+ aiRename: jaAiRename,
+ },
+ ko: {
+ common: {
+ ...koCommon,
+ chatgptAuthRecovery: {
+ ...koCommon.chatgptAuthRecovery,
+ devWriteBlocked: '개발 환경은 기본적으로 이 컴퓨터의 ChatGPT 로그인을 읽기 전용으로 공유하므로 OAuth를 시작하거나 자격 증명을 변경할 수 없습니다. OAuth를 테스트하려면 pnpm restart:desktop:remote -- --isolated-auth --isolated을 실행하세요. 스크립트가 샌드박스를 검증한 뒤에만 쓰기를 허용하므로 환경 변수를 직접 설정할 필요가 없습니다.',
+ },
+ },
+ aiRename: koAiRename,
+ },
} as const;
// 同步 init —— 没有 backend / detector / suspense,i18n.init 立即返回。
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index fa0c99cf71..10b49e4209 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -7456,12 +7456,17 @@
},
"chatgptAuthRecovery": {
"title": "ChatGPT Sign-In Is No Longer Valid",
- "systemSharedInvalidated": "Cindy is currently using this computer’s ChatGPT sign-in. That sign-in is no longer valid. Sign in again in Cindy, then retry.",
+ "systemSharedInvalidated": "Cindy is using this computer’s ChatGPT sign-in. Restore it in the ChatGPT App first; this avoids creating a second credential or signing this computer out.",
"instanceIsolatedInvalidated": "Cindy is currently using a separately signed-in ChatGPT account. That sign-in is no longer valid. Sign in again in Cindy, then retry.",
"unknownInvalidated": "Cindy’s current ChatGPT sign-in is no longer valid. Sign in again, then retry.",
"recovered": "ChatGPT sign-in has been restored. Please retry.",
"openApp": "Open ChatGPT App",
"relogin": "Sign In to ChatGPT Again",
+ "reloginRiskTitle": "Still sign in through Cindy?",
+ "reloginRiskDescription": "This creates a new OpenAI OAuth authorization and may immediately sign the ChatGPT App and Codex CLI out on this computer. You will need to sign in to those apps again afterward.",
+ "reloginRiskConfirm": "Accept Risk and Continue",
+ "devWriteBlocked": "Development builds use this computer’s ChatGPT sign-in read-only by default and cannot start OAuth or change its credentials. To test OAuth, use an isolated sandbox and explicitly set XDT_ALLOW_DEV_OAUTH_WRITE=1.",
+ "devReadOnly": "Read-only in Development",
"checking": "Checking…",
"recheck": "Check Again",
"later": "Later",
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index 53a3feec79..1a4a0c9498 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -7448,12 +7448,17 @@
},
"chatgptAuthRecovery": {
"title": "ChatGPT のログインが無効になりました",
- "systemSharedInvalidated": "Cindy は現在、このコンピューターの ChatGPT ログインを使用しています。このログインは無効になりました。Cindy で再度ログインしてから、再試行してください。",
+ "systemSharedInvalidated": "Cindy はこのコンピューターの ChatGPT ログインを使用しています。まず ChatGPT App でログインを復旧してください。別の認証情報を作成したり、このコンピューターをログアウトさせたりせずに済みます。",
"instanceIsolatedInvalidated": "Cindy は現在、個別にログインした ChatGPT アカウントを使用しています。このログインは無効になりました。Cindy で再度ログインしてから、再試行してください。",
"unknownInvalidated": "Cindy の現在の ChatGPT ログインは無効になりました。再度ログインしてから、再試行してください。",
"recovered": "ChatGPT ログインが復旧しました。再試行してください。",
"openApp": "ChatGPT App を開く",
"relogin": "ChatGPT に再ログイン",
+ "reloginRiskTitle": "それでも Cindy から再ログインしますか?",
+ "reloginRiskDescription": "新しい OpenAI OAuth 認証が作成され、このコンピューターの ChatGPT App と Codex CLI が直ちにログアウトする可能性があります。完了後、それらのアプリでもう一度ログインする必要があります。",
+ "reloginRiskConfirm": "リスクを承知して続行",
+ "devWriteBlocked": "開発環境は既定で、このコンピューターの ChatGPT ログインを読み取り専用で共有するため、OAuth の開始や認証情報の変更はできません。OAuth をテストする場合は、隔離サンドボックスで XDT_ALLOW_DEV_OAUTH_WRITE=1 を明示的に設定してください。",
+ "devReadOnly": "開発環境では読み取り専用",
"checking": "確認中…",
"recheck": "再確認",
"later": "後で",
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index 1220f24a33..e76a0f637c 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -7448,12 +7448,17 @@
},
"chatgptAuthRecovery": {
"title": "ChatGPT 로그인이 더 이상 유효하지 않습니다",
- "systemSharedInvalidated": "Cindy는 현재 이 컴퓨터의 ChatGPT 로그인을 사용하고 있습니다. 이 로그인이 만료되었습니다. Cindy에서 다시 로그인한 후 재시도하세요.",
+ "systemSharedInvalidated": "Cindy는 이 컴퓨터의 ChatGPT 로그인을 사용하고 있습니다. 먼저 ChatGPT App에서 로그인을 복구하세요. 그러면 두 번째 자격 증명을 만들거나 이 컴퓨터에서 로그아웃되는 일을 피할 수 있습니다.",
"instanceIsolatedInvalidated": "Cindy는 현재 별도로 로그인한 ChatGPT 계정을 사용하고 있습니다. 이 로그인이 만료되었습니다. Cindy에서 다시 로그인한 후 재시도하세요.",
"unknownInvalidated": "Cindy의 현재 ChatGPT 로그인이 만료되었습니다. 다시 로그인한 후 재시도하세요.",
"recovered": "ChatGPT 로그인이 복구되었습니다. 다시 시도하세요.",
"openApp": "ChatGPT App 열기",
"relogin": "ChatGPT 다시 로그인",
+ "reloginRiskTitle": "그래도 Cindy에서 다시 로그인할까요?",
+ "reloginRiskDescription": "새 OpenAI OAuth 인증이 생성되며 이 컴퓨터의 ChatGPT App과 Codex CLI가 즉시 로그아웃될 수 있습니다. 완료 후 해당 앱에서 다시 로그인해야 합니다.",
+ "reloginRiskConfirm": "위험을 감수하고 계속",
+ "devWriteBlocked": "개발 환경은 기본적으로 이 컴퓨터의 ChatGPT 로그인을 읽기 전용으로 공유하므로 OAuth를 시작하거나 자격 증명을 변경할 수 없습니다. OAuth를 테스트하려면 격리된 샌드박스에서 XDT_ALLOW_DEV_OAUTH_WRITE=1을 명시적으로 설정하세요.",
+ "devReadOnly": "개발 환경에서 읽기 전용",
"checking": "확인 중…",
"recheck": "다시 확인",
"later": "나중에",
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
index d1b4f27d21..284adc9f9f 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -7440,12 +7440,17 @@
},
"chatgptAuthRecovery": {
"title": "ChatGPT 登录已失效",
- "systemSharedInvalidated": "Cindy 当前沿用了本机的 ChatGPT 登录。该登录已失效。请在 Cindy 中重新登录后重试。",
+ "systemSharedInvalidated": "Cindy 当前沿用了本机的 ChatGPT 登录。请先在 ChatGPT App 中恢复登录;这不会创建第二份凭证或挤掉本机登录。",
"instanceIsolatedInvalidated": "Cindy 当前使用的是单独登录的 ChatGPT 账号。该登录已失效。请在 Cindy 中重新登录后重试。",
"unknownInvalidated": "Cindy 当前的 ChatGPT 登录已失效。请重新登录后重试。",
"recovered": "ChatGPT 登录已恢复,请重试。",
"openApp": "打开 ChatGPT App",
"relogin": "重新登录 ChatGPT",
+ "reloginRiskTitle": "仍要由 Cindy 重新登录?",
+ "reloginRiskDescription": "这会创建新的 OpenAI OAuth 授权,并可能让本机 ChatGPT App 和 Codex CLI 立即退出登录。完成后,你需要在本机应用中再次登录。",
+ "reloginRiskConfirm": "接受风险并继续",
+ "devWriteBlocked": "开发环境默认只读共享本机 ChatGPT 登录,不能发起登录或改写凭证。确需测试 OAuth 时,请用隔离沙箱并显式设置 XDT_ALLOW_DEV_OAUTH_WRITE=1。",
+ "devReadOnly": "开发环境只读",
"checking": "正在检测…",
"recheck": "重新检测",
"later": "稍后处理",
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
index 320978577d..c54ff1f09b 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
@@ -7446,6 +7446,11 @@
"recovered": "ChatGPT 登入已恢復,請重試。",
"openApp": "開啟 ChatGPT App",
"relogin": "重新登入 ChatGPT",
+ "reloginRiskTitle": "仍要由 Cindy 重新登入?",
+ "reloginRiskDescription": "這會建立新的 OpenAI OAuth 授權,並可能讓本機 ChatGPT App 和 Codex CLI 立即登出。完成後,你需要在本機應用程式中再次登入。",
+ "reloginRiskConfirm": "接受風險並繼續",
+ "devWriteBlocked": "開發環境預設以唯讀方式共用本機 ChatGPT 登入,不能發起登入或改寫憑證。確需測試 OAuth 時,請使用隔離沙箱並明確設定 XDT_ALLOW_DEV_OAUTH_WRITE=1。",
+ "devReadOnly": "開發環境唯讀",
"checking": "正在檢測…",
"recheck": "重新檢測",
"later": "稍後處理",
diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.ts
index 210642ee4a..dadb86f7a2 100644
--- a/apps/desktop/src/renderer/vite-env.d.ts
+++ b/apps/desktop/src/renderer/vite-env.d.ts
@@ -644,6 +644,7 @@ interface CodexAuthState {
expiresAt?: number;
errorReason?: string;
authSource?: 'oauth' | 'api-key';
+ oauthWritesBlocked?: boolean;
credentialScope?: 'system-shared' | 'instance-isolated' | 'unknown';
recoveryRequiredReason?: string;
}
diff --git a/packages/maker-core/src/types/common.ts b/packages/maker-core/src/types/common.ts
index dfde77069a..e74fad7f81 100644
--- a/packages/maker-core/src/types/common.ts
+++ b/packages/maker-core/src/types/common.ts
@@ -68,6 +68,7 @@ export interface AuthState {
expiresAt?: number;
errorReason?: string;
authSource?: 'oauth' | 'api-key';
+ oauthWritesBlocked?: boolean;
/**
* Codex OAuth 凭证当前的物理存储范围。
*
diff --git a/scripts/__tests__/restart-desktop-remote.test.mjs b/scripts/__tests__/restart-desktop-remote.test.mjs
index 7f312f2fa3..fba22fdb0b 100644
--- a/scripts/__tests__/restart-desktop-remote.test.mjs
+++ b/scripts/__tests__/restart-desktop-remote.test.mjs
@@ -10,10 +10,13 @@ import {
applyDesktopStartupConfigForPhase,
clearDesktopDevCaches,
commandUsesUserDataDir,
+ createIsolatedAuthLaunchProof,
defaultIsolatedUserDataDir,
desktopDevCacheDirs,
devEnvPrefix,
hasIsolationIntent,
+ isTrustedIsolatedAuthUserDataDir,
+ ISOLATED_AUTH_LAUNCH_PROOF_FILE,
isOfficialProductionUserDataDir,
isRepositoryDesktopDevProcess,
officialProductionUserDataDirs,
@@ -317,6 +320,125 @@ test("env-only XDT_ISOLATED=1 derives the default sandbox, not the official prof
assert.equal(named, defaultIsolatedUserDataDir("review", "global"));
});
+test("isolated auth accepts only the epoch sandbox derived by this restart", () => {
+ const isolatedArg = "--isolated=oauth-review";
+ const derived = defaultIsolatedUserDataDir("oauth-review", "global");
+ const trusted = {
+ isolatedArg,
+ userDataDir: derived,
+ userDataDirEpoch: "1",
+ userDataDerivedByRestart: true,
+ selectedRegion: "global",
+ };
+
+ // A freshly derived sandbox does not need an existing credential file.
+ assert.equal(isTrustedIsolatedAuthUserDataDir(trusted), true);
+ assert.equal(isTrustedIsolatedAuthUserDataDir({
+ ...trusted,
+ userDataDerivedByRestart: false,
+ }), false);
+ assert.equal(isTrustedIsolatedAuthUserDataDir({
+ ...trusted,
+ userDataDirEpoch: undefined,
+ }), false);
+ assert.equal(isTrustedIsolatedAuthUserDataDir({
+ ...trusted,
+ userDataDir: path.join(os.tmpdir(), "shared-cindy-profile"),
+ }), false);
+});
+
+test("isolated auth rejects an explicit userData even when it spoofs the derived path and epoch", () => {
+ const isolatedArg = "--isolated=oauth-review";
+ assert.equal(isTrustedIsolatedAuthUserDataDir({
+ isolatedArg,
+ userDataDir: defaultIsolatedUserDataDir("oauth-review", "global"),
+ userDataDirEpoch: "1",
+ userDataDerivedByRestart: false,
+ selectedRegion: "global",
+ }), false);
+});
+
+test("isolated auth rejects a derived userData symlink or junction before minting proof", () => {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), "cindy-isolated-alias-"));
+ const savedEnv = {
+ APPDATA: process.env.APPDATA,
+ HOME: process.env.HOME,
+ USERPROFILE: process.env.USERPROFILE,
+ XDG_CONFIG_HOME: process.env.XDG_CONFIG_HOME,
+ };
+ try {
+ if (process.platform === "win32") {
+ process.env.APPDATA = path.join(root, "appdata");
+ process.env.USERPROFILE = root;
+ } else if (process.platform === "darwin") {
+ process.env.HOME = root;
+ } else {
+ process.env.XDG_CONFIG_HOME = path.join(root, "config");
+ }
+ const isolatedArg = "--isolated=link-guard";
+ const derived = defaultIsolatedUserDataDir("link-guard", "global");
+ const unrelatedProfile = path.join(root, "unrelated-profile");
+ fs.mkdirSync(path.dirname(derived), { recursive: true });
+ fs.mkdirSync(unrelatedProfile, { recursive: true });
+ fs.symlinkSync(
+ unrelatedProfile,
+ derived,
+ process.platform === "win32" ? "junction" : "dir",
+ );
+
+ assert.equal(isTrustedIsolatedAuthUserDataDir({
+ isolatedArg,
+ userDataDir: derived,
+ userDataDirEpoch: "1",
+ userDataDerivedByRestart: true,
+ selectedRegion: "global",
+ }), false);
+ assert.throws(
+ () => createIsolatedAuthLaunchProof({ userDataDir: derived }),
+ /symlink or junction/,
+ );
+ assert.equal(
+ fs.existsSync(path.join(unrelatedProfile, ISOLATED_AUTH_LAUNCH_PROOF_FILE)),
+ false,
+ );
+ } finally {
+ for (const [key, value] of Object.entries(savedEnv)) {
+ if (value === undefined) delete process.env[key];
+ else process.env[key] = value;
+ }
+ fs.rmSync(root, { recursive: true, force: true });
+ }
+});
+
+test("isolated auth launch proof binds the current derived sandbox and is private", () => {
+ const userDataDir = fs.mkdtempSync(path.join(os.tmpdir(), "cindy-isolated-proof-"));
+ try {
+ const nonce = "b".repeat(64);
+ assert.equal(createIsolatedAuthLaunchProof({
+ userDataDir,
+ isolationName: "oauth-review",
+ now: 123_000,
+ nonce,
+ }), nonce);
+ const proofPath = path.join(userDataDir, ISOLATED_AUTH_LAUNCH_PROOF_FILE);
+ const proof = JSON.parse(fs.readFileSync(proofPath, "utf8"));
+ assert.deepEqual(proof, {
+ version: 1,
+ nonce,
+ userDataDir: canonicalizeUserDataDir(userDataDir),
+ profileKind: "isolated-sandbox",
+ epoch: 1,
+ isolationName: "oauth-review",
+ issuedAtMs: 123_000,
+ expiresAtMs: 723_000,
+ });
+ if (process.platform !== "win32") assert.equal(fs.statSync(proofPath).mode & 0o077, 0);
+ assert.deepEqual(fs.readdirSync(userDataDir), [ISOLATED_AUTH_LAUNCH_PROOF_FILE]);
+ } finally {
+ fs.rmSync(userDataDir, { recursive: true, force: true });
+ }
+});
+
test("isolated=@worktree derives the named sandbox from the checkout directory", () => {
const root = path.join("/repo", "cindy-local-ollama-models");
const name = isolationNameFromWorktree(root);
@@ -364,6 +486,28 @@ test("isolated official-profile refuse happens before mkdir in the restart main
assert.ok(mkdirIdx > refuseIdx);
});
+test("isolated auth trust gate runs before credential write flags and userData creation", () => {
+ const source = fs.readFileSync(new URL("../restart-desktop-remote.mjs", import.meta.url), "utf8");
+ const trustIdx = source.lastIndexOf("if (!isTrustedIsolatedAuthUserDataDir({");
+ const authFlagIdx = source.indexOf("process.env.XDT_ISOLATED_AUTH = '1';");
+ const mkdirIdx = source.indexOf("fs.mkdirSync(process.env.XDT_USER_DATA_DIR");
+ assert.ok(trustIdx > 0);
+ assert.ok(authFlagIdx > trustIdx);
+ assert.ok(mkdirIdx > authFlagIdx);
+});
+
+test("isolated auth proof is minted only by this invocation's accepted flag path", () => {
+ const source = fs.readFileSync(new URL("../restart-desktop-remote.mjs", import.meta.url), "utf8");
+ const ambientDeleteIdx = source.indexOf("delete process.env.XDT_ISOLATED_AUTH_PROOF;");
+ const authorizeIdx = source.indexOf("isolatedAuthAuthorizedByRestart = true;");
+ const mintGuardIdx = source.indexOf("if (isolatedAuthAuthorizedByRestart) {");
+ const mintIdx = source.indexOf("createIsolatedAuthLaunchProof({", mintGuardIdx);
+ assert.ok(ambientDeleteIdx > 0);
+ assert.ok(authorizeIdx > ambientDeleteIdx);
+ assert.ok(mintGuardIdx > authorizeIdx);
+ assert.ok(mintIdx > mintGuardIdx);
+});
+
test("preserve-running only shares a target with live records from the same region", () => {
const userData = fs.mkdtempSync(path.join(os.tmpdir(), "cindy-shared-region-"));
const records = path.join(userData, ".dev-instances");
@@ -782,6 +926,21 @@ test("devEnvPrefix omits harness envs when unset (whitelist stays opt-in)", () =
assert.equal(devEnvPrefix({}, "darwin"), "");
});
+test("devEnvPrefix passes the explicit isolated OAuth write escape hatch", () => {
+ assert.equal(
+ devEnvPrefix(
+ {
+ XDT_ISOLATED_AUTH: "1",
+ XDT_ALLOW_DEV_OAUTH_WRITE: "1",
+ XDT_ISOLATED_AUTH_PROOF: "proof-nonce",
+ },
+ "darwin",
+ ),
+ "XDT_ISOLATED_AUTH='1' XDT_ALLOW_DEV_OAUTH_WRITE='1' " +
+ "XDT_ISOLATED_AUTH_PROOF='proof-nonce' ",
+ );
+});
+
test("devEnvPrefix passes explicit model catalog test controls to Desktop", () => {
const prefix = devEnvPrefix(
{
diff --git a/scripts/restart-desktop-remote.mjs b/scripts/restart-desktop-remote.mjs
index a16c2fc376..0e4523ddcd 100644
--- a/scripts/restart-desktop-remote.mjs
+++ b/scripts/restart-desktop-remote.mjs
@@ -1,5 +1,6 @@
#!/usr/bin/env node
import { spawn, spawnSync } from 'node:child_process';
+import { randomBytes } from 'node:crypto';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
@@ -28,6 +29,8 @@ const gracefulTimeoutMs = 3000;
const forceTimeoutMs = 5000;
const pollIntervalMs = 150;
const startupReadyTimeoutMs = 120_000;
+export const ISOLATED_AUTH_LAUNCH_PROOF_FILE = '.isolated-auth-launch-proof.json';
+const isolatedAuthLaunchProofTtlMs = 10 * 60_000;
const forceKillLabel = process.platform === 'win32' ? 'taskkill /F /T' : 'kill -9';
const desktopDevCacheRelativeDirs = Object.freeze([
path.join('apps', 'desktop', 'node_modules', '.vite'),
@@ -629,6 +632,83 @@ export function resolveRestartTargetUserDataDir({
: productionUserDataDir(selectedRegion));
}
+/**
+ * Credential cleanup/write access is more destructive than ordinary isolated
+ * startup. Trust only the v2 sandbox selected by this restart invocation; an
+ * ambient userData path must not gain that authority by spoofing the epoch.
+ */
+export function isTrustedIsolatedAuthUserDataDir({
+ isolatedArg,
+ userDataDir,
+ userDataDirEpoch,
+ userDataDerivedByRestart,
+ selectedRegion,
+}) {
+ if (
+ !isolatedArg
+ || !userDataDir
+ || userDataDirEpoch !== '1'
+ || userDataDerivedByRestart !== true
+ ) {
+ return false;
+ }
+ const expectedDir = defaultIsolatedUserDataDir(
+ parseIsolationName(isolatedArg),
+ selectedRegion,
+ );
+ if (userDataDirEntryIsAliasOrUnverifiable(userDataDir)) return false;
+ return canonicalizeUserDataDir(userDataDir) === canonicalizeUserDataDir(expectedDir);
+}
+
+function userDataDirEntryIsAliasOrUnverifiable(dir) {
+ try {
+ return fs.lstatSync(path.resolve(dir)).isSymbolicLink();
+ } catch (error) {
+ // A not-yet-created derived sandbox is valid at the early trust gate. Every other lstat
+ // failure is ambiguous and must not authorize credential cleanup or OAuth writes.
+ return error?.code !== 'ENOENT';
+ }
+}
+
+/**
+ * Mint a single-use proof only after this restart invocation derived and accepted the sandbox.
+ * The nonce crosses Terminal/runner/Forge via env; the bound file is the second factor that an
+ * inherited ambient env does not carry. Desktop consumes it from its actual app userData path.
+ */
+export function createIsolatedAuthLaunchProof({
+ userDataDir,
+ isolationName = '',
+ now = Date.now(),
+ nonce = randomBytes(32).toString('hex'),
+}) {
+ // Recheck at the write boundary: process cleanup between authorization and proof minting leaves
+ // time for the derived directory to be swapped for a symlink / Windows junction.
+ if (userDataDirEntryIsAliasOrUnverifiable(userDataDir)) {
+ throw new Error('Refusing isolated-auth launch proof for a symlink or junction userData path');
+ }
+ const proofPath = path.join(userDataDir, ISOLATED_AUTH_LAUNCH_PROOF_FILE);
+ const tempPath = `${proofPath}.${process.pid}.${nonce}.tmp`;
+ const proof = {
+ version: 1,
+ nonce,
+ userDataDir: canonicalizeUserDataDir(userDataDir),
+ profileKind: 'isolated-sandbox',
+ epoch: 1,
+ isolationName,
+ issuedAtMs: now,
+ expiresAtMs: now + isolatedAuthLaunchProofTtlMs,
+ };
+ fs.rmSync(proofPath, { force: true });
+ try {
+ fs.writeFileSync(tempPath, `${JSON.stringify(proof)}\n`, { flag: 'wx', mode: 0o600 });
+ fs.renameSync(tempPath, proofPath);
+ } catch (error) {
+ fs.rmSync(tempPath, { force: true });
+ throw error;
+ }
+ return nonce;
+}
+
/**
* Refuse when restarting would suicide this checkout's host, or when a shared
* start is hosted by another checkout's desktop-dev (same official profile).
@@ -793,6 +873,8 @@ export function devEnvPrefix(env = process.env, platform = process.platform) {
['XDT_ISOLATED_NAME', env.XDT_ISOLATED_NAME],
// 沙箱凭证隔离(--isolated-auth):不与 ~/.codex 共享 auth 硬链,auth-adapters 消费。
['XDT_ISOLATED_AUTH', env.XDT_ISOLATED_AUTH],
+ ['XDT_ALLOW_DEV_OAUTH_WRITE', env.XDT_ALLOW_DEV_OAUTH_WRITE],
+ ['XDT_ISOLATED_AUTH_PROOF', env.XDT_ISOLATED_AUTH_PROOF],
// CDP 端口覆写(bootstrap-electron 消费): 并行多开沙箱时给后起实例换端口。
['XDT_CDP_PORT', env.XDT_CDP_PORT],
// 一次性 Grok wire 归因探针(dev-only;正常环境不设置,不产生额外日志)。
@@ -986,6 +1068,8 @@ export function applyDesktopStartupConfigForPhase(options) {
}
async function main() {
+ // Proofs are minted below only for this invocation's accepted --isolated-auth request.
+ delete process.env.XDT_ISOLATED_AUTH_PROOF;
let argv = normalizeDesktopRestartArgv(process.argv.slice(2), process.env);
const sharedArgvConflict = desktopRestartArgvConflictMessage(argv, process.env);
if (sharedArgvConflict) throw new Error(sharedArgvConflict);
@@ -1006,6 +1090,8 @@ async function main() {
const mode = argv.includes('--local') ? 'local' : 'remote';
const startupConfig = applyDesktopStartupConfigForPhase({ argv, mode });
const selectedRegion = startupConfig?.region ?? resolveDesktopDevRegion(argv, process.env);
+ let userDataDerivedByRestart = false;
+ let isolatedAuthAuthorizedByRestart = false;
if (isolatedArg && isolatedArg.includes('=')) {
const derivedDir = defaultIsolatedUserDataDir(parseIsolationName(isolatedArg), selectedRegion);
if (inheritedUserDataBlocksNamedIsolation(isolatedArg, process.env.XDT_USER_DATA_DIR, derivedDir)) {
@@ -1119,10 +1205,11 @@ async function main() {
// 进入)或旧 checkout 启动都不带该信号 → 观察模式,防旧代码对同一显式
// 路径以默认身份打开造成双身份互写(#912 review P1)。
process.env.XDT_USER_DATA_DIR_EPOCH = '1';
+ userDataDerivedByRestart = true;
}
}
- // --isolated-auth: 沙箱凭证隔离 —— 不与本机 ~/.codex 共享 auth 硬链(已共享的
- // 解除本沙箱一端),沙箱内的 OAuth 登录/登出不再触碰正式实例与本机 CLI 的凭证。
+ // --isolated-auth: 沙箱凭证隔离 —— 启动时清掉本沙箱旧 auth(共享硬链与独立孤岛
+ // 都处理),再显式允许沙箱自己的 OAuth 写入;正式实例与本机 CLI 凭证不受影响。
// 隔离沙箱里测登录流程时必用:共享硬链下沙箱登录会改写共用凭证文件,把正式版
// 一起退登(2026-08-13 实测)。实现:置 XDT_ISOLATED_AUTH=1,经 devEnvPrefix
// 白名单透传,maker-host auth-adapters 消费(仅非 packaged 生效)。
@@ -1134,7 +1221,25 @@ async function main() {
['==> --isolated-auth requires --isolated: 共享 userData 的实例不该单独隔离凭证'],
);
}
+ if (!isTrustedIsolatedAuthUserDataDir({
+ isolatedArg,
+ userDataDir: process.env.XDT_USER_DATA_DIR,
+ userDataDirEpoch: process.env.XDT_USER_DATA_DIR_EPOCH,
+ userDataDerivedByRestart,
+ selectedRegion,
+ })) {
+ exitWithFailure(
+ 'STARTUP_FAILED',
+ '--isolated-auth requires a userData sandbox derived by this restart invocation',
+ [
+ '==> Refusing --isolated-auth for an inherited or explicit XDT_USER_DATA_DIR.',
+ ' Unset XDT_USER_DATA_DIR and retry with --isolated-auth --isolated[=<name>].',
+ ],
+ );
+ }
process.env.XDT_ISOLATED_AUTH = '1';
+ process.env.XDT_ALLOW_DEV_OAUTH_WRITE = '1';
+ isolatedAuthAuthorizedByRestart = true;
console.log('==> Isolated auth: this sandbox will NOT share codex OAuth credentials with ~/.codex.');
}
if (startupConfig) ensureDesktopEnv();
@@ -1345,6 +1450,12 @@ async function main() {
writeDesktopStartupStatus(startupStatusPath, { state: 'pending', at: Date.now() });
process.env.XDT_DESKTOP_DEV_STARTUP_STATUS_FILE = startupStatusPath;
}
+ if (isolatedAuthAuthorizedByRestart) {
+ process.env.XDT_ISOLATED_AUTH_PROOF = createIsolatedAuthLaunchProof({
+ userDataDir: process.env.XDT_USER_DATA_DIR,
+ isolationName: process.env.XDT_ISOLATED_NAME || '',
+ });
+ }
startDesktopDev(mode);
if (startupStatusPath) {
try {