536 lines
15 KiB
Markdown
536 lines
15 KiB
Markdown
# Security Features Documentation
|
|
|
|
This document covers all security features implemented in TurboTrades, including Two-Factor Authentication (2FA), Email Verification, and Session Management.
|
|
|
|
---
|
|
|
|
## Table of Contents
|
|
|
|
1. [Two-Factor Authentication (2FA)](#two-factor-authentication-2fa)
|
|
2. [Email Verification](#email-verification)
|
|
3. [Session Management](#session-management)
|
|
4. [Email Service](#email-service)
|
|
5. [API Endpoints](#api-endpoints)
|
|
6. [Frontend Implementation](#frontend-implementation)
|
|
|
|
---
|
|
|
|
## Two-Factor Authentication (2FA)
|
|
|
|
### Overview
|
|
|
|
TurboTrades implements Time-based One-Time Password (TOTP) 2FA using the `speakeasy` library. Users can enable 2FA to add an extra layer of security to their accounts.
|
|
|
|
### Features
|
|
|
|
- QR code generation for easy setup with authenticator apps
|
|
- Manual secret key entry option
|
|
- Recovery codes for account recovery
|
|
- Email notification when 2FA is enabled
|
|
- Support for disabling 2FA with either a 2FA code or recovery code
|
|
|
|
### Setup Flow
|
|
|
|
1. User clicks "Enable 2FA" in Settings
|
|
2. Backend generates a secret key and QR code
|
|
3. User scans QR code with authenticator app (Google Authenticator, Authy, etc.)
|
|
4. User enters 6-digit code from app to verify setup
|
|
5. Backend enables 2FA and sends confirmation email with recovery code
|
|
6. User should save recovery code in a secure location
|
|
|
|
### Recovery
|
|
|
|
If a user loses access to their authenticator device, they can use their recovery code to disable 2FA and regain access to their account.
|
|
|
|
### Implementation Details
|
|
|
|
**Backend:**
|
|
- Secret generation: `speakeasy.generateSecret()`
|
|
- QR code generation: `qrcode.toDataURL()`
|
|
- Token verification: `speakeasy.totp.verify()` with 2-step window
|
|
- Recovery code: Random 8-character alphanumeric string
|
|
|
|
**Database (User Model):**
|
|
```javascript
|
|
twoFactor: {
|
|
enabled: { type: Boolean, default: false },
|
|
qrCode: { type: String, default: null },
|
|
secret: { type: String, default: null },
|
|
revocationCode: { type: String, default: null },
|
|
}
|
|
```
|
|
|
|
---
|
|
|
|
## Email Verification
|
|
|
|
### Overview
|
|
|
|
Email verification helps secure user accounts and enables communication for security alerts and account recovery.
|
|
|
|
### Features
|
|
|
|
- Email address validation
|
|
- Verification token generation
|
|
- Verification email with styled HTML template
|
|
- Email verification status tracking
|
|
- Ability to update email (requires re-verification)
|
|
|
|
### Verification Flow
|
|
|
|
1. User enters email address in Settings
|
|
2. Backend generates unique verification token
|
|
3. Backend sends verification email with link
|
|
4. User clicks link in email
|
|
5. Backend verifies token and marks email as verified
|
|
6. User can now receive security notifications
|
|
|
|
### Email Templates
|
|
|
|
The email service includes beautifully styled HTML email templates:
|
|
- **Verification Email**: Welcome message with verification link
|
|
- **2FA Setup Email**: Confirmation with recovery code
|
|
- **Session Alert Email**: New login notifications
|
|
|
|
### Implementation Details
|
|
|
|
**Backend:**
|
|
- Token generation: Random 30-character alphanumeric string
|
|
- Token expiration: 24 hours (recommended to implement)
|
|
- Email sending: Nodemailer with SMTP or console logging in development
|
|
|
|
**Database (User Model):**
|
|
```javascript
|
|
email: {
|
|
address: { type: String, default: null },
|
|
verified: { type: Boolean, default: false },
|
|
emailToken: { type: String, default: null },
|
|
}
|
|
```
|
|
|
|
---
|
|
|
|
## Session Management
|
|
|
|
### Overview
|
|
|
|
Session management tracks all active login sessions across devices and allows users to view and revoke sessions for enhanced security.
|
|
|
|
### Features
|
|
|
|
- Track all active sessions
|
|
- Display device, browser, OS, IP, and location information
|
|
- View last activity timestamp
|
|
- Identify current session
|
|
- Revoke individual sessions
|
|
- Revoke all sessions except current
|
|
- Automatic session expiration (7 days)
|
|
- Session activity tracking
|
|
|
|
### Session Information Tracked
|
|
|
|
- **User ID & Steam ID**: Links session to user
|
|
- **Tokens**: Access token and refresh token
|
|
- **Device Info**: Device type (Desktop/Mobile/Tablet)
|
|
- **Browser**: Chrome, Firefox, Safari, Edge
|
|
- **Operating System**: Windows, macOS, Linux, Android, iOS
|
|
- **IP Address**: For security monitoring
|
|
- **User Agent**: Full user agent string
|
|
- **Location**: Country, region, city (requires IP geolocation service)
|
|
- **Activity**: Creation time and last activity
|
|
- **Status**: Active/inactive flag
|
|
|
|
### Session Model
|
|
|
|
```javascript
|
|
{
|
|
userId: ObjectId,
|
|
steamId: String,
|
|
token: String (unique),
|
|
refreshToken: String (unique),
|
|
ip: String,
|
|
userAgent: String,
|
|
device: String,
|
|
browser: String,
|
|
os: String,
|
|
location: {
|
|
country: String,
|
|
city: String,
|
|
region: String,
|
|
},
|
|
isActive: Boolean,
|
|
lastActivity: Date,
|
|
expiresAt: Date, // TTL index for auto-deletion
|
|
createdAt: Date,
|
|
updatedAt: Date,
|
|
}
|
|
```
|
|
|
|
### Session Lifecycle
|
|
|
|
1. **Creation**: Session created on Steam login
|
|
2. **Activity**: Updated when token is refreshed
|
|
3. **Expiration**: Automatically deleted after 7 days via MongoDB TTL index
|
|
4. **Revocation**: User can manually revoke sessions
|
|
5. **Logout**: Session deactivated on logout
|
|
|
|
### Security Benefits
|
|
|
|
- Users can see if unauthorized access occurred
|
|
- Ability to remotely log out compromised devices
|
|
- Session alerts can be sent via email
|
|
- Audit trail of account access
|
|
|
|
---
|
|
|
|
## Email Service
|
|
|
|
### Overview
|
|
|
|
The email service (`utils/email.js`) handles all email communications with beautifully styled HTML templates.
|
|
|
|
### Configuration
|
|
|
|
**Environment Variables:**
|
|
```bash
|
|
SMTP_HOST=smtp.gmail.com
|
|
SMTP_PORT=587
|
|
SMTP_USER=your-email@gmail.com
|
|
SMTP_PASS=your-app-password
|
|
EMAIL_FROM=noreply@turbotrades.com
|
|
```
|
|
|
|
**Development Mode:**
|
|
- If SMTP credentials are not configured, emails are logged to console
|
|
- Useful for testing without sending real emails
|
|
|
|
### Email Templates
|
|
|
|
#### 1. Verification Email
|
|
- **Subject**: "Verify your TurboTrades email address"
|
|
- **Contents**: Welcome message, verification button, manual link
|
|
- **Styling**: TurboTrades branding with gold gradient
|
|
|
|
#### 2. 2FA Setup Email
|
|
- **Subject**: "🔐 Two-Factor Authentication Enabled - TurboTrades"
|
|
- **Contents**: Confirmation, recovery code, security tips
|
|
- **Styling**: Green theme for security
|
|
|
|
#### 3. Session Alert Email
|
|
- **Subject**: "🔔 New Login Detected - TurboTrades"
|
|
- **Contents**: Login details (time, IP, device, location)
|
|
- **Styling**: Blue theme for informational alerts
|
|
|
|
### Using the Email Service
|
|
|
|
```javascript
|
|
import { sendVerificationEmail, send2FASetupEmail, sendSessionAlertEmail } from '../utils/email.js';
|
|
|
|
// Send verification email
|
|
await sendVerificationEmail(email, username, token);
|
|
|
|
// Send 2FA setup confirmation
|
|
await send2FASetupEmail(email, username, revocationCode);
|
|
|
|
// Send session alert
|
|
await sendSessionAlertEmail(email, username, sessionData);
|
|
```
|
|
|
|
---
|
|
|
|
## API Endpoints
|
|
|
|
### Authentication Routes (`/auth`)
|
|
|
|
| Method | Endpoint | Description | Auth Required |
|
|
|--------|----------|-------------|---------------|
|
|
| GET | `/steam` | Initiate Steam login | No |
|
|
| GET | `/steam/return` | Steam OAuth callback | No |
|
|
| GET | `/me` | Get current user | Yes |
|
|
| POST | `/refresh` | Refresh access token | Refresh Token |
|
|
| POST | `/logout` | Logout user | Yes |
|
|
| GET | `/verify` | Verify token validity | Yes |
|
|
|
|
### User Routes (`/user`)
|
|
|
|
| Method | Endpoint | Description | Auth Required |
|
|
|--------|----------|-------------|---------------|
|
|
| GET | `/profile` | Get user profile | Yes |
|
|
| PATCH | `/email` | Update email address | Yes |
|
|
| GET | `/verify-email/:token` | Verify email | No |
|
|
| PATCH | `/trade-url` | Update trade URL | Yes |
|
|
| GET | `/balance` | Get user balance | Yes |
|
|
| GET | `/stats` | Get user statistics | Yes |
|
|
|
|
### 2FA Routes (`/user/2fa`)
|
|
|
|
| Method | Endpoint | Description | Auth Required |
|
|
|--------|----------|-------------|---------------|
|
|
| POST | `/2fa/setup` | Generate QR code & secret | Yes |
|
|
| POST | `/2fa/verify` | Verify code & enable 2FA | Yes |
|
|
| POST | `/2fa/disable` | Disable 2FA | Yes |
|
|
|
|
### Session Routes (`/user/sessions`)
|
|
|
|
| Method | Endpoint | Description | Auth Required |
|
|
|--------|----------|-------------|---------------|
|
|
| GET | `/sessions` | Get all active sessions | Yes |
|
|
| DELETE | `/sessions/:id` | Revoke specific session | Yes |
|
|
| POST | `/sessions/revoke-all` | Revoke all other sessions | Yes |
|
|
|
|
---
|
|
|
|
## Frontend Implementation
|
|
|
|
### Settings Page (`SettingsPage.vue`)
|
|
|
|
The Settings page provides a user-friendly interface for managing all security features.
|
|
|
|
#### Features:
|
|
|
|
1. **Email Section**
|
|
- Display current email and verification status
|
|
- Add/change email modal
|
|
- Visual indicators for verified/unverified status
|
|
|
|
2. **2FA Section**
|
|
- Enable/disable 2FA button
|
|
- QR code display modal
|
|
- 6-digit code input
|
|
- Recovery code display and warning
|
|
- Step-by-step setup instructions
|
|
|
|
3. **Active Sessions Section**
|
|
- List all active sessions
|
|
- Visual device icons (Desktop/Mobile/Tablet)
|
|
- Session details (browser, OS, IP, location)
|
|
- "Current" badge for active session
|
|
- Revoke individual sessions
|
|
- Revoke all other sessions button
|
|
- Last activity timestamps
|
|
|
|
#### UI Components:
|
|
|
|
- **Modals**: Email update, 2FA setup, 2FA disable
|
|
- **Icons**: Lucide Vue Next icons for visual appeal
|
|
- **Styling**: Consistent with TurboTrades theme
|
|
- **Loading States**: Spinners for async operations
|
|
- **Notifications**: Toast messages for user feedback
|
|
|
|
### Auth Store Integration
|
|
|
|
The Pinia auth store has been extended with methods for:
|
|
- `updateEmail(email)` - Update user email
|
|
- `verifyEmail(token)` - Verify email with token
|
|
|
|
### Axios Integration
|
|
|
|
API calls to security endpoints use the configured axios instance with:
|
|
- Automatic cookie handling (`withCredentials: true`)
|
|
- Error handling and toast notifications
|
|
- Token refresh on 401 errors
|
|
|
|
---
|
|
|
|
## Security Best Practices
|
|
|
|
### For Users
|
|
|
|
1. **Enable 2FA**: Always enable 2FA for maximum account security
|
|
2. **Save Recovery Code**: Store recovery code in a password manager or secure location
|
|
3. **Verify Email**: Verify your email to receive security alerts
|
|
4. **Monitor Sessions**: Regularly check active sessions and revoke unknown devices
|
|
5. **Use Strong Passwords**: (for Steam account)
|
|
|
|
### For Developers
|
|
|
|
1. **Never Log Secrets**: 2FA secrets should never be logged or exposed
|
|
2. **Secure Cookie Settings**: Use `httpOnly`, `secure`, and `sameSite` flags
|
|
3. **Rate Limiting**: Implement rate limiting on 2FA verification attempts
|
|
4. **Token Expiration**: Enforce short-lived access tokens (15 minutes)
|
|
5. **Session Cleanup**: Use MongoDB TTL indexes to auto-delete expired sessions
|
|
6. **Email Validation**: Validate and sanitize email inputs
|
|
7. **HTTPS Only**: Always use HTTPS in production
|
|
8. **IP Geolocation**: Consider integrating IP geolocation service for better session tracking
|
|
|
|
---
|
|
|
|
## Configuration Checklist
|
|
|
|
### Backend Setup
|
|
|
|
- [x] Install dependencies: `nodemailer`, `speakeasy`, `qrcode`
|
|
- [x] Create Session model
|
|
- [x] Update User model with 2FA and email fields
|
|
- [x] Implement email service
|
|
- [x] Add 2FA routes
|
|
- [x] Add session management routes
|
|
- [x] Update auth middleware to track tokens
|
|
- [x] Create sessions on login
|
|
- [x] Update sessions on token refresh
|
|
- [x] Deactivate sessions on logout
|
|
|
|
### Frontend Setup
|
|
|
|
- [x] Create SettingsPage.vue
|
|
- [x] Add Settings route to router
|
|
- [x] Update NavBar with correct Settings link
|
|
- [x] Integrate with auth store
|
|
- [x] Add toast notifications
|
|
- [x] Implement 2FA setup flow
|
|
- [x] Implement session management UI
|
|
|
|
### Environment Variables
|
|
|
|
```bash
|
|
# Email (Required for production)
|
|
SMTP_HOST=smtp.gmail.com
|
|
SMTP_PORT=587
|
|
SMTP_USER=your-email@gmail.com
|
|
SMTP_PASS=your-app-password
|
|
EMAIL_FROM=noreply@turbotrades.com
|
|
|
|
# CORS (Important!)
|
|
CORS_ORIGIN=http://localhost:5173
|
|
|
|
# Cookies
|
|
COOKIE_DOMAIN=localhost
|
|
COOKIE_SECURE=false # true in production
|
|
COOKIE_SAME_SITE=lax
|
|
|
|
# JWT
|
|
JWT_ACCESS_SECRET=your-secret-key
|
|
JWT_REFRESH_SECRET=your-refresh-secret
|
|
```
|
|
|
|
---
|
|
|
|
## Testing
|
|
|
|
### Manual Testing Checklist
|
|
|
|
#### Email Verification
|
|
- [ ] Add email in Settings
|
|
- [ ] Check console/email for verification link
|
|
- [ ] Click verification link
|
|
- [ ] Verify email is marked as verified in UI
|
|
- [ ] Try updating email and re-verifying
|
|
|
|
#### 2FA Setup
|
|
- [ ] Click "Enable 2FA" in Settings
|
|
- [ ] Scan QR code with Google Authenticator
|
|
- [ ] Enter 6-digit code
|
|
- [ ] Verify 2FA is enabled
|
|
- [ ] Save recovery code
|
|
- [ ] Test disabling 2FA with code
|
|
- [ ] Test disabling 2FA with recovery code
|
|
|
|
#### Session Management
|
|
- [ ] Log in and check sessions list
|
|
- [ ] Current session should be marked
|
|
- [ ] Log in from another browser/device
|
|
- [ ] Both sessions should appear
|
|
- [ ] Revoke one session
|
|
- [ ] Verify it disappears from list
|
|
- [ ] Test "Revoke All Other Sessions"
|
|
- [ ] Verify only current session remains
|
|
|
|
---
|
|
|
|
## Troubleshooting
|
|
|
|
### Email Not Sending
|
|
|
|
**Problem**: Emails not being sent
|
|
|
|
**Solutions**:
|
|
1. Check SMTP credentials in `.env`
|
|
2. For Gmail, use an App Password (not regular password)
|
|
3. Check console logs in development mode
|
|
4. Verify SMTP port (587 for TLS, 465 for SSL)
|
|
|
|
### 2FA Code Not Working
|
|
|
|
**Problem**: 6-digit code is rejected
|
|
|
|
**Solutions**:
|
|
1. Check device time is synchronized
|
|
2. Try waiting for next code (codes expire every 30 seconds)
|
|
3. Verify secret was properly saved to user document
|
|
4. Check backend logs for verification errors
|
|
|
|
### Sessions Not Appearing
|
|
|
|
**Problem**: Sessions list is empty
|
|
|
|
**Solutions**:
|
|
1. Verify Session model is imported in auth routes
|
|
2. Check MongoDB connection
|
|
3. Look for session creation errors in backend logs
|
|
4. Verify TTL index is created on `expiresAt` field
|
|
|
|
### Session Not Created on Login
|
|
|
|
**Problem**: Sessions aren't being created when users log in
|
|
|
|
**Solutions**:
|
|
1. Check Session import in `routes/auth.js`
|
|
2. Verify MongoDB is running
|
|
3. Check for errors in session creation try/catch
|
|
4. Ensure token and refreshToken are being saved correctly
|
|
|
|
---
|
|
|
|
## Future Enhancements
|
|
|
|
### Recommended Improvements
|
|
|
|
1. **IP Geolocation**: Integrate with MaxMind GeoIP2 or similar for accurate location tracking
|
|
2. **Email Rate Limiting**: Prevent email spam with rate limits
|
|
3. **2FA Backup Codes**: Generate multiple backup codes instead of one recovery code
|
|
4. **Trusted Devices**: Remember trusted devices to skip 2FA
|
|
5. **Security Events Log**: Log all security-related events (failed logins, password changes, etc.)
|
|
6. **Email Notifications**: Send alerts for suspicious activity
|
|
7. **WebAuthn/FIDO2**: Add hardware key support for passwordless authentication
|
|
8. **SMS 2FA**: Add SMS as a 2FA backup option
|
|
9. **Session Fingerprinting**: Enhanced device fingerprinting for better security
|
|
10. **Account Recovery**: Comprehensive account recovery flow
|
|
|
|
---
|
|
|
|
## Support
|
|
|
|
For issues or questions related to security features:
|
|
|
|
1. Check this documentation
|
|
2. Review backend logs for errors
|
|
3. Check browser console for frontend errors
|
|
4. Verify environment variables are set correctly
|
|
5. Ensure MongoDB is running and accessible
|
|
|
|
---
|
|
|
|
## Changelog
|
|
|
|
### Version 1.0.0 (Current)
|
|
|
|
**Added:**
|
|
- Two-Factor Authentication with QR codes
|
|
- Email verification system
|
|
- Session management and tracking
|
|
- Email service with HTML templates
|
|
- Settings page with security features
|
|
- Recovery codes for 2FA
|
|
- Session revocation capabilities
|
|
|
|
**Security:**
|
|
- HTTP-only cookies for tokens
|
|
- Secure session tracking
|
|
- Device and browser detection
|
|
- IP address logging
|
|
- Automatic session expiration
|
|
|
|
---
|
|
|
|
**Last Updated**: January 2025
|
|
**Author**: TurboTrades Development Team |