|
| 1 | +import { NextResponse } from 'next/server'; |
| 2 | +import type { NextRequest } from 'next/server'; |
| 3 | +import { LRUCache } from 'lru-cache'; |
| 4 | + |
| 5 | +// Configuration for Rate Limiting Limits |
| 6 | +const RATE_LIMITS = { |
| 7 | + auth: 10, // 10 req/min for /api/auth/* |
| 8 | + write: 50, // 50 req/min for POST/PUT/DELETE /api/* |
| 9 | + general: 100, // 100 req/min for GET /api/* |
| 10 | +}; |
| 11 | + |
| 12 | +// Rate limiting cache: max 10,000 IPs, items expire in 1 minute |
| 13 | +const rateLimitCache = new LRUCache<string, { count: number; expiresAt: number }>({ |
| 14 | + max: 10000, |
| 15 | + ttl: 60 * 1000, // 1 minute |
| 16 | +}); |
| 17 | + |
| 18 | +export function middleware(request: NextRequest) { |
| 19 | + const { pathname } = request.nextUrl; |
| 20 | + |
| 21 | + // Extract IP or fallback for key |
| 22 | + const forwardedFor = request.headers.get('x-forwarded-for'); |
| 23 | + let ip = '127.0.0.1'; |
| 24 | + if (forwardedFor) { |
| 25 | + ip = forwardedFor.split(',')[0].trim(); |
| 26 | + } else { |
| 27 | + // Fallback for local dev or when header is missing |
| 28 | + const remoteAddr = request.headers.get('x-real-ip'); |
| 29 | + if (remoteAddr) { |
| 30 | + ip = remoteAddr; |
| 31 | + } |
| 32 | + } |
| 33 | + |
| 34 | + // 0. Whitelist test environments (Playwright E2E) |
| 35 | + if ( |
| 36 | + request.headers.get('x-playwright-test') === 'true' && |
| 37 | + process.env.NODE_ENV !== 'production' |
| 38 | + ) { |
| 39 | + return NextResponse.next(); |
| 40 | + } |
| 41 | + |
| 42 | + // 1. Whitelist Health Check |
| 43 | + if (pathname === '/api/health' || pathname.startsWith('/api/health/')) { |
| 44 | + return NextResponse.next(); |
| 45 | + } |
| 46 | + |
| 47 | + // Determine Rate Limit based on route & method |
| 48 | + let limit = RATE_LIMITS.general; |
| 49 | + |
| 50 | + if (pathname.startsWith('/api/auth/')) { |
| 51 | + limit = RATE_LIMITS.auth; |
| 52 | + } else if (['POST', 'PUT', 'DELETE', 'PATCH'].includes(request.method)) { |
| 53 | + limit = RATE_LIMITS.write; |
| 54 | + } |
| 55 | + |
| 56 | + // Construct Cache Key |
| 57 | + // e.g., '127.0.0.1:/api/auth' (grouping auth limits separately if desired, |
| 58 | + // but let's just do by IP + limit Type to be safe, or just IP. |
| 59 | + // Standard is usually just "IP:auth", "IP:write", "IP:general") |
| 60 | + let limitType = 'general'; |
| 61 | + if (pathname.startsWith('/api/auth/')) { |
| 62 | + limitType = 'auth'; |
| 63 | + } else if (['POST', 'PUT', 'DELETE', 'PATCH'].includes(request.method)) { |
| 64 | + limitType = 'write'; |
| 65 | + } |
| 66 | + |
| 67 | + const cacheKey = `${ip}:${limitType}`; |
| 68 | + |
| 69 | + // Check and update cache |
| 70 | + const now = Date.now(); |
| 71 | + const tokenRecord = rateLimitCache.get(cacheKey) || { count: 0, expiresAt: now + 60000 }; |
| 72 | + |
| 73 | + if (now > tokenRecord.expiresAt) { |
| 74 | + tokenRecord.count = 0; |
| 75 | + tokenRecord.expiresAt = now + 60000; |
| 76 | + } |
| 77 | + |
| 78 | + tokenRecord.count += 1; |
| 79 | + rateLimitCache.set(cacheKey, tokenRecord); |
| 80 | + |
| 81 | + if (tokenRecord.count > limit) { |
| 82 | + // Exceeded limit |
| 83 | + const retryAfter = Math.ceil((tokenRecord.expiresAt - now) / 1000).toString(); |
| 84 | + |
| 85 | + return new NextResponse( |
| 86 | + JSON.stringify({ |
| 87 | + error: 'Too Many Requests', |
| 88 | + message: 'Rate limit exceeded.', |
| 89 | + }), |
| 90 | + { |
| 91 | + status: 429, |
| 92 | + headers: { |
| 93 | + 'Content-Type': 'application/json', |
| 94 | + 'Retry-After': retryAfter, |
| 95 | + 'X-RateLimit-Limit': limit.toString(), |
| 96 | + 'X-RateLimit-Remaining': '0', |
| 97 | + 'X-RateLimit-Reset': tokenRecord.expiresAt.toString(), |
| 98 | + }, |
| 99 | + } |
| 100 | + ); |
| 101 | + } |
| 102 | + |
| 103 | + // Allow Request |
| 104 | + const response = NextResponse.next(); |
| 105 | + response.headers.set('X-RateLimit-Limit', limit.toString()); |
| 106 | + response.headers.set('X-RateLimit-Remaining', (limit - tokenRecord.count).toString()); |
| 107 | + response.headers.set('X-RateLimit-Reset', tokenRecord.expiresAt.toString()); |
| 108 | + |
| 109 | + return response; |
| 110 | +} |
| 111 | + |
| 112 | +// Config ensures middleware only runs on API routes |
| 113 | +export const config = { |
| 114 | + matcher: '/api/:path*', |
| 115 | +}; |
0 commit comments