# Superstore MCP Authentication Guide
This document provides comprehensive information about the authentication system
implemented in the Superstore MCP server.
## Overview
The authentication system uses web scraping with Puppeteer to automate login to
the Real Canadian Superstore website. It maintains session state across requests
and handles automatic session refresh.
## Architecture
### Components
1. **SuperstoreAuth** - Core authentication class
2. **SessionManager** - Global session management with pooling
3. **ErrorHandler** - Comprehensive error handling with retry logic
### Authentication Flow
```
1. Check existing session validity
2. If invalid/expired, create new session
3. Use Puppeteer to automate login form
4. Extract and store session cookies
5. Maintain session state across requests
```
## Configuration
### Environment Variables
Set these in your `mcp.json` configuration:
```json
{
"superstore-mcp": {
"command": "node",
"args": ["/path/to/dist/index.js"],
"env": {
"NODE_ENV": "production",
"SUPERSTORE_EMAIL": "your-email@example.com",
"SUPERSTORE_PASSWORD": "your-password",
"SESSION_TIMEOUT": "3600000"
}
}
}
```
### Required Environment Variables
- `SUPERSTORE_EMAIL` - Your Superstore account email
- `SUPERSTORE_PASSWORD` - Your Superstore account password
- `SESSION_TIMEOUT` - Session timeout in milliseconds (optional, default: 1
hour)
## Features
### Session Management
- **Automatic Session Pooling**: Maintains session state across MCP server
lifetime
- **Intelligent Refresh**: Automatically refreshes sessions before expiry
- **Timeout Handling**: Gracefully handles session timeouts
- **Cookie Management**: Secure cookie storage and injection
### Error Handling
- **Retry Logic**: Exponential backoff with jitter for failed requests
- **Circuit Breaker**: Prevents cascading failures
- **Fallback Mechanisms**: Graceful degradation on errors
- **Timeout Protection**: Prevents hanging requests
### Security Features
- **Stealth Mode**: Uses puppeteer-extra-plugin-stealth to avoid detection
- **Realistic Headers**: Mimics real browser behavior
- **Rate Limiting**: Built-in delays to avoid overwhelming servers
- **Secure Storage**: Credentials stored in environment variables only
## Usage
### MCP Tools
The authentication system is exposed through these MCP tools:
#### `login`
Authenticate with Superstore account using environment variables.
**Input**: None (uses environment variables) **Output**: Success status and
session information
#### `logout`
End current session and clear cookies.
**Input**: None **Output**: Success status
#### `check_auth_status`
Check current authentication state and session statistics.
**Input**: None **Output**: Authentication status, session info, and statistics
### Programmatic Usage
```typescript
import { SessionManager } from "./SessionManager.js";
// Get authenticated session
const sessionManager = SessionManager.getInstance();
const auth = await sessionManager.getAuthenticatedSession();
// Check authentication status
const isAuthenticated = await sessionManager.isAuthenticated();
// Get session statistics
const stats = sessionManager.getSessionStats();
```
## Troubleshooting
### Common Issues
#### Authentication Failures
**Problem**: Login fails with "Authentication failed" error **Solutions**:
1. Verify `SUPERSTORE_EMAIL` and `SUPERSTORE_PASSWORD` are correct
2. Check if account is locked or requires 2FA
3. Ensure network connectivity to Superstore website
#### Session Timeouts
**Problem**: Sessions expire frequently **Solutions**:
1. Increase `SESSION_TIMEOUT` environment variable
2. Check for network issues causing premature timeouts
3. Verify Superstore website is accessible
#### Browser Initialization Errors
**Problem**: Puppeteer fails to launch browser **Solutions**:
1. Ensure system has Chrome/Chromium installed
2. Check for sufficient system resources
3. Verify no conflicting browser processes
### Debug Mode
Enable debug logging by setting:
```bash
DEBUG=superstore-mcp:*
```
### Session Statistics
Use the `check_auth_status` tool to get detailed session information:
```json
{
"isAuthenticated": true,
"session_info": {
"isAuthenticated": true,
"sessionExpiry": "2023-12-01T15:30:00.000Z",
"lastActivity": "2023-12-01T14:30:00.000Z"
},
"session_stats": {
"isAuthenticated": true,
"lastActivity": "2023-12-01T14:30:00.000Z",
"timeSinceLastActivity": 300000,
"isNearExpiry": false
}
}
```
## Security Considerations
### Best Practices
1. **Never log credentials** - Passwords are never logged or stored
2. **Use environment variables** - Store credentials securely
3. **Regular credential rotation** - Change passwords periodically
4. **Monitor session activity** - Watch for unusual patterns
5. **Secure MCP configuration** - Protect your `mcp.json` file
### Security Features
- **No credential storage** - Credentials only exist in environment variables
- **Session isolation** - Each MCP server instance has isolated sessions
- **Automatic cleanup** - Sessions are cleaned up on logout
- **Stealth mode** - Avoids detection as automated browser
## Performance
### Optimization Features
- **Session pooling** - Reuses sessions across requests
- **Intelligent caching** - Caches authentication state
- **Browser reuse** - Reuses browser instances when possible
- **Connection pooling** - Efficient network resource usage
### Monitoring
The system provides detailed performance metrics:
- Session lifetime tracking
- Authentication success rates
- Error frequency and types
- Performance metrics
## Development
### Testing
Run the authentication tests:
```bash
npm test tests/auth.test.ts
npm test tests/integration.test.ts
```
### Debugging
Enable detailed logging:
```typescript
// In your code
console.log("Session stats:", sessionManager.getSessionStats());
```
### Custom Configuration
You can customize the authentication behavior:
```typescript
const auth = new SuperstoreAuth({
sessionTimeout: 7200000, // 2 hours
});
```
## API Reference
### SuperstoreAuth Class
#### Methods
- `login()`: Authenticate with credentials
- `logout()`: End session and cleanup
- `isAuthenticated()`: Check authentication status
- `getSessionInfo()`: Get session information
- `cleanup()`: Cleanup resources
### SessionManager Class
#### Methods
- `getAuthenticatedSession()`: Get or create authenticated session
- `isAuthenticated()`: Check if currently authenticated
- `logout()`: End session and cleanup
- `getSessionStats()`: Get session statistics
- `cleanup()`: Cleanup all resources
### ErrorHandler Class
#### Methods
- `withRetry()`: Execute with retry logic
- `withFallback()`: Execute with fallback
- `withTimeout()`: Execute with timeout
- `withCircuitBreaker()`: Execute with circuit breaker
- `handleAuthError()`: Handle authentication errors
- `handleNetworkError()`: Handle network errors