# Auth Module Documentation
The Auth module provides authentication and session management tools for the Komodo MCP server.
## Overview
The Auth module exposes 4 MCP tools that handle user authentication, session management, and token operations:
1. **komodo_auth_Login** - Authenticate user credentials
2. **komodo_auth_Logout** - End current session
3. **komodo_auth_RefreshToken** - Refresh authentication token
4. **komodo_auth_ValidateSession** - Validate current session
## Tools
### komodo_auth_Login
Authenticate user credentials and create a new session.
**API Endpoint:** `POST /auth/login`
**Input Parameters:**
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `username` | string | Yes | Username or email address |
| `password` | string | Yes | User password |
| `remember` | boolean | No | Whether to create a long-lived session (default: false) |
**Response:**
```json
{
"success": true,
"session": {
"sessionId": "sess_abc123",
"userId": "usr_xyz",
"username": "admin",
"expiresAt": "2024-12-31T23:59:59Z",
"createdAt": "2024-01-01T00:00:00Z",
"updatedAt": "2024-01-01T00:00:00Z"
},
"token": {
"accessToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
"refreshToken": "refresh_xyz789",
"expiresIn": 3600,
"tokenType": "Bearer"
},
"user": {
"id": "usr_xyz",
"username": "admin",
"email": "admin@example.com",
"role": "admin"
}
}
```
**Example Usage:**
```typescript
import { login } from './modules/auth.js';
const result = await login({
username: 'admin',
password: 'secure-password',
remember: true
});
console.log('Logged in as:', result.user?.username);
console.log('Session expires:', result.session?.expiresAt);
```
**Error Handling:**
- Throws error if username is empty or whitespace-only
- Throws error if password is empty or whitespace-only
- Returns authentication error if credentials are invalid
- Returns network error if connection fails
---
### komodo_auth_Logout
End the current session and invalidate authentication tokens.
**API Endpoint:** `POST /auth/logout`
**Input Parameters:** None
**Response:**
```json
{
"success": true,
"message": "Logged out successfully"
}
```
**Example Usage:**
```typescript
import { logout } from './modules/auth.js';
const result = await logout();
console.log(result.message); // "Logged out successfully"
```
**Notes:**
- Invalidates the current session on the server
- Clears authentication tokens
- Safe to call even if no active session exists
---
### komodo_auth_RefreshToken
Refresh the authentication token using a refresh token. This extends the session without requiring re-authentication.
**API Endpoint:** `POST /auth/refresh`
**Input Parameters:**
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `refreshToken` | string | Yes | The current refresh token |
**Response:**
```json
{
"success": true,
"accessToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
"refreshToken": "refresh_abc123",
"expiresIn": 3600
}
```
**Example Usage:**
```typescript
import { refreshToken } from './modules/auth.js';
const result = await refreshToken({
refreshToken: 'refresh_xyz789'
});
console.log('New access token:', result.accessToken);
console.log('Expires in:', result.expiresIn, 'seconds');
```
**Error Handling:**
- Throws error if refreshToken is empty or whitespace-only
- Returns authentication error if refresh token is invalid or expired
- May rotate refresh token (returns new refreshToken in response)
**Best Practices:**
- Refresh tokens before they expire to maintain uninterrupted access
- Store new refresh token if provided in response (token rotation)
- Implement automatic token refresh in production applications
---
### komodo_auth_ValidateSession
Validate the current session to check if it is still active and has not expired.
**API Endpoint:** `GET /auth/validate`
**Input Parameters:** None
**Response:**
```json
{
"valid": true,
"sessionId": "sess_abc123",
"userId": "usr_xyz",
"expiresAt": "2024-12-31T23:59:59Z"
}
```
**Example Usage:**
```typescript
import { validateSession } from './modules/auth.js';
const result = await validateSession();
if (result.valid) {
console.log('Session is valid until:', result.expiresAt);
} else {
console.log('Session invalid:', result.reason);
}
```
**Use Cases:**
- Check if session is still active before making API calls
- Implement session timeout warnings
- Validate authentication state on page load
- Monitor session expiration in background
---
## Authentication Flow
### Standard Login Flow
```
1. User provides credentials
2. Call komodo_auth_Login
3. Receive session and tokens
4. Store tokens securely
5. Use access token for API requests
```
### Token Refresh Flow
```
1. Access token expires
2. Call komodo_auth_RefreshToken with refresh token
3. Receive new access token
4. Update stored tokens
5. Resume API requests with new token
```
### Session Validation Flow
```
1. Application starts
2. Call komodo_auth_ValidateSession
3. If valid: continue with existing session
4. If invalid: redirect to login
```
### Logout Flow
```
1. User requests logout
2. Call komodo_auth_Logout
3. Clear stored tokens
4. Redirect to login page
```
## Security Considerations
### Token Storage
- **Never** store tokens in localStorage (vulnerable to XSS)
- Use secure, httpOnly cookies when possible
- Consider sessionStorage for single-tab applications
- Encrypt tokens at rest in mobile applications
### Password Handling
- Never log passwords
- Use HTTPS for all authentication requests
- Implement rate limiting on login attempts
- Use strong password requirements
### Session Management
- Implement automatic session timeout
- Refresh tokens before expiration
- Validate sessions on critical operations
- Implement proper logout on all devices
### API Security
- All requests use HMAC-SHA256 authentication
- Request signatures prevent replay attacks
- Timestamps prevent request replay
- API keys and secrets must be kept secure
## Error Handling
All tools throw or return errors in a consistent format:
```typescript
try {
const result = await login({ username, password });
// Handle success
} catch (error) {
if (error instanceof AuthenticationError) {
// Invalid credentials
} else if (error instanceof NetworkError) {
// Connection failed
} else if (error instanceof TimeoutError) {
// Request timed out
} else {
// Other errors
}
}
```
### Common Error Codes
| Code | Description | Resolution |
|------|-------------|------------|
| `AUTH_ERROR` | Invalid credentials | Check username/password |
| `NETWORK_ERROR` | Connection failed | Check KOMODO_URL |
| `TIMEOUT_ERROR` | Request timed out | Increase timeout or check network |
| `VALIDATION_ERROR` | Invalid input | Check input parameters |
| `API_ERROR` | API request failed | Check API response |
## MCP Tool Integration
The auth module exports MCP tool definitions that can be registered with the MCP server:
```typescript
import { authTools } from './modules/auth.js';
import { Server } from '@modelcontextprotocol/sdk/server/index.js';
const server = new Server({
name: 'komodo-mcp',
version: '1.0.0'
}, {
capabilities: {
tools: {}
}
});
// Register auth tools
Object.values(authTools).forEach(tool => {
server.setRequestHandler('tools/call', async (request) => {
if (request.params.name === tool.name) {
return tool.handler(request.params.arguments);
}
});
});
```
## TypeScript Types
The module provides comprehensive TypeScript types:
```typescript
// Import types
import type {
LoginRequest,
LoginResponse,
LogoutResponse,
RefreshTokenRequest,
RefreshTokenResponse,
SessionValidation,
Credentials,
ApiCredentials,
TokenResponse,
Session,
AuthHeaders,
Permissions
} from './types/auth.js';
```
## Testing
The module includes comprehensive tests:
```bash
# Run all tests
npm test
# Run auth tests specifically
npm test -- auth.test.ts
# Run with coverage
npm test -- --coverage
```
**Note:** Integration tests require a running Komodo instance with valid credentials:
```bash
export KOMODO_URL="https://komodo.example.com"
export KOMODO_API_KEY="your-api-key"
export KOMODO_API_SECRET="your-api-secret"
export TEST_USERNAME="test-user"
export TEST_PASSWORD="test-password"
```
## Implementation Status
| Tool | Status | API Endpoint |
|------|--------|--------------|
| komodo_auth_Login | ✅ Implemented | POST /auth/login |
| komodo_auth_Logout | ✅ Implemented | POST /auth/logout |
| komodo_auth_RefreshToken | ✅ Implemented | POST /auth/refresh |
| komodo_auth_ValidateSession | ✅ Implemented | GET /auth/validate |
## Related Documentation
- [Environment Configuration](./ENVIRONMENT.md)
- [API Mapping](./API_MAPPING.md)
- [Error Handling](../src/utils/errors.ts)
- [API Client](../src/utils/api-client.ts)
## Support
For issues or questions:
- Check environment variables are set correctly
- Review error messages for specific issues
- Ensure Komodo API is accessible
- Verify API key and secret are valid