← back to Wine Finder Next

SECURITY.md

230 lines

# Security Implementation

## 🔒 Security Features Implemented

### 1. **HTTP Security Headers** (middleware.ts)
- ✅ Strict-Transport-Security (HSTS)
- ✅ X-Frame-Options (Clickjacking protection)
- ✅ X-Content-Type-Options (MIME sniffing protection)
- ✅ X-XSS-Protection
- ✅ Content-Security-Policy (CSP)
- ✅ Permissions-Policy
- ✅ Referrer-Policy

### 2. **Rate Limiting** (lib/rateLimit.ts)
- ✅ IP-based rate limiting
- ✅ Endpoint-specific limits:
  - Voting: 10 requests/minute
  - Marketplace: 20 requests/minute
  - General API: 60 requests/minute
- ✅ Rate limit headers in responses
- ✅ Automatic cleanup of expired entries

### 3. **Input Validation** (lib/inputValidation.ts)
- ✅ ID format validation (bottle, vote, user, membership unit)
- ✅ Email validation
- ✅ Price validation (range checks, finite numbers)
- ✅ Quantity validation
- ✅ Shipping address validation
- ✅ Input sanitization (XSS prevention)
- ✅ SQL injection prevention
- ✅ HTML escaping

### 4. **Authentication & Authorization** (lib/auth.ts)
- ✅ Password hashing (PBKDF2 with salt)
- ✅ Password strength requirements:
  - Minimum 12 characters
  - Special character required
  - Number required
  - Uppercase required
  - Lowercase required
- ✅ Session management
- ✅ CSRF token generation/validation
- ✅ Audit logging
- ✅ Admin user initialization

### 5. **Audit Logging**
All critical actions are logged:
- Vote casting
- Marketplace purchases
- Authentication attempts
- Rate limit violations
- Invalid input attempts

### 6. **API Security**
- ✅ Input sanitization on all endpoints
- ✅ Request validation
- ✅ Error handling (no sensitive data in errors)
- ✅ Rate limit headers
- ✅ Proper HTTP status codes

---

## 🚨 Security Best Practices

### Environment Variables
```bash
# Add to .env file
JWT_SECRET=your-secret-key-change-this-in-production
ADMIN_EMAIL=admin@yourdomain.com
ADMIN_PASSWORD=SecurePassword2025!@#$
```

### Password Requirements
- Minimum 12 characters
- Must include: uppercase, lowercase, number, special character
- No common passwords
- No personal information

### Rate Limits
```
Voting:      10 requests/minute
Marketplace: 20 requests/minute
General API: 60 requests/minute
```

### HTTPS Only
- Force HTTPS in production
- HSTS enabled (2 years)
- Secure cookies only

---

## 🛡️ Threat Mitigation

### Protected Against:
1. **SQL Injection** - Parameterized queries, input validation
2. **XSS (Cross-Site Scripting)** - Input sanitization, CSP headers
3. **CSRF** - Token validation
4. **Clickjacking** - X-Frame-Options header
5. **MIME Sniffing** - X-Content-Type-Options header
6. **DDoS** - Rate limiting
7. **Brute Force** - Rate limiting, account lockout
8. **Session Hijacking** - Secure session management
9. **Man-in-the-Middle** - HSTS, secure cookies

### NOT Yet Implemented (Production TODO):
- [ ] Database encryption at rest
- [ ] 2FA (Two-Factor Authentication)
- [ ] OAuth2/OpenID Connect
- [ ] Web Application Firewall (WAF)
- [ ] DDoS protection service (Cloudflare, etc.)
- [ ] Security scanning (OWASP ZAP, etc.)
- [ ] Penetration testing
- [ ] Bug bounty program

---

## 📋 Security Checklist for Production

### Pre-Deployment:
- [ ] Change all default passwords
- [ ] Set strong JWT_SECRET
- [ ] Enable HTTPS only
- [ ] Configure database backups
- [ ] Set up monitoring/alerting
- [ ] Review and test all endpoints
- [ ] Run security scanner
- [ ] Update dependencies

### Post-Deployment:
- [ ] Monitor audit logs
- [ ] Review rate limit violations
- [ ] Check for suspicious activity
- [ ] Regular security updates
- [ ] Periodic security audits

---

## 🔐 API Request Examples with Security

### Casting a Vote (with rate limiting)
```bash
curl -X POST http://45.61.58.125:7250/api/membership/votes/VOTE_ID/cast \
  -H "Content-Type: application/json" \
  -d '{
    "userId": "user_1",
    "membershipUnitId": "unit_123_abc",
    "choice": "for"
  }'

# Response includes rate limit headers:
# X-RateLimit-Limit: 10
# X-RateLimit-Remaining: 9
# X-RateLimit-Reset: 2025-11-15T20:00:00Z
```

### Rate Limit Exceeded Response
```json
{
  "success": false,
  "error": "Rate limit exceeded. Please try again later."
}
```

---

## 📊 Audit Log Example

```json
{
  "id": "abc123...",
  "userId": "user_1",
  "action": "VOTE_CAST",
  "resource": "vote/vote_123_xyz",
  "ipAddress": "192.168.1.1",
  "userAgent": "Mozilla/5.0...",
  "timestamp": "2025-11-15T19:30:00Z",
  "success": true,
  "metadata": {
    "membershipUnitId": "unit_123_abc",
    "choice": "for"
  }
}
```

---

## 🚀 Security Headers Response Example

```
Strict-Transport-Security: max-age=63072000; includeSubDomains; preload
X-Frame-Options: SAMEORIGIN
X-Content-Type-Options: nosniff
X-XSS-Protection: 1; mode=block
Content-Security-Policy: default-src 'self'; script-src 'self' 'unsafe-inline'...
Permissions-Policy: camera=(), microphone=(), geolocation=()
Referrer-Policy: origin-when-cross-origin
```

---

## 🔧 Monitoring Security

### Check Audit Logs
```bash
# View recent audit logs
pm2 logs wine-finder-next --lines 100 | grep AUDIT
```

### Monitor Rate Limits
```bash
# Check for rate limit violations
pm2 logs wine-finder-next --lines 100 | grep RATE_LIMIT_EXCEEDED
```

---

## 📞 Security Contacts

For security issues:
1. DO NOT open public GitHub issues
2. Email security concerns privately
3. Include detailed reproduction steps
4. Allow 90 days for responsible disclosure

---

**Last Updated**: 2025-11-15
**Security Review Required**: Every 90 days