15 KiB
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
- Two-Factor Authentication (2FA)
- Email Verification
- Session Management
- Email Service
- API Endpoints
- 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
- User clicks "Enable 2FA" in Settings
- Backend generates a secret key and QR code
- User scans QR code with authenticator app (Google Authenticator, Authy, etc.)
- User enters 6-digit code from app to verify setup
- Backend enables 2FA and sends confirmation email with recovery code
- 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):
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
- User enters email address in Settings
- Backend generates unique verification token
- Backend sends verification email with link
- User clicks link in email
- Backend verifies token and marks email as verified
- 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):
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
{
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
- Creation: Session created on Steam login
- Activity: Updated when token is refreshed
- Expiration: Automatically deleted after 7 days via MongoDB TTL index
- Revocation: User can manually revoke sessions
- 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:
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
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:
-
Email Section
- Display current email and verification status
- Add/change email modal
- Visual indicators for verified/unverified status
-
2FA Section
- Enable/disable 2FA button
- QR code display modal
- 6-digit code input
- Recovery code display and warning
- Step-by-step setup instructions
-
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 emailverifyEmail(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
- Enable 2FA: Always enable 2FA for maximum account security
- Save Recovery Code: Store recovery code in a password manager or secure location
- Verify Email: Verify your email to receive security alerts
- Monitor Sessions: Regularly check active sessions and revoke unknown devices
- Use Strong Passwords: (for Steam account)
For Developers
- Never Log Secrets: 2FA secrets should never be logged or exposed
- Secure Cookie Settings: Use
httpOnly,secure, andsameSiteflags - Rate Limiting: Implement rate limiting on 2FA verification attempts
- Token Expiration: Enforce short-lived access tokens (15 minutes)
- Session Cleanup: Use MongoDB TTL indexes to auto-delete expired sessions
- Email Validation: Validate and sanitize email inputs
- HTTPS Only: Always use HTTPS in production
- IP Geolocation: Consider integrating IP geolocation service for better session tracking
Configuration Checklist
Backend Setup
- Install dependencies:
nodemailer,speakeasy,qrcode - Create Session model
- Update User model with 2FA and email fields
- Implement email service
- Add 2FA routes
- Add session management routes
- Update auth middleware to track tokens
- Create sessions on login
- Update sessions on token refresh
- Deactivate sessions on logout
Frontend Setup
- Create SettingsPage.vue
- Add Settings route to router
- Update NavBar with correct Settings link
- Integrate with auth store
- Add toast notifications
- Implement 2FA setup flow
- Implement session management UI
Environment Variables
# 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:
- Check SMTP credentials in
.env - For Gmail, use an App Password (not regular password)
- Check console logs in development mode
- Verify SMTP port (587 for TLS, 465 for SSL)
2FA Code Not Working
Problem: 6-digit code is rejected
Solutions:
- Check device time is synchronized
- Try waiting for next code (codes expire every 30 seconds)
- Verify secret was properly saved to user document
- Check backend logs for verification errors
Sessions Not Appearing
Problem: Sessions list is empty
Solutions:
- Verify Session model is imported in auth routes
- Check MongoDB connection
- Look for session creation errors in backend logs
- Verify TTL index is created on
expiresAtfield
Session Not Created on Login
Problem: Sessions aren't being created when users log in
Solutions:
- Check Session import in
routes/auth.js - Verify MongoDB is running
- Check for errors in session creation try/catch
- Ensure token and refreshToken are being saved correctly
Future Enhancements
Recommended Improvements
- IP Geolocation: Integrate with MaxMind GeoIP2 or similar for accurate location tracking
- Email Rate Limiting: Prevent email spam with rate limits
- 2FA Backup Codes: Generate multiple backup codes instead of one recovery code
- Trusted Devices: Remember trusted devices to skip 2FA
- Security Events Log: Log all security-related events (failed logins, password changes, etc.)
- Email Notifications: Send alerts for suspicious activity
- WebAuthn/FIDO2: Add hardware key support for passwordless authentication
- SMS 2FA: Add SMS as a 2FA backup option
- Session Fingerprinting: Enhanced device fingerprinting for better security
- Account Recovery: Comprehensive account recovery flow
Support
For issues or questions related to security features:
- Check this documentation
- Review backend logs for errors
- Check browser console for frontend errors
- Verify environment variables are set correctly
- 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