Authentication 专题¶
重要性:⭐⭐⭐(鉴权全览——5 种方式、3 类凭据、多源合并) 真实位置:
src/utils/auth.ts(2002 行)+src/services/mcp/auth.ts(2465 行)+src/services/oauth/角色:统一鉴权入口 关联:topics/deep-dive-auth.md、topics/deep-dive-mcp-auth.md
1. 鉴权全貌¶
┌────────────────────────────────────────┐
│ Claude Code 鉴权 │
│ ───────── │
│ 1. Anthropic API key (env/settings) │
│ 2. API key helper (shell command) │
│ 3. Claude AI OAuth (订阅) │
│ 4. AWS Bedrock (STS) │
│ 5. GCP Vertex (metadata) │
│ + macOS keychain (存储) │
└────────────────────────────────────────┘
5 种 + 1 个存储。
2. 5 种鉴权方式¶
2.1 Anthropic API Key¶
// env
ANTHROPIC_API_KEY=sk-ant-...
// settings
{ "ANTHROPIC_API_KEY": "sk-ant-..." }
// OR macOS keychain
3 种来源 —— env / settings / keychain。
2.2 API Key Helper¶
自定义 shell 命令 —— 动态生成。
2.3 Claude AI OAuth¶
claude.ai 订阅 —— OAuth 流程。
2.4 AWS Bedrock¶
AWS 用户 —— STS 临时凭据。
2.5 GCP Vertex¶
GCP 用户 —— metadata server 拿凭据。
3. 优先级链¶
function getAnthropicApiKeyWithSource(): { apiKey, source } | null {
// 1. macOS keychain
// 2. env ANTHROPIC_API_KEY
// 3. settings apiKey
// 4. apiKeyHelper
// 5. Claude AI OAuth
// 6. AWS / GCP
}
6 步优先级 —— 找到就用。
4. 5 个 TTL 常量¶
| TTL | 值 | 用途 |
|---|---|---|
DEFAULT_API_KEY_HELPER_TTL |
5 min | helper 调用间隔 |
MCP_AUTH_CACHE_TTL_MS |
15 min | MCP OAuth 短记 |
DEFAULT_AWS_STS_TTL |
1h | AWS 凭据 |
DEFAULT_GCP_CREDENTIAL_TTL |
1h | GCP 凭据 |
DEFAULT_OTEL_HEADERS_DEBOUNCE_MS |
29 min | OTEL helper 防抖 |
5 个 TTL —— 不同场景。
5. 3 类凭据存储¶
| 凭据 | 存储 | 加密 |
|---|---|---|
| API key | env / keychain / settings | OS env + keychain |
| OAuth token | local file | filesystem perms |
| AWS / GCP | 内存 | OS mem |
3 类 —— 不同方式。
6. macOS Keychain 集成¶
6.1 getApiKeyFromConfigOrMacOSKeychain¶
// 推测
function getApiKeyFromConfigOrMacOSKeychain(): string | null {
if (platform === 'darwin') {
return readKeychain() // security framework
}
return null // 其他平台不存
}
仅 macOS —— 平台相关。
6.2 saveApiKey¶
async function saveApiKey(apiKey: string): Promise<void> {
// 1. validate
// 2. save to keychain (macOS)
// 3. save to env var (other)
}
保存。
6.3 removeApiKey¶
删除。
7. 5 种 Subscription Type¶
5 种 —— 不同权限。
7.1 检测函数¶
isMaxSubscriber() // Max
isTeamSubscriber() // Team
isTeamPremiumSubscriber() // Team Premium
isEnterpriseSubscriber() // Enterprise
isProSubscriber() // Pro
5 个 —— bool 判断。
7.2 getSubscriptionType¶
当前订阅。
7.3 getRateLimitTier¶
rate limit 等级。
8. 401 Refresh 机制¶
const pending401Handlers = new Map<string, Promise<boolean>>()
function handleOAuth401Error(serverId): Promise<boolean> {
if (pending401Handlers.has(serverId)) {
return pending401Handlers.get(serverId)! // 同 token 401 只刷一次
}
const promise = refreshAndRetry()
pending401Handlers.set(serverId, promise)
return promise
}
pending401Handlers Map —— 去重 401 refresh。
防止 refresh storm。
9. 15+ 鉴权相关函数¶
isAnthropicAuthEnabled
getAuthTokenSource
getAnthropicApiKey
hasAnthropicApiKeyAuth
getAnthropicApiKeyWithSource
getConfiguredApiKeyHelper
isApiKeyHelperFromProjectOrLocalSettings
getConfiguredAwsAuthRefresh
isAwsAuthRefreshFromProjectSettings
getConfiguredAwsCredentialExport
isAwsCredentialExportFromProjectSettings
calculateApiKeyHelperTTL
getApiKeyHelperElapsedMs
getApiKeyFromApiKeyHelper
getApiKeyFromApiKeyHelperCached
clearApiKeyHelperCache
prefetchApiKeyFromApiKeyHelperIfSafe
refreshAwsAuth
refreshGcpAuth
prefetchAwsCredentialsAndBedRockInfoIfSafe
prefetchGcpCredentialsIfSafe
getApiKeyFromConfigOrMacOSKeychain
isValidApiKey
saveApiKey
isCustomApiKeyApproved
removeApiKey
maybeRemoveApiKeyFromMacOSKeychain
saveOAuthTokensIfNeeded
getClaudeAIOAuthTokens
clearOAuthTokenCache
invalidateOAuthCacheIfDiskChanged
handleOAuth401Error
getClaudeAIOAuthTokensAsync
checkAndRefreshOAuthTokenIfNeeded
isClaudeAISubscriber
hasProfileScope
is1PApiCustomer
getOauthAccountInfo
isOverageProvisioningAllowed
hasOpusAccess
getSubscriptionType
isMaxSubscriber
isTeamSubscriber
isTeamPremiumSubscriber
isEnterpriseSubscriber
isProSubscriber
getRateLimitTier
getSubscriptionName
isUsing3PServices
// ...
50+ 鉴权函数。
10. 3 种预取(fire-and-forget)¶
prefetchApiKeyFromApiKeyHelperIfSafe()
prefetchAwsCredentialsAndBedRockInfoIfSafe()
prefetchGcpCredentialsIfSafe()
3 个预取 —— 启动后并行。
11. Source 追踪¶
type ApiKeySource =
| 'env'
| 'settings'
| 'keychain'
| 'helper'
| 'oauth'
| '3p'
| 'macos-keychain'
function getAnthropicApiKeyWithSource(): { apiKey, source }
Source 追踪 —— 知道 key 从哪来(debug 友好)。
12. 3 个 prefetch 时机¶
// main.tsx (top)
// startMdmRawRead, startKeychainPrefetch 立即触发
// startDeferredPrefetches (首屏后)
void prefetchApiKeyFromApiKeyHelperIfSafe()
void prefetchAwsCredentialsAndBedRockInfoIfSafe()
void prefetchGcpCredentialsIfSafe()
3 阶段预取。
13. OpenTelemetry Headers¶
OTEL 自定义 headers —— 通过 helper。
29 min debounce —— 不频繁调。
14. Account Info¶
账户信息 —— 邮箱、订阅等。
14.1 Org 验证¶
强制登录组织验证。
15. 关键设计模式¶
15.1 5 种统一抽象¶
不同入口,统一 API。
15.2 优先级链¶
6 步找到就返回。
15.3 5 个 TTL¶
不同场景不同 TTL。
15.4 pending401Handlers Map¶
去重 refresh storm。
15.5 Source 追踪¶
debug 友好。
15.6 3 阶段预取¶
顶层 / preAction / 首屏后。
15.7 macOS keychain 专属¶
平台相关。
15.8 3 种凭据存储¶
env / keychain / 内存。
16. 安全考虑¶
16.1 凭证脱敏¶
错误信息 redact。
16.2 keychain OS 加密¶
macOS 平台安全。
16.3 不存 plaintext¶
永远不存 plaintext 到文件。
16.4 5min helper TTL¶
避免频繁调。
16.5 15min OAuth TTL¶
避免频繁 refresh。
16.6 1h 3P TTL¶
不过期。
17. 改进方向¶
17.1 统一 OAuth 抽象¶
MCP 和 Claude AI 共享。
17.2 完整 keyring 支持¶
Linux / Windows keyring。
17.3 SSO 集成¶
企业 SSO。
17.4 Hardware key¶
YubiKey 等。
18. 关键洞察¶
18.1 5 种统一抽象¶
不同入口 统一 API。
18.2 优先级链 6 步¶
env / settings / keychain / helper / OAuth / 3P。
18.3 5 个 TTL¶
5min / 15min / 1h / 29min / 1h。
18.4 pending401Handlers Map¶
去重 refresh storm。
18.5 3 阶段预取¶
顶层 / preAction / 首屏后。
18.6 macOS keychain 专属¶
仅 macOS。
18.7 Source 追踪¶
debug 友好。
18.8 50+ 鉴权函数¶
完整覆盖。
18.9 5 种订阅类型¶
商业产品分级。
18.10 不存 plaintext¶
安全原则。
19. 阅读建议¶
- 看
auth.tsgetAnthropicApiKeyWithSource —— 主入口 - 看
auth.ts3 个 memoizeWithTTLAsync —— 凭据缓存 - 看
auth.tspending401Handlers —— 401 去重 - 看
mcp/auth.tsClaudeAuthProvider —— MCP 鉴权
20. 与其他专题的关系¶
| 文件 | 关系 |
|---|---|
deep-dive-auth.md |
深度 |
deep-dive-mcp-auth.md |
MCP 鉴权 |
cache-strategies.md |
TTL 缓存 |