Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(desktop): Codex 本机 CLI 凭证自动继承补绑定,消除「已连接」假报 (#294)
Dash2f3d141dfa8a
diff --git a/apps/desktop/src/main/maker-host/__tests__/codexAuthBindingClaim.test.ts b/apps/desktop/src/main/maker-host/__tests__/codexAuthBindingClaim.test.tsnew file mode 100644index 0000000000..466cd8fcd4--- /dev/null+++ b/apps/desktop/src/main/maker-host/__tests__/codexAuthBindingClaim.test.ts@@ -0,0 +1,189 @@+/**+ * Codex OAuth 绑定自愈(claimDetectedCodexOAuthBinding)+ readState 绑定 gate 集成测试。+ *+ * 背景 bug:一次性 legacy 迁移(migrateLegacyNativeProviderAuthBindings)在 reconcile+ * 硬链建立之前快照 hasCodexOAuthLoginUnbound(),openai 名额以 false 被永久消费;local+ * 模式 owner 则从不跑该迁移。结果 getState 报 authenticated(直读 auth.json)而+ * provider connected=false(查绑定)—— 设置页「已连接」与聊天门禁「无来源」自相矛盾。+ *+ * 修复后的期望:reconcile 收口为首个 owner 补绑定,getState / getAccessToken /+ * provider connected 三者同口径;换账号(绑定归属他人)保持 fail-closed,且 getState+ * 不再以 OAuth 已连接示人。+ */+import fs from 'node:fs';+import os from 'node:os';+import path from 'node:path';+import { afterEach, describe, expect, it, vi } from 'vitest';++const dirs: string[] = [];+const h = vi.hoisted(() => ({ userDataDir: '', dataOwnerId: null as string | null }));++vi.mock('electron', () => ({+ app: {+ getPath: () => h.userDataDir,+ getAppPath: () => h.userDataDir,+ isPackaged: false,+ },+ safeStorage: { isEncryptionAvailable: () => false },+}));++vi.mock('@cindy/maker-core', () => ({}));++// 只覆写 getActiveAppSession(绑定判定的唯一输入);其余导出保持原实现,供+// appCapabilities / providerSecretStore 等传递依赖正常加载。mode 用 'local':+// 绑定逻辑只看 dataOwnerId,而 local 模式关闭网关能力,readState 的网关 key+// fallback 分支确定性返回未认证,不触碰任何真实凭证存储。+vi.mock('../../appSessionState.js', async (importOriginal) => {+ const actual = await importOriginal<typeof import('../../appSessionState.js')>();+ return {+ ...actual,+ getActiveAppSession: () => ({+ mode: h.dataOwnerId ? ('local' as const) : ('signed-out' as const),+ dataOwnerId: h.dataOwnerId,+ generation: 1,+ }),+ };+});++function fixture(): { codexHome: string; systemAuth: string; localAuth: string; bindingFile: string } {+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'xdt-codex-binding-claim-'));+ dirs.push(root);+ h.userDataDir = path.join(root, 'user-data');+ fs.mkdirSync(h.userDataDir, { recursive: true });+ const home = path.join(root, 'home');+ fs.mkdirSync(path.join(home, '.codex'), { recursive: true });+ vi.spyOn(os, 'homedir').mockReturnValue(home);+ const systemAuth = path.join(home, '.codex', 'auth.json');+ // reconcile 的账号识别需要 account_id;access_token 是 OAuth 判定与绑定 claim 的凭证。+ fs.writeFileSync(+ systemAuth,+ JSON.stringify({+ account: { email: '[email protected]' },+ tokens: { access_token: 'system-token', account_id: 'acct-1' },+ }),+ );+ const codexHome = path.join(h.userDataDir, 'codex-home');+ return {+ codexHome,+ systemAuth,+ localAuth: path.join(codexHome, 'auth.json'),+ bindingFile: path.join(h.userDataDir, 'native-provider-auth.json'),+ };+}++function readBindingFile(bindingFile: string): Record<string, unknown> {+ return JSON.parse(fs.readFileSync(bindingFile, 'utf8')) as Record<string, unknown>;+}++afterEach(() => {+ vi.restoreAllMocks();+ h.dataOwnerId = null;+ for (const dir of dirs.splice(0)) fs.rmSync(dir, { recursive: true, force: true });+});++describe('codex OAuth binding auto-claim on reconcile', () => {+ it('binds the detected system CLI credential to the current owner within one getState call', async () => {+ const { bindingFile } = fixture();+ h.dataOwnerId = 'owner-a';+ const { DesktopCodexAuthAdapter } = await import('../auth-adapters.js');+ const adapter = new DesktopCodexAuthAdapter();++ await expect(adapter.getState()).resolves.toMatchObject({+ authenticated: true,+ authSource: 'oauth',+ identity: '[email protected]',+ });+ expect(readBindingFile(bindingFile)).toMatchObject({ openai: 'owner-a' });+ await expect(adapter.getAccessToken()).resolves.toBe('system-token');+ });++ it('repairs a claim that the one-shot migration consumed before the reconcile hardlink existed', async () => {+ const { bindingFile } = fixture();+ // 竞态残局:legacyClaimOwner 已写下,openai 名额被 false 消费。+ fs.writeFileSync(bindingFile, JSON.stringify({ legacyClaimOwner: 'owner-a' }));+ h.dataOwnerId = 'owner-a';+ const { DesktopCodexAuthAdapter } = await import('../auth-adapters.js');+ const adapter = new DesktopCodexAuthAdapter();++ await expect(adapter.getState()).resolves.toMatchObject({+ authenticated: true,+ authSource: 'oauth',+ });+ expect(readBindingFile(bindingFile)).toMatchObject({+ openai: 'owner-a',+ legacyClaimOwner: 'owner-a',+ });+ });++ it('keeps another owner fail-closed and stops reporting the unbound OAuth as connected', async () => {+ const { bindingFile } = fixture();+ fs.writeFileSync(+ bindingFile,+ JSON.stringify({ openai: 'owner-a', legacyClaimOwner: 'owner-a' }),+ );+ h.dataOwnerId = 'owner-b';+ const { DesktopCodexAuthAdapter } = await import('../auth-adapters.js');+ const adapter = new DesktopCodexAuthAdapter();++ await expect(adapter.getState()).resolves.toEqual({+ authenticated: false,+ errorReason: 'oauth_not_bound',+ });+ await expect(adapter.getAccessToken()).resolves.toBeNull();+ // 归属绝不被改写。+ expect(readBindingFile(bindingFile)).toMatchObject({ openai: 'owner-a' });+ });++ it('does not claim while a durable user disconnect suppresses the local credential', async () => {+ const { codexHome, systemAuth, localAuth, bindingFile } = fixture();+ fs.mkdirSync(codexHome, { recursive: true });+ fs.copyFileSync(systemAuth, localAuth);+ const { CODEX_USER_DISCONNECT_REASON, writeInvalidatedSystemCodexAuthMarker } = await import(+ '../codex-auth-invalidation.js'+ );+ expect(+ writeInvalidatedSystemCodexAuthMarker(+ codexHome,+ systemAuth,+ CODEX_USER_DISCONNECT_REASON,+ localAuth,+ ),+ ).toBe(true);+ h.dataOwnerId = 'owner-a';+ const { DesktopCodexAuthAdapter } = await import('../auth-adapters.js');+ const adapter = new DesktopCodexAuthAdapter();++ await expect(adapter.getState()).resolves.toMatchObject({ authenticated: false });+ expect(fs.existsSync(bindingFile)).toBe(false);+ });++ it('drops the claim when the app session switches owners during an in-flight reconcile', async () => {+ // review P1:claim 只允许写给「reconcile 发起时」的会话;在途期间切换账号必须放弃,+ // 绝不把 A 时代发起的认领写到 B 名下。B 自己的下一次 reconcile 会按 B 的规则重试。+ const { bindingFile } = fixture();+ h.dataOwnerId = 'owner-a';+ const { DesktopCodexAuthAdapter } = await import('../auth-adapters.js');+ const adapter = new DesktopCodexAuthAdapter();++ // getState 的同步段捕获 sessionAtStart(owner-a);首个 await 挂起后切到 owner-b。+ const statePromise = adapter.getState();+ h.dataOwnerId = 'owner-b';+ await expect(statePromise).resolves.toEqual({+ authenticated: false,+ errorReason: 'oauth_not_bound',+ });+ expect(fs.existsSync(bindingFile)).toBe(false);+ });++ it('keeps pre-session behavior without writing any binding when no owner is committed', async () => {+ const { bindingFile } = fixture();+ const { DesktopCodexAuthAdapter } = await import('../auth-adapters.js');+ const adapter = new DesktopCodexAuthAdapter();++ await expect(adapter.getState()).resolves.toMatchObject({+ authenticated: true,+ authSource: 'oauth',+ });+ expect(fs.existsSync(bindingFile)).toBe(false);+ });+});diff --git a/apps/desktop/src/main/maker-host/__tests__/nativeProviderAuthBinding.test.ts b/apps/desktop/src/main/maker-host/__tests__/nativeProviderAuthBinding.test.tsindex ffb29cb330..2d9a59b987 100644--- a/apps/desktop/src/main/maker-host/__tests__/nativeProviderAuthBinding.test.ts+++ b/apps/desktop/src/main/maker-host/__tests__/nativeProviderAuthBinding.test.ts@@ -19,6 +19,7 @@ vi.mock('../../appSessionState.js', () => ({}));import {+ claimDetectedNativeProviderAuth,isNativeProviderAuthBound,migrateLegacyNativeProviderAuthBindings,unbindNativeProviderAuth,@@ -56,3 +57,60 @@ describe('native provider auth legacy binding', () => {expect(isNativeProviderAuthBound('xai')).toBe(false);});});++describe('claimDetectedNativeProviderAuth', () => {+ it('repairs the binding when the one-shot migration consumed the claim before the credential appeared', () => {+ // 复现主 bug:legacy 迁移在 reconcile 硬链建立之前跑掉,openai 名额以 false 被消费。+ migrateLegacyNativeProviderAuthBindings('owner-a', { openai: false });+ expect(isNativeProviderAuthBound('openai')).toBe(false);++ expect(claimDetectedNativeProviderAuth('openai', () => true)).toBe(true);+ expect(isNativeProviderAuthBound('openai')).toBe(true);+ expect(JSON.parse(fs.readFileSync(bindingFile, 'utf8'))).toMatchObject({+ openai: 'owner-a',+ legacyClaimOwner: 'owner-a',+ });+ });++ it('claims for the current owner when no legacy claim ever ran (local mode path)', () => {+ expect(claimDetectedNativeProviderAuth('openai', () => true)).toBe(true);+ expect(JSON.parse(fs.readFileSync(bindingFile, 'utf8'))).toMatchObject({ openai: 'owner-a' });+ });++ it('stays fail-closed for an account that did not win the legacy claim', () => {+ migrateLegacyNativeProviderAuthBindings('owner-a', {});+ session.dataOwnerId = 'owner-b';++ expect(claimDetectedNativeProviderAuth('openai', () => true)).toBe(false);+ expect(isNativeProviderAuthBound('openai')).toBe(false);+ });++ it('never overwrites a binding held by another owner', () => {+ migrateLegacyNativeProviderAuthBindings('owner-a', { openai: true });+ session.dataOwnerId = 'owner-b';++ expect(claimDetectedNativeProviderAuth('openai', () => true)).toBe(false);+ session.dataOwnerId = 'owner-a';+ expect(isNativeProviderAuthBound('openai')).toBe(true);+ });++ it('writes nothing without a committed owner or without a credential', () => {+ session.dataOwnerId = null;+ expect(claimDetectedNativeProviderAuth('openai', () => true)).toBe(false);++ session.dataOwnerId = 'owner-a';+ expect(claimDetectedNativeProviderAuth('openai', () => false)).toBe(false);+ expect(fs.existsSync(bindingFile)).toBe(false);+ });++ it('treats corrupted falsy slot values as claimed-by-unknown and fails closed', () => {+ // 键存在但值为假(损坏 / 异常写入):按「归属不明」拒绝,绝不重认领。+ fs.mkdirSync(userDataDir, { recursive: true });+ fs.writeFileSync(bindingFile, JSON.stringify({ openai: '' }));+ expect(claimDetectedNativeProviderAuth('openai', () => true)).toBe(false);++ fs.writeFileSync(bindingFile, JSON.stringify({ legacyClaimOwner: '' }));+ expect(claimDetectedNativeProviderAuth('openai', () => true)).toBe(false);+ expect(JSON.parse(fs.readFileSync(bindingFile, 'utf8'))).toEqual({ legacyClaimOwner: '' });+ });+});diff --git a/apps/desktop/src/main/maker-host/auth-adapters.ts b/apps/desktop/src/main/maker-host/auth-adapters.tsindex 3707207e58..fcaa9fed59 100644--- a/apps/desktop/src/main/maker-host/auth-adapters.ts+++ b/apps/desktop/src/main/maker-host/auth-adapters.ts@@ -58,7 +58,17 @@ import { isAnthropicCompatProxyHandleReady } from './anthropic-compat-proxy-hostimport { claudeUpstreamEndpoint } from './runtime-configs.js';import { getProviderSecretStore } from '../secrets/providerSecretStore.js';import { getAppCapabilities } from '../appCapabilities.js';-import { bindNativeProviderAuth, isNativeProviderAuthBound, unbindNativeProviderAuth } from './nativeProviderAuthBinding.js';+import {+ getActiveAppSession,+ isAppSessionBoundaryPending,+ type ActiveAppSession,+} from '../appSessionState.js';+import {+ bindNativeProviderAuth,+ claimDetectedNativeProviderAuth,+ isNativeProviderAuthBound,+ unbindNativeProviderAuth,+} from './nativeProviderAuthBinding.js';const execFileP = promisify(execFile);const log = createLogger('auth-adapters');@@ -625,13 +635,60 @@ export class DesktopCodexAuthAdapter implements AuthAdapter {*/private reconcileWithSystemCodex(): Promise<void> {if (this.pendingReconcile) return this.pendingReconcile;- const run = this.runReconcileWithSystemCodex().finally(() => {- if (this.pendingReconcile === run) this.pendingReconcile = null;- });+ // 发起时刻固定会话快照:reconcile 是异步的,期间可能发生账号切换;绑定自愈+ // 只允许写给「发起时与完成时都是同一个已提交会话」的 owner(见 claim 内校验)。+ const sessionAtStart = getActiveAppSession();+ const run = this.runReconcileWithSystemCodex()+ .then(() => this.claimDetectedCodexOAuthBinding(sessionAtStart))+ .finally(() => {+ if (this.pendingReconcile === run) this.pendingReconcile = null;+ });this.pendingReconcile = run;return run;}+ /**+ * reconcile 收口后的绑定自愈:codex-home 里存在可用 OAuth token(硬链自本机 CLI 或+ * 早年隔离登录)、而 openai 尚无任何 owner 绑定时,把它绑给当前 owner。+ *+ * 修复的时序竞态:一次性 legacy 迁移(migrateLegacyNativeProviderAuthBindings)在+ * 首次登录时快照 hasCodexOAuthLoginUnbound(),但 reconcile 硬链往往还没建立 ——+ * 名额被以 openai:false 永久消费,首个 owner 从此拿不到设计内的自动继承;local 模式+ * owner 更是从不跑该迁移。结果是 getState 报 authenticated(读 auth.json)而+ * provider connected=false(查绑定),设置页「已连接」与聊天门禁「无来源」自相矛盾。+ *+ * 安全边界不变:已有归属(含别的账号)/ legacyClaimOwner 是别的账号 / durable+ * disconnect 抑制中,一律不写(见 claimDetectedNativeProviderAuth),换账号继续+ * fail-closed。写失败只记日志,不让 reconcile 链路抛穿。+ *+ * 会话边界防护(review P1):claim 在异步 reconcile 完成后执行,期间可能发生账号+ * 切换。只在「发起时与完成时是同一个已提交会话(owner + generation 均未变)、且+ * 没有会话边界切换在途」时才允许写入;否则放弃本轮 —— 新会话自己的下一次+ * reconcile 会带着自己的快照重试,自愈不丢,只是绝不把 A 时代发起的认领写到 B 名下。+ */+ private claimDetectedCodexOAuthBinding(sessionAtStart: ActiveAppSession): void {+ const session = getActiveAppSession();+ if (isAppSessionBoundaryPending()) return;+ if (+ session.generation !== sessionAtStart.generation ||+ session.dataOwnerId !== sessionAtStart.dataOwnerId+ ) {+ return;+ }+ if (this.oauthInvalidatedReason) return;+ const authPath = path.join(this.codexHome, 'auth.json');+ if (shouldSuppressLocalCodexAuth(this.codexHome, authPath)) return;+ try {+ if (claimDetectedNativeProviderAuth('openai', () => this.hasCodexOAuthLoginUnbound())) {+ log.info('codex OAuth credential auto-bound to current owner after reconcile');+ }+ } catch (err) {+ log.warn('codex OAuth binding claim failed', {+ error: err instanceof Error ? err.message : String(err),+ });+ }+ }+/*** 登录成功后专用: 先等在途的 reconcile 结束, 再保证用刚写好的 auth.json 重新跑一遍。* 否则 dedup 可能把这次"必须基于最新 auth.json"的 reconcile 合并到一个用登录前状态@@ -822,6 +879,22 @@ export class DesktopCodexAuthAdapter implements AuthAdapter {return { authenticated: false, errorReason: localState.errorReason ?? 'no_oauth' };}const localState = await this.readLocalCodexAuthState();+ // 绑定 gate(与 provider 目录 connected / getAccessToken 同口径,对齐 Anthropic 侧+ // readClaudeAiOAuth 的读取层校验):auth.json 是与系统 CLI 共享的存储,凭证在、但+ // openai 未绑定到当前 owner 时,不得以 OAuth 已连接示人 —— 否则设置页显示「已连接」+ // 而聊天门禁按无来源拦截,状态自相矛盾。上方 reconcile 收口已把「首个 owner 检测到+ // 本机 CLI 凭证」的合法自动继承补好绑定(claimDetectedCodexOAuthBinding);走到这里+ // 仍未绑定的只剩换账号等 fail-closed 场景,按无 OAuth 处理,可退网关 key。+ if (+ localState.authenticated &&+ localState.authSource === 'oauth' &&+ !isNativeProviderAuthBound('openai')+ ) {+ if (readClaudeApiKey()) {+ return { authenticated: true, identity: 'API Key · Cindy AI', authSource: 'api-key' };+ }+ return { authenticated: false, errorReason: 'oauth_not_bound' };+ }if (localState.authenticated) {// api-key 型 auth.json(可解析但无 access_token)且配了网关 key:fallback spawn// 实际会走 gateway key(hasCodexOAuthLogin=false),authSource 补成 'api-key'@@ -1178,13 +1251,16 @@ export class DesktopCodexAuthAdapter implements AuthAdapter {* are covered by the active Codex login.*/async getAccessToken(): Promise<string | null> {- if (!isNativeProviderAuthBound('openai')) return null;this.ensureInvalidationMarkerLoaded();if (this.oauthInvalidatedReason) {await this.clearStaleInvalidationIfSystemCodexChanged();}if (this.oauthInvalidatedReason) return null;+ // 绑定校验放在 reconcile 之后:reconcile 收口会为首个 owner 补绑定+ // (claimDetectedCodexOAuthBinding),同一次调用内即可生效;校验仍在 token+ // 读取之前,未绑定(换账号等)保持 fail-closed 返回 null。await this.reconcileWithSystemCodex();+ if (!isNativeProviderAuthBound('openai')) return null;const authPath = path.join(this.codexHome, 'auth.json');if (shouldSuppressLocalCodexAuth(this.codexHome, authPath)) return null;try {@@ -1209,13 +1285,14 @@ export class DesktopCodexAuthAdapter implements AuthAdapter {* user id, not a workspace id, and must not bind reset-credit operations.*/async getAccountId(): Promise<string | null> {- if (!isNativeProviderAuthBound('openai')) return null;this.ensureInvalidationMarkerLoaded();if (this.oauthInvalidatedReason) {await this.clearStaleInvalidationIfSystemCodexChanged();}if (this.oauthInvalidatedReason) return null;+ // 同 getAccessToken:绑定校验在 reconcile(含首个 owner 补绑定)之后、读取之前。await this.reconcileWithSystemCodex();+ if (!isNativeProviderAuthBound('openai')) return null;const authPath = path.join(this.codexHome, 'auth.json');if (shouldSuppressLocalCodexAuth(this.codexHome, authPath)) return null;return readCodexAccountId(authPath);diff --git a/apps/desktop/src/main/maker-host/createDesktopProviderService.ts b/apps/desktop/src/main/maker-host/createDesktopProviderService.tsindex 02762e9712..6ccd4ff5fc 100644--- a/apps/desktop/src/main/maker-host/createDesktopProviderService.ts+++ b/apps/desktop/src/main/maker-host/createDesktopProviderService.ts@@ -312,7 +312,11 @@ export function getDesktopProviderService(): ProviderService {connection: {xd: () => getAppCapabilities().canUseCindyGateway && readClaudeApiKey() != null,anthropic: () => isNativeProviderAuthBound('anthropic') && hasClaudeAiOAuth(),- openai: () => isNativeProviderAuthBound('openai') && desktopCodexAuthAdapter.hasCodexOAuthLogin(),+ // openai 不再前置 isNativeProviderAuthBound 短路:hasCodexOAuthLogin →+ // getAccessToken 内部已是「reconcile(含首个 owner 绑定自愈)→ 绑定校验 → 读+ // token」的完整口径,未绑定仍 fail-closed 返回 null;前置短路反而会拦掉+ // listProviders 路径触发绑定自愈的机会(claimDetectedCodexOAuthBinding)。+ openai: () => desktopCodexAuthAdapter.hasCodexOAuthLogin(),xai: () => isNativeProviderAuthBound('xai') && hasGrokOAuthLogin(),},// 通用 OAuth 供应商(目录 auth.oauth 描述符驱动):连接态 = 本机凭证 blob 是否存在。diff --git a/apps/desktop/src/main/maker-host/nativeProviderAuthBinding.ts b/apps/desktop/src/main/maker-host/nativeProviderAuthBinding.tsindex 3411381dcc..294b117290 100644--- a/apps/desktop/src/main/maker-host/nativeProviderAuthBinding.ts+++ b/apps/desktop/src/main/maker-host/nativeProviderAuthBinding.ts@@ -73,3 +73,32 @@ export function migrateLegacyNativeProviderAuthBindings(}writeBindings(next);}++/**+ * Claim an auto-detected local CLI credential for the current owner.+ *+ * The Codex import channel materializes its credential lazily (the ~/.codex+ * reconcile hardlink is created after startup), so the one-shot legacy+ * migration above can consume `legacyClaimOwner` while the credential is not+ * visible yet — stranding the intended first-owner auto-connect forever, and+ * local-mode owners never run that migration at all. This repairs exactly+ * that: only when the slot has no owner, the credential exists, and no OTHER+ * account won the legacy claim. An existing binding is never overwritten, so+ * account switches stay fail-closed like migrateLegacyNativeProviderAuthBindings.+ */+export function claimDetectedNativeProviderAuth(+ provider: NativeProviderId,+ hasCredential: () => boolean,+): boolean {+ const owner = getActiveAppSession().dataOwnerId;+ if (!owner) return false;+ const bindings = readBindings();+ // Key-presence, not truthiness: a corrupted/empty-string slot must count as+ // "claimed by unknown" and fail closed, never as re-claimable (matches+ // unbindNativeProviderAuth's `in` pattern).+ if (provider in bindings) return false;+ if ('legacyClaimOwner' in bindings && bindings.legacyClaimOwner !== owner) return false;+ if (!hasCredential()) return false;+ writeBindings({ ...bindings, [provider]: owner });+ return true;+}