/** * FX-1 Secure Backend Server * Advanced Security Implementation * * Features: * - Rate Limiting & DDoS Protection * - Helmet Security Headers * - CORS Protection * - XSS & SQL Injection Prevention * - JWT Authentication with Refresh Tokens * - Request Validation & Sanitization * - Security Logging & Monitoring */ import express from 'express'; import helmet from 'helmet'; import cors from 'cors'; import compression from 'compression'; import cookieParser from 'cookie-parser'; import morgan from 'morgan'; import mongoSanitize from 'express-mongo-sanitize'; import hpp from 'hpp'; import rateLimit from 'express-rate-limit'; import slowDown from 'express-slow-down'; import dotenv from 'dotenv'; import winston from 'winston'; import DailyRotateFile from 'winston-daily-rotate-file'; import { fileURLToPath } from 'url'; import { dirname, join } from 'path'; // Load environment variables const __filename = fileURLToPath(import.meta.url); const __dirname = dirname(__filename); dotenv.config({ path: join(__dirname, '.env') }); // Import routes import authRoutes from './routes/auth.routes.js'; import userRoutes from './routes/user.routes.js'; import modRoutes from './routes/mod.routes.js'; import uploadRoutes from './routes/upload.routes.js'; import adminRoutes from './routes/admin.routes.js'; import securityRoutes from './routes/security.routes.js'; // Import middleware import { errorHandler } from './middleware/error.middleware.js'; import { securityHeaders } from './middleware/security.middleware.js'; import { requestValidator } from './middleware/validation.middleware.js'; import { ipBlocker } from './middleware/ip-blocker.middleware.js'; // Initialize Express app const app = express(); const PORT = process.env.PORT || 5000; const NODE_ENV = process.env.NODE_ENV || 'development'; // ============================================ // SECURITY LOGGER CONFIGURATION // ============================================ const securityLogger = winston.createLogger({ level: 'info', format: winston.format.combine( winston.format.timestamp(), winston.format.errors({ stack: true }), winston.format.json() ), defaultMeta: { service: 'fx1-security' }, transports: [ new winston.transports.Console({ format: winston.format.combine( winston.format.colorize(), winston.format.simple() ) }), new DailyRotateFile({ filename: 'logs/security-%DATE%.log', datePattern: 'YYYY-MM-DD', zippedArchive: true, maxSize: '20m', maxFiles: '14d' }), new DailyRotateFile({ filename: 'logs/error-%DATE%.log', datePattern: 'YYYY-MM-DD', level: 'error', zippedArchive: true, maxSize: '20m', maxFiles: '30d' }) ] }); // ============================================ // SECURITY MIDDLEWARE - ORDER IS CRITICAL // ============================================ // 1. Trust Proxy (for reverse proxy setups) app.set('trust proxy', 1); // 2. Security Headers with Helmet app.use(helmet({ contentSecurityPolicy: { directives: { defaultSrc: ["'self'"], styleSrc: ["'self'", "'unsafe-inline'", "https://fonts.googleapis.com"], scriptSrc: ["'self'", "'unsafe-inline'"], imgSrc: ["'self'", "data:", "https:", "blob:"], connectSrc: ["'self'", process.env.FRONTEND_URL || "http://localhost:5173"], fontSrc: ["'self'", "https://fonts.gstatic.com"], objectSrc: ["'none'"], mediaSrc: ["'self'"], frameSrc: ["'none'"], upgradeInsecureRequests: [], }, }, crossOriginEmbedderPolicy: false, hsts: { maxAge: 31536000, includeSubDomains: true, preload: true }, referrerPolicy: { policy: 'strict-origin-when-cross-origin' }, xContentTypeOptions: true, xFrameOptions: { action: 'deny' }, xXssProtection: true, dnsPrefetchControl: { allow: false }, permittedCrossDomainPolicies: { permittedPolicies: 'none' } })); // 3. Custom Security Headers app.use(securityHeaders); // 4. CORS Configuration const corsOptions = { origin: (origin, callback) => { const allowedOrigins = [ process.env.FRONTEND_URL, 'http://localhost:5173', 'http://localhost:3000', 'https://fx-craft.vercel.app', 'https://fx-1.vercel.app' ].filter(Boolean); if (!origin || allowedOrigins.includes(origin)) { callback(null, true); } else { securityLogger.warn(`CORS blocked request from: ${origin}`); callback(new Error('Not allowed by CORS')); } }, credentials: true, methods: ['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'OPTIONS'], allowedHeaders: [ 'Content-Type', 'Authorization', 'X-Requested-With', 'X-CSRF-Token', 'X-API-Key' ], exposedHeaders: ['X-RateLimit-Limit', 'X-RateLimit-Remaining'], maxAge: 86400 }; app.use(cors(corsOptions)); // 5. Compression app.use(compression({ level: 6, filter: (req, res) => { if (req.headers['x-no-compression']) return false; return compression.filter(req, res); } })); // 6. Body Parsing with Limits app.use(express.json({ limit: '10mb', verify: (req, res, buf) => { req.rawBody = buf; } })); app.use(express.urlencoded({ extended: true, limit: '10mb' })); app.use(cookieParser(process.env.COOKIE_SECRET || 'fx1-secure-cookie-secret')); // 7. Request Logging app.use(morgan('combined', { stream: { write: (message) => securityLogger.info(message.trim()) } })); // 8. IP Blocker (blocks known malicious IPs) app.use(ipBlocker); // 9. Rate Limiting - General API const generalLimiter = rateLimit({ windowMs: 15 * 60 * 1000, // 15 minutes max: 100, // 100 requests per window standardHeaders: true, legacyHeaders: false, message: { success: false, message: 'Too many requests, please try again later', retryAfter: 900 }, handler: (req, res, next, options) => { securityLogger.warn(`Rate limit exceeded for IP: ${req.ip}, Path: ${req.path}`); res.status(429).json(options.message); }, skip: (req) => { // Skip rate limiting for health checks return req.path === '/health'; } }); app.use(generalLimiter); // 10. Speed Limiter - Slow down after repeated requests const speedLimiter = slowDown({ windowMs: 15 * 60 * 1000, delayAfter: 50, delayMs: (hits) => hits * 100, maxDelayMs: 20000 }); app.use(speedLimiter); // 11. Strict Rate Limiting for Auth Routes const authLimiter = rateLimit({ windowMs: 60 * 60 * 1000, // 1 hour max: 10, // 10 attempts per hour skipSuccessfulRequests: true, message: { success: false, message: 'Too many authentication attempts, please try again after 1 hour' }, handler: (req, res, next, options) => { securityLogger.warn(`Auth rate limit exceeded for IP: ${req.ip}`); res.status(429).json(options.message); } }); // 12. Data Sanitization against NoSQL injection app.use(mongoSanitize({ replaceWith: '_', onSanitize: ({ req, key }) => { securityLogger.warn(`Sanitized NoSQL injection attempt: ${key}`, { ip: req.ip, path: req.path, key: key }); } })); // 13. Prevent Parameter Pollution app.use(hpp({ whitelist: ['sort', 'fields', 'page', 'limit'] // Allowed duplicate parameters })); // 14. Request Validation Middleware app.use(requestValidator); // ============================================ // ROUTES // ============================================ // Health Check (no auth required) app.get('/health', (req, res) => { res.status(200).json({ success: true, status: 'healthy', timestamp: new Date().toISOString(), uptime: process.uptime(), environment: NODE_ENV }); }); // API Routes app.use('/api/auth', authLimiter, authRoutes); app.use('/api/users', userRoutes); app.use('/api/mods', modRoutes); app.use('/api/upload', uploadRoutes); app.use('/api/admin', adminRoutes); app.use('/api/security', securityRoutes); // ============================================ // ERROR HANDLING // ============================================ // 404 Handler app.use((req, res) => { securityLogger.warn(`404 - Route not found: ${req.method} ${req.path}`, { ip: req.ip, userAgent: req.headers['user-agent'] }); res.status(404).json({ success: false, message: 'Route not found' }); }); // Global Error Handler app.use(errorHandler); // ============================================ // SERVER STARTUP // ============================================ app.listen(PORT, () => { securityLogger.info(`FX-1 Secure Server running on port ${PORT}`, { environment: NODE_ENV, port: PORT, timestamp: new Date().toISOString() }); console.log(` ╔════════════════════════════════════════════════════════════╗ ║ ║ ║ 🔒 FX-1 SECURE BACKEND SERVER ║ ║ ║ ║ Environment: ${NODE_ENV.padEnd(35)}║ ║ Port: ${PORT.toString().padEnd(44)}║ ║ Security Level: MAXIMUM ║ ║ ║ ║ Features: ║ ║ ✓ DDoS Protection ║ ║ ✓ Rate Limiting ║ ║ ✓ XSS/SQL Injection Prevention ║ ║ ✓ JWT Authentication ║ ║ ✓ Security Headers ║ ║ ✓ Request Validation ║ ║ ║ ╚════════════════════════════════════════════════════════════╝ `); }); // Graceful Shutdown process.on('SIGTERM', () => { securityLogger.info('SIGTERM received, shutting down gracefully'); process.exit(0); }); process.on('SIGINT', () => { securityLogger.info('SIGINT received, shutting down gracefully'); process.exit(0); }); // Uncaught Exception Handler process.on('uncaughtException', (err) => { securityLogger.error('Uncaught Exception', { error: err.message, stack: err.stack }); process.exit(1); }); // Unhandled Rejection Handler process.on('unhandledRejection', (reason, promise) => { securityLogger.error('Unhandled Rejection', { reason, promise }); }); export default app;