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(codex): prefer valid local auth over expired release snapshot

Lizi97799b083e18
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 4d7e3d17fa..919247fa04 100644
--- a/apps/desktop/src/main/maker-host/__tests__/codexAuthIsolatedSandbox.test.ts
+++ b/apps/desktop/src/main/maker-host/__tests__/codexAuthIsolatedSandbox.test.ts
@@ -18,6 +18,7 @@ import {
getCodexAuthInvalidationMarkerPath,
writeInvalidatedSystemCodexAuthMarker,
} from '../codex-auth-invalidation.js';
+import { getPreferredSharedCodexAuthPath } from '../codex-shared-auth.js';
const dirs: string[] = [];
const h = vi.hoisted(() => ({
@@ -297,6 +298,71 @@ describe('dev 沙箱凭证隔离(XDT_ISOLATED_AUTH)', () => {
expect(fs.existsSync(getCodexAuthInvalidationMarkerPath(codexHome))).toBe(true);
});
+ // 测试价值(unit):2026-10-23 实例反复复制已过期的 Release 授权,重新检测持续 401。
+ // 现有覆盖只区分文件缺失、owner 和失效标记,没有过期 Release + 有效本机授权的输入。
+ // 通过真实 getState/getAccessToken 验证选中的授权及落盘结果;下方矩阵保护共享目录与账号边界。
+ // 整文件实测:6.65s(Windows,含既有 adapter 依赖图加载);未新增模块重置或真实等待。
+ it('普通 Dev 在 Release 授权过期后使用同账号的有效本机授权', async () => {
+ const { localAuth, releaseAuth, systemAuth } = fixture();
+ const now = Math.floor(Date.now() / 1000);
+ const token = (exp: number) =>
+ `header.${Buffer.from(JSON.stringify({ exp })).toString('base64url')}.signature`;
+ const releaseToken = token(now - 3600);
+ const systemToken = token(now + 3600);
+ fs.mkdirSync(path.dirname(releaseAuth), { recursive: true });
+ fs.writeFileSync(
+ releaseAuth,
+ JSON.stringify({ tokens: { access_token: releaseToken, account_id: 'acct-1' } }),
+ );
+ fs.writeFileSync(
+ systemAuth,
+ JSON.stringify({ tokens: { access_token: systemToken, account_id: 'acct-1' } }),
+ );
+ bindReleaseOpenAi(releaseAuth);
+ const releaseBytes = fs.readFileSync(releaseAuth);
+ const systemBytes = fs.readFileSync(systemAuth);
+ h.dataOwnerId = 'owner-a';
+ const { DesktopCodexAuthAdapter } = 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,
+ });
+ await expect(adapter.getAccessToken()).resolves.toBe(systemToken);
+ expect(fs.readFileSync(localAuth)).toEqual(systemBytes);
+ expect(fs.readFileSync(releaseAuth)).toEqual(releaseBytes);
+ expect(fs.readFileSync(systemAuth)).toEqual(systemBytes);
+ });
+
+ it.each([
+ { label: 'Release 授权仍有效', releaseOffset: 3600, cliOffset: 7200, cliAccount: 'acct-1', shared: false },
+ { label: '本机授权也已过期', releaseOffset: -3600, cliOffset: -1800, cliAccount: 'acct-1', shared: false },
+ { label: '本机授权有效期未知', releaseOffset: -3600, cliOffset: null, cliAccount: 'acct-1', shared: false },
+ { label: '本机授权属于其他账号', releaseOffset: -3600, cliOffset: 3600, cliAccount: 'acct-other', shared: false },
+ { label: 'Dev 与 Release 共用目录', releaseOffset: -3600, cliOffset: 3600, cliAccount: 'acct-1', shared: true },
+ ])('$label 时保持 Release 授权来源', ({ releaseOffset, cliOffset, cliAccount, shared }) => {
+ const { releaseAuth, systemAuth } = fixture();
+ const now = Math.floor(Date.now() / 1000);
+ const token = (offset: number | null) => offset === null
+ ? 'opaque-token'
+ : `header.${Buffer.from(JSON.stringify({ exp: now + offset })).toString('base64url')}.signature`;
+ fs.mkdirSync(path.dirname(releaseAuth), { recursive: true });
+ fs.writeFileSync(
+ releaseAuth,
+ JSON.stringify({ tokens: { access_token: token(releaseOffset), account_id: 'acct-1' } }),
+ );
+ fs.writeFileSync(
+ systemAuth,
+ JSON.stringify({ tokens: { access_token: token(cliOffset), account_id: cliAccount } }),
+ );
+ bindReleaseOpenAi(releaseAuth);
+ if (shared) h.userDataDir = path.dirname(path.dirname(releaseAuth));
+
+ expect(getPreferredSharedCodexAuthPath('owner-a')).toBe(releaseAuth);
+ });
+
it('共享 Dev 直接使用 Release 登录态,不重链接或改 binding', async () => {
const { releaseAuth, systemAuth } = fixture();
h.userDataDir = path.join(h.appDataDir, 'CindyGlobal');
diff --git a/apps/desktop/src/main/maker-host/codex-shared-auth.ts b/apps/desktop/src/main/maker-host/codex-shared-auth.ts
index a08b4a0118..3a209506c4 100644
--- a/apps/desktop/src/main/maker-host/codex-shared-auth.ts
+++ b/apps/desktop/src/main/maker-host/codex-shared-auth.ts
@@ -52,22 +52,39 @@ function releaseOpenAiConnectionOwner(): string | null {
}
}
-function hasUsableCodexOAuth(pathname: string): boolean {
+type CodexOAuthCandidate = { accountId: string | null; expiresAtMs: number | null };
+
+function readCodexOAuthCandidate(pathname: string): CodexOAuthCandidate | null {
try {
const parsed = JSON.parse(fs.readFileSync(pathname, 'utf8')) as {
- tokens?: { access_token?: unknown };
+ tokens?: { access_token?: unknown; account_id?: unknown };
+ };
+ const token = parsed.tokens?.access_token;
+ if (typeof token !== 'string' || token.length === 0) return null;
+ let expiresAtMs: number | null = null;
+ try {
+ // Expiry is only a source-selection hint. Opaque tokens keep their existing behavior;
+ // the account RPC remains authoritative about whether a credential actually works.
+ const claims = JSON.parse(Buffer.from(token.split('.')[1], 'base64url').toString('utf8'));
+ if (typeof claims.exp === 'number' && Number.isFinite(claims.exp)) {
+ expiresAtMs = claims.exp * 1000;
+ }
+ } catch {
+ // Unknown expiry must not discard an otherwise supported login format.
+ }
+ return {
+ accountId: typeof parsed.tokens?.account_id === 'string' ? parsed.tokens.account_id : null,
+ expiresAtMs,
};
- return (
- typeof parsed.tokens?.access_token === 'string' && parsed.tokens.access_token.length > 0
- );
} catch {
- return false;
+ return null;
}
}
/**
* 普通 Dev 只读复用同 owner、同区域 Release 的登录态;Release 不可用时沿用
- * 原有的本机 Codex 共享来源。Packaged 行为保持不变,仍只与本机 Codex 协调。
+ * 原有的本机 Codex 共享来源。Release 已过期且本机有同账号的有效授权时优先本机,
+ * 避免旧快照挡住已经恢复的本机登录。Packaged 仍只与本机 Codex 协调。
*/
export function getPreferredSharedCodexAuthPath(activeOwnerId: string | null): string {
if (!app.isPackaged) {
@@ -81,12 +98,28 @@ export function getPreferredSharedCodexAuthPath(activeOwnerId: string | null): s
return releaseAuth;
}
const releaseOwner = releaseOpenAiConnectionOwner();
+ const release = readCodexOAuthCandidate(releaseAuth);
if (
- hasUsableCodexOAuth(releaseAuth) &&
+ release &&
!shouldSuppressLocalCodexAuth(path.dirname(releaseAuth), releaseAuth) &&
activeOwnerId !== null &&
activeOwnerId === releaseOwner
) {
+ const now = Date.now();
+ if (release.expiresAtMs !== null && release.expiresAtMs <= now) {
+ const cliAuth = getCodexCliAuthPath();
+ const cli = readCodexOAuthCandidate(cliAuth);
+ // Do not switch accounts/workspaces or replace a refreshable Release credential
+ // with another expired/unknown token. Both source files remain untouched.
+ if (
+ release.accountId &&
+ cli?.accountId === release.accountId &&
+ cli.expiresAtMs !== null &&
+ cli.expiresAtMs > now
+ ) {
+ return cliAuth;
+ }
+ }
return releaseAuth;
}
}
diff --git a/docs/dev-rules/desktop-development.md b/docs/dev-rules/desktop-development.md
index 5b47500b89..0239b8cd61 100644
--- a/docs/dev-rules/desktop-development.md
+++ b/docs/dev-rules/desktop-development.md
@@ -14,7 +14,12 @@ Agent 启动 Desktop 只使用仓库根的安全包装命令,并显式选择
命令默认使用固定的 `dev` 命名隔离沙箱(等价于自动附加 `--isolated=dev`),
不再默认共享 Cindy 账号登录态与业务数据。OpenAI 模型登录态是刻意保留的例外:
普通 Dev 可只读复用同区域 Release/本机 Codex 已有登录态,能够调用模型,但不能在
-Dev 内发起 OpenAI 登录或断开共享登录态。Claude Code 的配置目录同样不隔离:Dev 与正式版
+Dev 内发起 OpenAI 登录或断开共享登录态。同 owner 的 Release 授权通常优先;若其 access
+token 已过期,且本机 Codex 有同账号/workspace、有效期明确且尚未过期的授权,则改用
+本机授权,避免旧 Release 快照挡住已恢复的登录。有效期未知或账号无法确认时保持原优先级;
+与 Release 共用 userData 的 Dev 不自动切换来源。实现与回归见
+`maker-host/codex-shared-auth.ts`、`codexAuthIsolatedSandbox.test.ts`。
+Claude Code 的配置目录同样不隔离:Dev 与正式版
一样使用 CLI 默认的 `~/.claude`(不设 `CLAUDE_CONFIG_DIR`),所以直接沿用本机 Claude Code
的订阅登录;在 Dev 里「使用 Claude Code 登录」等同于在终端运行 `claude auth login`,「断开」
只撤销本实例的使用许可。代价是多个 Dev 实例与安装版在同机共用 `~/.claude` 下的 Claude 转录