const express = require('express'); const rateLimit = require('express-rate-limit'); const app = express(); const port = 3000; // --- Global Rate Limiter --- // Apply to all requests to prevent brute-force attacks and resource exhaustion. // Limit to 100 requests per 15 minutes per IP address. const globalLimiter = rateLimit({ windowMs: 15 * 60 * 1000, // 15 minutes max: 100, // Limit each IP to 100 requests per windowMs message: 'Too many requests from this IP, please try again after 15 minutes', standardHeaders: true, // Return rate limit info in the `RateLimit-*` headers legacyHeaders: false, // Disable the `X-RateLimit-*` headers }); // --- Stronger Rate Limiter for Login/Sensitive Routes --- // Apply specifically to login attempts to deter brute-force password guessing. // Limit to 5 requests per 5 minutes per IP address. const loginLimiter = rateLimit({ windowMs: 5 * 60 * 1000, // 5 minutes max: 5, // Limit each IP to 5 login requests per windowMs message: 'Too many login attempts from this IP, please try again after 5 minutes', handler: (req, res, next) => { // Customize response for login failures res.status(429).json({ error: 'Too many login attempts. Please try again later.' }); }, keyGenerator: (req) => { // Optionally, use a combination of IP and username for more specific login rate limiting // return req.ip + ':' + req.body.username; // Requires body-parser middleware return req.ip; }, standardHeaders: true, legacyHeaders: false, }); // Apply the global rate limiter to all requests app.use(globalLimiter); // Public route (also covered by globalLimiter) app.get('/', (req, res) => { res.send('Welcome! This endpoint has a global rate limit.'); }); // Login route with a stricter rate limit app.post('/login', loginLimiter, (req, res) => { // In a real application, you would validate credentials here const { username, password } = req.body; console.log(`Login attempt for user: ${username}`); res.send(`Login request received for ${username}. (Credentials not verified)`); }); // Example of another sensitive route app.post('/reset-password', loginLimiter, (req, res) => { // Logic for password reset res.send('Password reset request received.'); }); // Start the server app.listen(port, () => { console.log(`Server listening at http://localhost:${port}`); console.log('Try sending more than 100 requests to / in 15 mins, or 5 requests to /login in 5 mins.'); });