# Security Documentation This document outlines the security measures implemented in the Reading Tracker application and provides recommendations for secure production deployment. ## Implemented Security Measures ### 1. Security Headers (Helmet.js) - **Content Security Policy (CSP)**: Prevents XSS attacks by controlling resource loading - **X-Frame-Options**: Prevents clickjacking attacks - **X-Content-Type-Options**: Prevents MIME type sniffing - **Referrer-Policy**: Controls referrer information sent to other sites - **X-Download-Options**: Prevents file downloads in older IE versions ### 2. Rate Limiting - **General API Rate Limit**: 100 requests per 15 minutes per IP - **Strict POST Rate Limit**: 20 save operations per 15 minutes per IP - **Rate Limit Headers**: Standard headers included for client awareness - **Custom Error Messages**: Clear feedback without revealing system details ### 3. Input Validation & Sanitization - **JSON Size Limit**: Reduced to 1MB to prevent DoS attacks - **Book Data Validation**: - String length limits (200 chars for title/author) - Numeric bounds checking (1-100,000 pages) - Date format validation (YYYY-MM-DD) - Type coercion prevention - **Reading History Sanitization**: Validates date keys and page values - **Array/Object Type Checking**: Prevents malformed data injection ### 4. Error Information Disclosure Prevention - **Generic Error Messages**: No sensitive system information in responses - **Log Message Sanitization**: Only error messages logged, not full error objects - **Health Check Information**: Removed sensitive directory paths from health endpoint ### 5. CORS Configuration - **Production Origins**: Configurable allowed origins via environment variable - **Development Mode**: Unrestricted for local development - **No Credentials**: Disabled credential sharing for security ### 6. Container Security - **Non-root User**: Application runs as 'node' user, not root - **Minimal Base Image**: Alpine Linux for reduced attack surface - **Read-only File System**: Static files served read-only - **Health Checks**: Automated container health monitoring ## Security Configurations ### Environment Variables For production deployment, set these environment variables: ```bash NODE_ENV=production ALLOWED_ORIGINS=https://your-domain.com,https://www.your-domain.com DATA_DIR=/app/data PORT=80 ``` ### Content Security Policy The CSP is configured to allow: - **Self-hosted resources**: Scripts, styles, and images from same origin - **Inline styles**: Required for Tailwind CSS (consider moving to external stylesheet for enhanced security) - **Data URIs**: For inline images and icons - **HTTPS images**: For external image sources ## Recommendations for Enhanced Security ### 1. HTTPS Enforcement (HIGH PRIORITY) ```bash # Use a reverse proxy like Nginx or Traefik with SSL termination # Or deploy behind a cloud load balancer with SSL certificates # Example Nginx configuration: server { listen 443 ssl http2; server_name your-domain.com; ssl_certificate /path/to/cert.pem; ssl_certificate_key /path/to/key.pem; location / { proxy_pass http://reading-tracker:80; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; } } ``` ### 2. Authentication System (HIGH PRIORITY) Consider implementing user authentication for multi-user scenarios: - JWT-based authentication - Session management - User isolation for data access - Password security requirements ### 3. Database Migration (MEDIUM PRIORITY) For production scale, consider migrating from JSON files to a proper database: - PostgreSQL or SQLite for relational data - Proper connection pooling - Query parameterization to prevent SQL injection - Data encryption at rest ### 4. Additional Security Headers ```javascript app.use(helmet({ // Add additional security headers hsts: { maxAge: 31536000, includeSubDomains: true, preload: true } })); ``` ### 5. Request Validation Middleware ```javascript // Consider adding express-validator for more robust validation import { body, validationResult } from 'express-validator'; app.post('/api/books', [ body('*.title').isLength({ min: 1, max: 200 }).trim().escape(), body('*.author').isLength({ min: 1, max: 200 }).trim().escape(), body('*.totalPages').isInt({ min: 1, max: 100000 }), // ... additional validation rules ], (req, res, next) => { const errors = validationResult(req); if (!errors.isEmpty()) { return res.status(400).json({ error: 'Invalid input data' }); } next(); }); ``` ### 6. Logging and Monitoring ```javascript // Add structured logging with winston or similar import winston from 'winston'; const logger = winston.createLogger({ level: 'info', format: winston.format.json(), transports: [ new winston.transports.File({ filename: 'error.log', level: 'error' }), new winston.transports.File({ filename: 'combined.log' }) ] }); // Log security events app.use('/api', (req, res, next) => { logger.info('API request', { method: req.method, url: req.url, ip: req.ip, userAgent: req.get('User-Agent') }); next(); }); ``` ## Security Testing ### Automated Security Scanning ```bash # Install security audit tools npm audit # Use snyk for vulnerability scanning npx snyk test # Docker security scanning docker scan reading-tracker:latest ``` ### Manual Security Testing 1. **XSS Testing**: Try injecting scripts in book titles/authors 2. **CSRF Testing**: Verify CORS policies prevent unauthorized requests 3. **Rate Limit Testing**: Verify rate limits are enforced 4. **Input Validation**: Test with malformed JSON and invalid data types 5. **Path Traversal**: Ensure file access is restricted to intended directories ## Incident Response ### Security Event Monitoring Monitor these events for potential security incidents: - Rate limit violations - Validation errors - Unexpected server errors - Health check failures ### Response Procedures 1. **Immediate**: Block suspicious IP addresses at load balancer level 2. **Investigation**: Review application logs for attack patterns 3. **Recovery**: Restore from known good backup if data integrity is compromised 4. **Post-incident**: Update security measures based on lessons learned ## Compliance Notes ### Data Privacy - No personally identifiable information is collected - Reading data is stored locally per user/session - Consider GDPR compliance if deploying in EU ### Data Retention - JSON files persist indefinitely - Consider implementing data retention policies - Provide data export/deletion capabilities ## Security Contact For security vulnerabilities or concerns, create an issue in the project repository with the "security" label. Do not disclose security vulnerabilities publicly until they have been addressed.