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 association
  • providerOptions (Lines 12-18): Provider configuration needed for callback reconstruction:
    • serverUrl: The MCP server URL
    • storageKeyPrefix: localStorage key prefix
    • clientName: OAuth client name
    • clientUri: OAuth client URI
    • callbackUrl: 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.origin
    • callbackUrl: 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 localStorage
  • saveClientInformation(): Persists client data (supports dynamic registration)
  • Error handling: Removes corrupted data automatically

Token Management (Lines 79-117):

  • tokens(): Retrieves stored OAuth tokens
  • saveTokens(): Persists tokens and cleans up temporary data
  • saveCodeVerifier(): Stores PKCE code verifier
  • codeVerifier(): Retrieves PKCE code verifier with error handling

Authorization Flow Management (Lines 119-188)

prepareAuthorizationUrl() Method (Lines 125-156):

  1. State Generation (Line 127): Creates cryptographically random state parameter
  2. State Storage (Lines 131-143): Stores complete provider context in localStorage
  3. URL Construction (Lines 146-150): Adds state parameter and sanitizes URL
  4. Persistence (Line 153): Stores auth URL for manual fallback

redirectToAuthorization() Method (Lines 163-188):

  1. URL Preparation (Line 165): Calls prepareAuthorizationUrl()
  2. Popup Creation (Lines 168-170): Opens OAuth flow in popup window
  3. Error Handling (Lines 172-187): Manages popup blocking gracefully
  4. 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)

  1. State Retrieval (Lines 37-45): Gets stored state from localStorage
  2. Expiry Check (Lines 47-51): Validates state hasn't expired (security)
  3. Provider Options Validation (Lines 53-57): Ensures complete configuration
  4. Provider Instantiation (Lines 60-61): Recreates provider instance

Token Exchange (Lines 63-88)

  1. SDK Auth Call (Line 70): Uses MCP SDK's auth() function for token exchange
  2. Success Handling (Lines 72-83):
    • Notifies parent window via postMessage
    • Closes popup window
    • Cleans up stored state
  3. Unexpected Results (Lines 84-88): Handles edge cases

Error Handling (Lines 89-127)

  1. Error Notification (Lines 94-98): Sends error to parent window
  2. Error Display (Lines 102-113): Shows user-friendly error page
  3. 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-sanitise library
  • 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.