Authentication System Analysis
Overview
The authentication system provides browser-compatible OAuth support for MCP connections. It implements the Model Context Protocol's OAuth client specification with browser-specific adaptations for popup-based authentication flows.
File Structure
src/auth/types.ts - Type Definitions
StoredState Interface (Lines 7-19)
Purpose: Defines the structure for OAuth state stored in localStorage during popup authentication flows.
Properties:
expiry(Line 8): Timestamp when the stored state expires (security measure)metadata(Line 9): Optional OAuth metadata (may be rediscovered by auth function)serverUrlHash(Line 10): Hashed server URL for state associationproviderOptions(Lines 12-18): Provider configuration needed for callback reconstruction:serverUrl: The MCP server URLstorageKeyPrefix: localStorage key prefixclientName: OAuth client nameclientUri: OAuth client URIcallbackUrl: OAuth callback URL
src/auth/browser-provider.ts - OAuth Client Provider
Class Overview (Lines 11-37)
The BrowserOAuthClientProvider implements the MCP SDK's OAuthClientProvider interface for browser environments.
Constructor Parameters (Lines 19-36):
serverUrl: The MCP server URL (required)options: Configuration object with:storageKeyPrefix: Defaults to 'mcp:auth'clientName: Defaults to 'MCP Browser Client'clientUri: Defaults to window.location.origincallbackUrl: Defaults to '/oauth/callback' on current origin
Security Features:
- Line 30: Server URL hashing for unique storage keys
- Lines 33-36: URL sanitization to prevent XSS attacks
OAuth Client Interface Implementation (Lines 39-117)
redirectUrl Property (Lines 41-43):
- Returns sanitized callback URL
- Used by OAuth servers for redirect validation
clientMetadata Property (Lines 45-55):
- Defines OAuth client configuration per RFC 7591
- Line 48: Uses 'none' authentication (public client)
- Lines 49-50: Supports authorization code + PKCE flow
- Lines 51-52: Client identification metadata
Client Information Management (Lines 57-77):
clientInformation(): Retrieves stored client data from localStoragesaveClientInformation(): Persists client data (supports dynamic registration)- Error handling: Removes corrupted data automatically
Token Management (Lines 79-117):
tokens(): Retrieves stored OAuth tokenssaveTokens(): Persists tokens and cleans up temporary datasaveCodeVerifier(): Stores PKCE code verifiercodeVerifier(): Retrieves PKCE code verifier with error handling
Authorization Flow Management (Lines 119-188)
prepareAuthorizationUrl() Method (Lines 125-156):
- State Generation (Line 127): Creates cryptographically random state parameter
- State Storage (Lines 131-143): Stores complete provider context in localStorage
- URL Construction (Lines 146-150): Adds state parameter and sanitizes URL
- Persistence (Line 153): Stores auth URL for manual fallback
redirectToAuthorization() Method (Lines 163-188):
- URL Preparation (Line 165): Calls
prepareAuthorizationUrl() - Popup Creation (Lines 168-170): Opens OAuth flow in popup window
- Error Handling (Lines 172-187): Manages popup blocking gracefully
- Logging: Provides detailed feedback for debugging
Utility Methods (Lines 190-252)
getLastAttemptedAuthUrl() (Lines 195-198):
- Retrieves last authorization URL for manual authentication
- Used when popup is blocked
clearStorage() (Lines 200-237):
- Removes all stored data for this provider instance
- Prefix-based cleanup: Removes provider-specific keys
- State cleanup: Removes associated OAuth state data
- Security: Only removes data belonging to this server URL hash
hashString() (Lines 239-247):
- Simple hash function for creating unique storage keys
- Prevents conflicts between different server instances
getKey() (Lines 249-251):
- Generates consistent localStorage keys
- Format:
{prefix}_{serverHash}_{suffix}
src/auth/callback.ts - OAuth Callback Handler
Function Overview (Lines 10-128)
The onMcpAuthorization() function handles OAuth callbacks in the redirect page.
Parameter Extraction (Lines 11-18)
- Lines 12-15: Extracts OAuth parameters from URL query string
- Line 17: Sets up logging prefix for debugging
Error Validation (Lines 24-34)
- Lines 26-28: Handles OAuth error responses
- Lines 29-31: Validates authorization code presence
- Lines 32-34: Validates state parameter
State Validation and Provider Reconstruction (Lines 36-61)
- State Retrieval (Lines 37-45): Gets stored state from localStorage
- Expiry Check (Lines 47-51): Validates state hasn't expired (security)
- Provider Options Validation (Lines 53-57): Ensures complete configuration
- Provider Instantiation (Lines 60-61): Recreates provider instance
Token Exchange (Lines 63-88)
- SDK Auth Call (Line 70): Uses MCP SDK's
auth()function for token exchange - Success Handling (Lines 72-83):
- Notifies parent window via postMessage
- Closes popup window
- Cleans up stored state
- Unexpected Results (Lines 84-88): Handles edge cases
Error Handling (Lines 89-127)
- Error Notification (Lines 94-98): Sends error to parent window
- Error Display (Lines 102-113): Shows user-friendly error page
- Cleanup (Lines 117-126): Removes invalid state and temporary data
Security Considerations
1. State Parameter Protection
- Cryptographically random state generation (crypto.randomUUID())
- State expiry (10 minutes) prevents replay attacks
- State validation ensures callback authenticity
2. URL Sanitization
- All URLs processed through
strict-url-sanitiselibrary - Prevents XSS attacks from malicious server URLs
- Applied to authorization URLs and callback URLs
3. Origin Validation
- postMessage communication validates message origin
- Prevents cross-origin attacks on auth flow
4. Storage Isolation
- Server URL hashing creates unique storage namespaces
- Prevents data leakage between different MCP servers
- Configurable storage prefixes for multi-tenant scenarios
5. Error Handling
- Graceful degradation when localStorage is corrupted
- Automatic cleanup of invalid or expired data
- Detailed error logging for debugging
Integration Patterns
1. Popup-based Authentication
- Opens OAuth flow in popup window for better UX
- Handles popup blocking with manual fallback
- Parent-child communication via postMessage
2. PKCE Implementation
- Generates and stores code verifier securely
- Automatic cleanup after successful token exchange
- Follows RFC 7636 specification
3. Dynamic Client Registration
- Supports both pre-registered and dynamic clients
- Stores client information after registration
- Implements RFC 7591 client metadata
4. Token Lifecycle Management
- Secure token storage in localStorage
- Automatic refresh token handling via SDK
- Cleanup of temporary auth data on success
Error Recovery Mechanisms
1. Popup Blocking
- Detects blocked popups automatically
- Provides manual authentication URL fallback
- User can complete auth in new tab/window
2. State Corruption
- Validates and removes corrupted localStorage data
- Fails gracefully with helpful error messages
- Allows retry without manual cleanup
3. Timeout Handling
- State expiry prevents indefinite auth sessions
- Automatic cleanup of expired state data
- Clear error messages for expired sessions
4. Network Failures
- Detailed error logging for debugging
- Preservation of auth context for retry
- Graceful fallback to manual authentication
This authentication system provides a robust, secure, and user-friendly OAuth implementation specifically designed for browser environments while maintaining full compatibility with the MCP protocol specification.