Skip to content

Conversation

nickytonline
Copy link
Owner

This PR adds OAuth to the template.

nickytonline and others added 26 commits July 31, 2025 12:46
- Added environment configuration for authentication options in .env.example and config.ts.
- Introduced GatewayTokenValidator and BuiltinTokenValidator for token validation.
- Created OAuthProvider class to handle authorization code flow and token issuance.
- Implemented OAuth routes: /authorize, /callback, /token, /introspect, and /revoke.
- Added discovery endpoints for OAuth 2.1 compliance.
- Updated README.md with detailed authentication setup instructions.
- Modified index.ts to conditionally apply authentication middleware based on configuration.
- Enhanced error handling and logging throughout the authentication process.
✅ **Features Added:**
- **AUTH_MODE support**: none|resource_server|full modes
- **OAuthTokenValidator**: Renamed from GatewayTokenValidator for clarity
- **OAuth Provider integration**: Full OAuth server support for 'full' mode
- **Comprehensive unit tests**: Config validation and token validator testing

✅ **Components:**
- **Config validation**: Proper AUTH_MODE validation with detailed error messages
- **Token validation**: JWT + introspection with proper error handling
- **OAuth Provider**: Authorization flows for full OAuth server mode
- **Unit tests**: 46 tests covering config and token validation scenarios

✅ **AUTH_MODE Behaviors:**
- **none**: No authentication required
- **resource_server**: Validates tokens from external OAuth provider
- **full**: Acts as OAuth authorization server + validates tokens

🔒 **Security**: Proper JWT validation, audience checking, and error handling
Updates OAuth implementation to follow the MCP specification's recommended
proxy pattern for external OAuth providers (e.g., Auth0):

## OAuth Proxy Pattern Changes

- **Authorization Flow**: Proxy /oauth/authorize requests to external provider
- **Token Exchange**: Proxy /oauth/token requests with PKCE validation
- **Token Introspection**: Proxy /oauth/introspect to external provider
- **Discovery Endpoints**: Advertise proxy endpoints in OAuth metadata

## Configuration Updates

- **OAuth Audience Validation**:
  - `full` mode: Optional with warning if missing
  - `resource_server` mode: Required, throws error if missing
- **Updated AUTH_MODE**: Uses none|full|resource_server values

## Benefits

✅ MCP specification compliant - follows OAuth proxy pattern
✅ Works with external identity providers (Auth0, Okta, etc.)
✅ Maintains MCP client compatibility
✅ Clean separation between OAuth provider and MCP server

## Implementation Details

- External OAuth flows proxied through MCP server endpoints
- PKCE validation enforced for OAuth 2.1 compliance
- Comprehensive unit test coverage (47 passing tests)
- Proper error handling and logging for all proxy operations

This implements the "MCP way" of OAuth integration as recommended
in the MCP specification for external identity provider scenarios.

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>
- Simplified the authentication initialization process by removing the OAuthProvider from the `initializeAuth` function.
- Enhanced the `createAuthenticationMiddleware` to conditionally use the OAuthProvider for full mode.
- Introduced a new `createOAuthProviderAuthMiddleware` for handling authentication with the external OAuth provider.
- Added a new `oauth-model.ts` file to manage OAuth-related data and operations, including token and authorization code handling.
- Updated the `OAuthProvider` class to store external token information and manage authorization codes with PKCE support.
- Implemented a new token exchange flow in the `createCallbackHandler` to handle authorization code exchanges with the external provider.
- Enhanced error handling and logging throughout the OAuth flow.
- Updated configuration validation to ensure required OAuth parameters are set for full mode.
- Registered new OAuth routes and discovery endpoints in the main application setup.
- Replace custom error format with standard JSON-RPC 2.0 structure
- Use appropriate error codes: -32600 (Invalid Request), -32000 (Connection Closed), -32603 (Internal Error)
- Improves MCP specification compliance

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>
- Enable client authentication for authorization code flow (OAuth 2.1 compliance)
- Remove sensitive token fragments from log messages
- Replace token substrings with token length for debugging
- Improves security by preventing token exposure in logs

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>
…eration

- Replace hardcoded "demo-user" fallbacks with proper random user ID generation
- Update variable names from "demoClient" to "configuredClient" for clarity
- Generate unique user IDs using randomBytes for better security
- Update comments to reflect production considerations
- Add generateUserId() method to OAuthProvider for consistent ID generation

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>
- Install express-rate-limit dependency for protection against abuse
- Add comprehensive rate limiting configuration with JSON-RPC 2.0 error format
- Configure different limits: 100/15min for OAuth endpoints, 10/15min for token endpoint
- Include structured logging for rate limit violations
- Prepare for applying rate limits to sensitive OAuth routes

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>
- Apply comprehensive rate limiting to /oauth/authorize and callback endpoints (100 req/15min)
- Apply stricter rate limiting to /oauth/token endpoint (10 req/15min)
- Include structured logging for rate limit violations with IP and user agent tracking
- Use JSON-RPC 2.0 compliant error responses for rate limit exceeded scenarios
- Protect against OAuth abuse and brute force attacks

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>
- Add session timestamp tracking for MCP transport connections
- Implement automatic cleanup of stale sessions (30+ minutes inactive)
- Properly close transport connections to prevent resource leaks
- Schedule cleanup every 10 minutes with structured logging
- Track both session creation and access times for accurate timeout detection
- Log cleanup statistics including cleaned and active session counts

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant