|
| 1 | +import { |
| 2 | + Injectable, |
| 3 | + CanActivate, |
| 4 | + ExecutionContext, |
| 5 | + HttpException, |
| 6 | + HttpStatus, |
| 7 | + Logger, |
| 8 | +} from '@nestjs/common' |
| 9 | +import { Reflector } from '@nestjs/core' |
| 10 | +import { RATE_LIMIT_KEY, RateLimitOptions } from '../decorators/rate-limit.decorator' |
| 11 | + |
| 12 | +interface RequestRecord { |
| 13 | + count: number |
| 14 | + resetTime: number |
| 15 | +} |
| 16 | + |
| 17 | +@Injectable() |
| 18 | +export class RateLimitGuard implements CanActivate { |
| 19 | + private readonly logger = new Logger(RateLimitGuard.name) |
| 20 | + |
| 21 | + /** Per-key request records keyed by `${routeKey}::${clientKey}` */ |
| 22 | + private readonly hits = new Map<string, RequestRecord>() |
| 23 | + |
| 24 | + /** Periodic cleanup timer (10 minute interval) */ |
| 25 | + private readonly cleanupInterval: ReturnType<typeof setInterval> |
| 26 | + |
| 27 | + constructor(private readonly reflector: Reflector) { |
| 28 | + this.cleanupInterval = setInterval(() => this.cleanup(), 10 * 60 * 1000) |
| 29 | + } |
| 30 | + |
| 31 | + canActivate(context: ExecutionContext): boolean { |
| 32 | + const options = this.reflector.getAllAndOverride<RateLimitOptions>( |
| 33 | + RATE_LIMIT_KEY, |
| 34 | + [context.getHandler(), context.getClass()], |
| 35 | + ) |
| 36 | + |
| 37 | + if (!options) { |
| 38 | + return true // No rate limit configured — allow the request |
| 39 | + } |
| 40 | + |
| 41 | + const request = context.switchToHttp().getRequest() |
| 42 | + const clientKey = this.extractClientKey(request) |
| 43 | + const routeKey = this.getRouteKey(context) |
| 44 | + const mapKey = `${routeKey}::${clientKey}` |
| 45 | + |
| 46 | + const now = Date.now() |
| 47 | + const record = this.hits.get(mapKey) |
| 48 | + |
| 49 | + if (!record || now > record.resetTime) { |
| 50 | + // First request in window or window expired — start a new window |
| 51 | + this.hits.set(mapKey, { |
| 52 | + count: 1, |
| 53 | + resetTime: now + options.windowMs, |
| 54 | + }) |
| 55 | + return true |
| 56 | + } |
| 57 | + |
| 58 | + if (record.count >= options.limit) { |
| 59 | + const retryAfter = Math.ceil((record.resetTime - now) / 1000) |
| 60 | + this.logger.warn( |
| 61 | + `Rate limit exceeded for ${clientKey} on ${routeKey} ` + |
| 62 | + `(${record.count}/${options.limit} in ${options.windowMs / 1000}s)`, |
| 63 | + ) |
| 64 | + throw new HttpException( |
| 65 | + { |
| 66 | + statusCode: HttpStatus.TOO_MANY_REQUESTS, |
| 67 | + message: 'Rate limit exceeded. Please try again later.', |
| 68 | + error: 'Too Many Requests', |
| 69 | + retryAfter, |
| 70 | + }, |
| 71 | + HttpStatus.TOO_MANY_REQUESTS, |
| 72 | + ) |
| 73 | + } |
| 74 | + |
| 75 | + record.count++ |
| 76 | + return true |
| 77 | + } |
| 78 | + |
| 79 | + /** |
| 80 | + * Extract a client identifier from the request. |
| 81 | + * Uses a custom header (X-Forwarded-For), then falls back to remote IP. |
| 82 | + */ |
| 83 | + private extractClientKey(request: Record<string, unknown>): string { |
| 84 | + const headers = request.headers as Record<string, string | string[]> | undefined |
| 85 | + if (headers) { |
| 86 | + const forwarded = headers['x-forwarded-for'] |
| 87 | + if (forwarded) { |
| 88 | + return Array.isArray(forwarded) ? forwarded[0] : forwarded.split(',')[0].trim() |
| 89 | + } |
| 90 | + } |
| 91 | + return (request.ip as string) || 'unknown' |
| 92 | + } |
| 93 | + |
| 94 | + /** Build a unique key for the route handler. */ |
| 95 | + private getRouteKey(context: ExecutionContext): string { |
| 96 | + const handler = context.getHandler() |
| 97 | + const className = context.getClass()?.name || 'Unknown' |
| 98 | + return `${className}.${handler.name}` |
| 99 | + } |
| 100 | + |
| 101 | + /** Remove expired entries to prevent unbounded memory growth. */ |
| 102 | + private cleanup(): void { |
| 103 | + const now = Date.now() |
| 104 | + let cleaned = 0 |
| 105 | + for (const [key, record] of this.hits) { |
| 106 | + if (now > record.resetTime) { |
| 107 | + this.hits.delete(key) |
| 108 | + cleaned++ |
| 109 | + } |
| 110 | + } |
| 111 | + if (cleaned > 0) { |
| 112 | + this.logger.debug(`Rate limit cleanup: removed ${cleaned} expired entries`) |
| 113 | + } |
| 114 | + } |
| 115 | +} |
0 commit comments