← back to Watches
SECURITY_IMPLEMENTATION_GUIDE.md
763 lines
# SECURITY IMPLEMENTATION GUIDE
## Omega Watch Price History Platform
This guide walks you through the enterprise-grade security implementation for the Omega Watch Price History platform.
---
## TABLE OF CONTENTS
1. [Quick Start](#quick-start)
2. [Security Features Overview](#security-features-overview)
3. [Configuration](#configuration)
4. [API Authentication](#api-authentication)
5. [GDPR Compliance](#gdpr-compliance)
6. [Testing Security](#testing-security)
7. [Production Deployment](#production-deployment)
8. [Troubleshooting](#troubleshooting)
---
## QUICK START
### 1. Install Dependencies
```bash
cd /root/Projects/watches
npm install
```
### 2. Create Environment File
```bash
cp .env.example .env
nano .env
```
**Minimum required configuration:**
```env
PORT=7600
NODE_ENV=production
JWT_SECRET=your-32-character-secret-key-here
ADMIN_USERNAME=admin
ADMIN_PASSWORD=YourSecurePassword123!
VALID_API_KEYS=api-key-1,api-key-2
```
### 3. Start Secure Server
```bash
# Using Node
node server-secure.js
# Or using PM2 (recommended)
pm2 start server-secure.js --name omega-watches-secure
# View logs
pm2 logs omega-watches-secure
```
### 4. Verify Security
```bash
# Check security status
curl http://45.61.58.125:7600/api/security/status
# Check health
curl http://45.61.58.125:7600/api/health
```
---
## SECURITY FEATURES OVERVIEW
### 🛡️ Authentication & Authorization
- **JWT Authentication** for admin endpoints
- **API Key Authentication** for analytics endpoints
- **WebSocket Authentication** with token validation
- **Session Management** with secure cookies
### 🚦 Rate Limiting
- **General API:** 100 requests per 15 minutes
- **Read Operations:** 200 requests per 15 minutes
- **Write Operations:** 20 requests per 15 minutes
- **Authentication:** 5 attempts per 15 minutes (brute force protection)
### 🔒 Security Headers
- **Content Security Policy (CSP)** - XSS prevention
- **Strict-Transport-Security (HSTS)** - HTTPS enforcement
- **X-Frame-Options** - Clickjacking prevention
- **X-Content-Type-Options** - MIME sniffing prevention
- **Referrer-Policy** - Information leakage prevention
- **Permissions-Policy** - Feature control
### ✅ Input Validation
- **express-validator** on all endpoints
- **Regex patterns** for IDs and queries
- **Length limits** enforced
- **Type checking** (integers, strings, arrays)
- **Sanitization** for XSS and NoSQL injection
### 🇪🇺 GDPR Compliance
- **Cookie Consent Banner** with granular options
- **Privacy Policy Page** with full disclosure
- **Right to Access** (data export)
- **Right to be Forgotten** (data deletion)
- **Data Retention Policies** (auto-cleanup)
- **IP Anonymization** for privacy
### 📊 Security Monitoring
- **Security Event Logging** (10,000 events in memory)
- **Severity Levels** (INFO, WARNING, HIGH, CRITICAL)
- **Real-time Statistics** via admin API
- **Audit Trail** for data access
---
## CONFIGURATION
### Environment Variables
Create `/root/Projects/watches/.env` with the following:
```env
# ========================================
# SERVER CONFIGURATION
# ========================================
PORT=7600
NODE_ENV=production
# ========================================
# SECURITY - JWT AUTHENTICATION
# ========================================
# Generate strong secret:
# openssl rand -base64 32
JWT_SECRET=your-super-secret-jwt-key-minimum-32-characters
JWT_EXPIRY=24h
# ========================================
# ADMIN CREDENTIALS
# ========================================
ADMIN_USERNAME=admin
ADMIN_PASSWORD=SecurePassword123!
# Requirements:
# - Min 12 characters
# - Mixed case (A-Z, a-z)
# - Numbers (0-9)
# - Special characters (!@#$%^&*)
# ========================================
# API KEYS FOR ANALYTICS
# ========================================
# Comma-separated list
# Generate via: POST /api/admin/generate-api-key
VALID_API_KEYS=key1,key2,key3
# ========================================
# CORS CONFIGURATION
# ========================================
ALLOWED_ORIGINS=http://45.61.58.125:7600,https://45.61.58.125:7600
# ========================================
# RATE LIMITING
# ========================================
RATE_LIMIT_WINDOW_MS=900000
RATE_LIMIT_MAX_REQUESTS=100
# ========================================
# SSL/TLS (HTTPS)
# ========================================
# SSL_CERT_PATH=/etc/ssl/certs/omega-watches.crt
# SSL_KEY_PATH=/etc/ssl/private/omega-watches.key
# ========================================
# GDPR COMPLIANCE
# ========================================
DATA_RETENTION_DAYS=90
COOKIE_CONSENT_REQUIRED=true
# ========================================
# BACKUP CONFIGURATION
# ========================================
BACKUP_ENABLED=true
BACKUP_INTERVAL=86400000
BACKUP_RETENTION_DAYS=30
```
### Generating Secure Values
**JWT Secret:**
```bash
openssl rand -base64 32
```
**Admin Password:**
```bash
# Use a password manager or generate:
openssl rand -base64 24
```
**API Keys:**
Use the admin endpoint after login:
```bash
curl -X POST http://45.61.58.125:7600/api/admin/generate-api-key \
-H "Authorization: Bearer YOUR_JWT_TOKEN"
```
---
## API AUTHENTICATION
### JWT Authentication (Admin Endpoints)
#### 1. Login to Get Token
```bash
curl -X POST http://45.61.58.125:7600/api/admin/login \
-H "Content-Type: application/json" \
-d '{
"username": "admin",
"password": "SecurePassword123!"
}'
```
**Response:**
```json
{
"success": true,
"token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
"expiresIn": "24h",
"message": "Authentication successful"
}
```
#### 2. Use Token in Requests
```bash
curl -X POST http://45.61.58.125:7600/api/admin/clear-cache \
-H "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
```
#### 3. JWT-Protected Endpoints
- `POST /api/admin/clear-cache` - Clear server cache
- `GET /api/admin/backup` - Create database backup
- `POST /api/admin/restore` - Restore from backup
- `GET /api/admin/security-logs` - View security logs
- `POST /api/admin/generate-api-key` - Generate new API key
### API Key Authentication (Analytics Endpoints)
#### 1. Generate API Key
```bash
curl -X POST http://45.61.58.125:7600/api/admin/generate-api-key \
-H "Authorization: Bearer YOUR_JWT_TOKEN"
```
**Response:**
```json
{
"success": true,
"apiKey": "a1b2c3d4e5f6...",
"message": "New API key generated. Store securely!",
"usage": "Include in requests as X-API-Key header or apiKey query parameter"
}
```
#### 2. Use API Key in Requests
**Header Method (Recommended):**
```bash
curl http://45.61.58.125:7600/api/analytics/predictions \
-H "X-API-Key: a1b2c3d4e5f6..."
```
**Query Parameter Method:**
```bash
curl "http://45.61.58.125:7600/api/analytics/predictions?apiKey=a1b2c3d4e5f6..."
```
#### 3. API Key-Protected Endpoints
- `GET /api/analytics/predictions` - Price predictions
- `GET /api/analytics/market` - Market analysis
- `GET /api/analytics/statistics` - Statistical insights
### WebSocket Authentication
WebSocket connections require JWT token:
```javascript
// Connect with token
const ws = new WebSocket('ws://45.61.58.125:7600?token=YOUR_JWT_TOKEN');
ws.onopen = () => {
console.log('Connected');
// Subscribe to watch updates
ws.send(JSON.stringify({
type: 'subscribe',
watchId: 'speedmaster-1957'
}));
};
ws.onmessage = (event) => {
const data = JSON.parse(event.data);
console.log('Received:', data);
};
```
---
## GDPR COMPLIANCE
### Cookie Consent Management
#### Frontend Integration
Add the `CookieConsent` component to your React app:
```javascript
// In src/App.jsx
import CookieConsent from './components/CookieConsent';
function App() {
return (
<div>
{/* Your app content */}
<CookieConsent />
</div>
);
}
```
#### Backend API
**Update Consent:**
```bash
curl -X POST http://45.61.58.125:7600/api/gdpr/consent \
-H "Content-Type: application/json" \
-d '{
"preferences": {
"necessary": true,
"analytics": true,
"marketing": false,
"preferences": true
}
}'
```
### User Data Rights
#### Right to Access (Data Export)
```bash
curl http://45.61.58.125:7600/api/gdpr/data-request/USER_ID
```
**Response:** Complete data export in JSON format
#### Right to be Forgotten (Data Deletion)
```bash
curl -X DELETE http://45.61.58.125:7600/api/gdpr/data-deletion/USER_ID
```
**Response:** Confirmation of deletion
#### Privacy Policy
Access at: http://45.61.58.125:7600/privacy-policy.html
Machine-readable version:
```bash
curl http://45.61.58.125:7600/api/privacy-policy
```
### Data Retention
Automatic cleanup runs daily:
| Data Type | Retention | Auto-Delete |
|-----------|-----------|-------------|
| View counts | 90 days | Yes |
| Watchlists | 365 days | Yes |
| Security logs | 90 days | Yes |
| User preferences | 730 days | Yes |
| Anonymous data | 30 days | Yes |
---
## TESTING SECURITY
### 1. Rate Limiting Test
```bash
# Send 200 rapid requests
for i in {1..200}; do
curl http://45.61.58.125:7600/api/health &
done
wait
# Expected: First 100 succeed, rest get HTTP 429
```
### 2. SQL Injection Test
```bash
curl "http://45.61.58.125:7600/api/search?q='; DROP TABLE watches; --"
# Expected: Sanitized input, no execution
```
### 3. XSS Test
```bash
curl -X POST http://45.61.58.125:7600/api/watchlist \
-H "Content-Type: application/json" \
-d '{"userId":"<script>alert(1)</script>","watchId":"test","action":"add"}'
# Expected: Script tags removed
```
### 4. Authentication Test
```bash
# Without token (should fail)
curl -X POST http://45.61.58.125:7600/api/admin/clear-cache
# Expected: HTTP 401 Unauthorized
```
### 5. Security Headers Test
```bash
curl -I http://45.61.58.125:7600/api/health | grep -E "(X-|Content-Security|Strict-Transport)"
# Expected: All security headers present
```
### 6. Brute Force Protection
```bash
# Try 10 failed logins
for i in {1..10}; do
curl -X POST http://45.61.58.125:7600/api/admin/login \
-H "Content-Type: application/json" \
-d '{"username":"admin","password":"wrong"}' &
done
# Expected: Rate limited after 5 attempts
```
---
## PRODUCTION DEPLOYMENT
### Step 1: Server Preparation
```bash
# Update system
sudo apt update && sudo apt upgrade -y
# Install Node.js (if not installed)
curl -fsSL https://deb.nodesource.com/setup_18.x | sudo -E bash -
sudo apt install -y nodejs
# Install PM2
sudo npm install -g pm2
```
### Step 2: SSL/TLS Setup
```bash
# Install Certbot
sudo apt install certbot
# Obtain SSL certificate
sudo certbot certonly --standalone -d yourdomain.com
# Or for nginx
sudo certbot --nginx -d yourdomain.com
```
### Step 3: Firewall Configuration
```bash
# Configure UFW
sudo ufw allow 22/tcp # SSH
sudo ufw allow 80/tcp # HTTP
sudo ufw allow 443/tcp # HTTPS
sudo ufw allow 7600/tcp # App (if direct access needed)
sudo ufw enable
# Configure fail2ban
sudo apt install fail2ban
sudo systemctl enable fail2ban
sudo systemctl start fail2ban
```
### Step 4: Environment Setup
```bash
# Create production .env
cd /root/Projects/watches
nano .env
# Set production values:
NODE_ENV=production
JWT_SECRET=$(openssl rand -base64 32)
ADMIN_PASSWORD=$(openssl rand -base64 24)
```
### Step 5: Start with PM2
```bash
# Start application
pm2 start server-secure.js --name omega-watches
# Save PM2 configuration
pm2 save
# Setup PM2 startup script
pm2 startup systemd
# Follow the instructions displayed
# Configure log rotation
pm2 install pm2-logrotate
```
### Step 6: Monitoring Setup
```bash
# View logs
pm2 logs omega-watches
# Monitor resources
pm2 monit
# Web monitoring (optional)
pm2 plus
```
### Step 7: Automated Backups
Create backup script: `/root/Projects/watches/scripts/backup.sh`
```bash
#!/bin/bash
BACKUP_DIR="/root/Projects/watches/data/backups"
DATE=$(date +%Y%m%d_%H%M%S)
TOKEN="YOUR_ADMIN_JWT_TOKEN"
curl -H "Authorization: Bearer $TOKEN" \
http://localhost:7600/api/admin/backup
# Sync to remote storage (optional)
# rsync -avz $BACKUP_DIR user@backupserver:/backups/
```
Add to crontab:
```bash
crontab -e
# Add line:
0 2 * * * /root/Projects/watches/scripts/backup.sh
```
---
## TROUBLESHOOTING
### Issue: Rate Limit Reached
**Symptoms:** HTTP 429 Too Many Requests
**Solutions:**
1. Wait 15 minutes for reset
2. If legitimate traffic, increase limits in `.env`:
```env
RATE_LIMIT_MAX_REQUESTS=200
```
3. Implement IP whitelisting for known services
### Issue: JWT Token Expired
**Symptoms:** HTTP 403 Forbidden - "Invalid or expired token"
**Solutions:**
1. Login again to get new token:
```bash
curl -X POST http://45.61.58.125:7600/api/admin/login \
-H "Content-Type: application/json" \
-d '{"username":"admin","password":"yourpassword"}'
```
2. Increase token expiry in `.env`:
```env
JWT_EXPIRY=48h
```
### Issue: Validation Errors
**Symptoms:** HTTP 400 - "Validation failed"
**Solutions:**
1. Check input format matches requirements
2. Review validation rules in response
3. Example fix:
```bash
# Wrong (special chars in ID)
curl "http://45.61.58.125:7600/api/watches/watch@123"
# Correct (alphanumeric + hyphen/underscore)
curl "http://45.61.58.125:7600/api/watches/watch-123"
```
### Issue: CORS Errors
**Symptoms:** "Access-Control-Allow-Origin" error in browser
**Solutions:**
1. Add your domain to `.env`:
```env
ALLOWED_ORIGINS=http://yourdomain.com,https://yourdomain.com
```
2. Restart server:
```bash
pm2 restart omega-watches
```
### Issue: WebSocket Connection Failed
**Symptoms:** WebSocket closes immediately after connection
**Solutions:**
1. Ensure JWT token is valid
2. Check token is passed in URL:
```javascript
ws://45.61.58.125:7600?token=YOUR_TOKEN
```
3. Verify token hasn't expired
### Issue: Security Logs Full
**Symptoms:** Old events being dropped
**Solutions:**
1. Increase buffer size in `middleware/security.js`:
```javascript
this.maxEvents = 50000; // Increase from 10000
```
2. Implement external logging service:
```env
SENTRY_DSN=your-sentry-dsn
```
---
## SECURITY BEST PRACTICES
### 1. Credential Management
- ✅ Use strong passwords (min 16 chars, mixed case, numbers, symbols)
- ✅ Rotate JWT secret every 90 days
- ✅ Store credentials in environment variables, never in code
- ✅ Use password manager for admin credentials
- ✅ Enable 2FA when available
### 2. Access Control
- ✅ Follow principle of least privilege
- ✅ Regularly audit API key usage
- ✅ Revoke unused or compromised keys immediately
- ✅ Implement role-based access control (RBAC)
- ✅ Log all admin actions
### 3. Network Security
- ✅ Always use HTTPS in production
- ✅ Configure firewall to allow only necessary ports
- ✅ Implement rate limiting on all endpoints
- ✅ Use VPN for administrative access
- ✅ Keep server OS and packages updated
### 4. Monitoring & Response
- ✅ Monitor security logs daily
- ✅ Set up alerts for critical events
- ✅ Test backup restoration monthly
- ✅ Have incident response plan ready
- ✅ Conduct security audits quarterly
### 5. Data Protection
- ✅ Encrypt data in transit (HTTPS/TLS)
- ✅ Encrypt sensitive data at rest
- ✅ Anonymize IP addresses
- ✅ Implement data retention policies
- ✅ Regular backup with off-site storage
---
## ADDITIONAL RESOURCES
### Documentation
- **API Docs:** http://45.61.58.125:7600/api/docs
- **Privacy Policy:** http://45.61.58.125:7600/privacy-policy.html
- **Security Audit Report:** `/root/Projects/watches/SECURITY_AUDIT_REPORT.md`
### External Resources
- **OWASP Top 10:** https://owasp.org/Top10/
- **GDPR Guide:** https://gdpr.eu/
- **Helmet.js Docs:** https://helmetjs.github.io/
- **Express Validator:** https://express-validator.github.io/
- **JWT Best Practices:** https://tools.ietf.org/html/rfc8725
### Support
- **Security Issues:** Report privately to security team
- **General Support:** Create GitHub issue
- **Data Privacy:** privacy@omegawatches.local
---
## QUICK COMMAND REFERENCE
```bash
# Start server
node server-secure.js
# Start with PM2
pm2 start server-secure.js --name omega-watches
# Admin login
curl -X POST http://45.61.58.125:7600/api/admin/login \
-H "Content-Type: application/json" \
-d '{"username":"admin","password":"yourpassword"}'
# Generate API key
curl -X POST http://45.61.58.125:7600/api/admin/generate-api-key \
-H "Authorization: Bearer YOUR_JWT"
# View security logs
curl http://45.61.58.125:7600/api/admin/security-logs \
-H "Authorization: Bearer YOUR_JWT"
# Security status
curl http://45.61.58.125:7600/api/security/status
# Clear cache
curl -X POST http://45.61.58.125:7600/api/admin/clear-cache \
-H "Authorization: Bearer YOUR_JWT"
# Create backup
curl http://45.61.58.125:7600/api/admin/backup \
-H "Authorization: Bearer YOUR_JWT"
# Test rate limiting
for i in {1..200}; do curl http://45.61.58.125:7600/api/health & done
```
---
**Implementation Guide v1.0**
*Last Updated: November 17, 2024*