Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(auth): 修复独立 Claude 订阅账号认证 (#4243)
Lizic048a692dcfc
diff --git a/apps/desktop/src/main/maker-host/__tests__/claudeAuthAdapterOAuthEnv.test.ts b/apps/desktop/src/main/maker-host/__tests__/claudeAuthAdapterOAuthEnv.test.tsindex b8fd38eb66..918668f0a6 100644--- a/apps/desktop/src/main/maker-host/__tests__/claudeAuthAdapterOAuthEnv.test.ts+++ b/apps/desktop/src/main/maker-host/__tests__/claudeAuthAdapterOAuthEnv.test.ts@@ -9,6 +9,7 @@* gateway-key 模式不受影响、不带订阅 token。*/import { beforeEach, describe, expect, it, vi } from 'vitest';+import { buildClaudeEnv } from '../../../../../../packages/maker-core/src/agents/claude-code/env-builder.js';const h = vi.hoisted(() => ({hasOAuth: true,@@ -23,6 +24,8 @@ const h = vi.hoisted(() => ({encryptionAvailable: true,proxyReady: true,canUseGateway: true,+ accounts: new Map<string, Record<string, unknown> | null>(),+ refreshAccount: vi.fn(),}));vi.mock('electron', () => ({@@ -67,6 +70,13 @@ vi.mock('../claude-oauth-refresh.js', () => ({},}));+vi.mock('../subscription-account-auth.js', () => ({+ subscriptionAccountKind: (id: string) => h.accounts.has(id) ? 'claude' : null,+ readClaudeAccountOAuth: (id: string) => h.accounts.get(id) ?? null,+ subscriptionAccountState: (id: string) => ({ authenticated: !!h.accounts.get(id), authSource: 'oauth' }),+ getValidClaudeAccountOAuth: (...args: unknown[]) => h.refreshAccount(...args),+}));+vi.mock('../../secrets/providerSecretStore.js', () => ({getProviderSecretStore: () => ({get: () => h.gatewayKey,@@ -102,6 +112,8 @@ describe('DesktopClaudeAuthAdapter.getAuthEnv — 订阅 OAuth env 注入', () =h.encryptionAvailable = true;h.proxyReady = true;h.canUseGateway = true;+ h.accounts.clear();+ h.refreshAccount.mockReset();});it('keeps the owner-scoped BYOK key readable when Cindy gateway access is disabled', async () => {@@ -129,6 +141,49 @@ describe('DesktopClaudeAuthAdapter.getAuthEnv — 订阅 OAuth env 注入', () =expect(env.ANTHROPIC_API_KEY).toBeUndefined();});+ it('builds native OAuth environments for the selected independent accounts', async () => {+ h.hasOAuth = false;+ h.gatewayKey = null;+ const adapter = await makeAdapter();+ for (const providerId of ['anthropic-a', 'anthropic-b']) {+ h.accounts.set(providerId, { ...h.oauth, accessToken: `test-token-${providerId}` });+ await expect(adapter.getState({ credentialMode: 'provider-oauth', providerId })).resolves.toMatchObject({+ authenticated: true, authSource: 'oauth',+ });+ const env = await buildClaudeEnv(adapter, { endpoint: 'http://127.0.0.1:1' }, {+ credentialMode: 'provider-oauth', sessionProviderId: providerId,+ });+ expect(env.CLAUDE_CODE_OAUTH_TOKEN).toBe(`test-token-${providerId}`);+ expect(env.CINDY_CLAUDE_ACCOUNT_PROVIDER_ID).toBe(providerId);+ expect(env.CLAUDE_CODE_OAUTH_SCOPES).toBe('user:inference user:profile');+ expect(env.CLAUDE_CODE_SUBSCRIPTION_TYPE).toBe('max');+ expect(env.CLAUDE_CODE_RATE_LIMIT_TIER).toBe('default_claude_max_20x');+ expect(env.ANTHROPIC_API_KEY).toBeUndefined();+ expect(env.ANTHROPIC_AUTH_TOKEN).toBeUndefined();+ }+ h.refreshAccount.mockResolvedValue({ accessToken: 'test-refreshed-a' });+ await expect(adapter.getFreshSubscriptionToken('test-token-anthropic-a', 'anthropic-a')).resolves.toBe('test-refreshed-a');+ expect(h.refreshAccount).toHaveBeenCalledWith('anthropic-a', {+ forceRefresh: true, staleToken: 'test-token-anthropic-a',+ });+ });++ it('keeps independent account startup closed when the proxy or account is unavailable', async () => {+ const providerId = 'anthropic-a';+ h.accounts.set(providerId, { accessToken: 'test-account-a' });+ const adapter = await makeAdapter();+ h.proxyReady = false;+ await expect(adapter.getState({ credentialMode: 'provider-oauth', providerId })).resolves.toEqual({+ authenticated: false, errorReason: 'proxy_not_ready',+ });+ h.proxyReady = true;+ h.accounts.set(providerId, null);+ await expect(adapter.getState({ credentialMode: 'provider-oauth', providerId })).resolves.toMatchObject({+ authenticated: false,+ });+ await expect(adapter.getAuthEnv({ credentialMode: 'provider-oauth', providerId })).rejects.toThrow('Claude account requires login');+ });+it('订阅字段缺省时只注入 token 本体,不留空值 env', async () => {h.oauth = { accessToken: 'at-live' };const adapter = await makeAdapter();diff --git a/apps/desktop/src/main/maker-host/__tests__/providerRoute.test.ts b/apps/desktop/src/main/maker-host/__tests__/providerRoute.test.tsindex 2a484d6d21..b89b00b3d0 100644--- a/apps/desktop/src/main/maker-host/__tests__/providerRoute.test.ts+++ b/apps/desktop/src/main/maker-host/__tests__/providerRoute.test.ts@@ -855,6 +855,30 @@ describe('none (无鉴权自定义代理 buildRouteDecision)', () => {});describe('resolveSessionRouteDecision — 自定义供应商(resolve 时注入 key)', () => {+ it('routes independent Claude accounts with their own bearer and removes the CLI API key', async () => {+ setCustomProviders(['anthropic-a', 'anthropic-b'].map(id => buildUserProvider({+ id, name: 'Claude subscription', auth: { method: 'oauth', native: 'claude' },+ runtimes: { 'claude-code': { baseUrl: ANTHROPIC_DIRECT_UPSTREAM, models: [] } },+ })));+ const readToken = vi.fn(async (id: string) => `test-token-${id}`);+ setProviderOAuthTokenReader(readToken);+ for (const id of ['anthropic-a', 'anthropic-b', 'anthropic-a']) {+ setSessionProvider('s-user', id);+ expect(await resolveSessionRouteDecision('s-user', 'claude-code', KEY, 'claude-opus-4-6')).toEqual({+ upstreamOverride: ANTHROPIC_DIRECT_UPSTREAM,+ headerOverride: { authorization: `Bearer test-token-${id}` },+ headerDelete: ['x-api-key'],+ });+ expect(readToken).toHaveBeenLastCalledWith(id, 'claude-code');+ }+ setProviderOAuthTokenReader(() => null);+ expect(await resolveSessionRouteDecision('s-user', 'claude-code', KEY, 'claude-opus-4-6')).toMatchObject({+ upstreamOverride: ANTHROPIC_DIRECT_UPSTREAM,+ headerOverride: { authorization: 'Bearer xdt-missing-provider-oauth-token' },+ headerDelete: ['x-api-key'],+ });+ });+it('routes A → B → A by connection id despite identical provider and model names', () => {setCustomProviders(['account-a', 'account-b'].map(id => buildUserProvider({id, name: 'Same provider', runtimes: { codex: {diff --git a/apps/desktop/src/main/maker-host/auth-adapters.ts b/apps/desktop/src/main/maker-host/auth-adapters.tsindex c3830f36eb..0c24fa2a81 100644--- a/apps/desktop/src/main/maker-host/auth-adapters.ts+++ b/apps/desktop/src/main/maker-host/auth-adapters.ts@@ -622,7 +622,12 @@ export class DesktopClaudeAuthAdapter implements AuthAdapter {}async getState(options?: AuthAdapterOptions): Promise<AuthState> {- if (options?.providerId && subscriptionAccountKind(options.providerId)) return subscriptionAccountState(options.providerId);+ if (options?.providerId && subscriptionAccountKind(options.providerId)) {+ if (!isAnthropicCompatProxyHandleReady()) {+ return { authenticated: false, errorReason: 'proxy_not_ready' };+ }+ return subscriptionAccountState(options.providerId);+ }if (!safeStorage.isEncryptionAvailable()) {return { authenticated: false, errorReason: 'no_encryption' };}diff --git a/packages/maker-core/src/agents/claude-code/__tests__/env-builder.test.ts b/packages/maker-core/src/agents/claude-code/__tests__/env-builder.test.tsindex 4753b5d656..dda079ca6f 100644--- a/packages/maker-core/src/agents/claude-code/__tests__/env-builder.test.ts+++ b/packages/maker-core/src/agents/claude-code/__tests__/env-builder.test.ts@@ -1,6 +1,6 @@import { afterEach, describe, expect, it, vi } from 'vitest';-import type { AuthAdapter } from '../../../interfaces/auth-adapter.js';+import type { AuthAdapter, AuthAdapterOptions } from '../../../interfaces/auth-adapter.js';import type { AgentRuntimeConfig } from '../../../interfaces/runtime-config.js';import {EXPLORE_INHERIT_CAP_DISABLE_ENV,@@ -109,6 +109,47 @@ describe('buildClaudeEnv', () => {expect(env.ANTHROPIC_API_KEY).toBe('key');});+ it.each(['local', 'remote'] as const)('passes the selected subscription account into %s auth', async (mode) => {+ const getAuthEnv = vi.fn(async (options?: AuthAdapterOptions) => ({+ CLAUDE_CODE_OAUTH_TOKEN: `test-token-${options?.providerId ?? 'wrong-account'}`,+ }));+ const auth = { ...createAuthAdapter(), getAuthEnv };+ for (const providerId of ['anthropic-a', 'anthropic-b']) {+ const env = await buildClaudeEnv(auth, {}, {+ credentialMode: 'provider-oauth', sessionProviderId: providerId, mode,+ });+ expect(getAuthEnv).toHaveBeenLastCalledWith({ credentialMode: 'provider-oauth', providerId });+ expect(env.CLAUDE_CODE_OAUTH_TOKEN).toBe(`test-token-${providerId}`);+ expect(env.ANTHROPIC_API_KEY).toBeUndefined();+ }+ });++ it('keeps a remote gateway fallback independent of the selected subscription account', async () => {+ const getAuthEnv = vi.fn(async (options?: AuthAdapterOptions): Promise<Record<string, string>> =>+ options?.providerId+ ? { CLAUDE_CODE_OAUTH_TOKEN: 'test-token-must-not-reach-gateway' }+ : { ANTHROPIC_API_KEY: 'test-gateway-key' },+ );+ const env = await buildClaudeEnv({ ...createAuthAdapter(), getAuthEnv }, {}, {+ credentialMode: 'gateway-key', sessionProviderId: 'anthropic-a', mode: 'remote',+ });+ expect(getAuthEnv).toHaveBeenCalledWith({ credentialMode: 'gateway-key' });+ expect(env.ANTHROPIC_API_KEY).toBe('test-gateway-key');+ expect(env.CLAUDE_CODE_OAUTH_TOKEN).toBeUndefined();+ });++ it('does not inherit another Claude account refresh identity from the parent process', async () => {+ const previous = process.env.CINDY_CLAUDE_ACCOUNT_PROVIDER_ID;+ process.env.CINDY_CLAUDE_ACCOUNT_PROVIDER_ID = 'anthropic-parent';+ try {+ const env = await buildClaudeEnv(createAuthAdapter({ CLAUDE_CODE_OAUTH_TOKEN: 'test-native-token' }), {});+ expect(env.CINDY_CLAUDE_ACCOUNT_PROVIDER_ID).toBeUndefined();+ } finally {+ if (previous === undefined) delete process.env.CINDY_CLAUDE_ACCOUNT_PROVIDER_ID;+ else process.env.CINDY_CLAUDE_ACCOUNT_PROVIDER_ID = previous;+ }+ });+it('evaluates function-form behaviorFlags with the spawn route context', async () => {const behaviorFlags = vi.fn(() => ({ CLAUDE_CODE_ATTRIBUTION_HEADER: '0' }));diff --git a/packages/maker-core/src/agents/claude-code/__tests__/plan-mode.test.ts b/packages/maker-core/src/agents/claude-code/__tests__/plan-mode.test.tsindex 40df4aa911..5f02b7a0b1 100644--- a/packages/maker-core/src/agents/claude-code/__tests__/plan-mode.test.ts+++ b/packages/maker-core/src/agents/claude-code/__tests__/plan-mode.test.ts@@ -14,7 +14,7 @@ import path from 'node:path';import { afterEach, describe, expect, it, vi } from 'vitest';import type { AgentDeps, RemoteClaudeRoute } from '../../base-agent.js';-import type { AuthAdapter } from '../../../interfaces/auth-adapter.js';+import type { AuthAdapter, AuthAdapterOptions } from '../../../interfaces/auth-adapter.js';import type { PermissionMode } from '../../../types/common.js';import type { AgentEvent, InteractionDecision, InteractionRequest } from '../../../types/events.js';import type { Logger } from '../../../interfaces/logger.js';@@ -741,6 +741,60 @@ describe('ClaudeCodeAgent plan mode', () => {await handle.close();});+ it('keeps independent Claude accounts bound through startup and SDK token refresh', async () => {+ const configDir = await makeTempDir();+ process.env.CLAUDE_CONFIG_DIR = configDir;+ const workingDir = await makeTempDir();+ sdkMock.query.mockImplementation(() => createFakeQuery());+ const accounts = ['anthropic-a', 'anthropic-b'];+ const auth: AuthAdapter = {+ ...createDeps().auth,+ getState: vi.fn(async (options?: AuthAdapterOptions) => ({+ authenticated: accounts.includes(options?.providerId ?? ''),+ authSource: 'oauth' as const,+ })),+ getAuthEnv: vi.fn(async (options?: AuthAdapterOptions) => ({+ CLAUDE_CODE_OAUTH_TOKEN: `test-token-${options?.providerId}`,+ CINDY_CLAUDE_ACCOUNT_PROVIDER_ID: options?.providerId ?? '',+ })),+ getFreshSubscriptionToken: vi.fn(async (_staleToken, providerId) => `test-refreshed-${providerId}`),+ };+ const agent = new ClaudeCodeAgent(createDeps({ auth }));+ const handles = [];+ try {+ for (const providerId of accounts) {+ handles.push(await agent.startSession({+ sessionId: `session-${providerId}`, model: 'claude-opus-4-6', providerId,+ workingDir, permissionMode: 'acceptEdits',+ }));+ expect(auth.getState).toHaveBeenLastCalledWith({ credentialMode: 'provider-oauth', providerId });+ expect(auth.getAuthEnv).toHaveBeenLastCalledWith({ credentialMode: 'provider-oauth', providerId });+ }+ // Refresh A after B has started: a global/current account fallback would select B here.+ for (let i = 0; i < accounts.length; i += 1) {+ const options = sdkMock.query.mock.calls[i][0].options;+ expect(options.env.CLAUDE_CODE_OAUTH_TOKEN).toBe(`test-token-${accounts[i]}`);+ expect(options.env.ANTHROPIC_API_KEY).toBeUndefined();+ await expect(options.getOAuthToken()).resolves.toBe(`test-refreshed-${accounts[i]}`);+ expect(auth.getFreshSubscriptionToken).toHaveBeenLastCalledWith(`test-token-${accounts[i]}`, accounts[i]);+ expect(options.env.CLAUDE_CODE_OAUTH_TOKEN).toBe(`test-refreshed-${accounts[i]}`);+ }+ } finally {+ await Promise.all(handles.map(handle => handle.close()));+ }+ });++ it('rejects a disconnected independent Claude account before creating the SDK process', async () => {+ const getState = vi.fn(async () => ({ authenticated: false }));+ const agent = new ClaudeCodeAgent(createDeps({ auth: { ...createDeps().auth, getState } }));+ await expect(agent.startSession({+ sessionId: 'session-disconnected-account', model: 'claude-opus-4-6',+ providerId: 'anthropic-disconnected', workingDir: await makeTempDir(), permissionMode: 'acceptEdits',+ })).rejects.toThrow('not authenticated');+ expect(getState).toHaveBeenCalledWith({ credentialMode: 'provider-oauth', providerId: 'anthropic-disconnected' });+ expect(sdkMock.query).not.toHaveBeenCalled();+ });+it('passes the local session provider into spawn-time behavior flags', async () => {const configDir = await makeTempDir();process.env.CLAUDE_CONFIG_DIR = configDir;diff --git a/packages/maker-core/src/agents/claude-code/env-builder.ts b/packages/maker-core/src/agents/claude-code/env-builder.tsindex 7222e67ca3..dc6d2567cb 100644--- a/packages/maker-core/src/agents/claude-code/env-builder.ts+++ b/packages/maker-core/src/agents/claude-code/env-builder.ts@@ -118,6 +118,7 @@ export const SENSITIVE_ANTHROPIC_ENV_KEYS = ['ANTHROPIC_API_KEY','ANTHROPIC_AUTH_TOKEN','CLAUDE_CODE_OAUTH_TOKEN',+ 'CINDY_CLAUDE_ACCOUNT_PROVIDER_ID','CLAUDE_CODE_OAUTH_TOKEN_FILE_DESCRIPTOR','CLAUDE_CODE_API_KEY_FILE_DESCRIPTOR',// 订阅身份元数据(与 OAUTH_TOKEN 配套,cc env-token 分支消费):不剥离的话,从@@ -163,6 +164,7 @@ export const REMOTE_ROUTE_OVERRIDE_ENV_KEYS = ['ANTHROPIC_API_KEY','ANTHROPIC_AUTH_TOKEN','CLAUDE_CODE_OAUTH_TOKEN',+ 'CINDY_CLAUDE_ACCOUNT_PROVIDER_ID','CLAUDE_CODE_OAUTH_SCOPES','CLAUDE_CODE_SUBSCRIPTION_TYPE','CLAUDE_CODE_RATE_LIMIT_TIER',@@ -448,7 +450,13 @@ export async function buildClaudeEnv(env.ANTHROPIC_BASE_URL = endpoint;}const authOptions = options.credentialMode- ? { credentialMode: options.credentialMode }+ ? {+ credentialMode: options.credentialMode,+ // A remote gateway fallback must not pick credentials from the original subscription.+ ...(options.credentialMode !== 'gateway-key' && options.sessionProviderId+ ? { providerId: options.sessionProviderId }+ : {}),+ }: undefined;const authEnv = { ...(await auth.getAuthEnv(authOptions)) };if (mode === 'remote') {diff --git a/packages/maker-core/src/agents/claude-code/index.ts b/packages/maker-core/src/agents/claude-code/index.tsindex 103e996fc6..c8b84fd8cd 100644--- a/packages/maker-core/src/agents/claude-code/index.ts+++ b/packages/maker-core/src/agents/claude-code/index.ts@@ -1215,7 +1215,12 @@ export class ClaudeCodeAgent extends BaseAgent {providerId: opts.providerId,model: opts.model,});- const authOptions = credentialMode ? { credentialMode } : undefined;+ const authOptions = credentialMode+ ? {+ credentialMode,+ ...(credentialMode !== 'gateway-key' && opts.providerId ? { providerId: opts.providerId } : {}),+ }+ : undefined;const authState = await this.deps.auth.getState(authOptions);if (!authState.authenticated) {throw new AgentNotAuthenticatedError(diff --git a/packages/model-providers/src/__tests__/user-provider.test.ts b/packages/model-providers/src/__tests__/user-provider.test.tsindex 494d6d1e20..fc6b97cb8e 100644--- a/packages/model-providers/src/__tests__/user-provider.test.ts+++ b/packages/model-providers/src/__tests__/user-provider.test.ts@@ -38,6 +38,14 @@ describe('native subscription instances', () => {expect(a.agents).toEqual(expect.arrayContaining(['claude-code', 'codex', 'pi']));expect(a.models).toEqual(b.models);for (const agent of a.agents) expect(a.routing[agent]?.authStrategy).toBe('provider-oauth-header');+ const builtin = BUNDLED_CATALOG.providers.find(provider => provider.id === brand)!;+ for (const agent of a.agents) {+ expect(a.routing[agent]).toEqual({+ ...builtin.routing[agent],+ authStrategy: 'provider-oauth-header',+ ...(native === 'claude' && agent === 'claude-code' ? { headerDelete: ['x-api-key'] } : {}),+ });+ }expect(a.auth.native).toBe(native);expect(a.imageModels).toBeUndefined();expect(a.imageDefaults).toBeUndefined();diff --git a/packages/model-providers/src/user-provider.ts b/packages/model-providers/src/user-provider.tsindex 409e3647e7..f710654815 100644--- a/packages/model-providers/src/user-provider.ts+++ b/packages/model-providers/src/user-provider.ts@@ -506,7 +506,14 @@ export function buildUserProvider(source: 'user',auth: { method: 'oauth', native },routing: Object.fromEntries(Object.entries(identity.routing).map(([agent, route]) => [- agent, { ...route, authStrategy: 'provider-oauth-header' },+ agent, {+ ...route,+ authStrategy: 'provider-oauth-header',+ // Claude subscription requests must not carry a CLI placeholder API key alongside OAuth.+ ...(native === 'claude' && agent === 'claude-code'+ ? { headerDelete: [...new Set([...(route.headerDelete ?? []), 'x-api-key'])] }+ : {}),+ },])),// Media remains explicitly bound to the original provider until it supports account selection.imageModels: undefined,