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(auth): 完整收口独立 Claude 账号刷新失效

Dash02e02b1b0d20
diff --git a/apps/desktop/src/main/bootstrap-electron.ts b/apps/desktop/src/main/bootstrap-electron.ts
index 4021ba83f1..a1fd0150e7 100644
--- a/apps/desktop/src/main/bootstrap-electron.ts
+++ b/apps/desktop/src/main/bootstrap-electron.ts
@@ -1,5 +1,6 @@
import { codexAccountState } from './maker-host/codex-account-auth.js';
import { syncSubscriptionAccountUsage } from './usage/subscriptionAccountUsage.js';
+import { setSubscriptionAccountInvalidatedHandler } from './maker-host/subscription-account-auth.js';
import { setXaiDiscoveredModels } from './maker-host/active-catalog.js';
import { startWorktreeRecycleMaintenance, stopWorktreeRecycleMaintenance, auditRegisteredWorktrees } from './worktree/recycleMaintenance';
import { requestWorktreeRecycle } from './worktree/managedRecycle';
@@ -561,6 +562,7 @@ import {
finalizeCodexAfterAuthModeChange,
readCodexRuntimeRoute,
broadcastClaudeAuthStateChanged,
+ refreshSelectableModelsAndBroadcast,
broadcastXaiAuthStateChanged,
refreshProviderAccessAfterAuthChange,
setProviderAccessRuntimeRefreshListener,
@@ -4881,6 +4883,15 @@ const registerIpcHandlers = () => {
// 上游作废 xAI 凭证、收口自动登出后,走和手动登出完全一致的 UI 收尾(广播 + 清账号级
// 限流快照),否则用户会停在「显示已连接、请求连环 403」的假状态。
+ setSubscriptionAccountInvalidatedHandler((providerId) => {
+ const scope = activeOwnerScopeKey();
+ const broadcast = () => {
+ if (scope === activeOwnerScopeKey() && !isAppSessionBoundaryPending()) {
+ refreshSelectableModelsAndBroadcast({ providerId });
+ }
+ };
+ void syncSubscriptionAccountUsage(providerId).then(broadcast, broadcast);
+ });
setXaiAuthInvalidatedHandler((providerId) => {
if (providerId !== 'xai') {
setXaiDiscoveredModels(null, providerId);
diff --git a/apps/desktop/src/main/maker-host/__tests__/subscription-account-auth.test.ts b/apps/desktop/src/main/maker-host/__tests__/subscription-account-auth.test.ts
index 517868efe6..8ed6af4200 100644
--- a/apps/desktop/src/main/maker-host/__tests__/subscription-account-auth.test.ts
+++ b/apps/desktop/src/main/maker-host/__tests__/subscription-account-auth.test.ts
@@ -4,6 +4,9 @@ const state = vi.hoisted(() => ({
pending: false,
secrets: new Map<string, string>(),
login: vi.fn(),
+ removeFails: false,
+ revokeDuringRefresh: false,
+ callbacks: [] as Array<() => void>,
}));
vi.mock('electron', () => ({ app: { getPath: () => '/tmp/cindy-scoped-auth-test' } }));
vi.mock('../../appSessionState.js', () => ({
@@ -24,6 +27,7 @@ vi.mock('../../secrets/providerSecretStore.js', () => ({
return true;
},
remove: (id: string) => {
+ if (state.removeFails) return false;
state.secrets.delete(`${state.scope}:${id}`);
return true;
},
@@ -33,11 +37,18 @@ vi.mock('../claude-credentials-store.js', () => ({
readClaudeAiOAuth: () => ({ accessToken: 'fake-local-token' }),
}));
vi.mock('../claude-oauth-refresh.js', () => ({
- createClaudeOAuthRefresher: (deps: { readOAuth: () => unknown }) => ({
- getValidOAuth: async () => deps.readOAuth(),
+ createClaudeOAuthRefresher: (deps: { readOAuth: () => unknown; onInvalidGrant: () => void }) => {
+ state.callbacks.push(deps.onInvalidGrant);
+ return ({
+ getValidOAuth: async () => {
+ const captured = deps.readOAuth();
+ if (state.revokeDuringRefresh) deps.onInvalidGrant();
+ return captured;
+ },
invalidate: vi.fn(),
backfillSubscriptionProfile: vi.fn(),
- }),
+ });
+ },
}));
vi.mock('../claude-oauth-login.js', () => ({
runClaudeOAuthLogin: (...args: unknown[]) => state.login(...args),
@@ -58,6 +69,9 @@ import {
cancelSubscriptionAccountLogin,
removeSubscriptionAccountCredentialsReversibly,
resetSubscriptionAccountCaches,
+ getValidClaudeAccountOAuth,
+ setSubscriptionAccountInvalidatedHandler,
+ subscriptionAccountState,
} from '../subscription-account-auth.js';
describe('independent Claude account credentials', () => {
@@ -78,6 +92,44 @@ describe('independent Claude account credentials', () => {
state.pending = false;
state.secrets.clear();
state.login.mockReset();
+ state.callbacks = [];
+ state.removeFails = false;
+ state.revokeDuringRefresh = false;
+ setSubscriptionAccountInvalidatedHandler(() => {});
+ });
+ it.each([false, true])('invalid grant disconnects only the failed account even when removal fails=%s', async (removeFails) => {
+ state.secrets.set(`${state.scope}:claude-a`, JSON.stringify({ accessToken: 'fake-a' }));
+ state.secrets.set(`${state.scope}:claude-b`, JSON.stringify({ accessToken: 'fake-b' }));
+ await getValidClaudeAccountOAuth('claude-a');
+ const broadcast = vi.fn();
+ setSubscriptionAccountInvalidatedHandler(broadcast);
+ state.removeFails = removeFails;
+ state.callbacks[0]();
+ expect(broadcast).toHaveBeenCalledWith('claude-a');
+ expect(subscriptionAccountState('claude-a').authenticated).toBe(false);
+ expect(await getValidClaudeAccountOAuth('claude-a')).toBeNull();
+ expect(readClaudeAccountOAuth('claude-b')?.accessToken).toBe('fake-b');
+ expect(readClaudeAccountOAuth()?.accessToken).toBe('fake-local-token');
+ state.login.mockImplementation(async opts => { opts.persist({ accessToken: 'fake-new' }); return { ok: true }; });
+ await loginSubscriptionAccount('claude-a', () => true);
+ expect(readClaudeAccountOAuth('claude-a')?.accessToken).toBe('fake-new');
+ });
+ it('late invalid grant from an old owner cannot clear or broadcast the new owner', async () => {
+ await getValidClaudeAccountOAuth('claude-a');
+ const broadcast = vi.fn();
+ setSubscriptionAccountInvalidatedHandler(broadcast);
+ state.scope = 'owner-b:2';
+ state.secrets.set(`${state.scope}:claude-a`, JSON.stringify({ accessToken: 'fake-new-owner' }));
+ state.callbacks[0]();
+ expect(broadcast).not.toHaveBeenCalled();
+ expect(readClaudeAccountOAuth('claude-a')?.accessToken).toBe('fake-new-owner');
+ });
+ it('does not return the refresher fallback credential on the invalid-grant request itself', async () => {
+ state.secrets.set(`${state.scope}:claude-a`, JSON.stringify({ accessToken: 'fake-revoked' }));
+ state.revokeDuringRefresh = true;
+ state.removeFails = true;
+ expect(await getValidClaudeAccountOAuth('claude-a')).toBeNull();
+ expect(readClaudeAccountOAuth('claude-a')).toBeNull();
});
it('commits each login to its provider, preserving the local account and supporting rollback', async () => {
state.login.mockImplementation(async (opts) => {
diff --git a/apps/desktop/src/main/maker-host/index.ts b/apps/desktop/src/main/maker-host/index.ts
index a94a20558b..8374872f8c 100644
--- a/apps/desktop/src/main/maker-host/index.ts
+++ b/apps/desktop/src/main/maker-host/index.ts
@@ -393,7 +393,7 @@ const reviewAutoPermissionAction = createAutoPermissionReviewer({
let _codexModelBackfill: CodexModelBackfillCoordinator | null = null;
/** Refresh selectable model capabilities, then notify every local/remote renderer. */
-function refreshSelectableModelsAndBroadcast(payload: Record<string, unknown>): void {
+export function refreshSelectableModelsAndBroadcast(payload: Record<string, unknown>): void {
if (_maker) refreshCatalogDerivedModels(_maker, getDesktopSelectableCatalog());
try {
providerAccessRuntimeRefreshListener?.();
diff --git a/apps/desktop/src/main/maker-host/subscription-account-auth.ts b/apps/desktop/src/main/maker-host/subscription-account-auth.ts
index 518ef621e0..ee778a709b 100644
--- a/apps/desktop/src/main/maker-host/subscription-account-auth.ts
+++ b/apps/desktop/src/main/maker-host/subscription-account-auth.ts
@@ -16,6 +16,21 @@ import {
resetGrokOAuthMemoryCache,
} from './grok-oauth-login.js';
import { outboundFetch } from './outbound-fetch.js';
+import { createLogger } from '../logger.js';
+
+const log = createLogger('subscription-account-auth');
+let onInvalidated: (providerId: string) => void = () => {};
+export function setSubscriptionAccountInvalidatedHandler(handler: typeof onInvalidated): void {
+ onInvalidated = handler;
+}
+type AccountRefreshState = {
+ refresher: ReturnType<typeof createClaudeOAuthRefresher>;
+ invalidatedCredential?: string;
+};
+const refreshers = new Map<string, AccountRefreshState>();
+function credentialFingerprint(raw: string): string {
+ return createHash('sha256').update(raw).digest('hex');
+}
export function subscriptionAccountKind(providerId?: string | null): 'claude' | 'xai' | null {
const native = getActiveCatalog().providers.find((p) => p.id === providerId)?.auth.native;
@@ -32,25 +47,26 @@ export function readClaudeAccountOAuth(providerId = 'anthropic'): ClaudeAiOAuth
if (subscriptionAccountKind(providerId) !== 'claude' || isAppSessionBoundaryPending())
return null;
try {
- const blob = JSON.parse(genericOAuthSecretIo.read(providerId) ?? 'null');
+ const raw = genericOAuthSecretIo.read(providerId) ?? 'null';
+ if (refreshers.get(`${activeOwnerScopeKey()}:${providerId}`)?.invalidatedCredential === credentialFingerprint(raw)) return null;
+ const blob = JSON.parse(raw);
return typeof blob?.accessToken === 'string' && blob.accessToken ? blob : null;
} catch {
return null;
}
}
-const refreshers = new Map<string, ReturnType<typeof createClaudeOAuthRefresher>>();
function claudeAccount(providerId: string) {
const scope = activeOwnerScopeKey();
const key = `${scope}:${providerId}`;
- let refresher = refreshers.get(key);
- if (!refresher) {
+ let account = refreshers.get(key);
+ if (!account) {
const current = () => activeOwnerScopeKey() === scope && !isAppSessionBoundaryPending();
const directory = path.join(
app.getPath('userData'),
'subscription-accounts',
createHash('sha256').update(key).digest('hex'),
);
- refresher = createClaudeOAuthRefresher({
+ const refresher = createClaudeOAuthRefresher({
readOAuth: () => (current() ? readClaudeAccountOAuth(providerId) : null),
writeOAuth: (oauth) => {
if (!current() || !genericOAuthSecretIo.write(providerId, JSON.stringify(oauth)))
@@ -60,20 +76,33 @@ function claudeAccount(providerId: string) {
now: Date.now,
lockDir: () => directory,
onInvalidGrant: () => {
- if (current()) genericOAuthSecretIo.remove(providerId);
+ if (!current()) return;
+ const raw = genericOAuthSecretIo.readStrict(providerId);
+ if (raw) account!.invalidatedCredential = credentialFingerprint(raw);
+ account!.refresher.invalidate();
+ if (!genericOAuthSecretIo.remove(providerId)) {
+ log.warn('revoked account credential could not be removed; suppressing retained credential', { providerId });
+ }
+ onInvalidated(providerId);
},
});
- refreshers.set(key, refresher);
+ account = { refresher };
+ refreshers.set(key, account);
}
- return refresher;
+ return account.refresher;
}
-export function getValidClaudeAccountOAuth(providerId: string, options?: GetValidOAuthOptions) {
- return claudeAccount(providerId).getValidOAuth(options);
+export async function getValidClaudeAccountOAuth(providerId: string, options?: GetValidOAuthOptions) {
+ const scope = activeOwnerScopeKey();
+ const result = await claudeAccount(providerId).getValidOAuth(options);
+ // The native refresher may return its pre-refresh credential on a failed refresh.
+ // Re-read after invalidation/login so that captured revoked credentials cannot escape.
+ return result && activeOwnerScopeKey() === scope && !isAppSessionBoundaryPending()
+ ? readClaudeAccountOAuth(providerId) : null;
}
export async function prepareClaudeAccountUsage(providerId: string): Promise<ClaudeAiOAuth | null> {
const scope = activeOwnerScopeKey();
const refresher = claudeAccount(providerId);
- const oauth = await refresher.getValidOAuth();
+ const oauth = await getValidClaudeAccountOAuth(providerId);
if (!oauth || activeOwnerScopeKey() !== scope) return null;
if (!oauth.subscriptionType) await refresher.backfillSubscriptionProfile(oauth.accessToken);
return activeOwnerScopeKey() === scope ? readClaudeAccountOAuth(providerId) : null;
@@ -98,7 +127,7 @@ export function cancelSubscriptionAccountLogin(providerId: string): void {
}
export function resetSubscriptionAccountCaches(): void {
for (const operation of logins.values()) operation.cancel();
- for (const refresher of refreshers.values()) refresher.invalidate();
+ for (const account of refreshers.values()) account.refresher.invalidate();
refreshers.clear();
}
export async function loginSubscriptionAccount(