MODULO 6.2

🔑 OAuth Authentication

6
Topicos
~60
Minutos
Deep
Nivel
Source
Tipo
1

🔐 PKCE Flow

Claude Code implements OAuth 2.0 Authorization Code flow with PKCE (Proof Key for Code Exchange). Three layers: crypto primitives (verifier, S256 challenge, CSRF state), network client (auth URLs, token exchange, profile), and orchestrator (listener, auto vs manual race).

ValueHow GeneratedPurpose
codeVerifier32 random bytes, base64urlProves this process started the flow
codeChallengeSHA-256(verifier), base64urlServer stores and later verifies
state32 random bytes, base64urlCSRF protection
2

🎯 Auto vs Manual Auth Flow

Automatic (browser redirect)

AuthCodeListener starts HTTP server on OS-assigned port. Browser opens automaticFlowUrl. After login, auth server redirects to localhost. Callback validates state, resolves auth code.

Manual (copy-paste fallback)

Terminal displays manualFlowUrl. User opens URL, authenticates, copies code and pastes into terminal. Used in SSH or unreachable localhost environments.

💡 Race Pattern

Both flows start simultaneously. Whichever delivers an authorization code first wins. The OAuthService races two resolvers against a single Promise.

3

💳 Token Exchange & Scopes

Authorization code is exchanged for tokens via POST to platform.claude.com/v1/oauth/token. The redirect_uri must exactly match the authorization request.

ScopeUsed For
org:create_api_keyConsole path - create permanent API key
user:profileFetch subscription type, rate-limit tier
user:inferenceClaude.ai path - direct inference via subscription
user:sessions:claude_codeSession management for Claude Code client
user:mcp_serversAccess MCP servers associated with account
user:file_uploadUpload files to Anthropic infrastructure
4

📊 Profile & Subscription Types

Subscriptionorg_type Key
maxclaude_max
proclaude_pro
teamclaude_team
enterpriseclaude_enterprise

💡 Profile Skip Optimization

During routine token refresh, if global config already has billingType, accountCreatedAt, subscriptionCreatedAt AND secure storage has non-null subscriptionType and rateLimitTier, the profile call is skipped. This cuts ~7 million requests/day fleet-wide.

5

🗄️ Token Storage Architecture

macOS

macOsKeychainStorage via security CLI. JSON payload hex-encoded and passed via stdin (-i flag) to keep tokens out of process argument lists.

Linux/Windows

plainTextStorage - encrypted JSON in ~/.claude/ with chmod 0o600.

Stale-while-error

If security subprocess fails transiently, last known good value served from cache.

6

🔄 Token Refresh & Logout

Access tokens refreshed proactively with 5-minute buffer. Backend allows scope expansion on refresh (ALLOWED_SCOPE_EXPANSIONS).

💡 Telemetry-First Logout

performLogout() flushes telemetry BEFORE clearing credentials. In-flight events carry org attribution; flushing after wipe would send them as anonymous, corrupting usage analytics.

📋 Resumo do Modulo

No client secret in binary - PKCE replaces it. Code verifier generated fresh each login, lives only in memory.
Auto and manual flows race simultaneously. AuthCodeListener captures browser redirect on temporary localhost server.
Tokens stored in OS keychain on macOS (hex-encoded via stdin). Stale-while-error cache prevents transient failures from logging users out.
Profile fetching optimized away during refresh when all fields already cached.
Logout flushes telemetry first to preserve org attribution in analytics events.
Two auth paths based on scopes: user:inference means Claude.ai subscriber; absence means Console API key path.
Voltar Proximo