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): 恢复同账号修复后的 Codex 凭证刷新 (#4933)

Dash628dc029b42a
diff --git a/apps/desktop/src/main/maker-host/__tests__/codexAuthTokenReaderBoundary.test.ts b/apps/desktop/src/main/maker-host/__tests__/codexAuthTokenReaderBoundary.test.ts
index e37bcf9d92..fe5200d6d5 100644
--- a/apps/desktop/src/main/maker-host/__tests__/codexAuthTokenReaderBoundary.test.ts
+++ b/apps/desktop/src/main/maker-host/__tests__/codexAuthTokenReaderBoundary.test.ts
@@ -1,6 +1,14 @@
import { readFileSync } from 'node:fs';
+import fs from 'node:fs/promises';
+import os from 'node:os';
+import path from 'node:path';
+import { createServer } from 'node:http';
import { runInNewContext } from 'node:vm';
import { describe, expect, it, vi } from 'vitest';
+import { CodexExternalAuthSession, useCodexHistoryHome } from '../../../../../../packages/maker-core/src/agents/codex/app-server/external-auth';
+import { AppServerHost } from '../../../../../../packages/maker-core/src/agents/codex/app-server/host';
+import { createStdioTransport } from '../../../../../../packages/maker-core/src/agents/codex/app-server/stdioTransport';
+import type { Logger } from '../../../../../../packages/maker-core/src/interfaces/logger';
// Execute the actual host callback without bootstrapping Electron or real credentials.
const source = readFileSync(new URL('../index.ts', import.meta.url), 'utf8');
@@ -11,6 +19,7 @@ describe('Codex token reader owner boundary', () => {
it.each(['before', 'during', 'stable', 'owner-change'])('handles %s credential reads', async phase => {
let pending = phase === 'before';
let owner = 'owner-a';
+ const agent = {};
const readOneShotCreds = vi.fn(() => ({ accessToken: 'fixture-token', accountId: 'account-b' }));
const getState = vi.fn(async () => {
if (phase === 'during') pending = true;
@@ -19,6 +28,10 @@ describe('Codex token reader owner boundary', () => {
});
const createReader = runInNewContext(`(${callback})`, {
activeOwnerScopeKey: () => owner,
+ getActiveAppSession: () => ({ mode: 'cloud', dataOwnerId: owner }),
+ getActiveAuthRealm: () => 'global',
+ codexAgent: agent,
+ _codexAgent: agent,
isAppSessionBoundaryPending: () => pending,
desktopCodexAuthAdapter: { getState, readOneShotCreds },
});
@@ -32,4 +45,199 @@ describe('Codex token reader owner boundary', () => {
if (phase === 'before') expect(getState).not.toHaveBeenCalled();
}
});
+
+ function fixture(oldToken = 'fixture-old-token', newToken = 'fixture-new-token', initialRealm = 'global') {
+ const owner = { mode: 'cloud', dataOwnerId: 'owner-a', generation: 1 };
+ const agent = {};
+ let pending = false;
+ let realm = initialRealm;
+ let accessToken = oldToken;
+ const readOneShotCreds = vi.fn(() => ({ accessToken, accountId: 'account-b' }));
+ const getState = vi.fn(async () => ({ authenticated: true }));
+ const context = {
+ activeOwnerScopeKey: () => `${owner.mode}:${owner.dataOwnerId}:${owner.generation}`,
+ getActiveAppSession: () => ({ ...owner }),
+ getActiveAuthRealm: () => realm,
+ isAppSessionBoundaryPending: () => pending,
+ codexAgent: agent,
+ _codexAgent: agent as object | null,
+ desktopCodexAuthAdapter: { getState, readOneShotCreds },
+ };
+ const createReader = runInNewContext(`(${callback})`, context);
+ return { owner, context, getState, readOneShotCreds, reader: createReader('account-b'),
+ setPending: (value: boolean) => { pending = value; },
+ setRealm: (value: string) => { realm = value; },
+ renew: () => { accessToken = newToken; },
+ };
+ }
+
+ it('refreshes a live cross-account task after a completed same-owner projection repair', async () => {
+ const f = fixture();
+ const session = new CodexExternalAuthSession({ readTokens: f.reader });
+ await expect(session.tokens(false)).resolves.toMatchObject({ accessToken: 'fixture-old-token' });
+ // Ghost repair fences in-flight reads, but preserves Maker and the task's native host.
+ f.owner.generation++;
+ f.renew();
+ await expect(session.tokens(true, 'account-b')).resolves.toEqual({
+ accessToken: 'fixture-new-token', chatgptAccountId: 'account-b',
+ });
+ expect(f.readOneShotCreds).toHaveBeenCalledTimes(2);
+ });
+
+ it('rejects a read spanning same-owner repair and permits the next stable read', async () => {
+ const f = fixture();
+ f.getState.mockImplementationOnce(async () => {
+ f.owner.generation++;
+ return { authenticated: true };
+ });
+ await expect(f.reader()).rejects.toThrow('Codex authentication owner changed');
+ expect(f.readOneShotCreds).not.toHaveBeenCalled();
+ f.renew();
+ await expect(f.reader()).resolves.toMatchObject({ accessToken: 'fixture-new-token' });
+ });
+
+ it('does not latch a temporary owner boundary as a permanent authentication failure', async () => {
+ const f = fixture();
+ f.setPending(true);
+ await expect(f.reader()).rejects.toThrow('Codex authentication owner changed');
+ expect(f.getState).not.toHaveBeenCalled();
+ f.owner.generation++;
+ f.setPending(false);
+ await expect(f.reader()).resolves.toMatchObject({ chatgptAccountId: 'account-b' });
+ });
+
+ it.each(['owner', 'mode', 'replacement', 'reset'] as const)('rejects %s changes between reads', async change => {
+ const f = fixture();
+ await f.reader();
+ f.readOneShotCreds.mockClear();
+ f.getState.mockClear();
+ if (change === 'owner') f.owner.dataOwnerId = 'owner-b';
+ if (change === 'mode') f.owner.mode = 'local';
+ if (change === 'replacement') f.context._codexAgent = {};
+ if (change === 'reset') f.context._codexAgent = null;
+ f.owner.generation++;
+ await expect(f.reader()).rejects.toThrow('Codex authentication owner changed');
+ expect(f.getState).not.toHaveBeenCalled();
+ expect(f.readOneShotCreds).not.toHaveBeenCalled();
+ });
+
+ it('rejects a retired Maker even when the user switches away and back to the same owner', async () => {
+ const f = fixture();
+ f.context._codexAgent = {};
+ f.owner.generation += 2;
+ await expect(f.reader()).rejects.toThrow('Codex authentication owner changed');
+ expect(f.getState).not.toHaveBeenCalled();
+ });
+
+ it('rejects runtime replacement during a credential read even without a scope change', async () => {
+ const f = fixture();
+ f.getState.mockImplementationOnce(async () => {
+ f.context._codexAgent = {};
+ return { authenticated: true };
+ });
+ await expect(f.reader()).rejects.toThrow('Codex authentication owner changed');
+ expect(f.readOneShotCreds).not.toHaveBeenCalled();
+ });
+
+ it.each(['global', 'cn'])('rejects same-ID realm changes from %s between reads', async realm => {
+ const f = fixture('fixture-old-token', 'fixture-new-token', realm);
+ await f.reader();
+ f.getState.mockClear();
+ f.readOneShotCreds.mockClear();
+ f.setRealm(realm === 'global' ? 'cn' : 'global');
+ f.owner.generation++;
+ f.renew();
+ // Same membership ID and retained CodexAgent are insufficient across realms.
+ await expect(f.reader()).rejects.toThrow('Codex authentication owner changed');
+ expect(f.getState).not.toHaveBeenCalled();
+ expect(f.readOneShotCreds).not.toHaveBeenCalled();
+ });
+
+ it.each(['global', 'cn'])('rejects a realm change from %s during a credential read', async realm => {
+ const f = fixture('fixture-old-token', 'fixture-new-token', realm);
+ f.getState.mockImplementationOnce(async () => {
+ f.setRealm(realm === 'global' ? 'cn' : 'global');
+ f.owner.generation++;
+ return { authenticated: true };
+ });
+ await expect(f.reader()).rejects.toThrow('Codex authentication owner changed');
+ expect(f.readOneShotCreds).not.toHaveBeenCalled();
+ // The new realm remains rejected after its transition has settled.
+ await expect(f.reader()).rejects.toThrow('Codex authentication owner changed');
+ expect(f.getState).toHaveBeenCalledTimes(1);
+ });
+
+ // Explicit opt-in: real binary, fake credentials, temporary home, loopback only.
+ it.skipIf(!process.env.CINDY_CODEX_TEST_BINARY)('recovers a native 401 in the same live thread after owner repair', async () => {
+ const token = (revision: string) => `test.${Buffer.from(JSON.stringify({
+ email: '[email protected]', revision, exp: 4102444800,
+ 'https://api.openai.com/auth': { chatgpt_account_id: 'account-b', chatgpt_plan_type: 'pro' },
+ })).toString('base64url')}.not-a-signature`;
+ const oldToken = token('old');
+ const newToken = token('new');
+ const f = fixture(oldToken, newToken);
+ const root = await fs.mkdtemp(path.join(os.tmpdir(), 'cindy-auth-owner-repair-'));
+ const requests: Array<{ authorization: string | undefined; account: unknown }> = [];
+ const server = createServer((request, response) => {
+ request.resume();
+ if (request.method === 'POST' && request.url?.endsWith('/responses')) {
+ requests.push({ authorization: request.headers.authorization, account: request.headers['chatgpt-account-id'] });
+ if (request.headers.authorization !== `Bearer ${newToken}`) {
+ response.writeHead(401, { 'content-type': 'application/json' });
+ response.end(JSON.stringify({ error: { code: 'token_expired', message: 'Provided authentication token is expired.' } }));
+ return;
+ }
+ response.writeHead(200, { 'content-type': 'text/event-stream' });
+ response.end(`event: response.completed\ndata: ${JSON.stringify({ type: 'response.completed', response: {
+ id: 'resp_fixture', object: 'response', created_at: 1, status: 'completed', model: 'gpt-6-astra', output: [],
+ usage: { input_tokens: 10, output_tokens: 1, total_tokens: 11 },
+ } })}\n\n`);
+ return;
+ }
+ response.setHeader('content-type', 'application/json');
+ response.end(JSON.stringify({ models: [] }));
+ });
+ const logger: Logger = { trace() {}, debug() {}, info() {}, warn() {}, error() {}, fatal() {}, child: () => logger };
+ let host: AppServerHost | undefined;
+ try {
+ await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve));
+ const address = server.address();
+ if (!address || typeof address === 'string') throw new Error('missing fixture listener');
+ const base = `http://127.0.0.1:${address.port}`;
+ host = new AppServerHost({ logger, clientInfo: { name: 'cindy-test', version: '0.0.0' },
+ externalAuth: { readTokens: f.reader },
+ createTransport: () => createStdioTransport({ binaryPath: process.env.CINDY_CODEX_TEST_BINARY!, cwd: root,
+ env: useCodexHistoryHome({ PATH: process.env.PATH ?? '', HOME: root, USERPROFILE: root, TMPDIR: root,
+ ...(process.env.SystemRoot ? { SystemRoot: process.env.SystemRoot } : {}) }, root),
+ extraArgs: ['--disable', 'plugins', '--disable', 'remote_plugin',
+ '-c', 'cli_auth_credentials_store="ephemeral"', '-c', 'model_provider="probe"',
+ '-c', 'model_providers.probe.name="Probe"', '-c', `model_providers.probe.base_url=${JSON.stringify(base)}`,
+ '-c', 'model_providers.probe.wire_api="responses"', '-c', 'model_providers.probe.requires_openai_auth=true',
+ '-c', `chatgpt_base_url=${JSON.stringify(base)}`],
+ }),
+ });
+ const { thread } = await host.request<{ thread: { id: string } }>('thread/start', {
+ cwd: root, model: 'gpt-6-astra', approvalPolicy: 'never', sandbox: 'read-only',
+ });
+ // Match the incident: retained native process, same owner, newer disk token.
+ f.owner.generation++;
+ f.renew();
+ let complete!: (value: unknown) => void;
+ const completed = new Promise(resolve => { complete = resolve; });
+ const subscription = host.subscribeThread(thread.id, { turnCompleted: complete });
+ try {
+ await host.request('turn/start', { threadId: thread.id, input: [{ type: 'text', text: 'fixture' }] });
+ await expect(completed).resolves.toMatchObject({ threadId: thread.id, turn: { status: 'completed' } });
+ expect(requests).toEqual([
+ { authorization: `Bearer ${oldToken}`, account: 'account-b' },
+ { authorization: `Bearer ${newToken}`, account: 'account-b' },
+ ]);
+ await expect(fs.stat(path.join(root, 'auth.json'))).rejects.toMatchObject({ code: 'ENOENT' });
+ } finally { await subscription.release(); }
+ } finally {
+ await host?.retire('fixture complete');
+ await new Promise<void>(resolve => { server.close(() => resolve()); server.closeAllConnections(); });
+ await fs.rm(root, { recursive: true, force: true });
+ }
+ }, 30_000);
});
diff --git a/apps/desktop/src/main/maker-host/index.ts b/apps/desktop/src/main/maker-host/index.ts
index bf7826b74b..c1e6111d4a 100644
--- a/apps/desktop/src/main/maker-host/index.ts
+++ b/apps/desktop/src/main/maker-host/index.ts
@@ -17,6 +17,7 @@ import { createMediaDownloadContext } from '../cindy-media/mediaDownloadApproval
import { isCodexAccountProvider, codexAccountHome, setCodexAccountRetirement } from './codex-account-auth.js';
import { CodexThreadLocations } from './codex-thread-locations.js';
import { getActiveAppSession } from '../appSessionState.js';
+import { getActiveAuthRealm } from '../authManager.js';
import { getCustomProvider, updateCustomProviderIfUnchanged } from './custom-provider-store.js';
import { refreshCustomProvidersIntoCatalog } from './createDesktopProviderService.js';
import { acquireWorktreeRuntimeLease, releaseWorktreeRuntimeLease, type WorktreeRuntimeLease } from '../worktree/runtimeLeases';
@@ -1949,11 +1950,25 @@ export function getMaker(): Maker {
return storage;
},
createCodexAuthTokenReader: (providerId) => {
- const ownerScope = activeOwnerScopeKey();
+ const owner = getActiveAppSession();
+ const authRealm = getActiveAuthRealm();
+ const assertOwner = () => {
+ const current = getActiveAppSession();
+ if (isAppSessionBoundaryPending() || _codexAgent !== codexAgent ||
+ getActiveAuthRealm() !== authRealm ||
+ current.mode !== owner.mode || current.dataOwnerId !== owner.dataOwnerId) {
+ throw new Error('Codex authentication owner changed');
+ }
+ };
return async () => {
- if (isAppSessionBoundaryPending() || activeOwnerScopeKey() !== ownerScope) throw new Error('Codex authentication owner changed');
+ // Same-owner Ghost repair advances the scope generation while retaining
+ // this Maker and its live tasks. Fence each read, not the reader's lifetime.
+ // The agent identity also rejects old readers after logout/login to the same owner.
+ assertOwner();
+ const ownerScope = activeOwnerScopeKey();
const state = await desktopCodexAuthAdapter.getState({ credentialMode: 'oauth-bearer', providerId });
- if (isAppSessionBoundaryPending() || activeOwnerScopeKey() !== ownerScope) throw new Error('Codex authentication owner changed');
+ assertOwner();
+ if (activeOwnerScopeKey() !== ownerScope) throw new Error('Codex authentication owner changed');
const credentials = state.authenticated ? desktopCodexAuthAdapter.readOneShotCreds(providerId) : null;
if (!credentials) throw new Error('Codex account credentials are unavailable');
return { accessToken: credentials.accessToken, chatgptAccountId: credentials.accountId };
diff --git a/docs/dev-rules/maker-core-and-agent-behavior.md b/docs/dev-rules/maker-core-and-agent-behavior.md
index ba506dc60a..ef885af70f 100644
--- a/docs/dev-rules/maker-core-and-agent-behavior.md
+++ b/docs/dev-rules/maker-core-and-agent-behavior.md
@@ -107,6 +107,12 @@ Codex 跨凭证时先按目标来源 resume 同一个原生线程,不因 `ordi
配置;每次重连重新认证,刷新必须匹配冻结的 owner、host 代次及账号,且不能复用刚被
拒绝的 token。owner 切换 pending 期间,即使 owner key 尚未提交变化,也必须在异步认证
读取前后拒绝提供 token。刷新有超时,失败走正常错误路径,不切回历史所属账号。
+同 owner 的 Ghost 投影修复会更新账号代次但保留 Maker 与活跃任务;凭证 reader 固定
+owner 身份、认证 realm 和 CodexAgent 实例,每次读取单独捕获代次,不能将创建时的代次永久锁在
+reader 上。跨修复的在途读取仍拒绝,修复完成后的新读取可正常刷新;真正切账号或
+切到另一认证 realm(即使 membership ID 相同且 Maker 保留)时不能提供凭证;
+Maker 被替换后旧 reader 必须失效,包括切走再切回同一 owner。回归见 Desktop
+`codexAuthTokenReaderBoundary.test.ts`,可通过 `CINDY_CODEX_TEST_BINARY` 实跑原生 401 恢复。
该 adapter 依赖 Codex 实验性的 `chatgptAuthTokens` 协议,0.145.0 已支持该协议且通过
真实登录及 401 刷新契约验证,不能把 0.153.4 当作协议最低版本。更换原生运行时前必须
用目标二进制运行 `CINDY_CODEX_TEST_BINARY=<绝对路径> pnpm --filter @cindy/maker-core exec