|
| 1 | +import { |
| 2 | + Injectable, |
| 3 | + CanActivate, |
| 4 | + ExecutionContext, |
| 5 | + HttpException, |
| 6 | + HttpStatus, |
| 7 | +} from '@nestjs/common'; |
| 8 | +import { Request } from 'express'; |
| 9 | + |
| 10 | +interface RequestWindow { |
| 11 | + count: number; |
| 12 | + windowStart: number; |
| 13 | +} |
| 14 | + |
| 15 | +@Injectable() |
| 16 | +export class ThrottleGuard implements CanActivate { |
| 17 | + private readonly requests = new Map<string, RequestWindow>(); |
| 18 | + private readonly MAX_REQUESTS = 60; |
| 19 | + private readonly TIME_WINDOW_MS = 60_000; |
| 20 | + |
| 21 | + constructor() { |
| 22 | + setInterval(() => { |
| 23 | + const now = Date.now(); |
| 24 | + for (const [ip, window] of this.requests) { |
| 25 | + if (now - window.windowStart > this.TIME_WINDOW_MS) { |
| 26 | + this.requests.delete(ip); |
| 27 | + } |
| 28 | + } |
| 29 | + }, this.TIME_WINDOW_MS).unref(); |
| 30 | + } |
| 31 | + |
| 32 | + canActivate(context: ExecutionContext): boolean { |
| 33 | + const request = context.switchToHttp().getRequest<Request>(); |
| 34 | + const ip = this.extractIP(request); |
| 35 | + const now = Date.now(); |
| 36 | + |
| 37 | + const window = this.requests.get(ip); |
| 38 | + |
| 39 | + if (!window || now - window.windowStart > this.TIME_WINDOW_MS) { |
| 40 | + this.requests.set(ip, { count: 1, windowStart: now }); |
| 41 | + return true; |
| 42 | + } |
| 43 | + |
| 44 | + if (window.count >= this.MAX_REQUESTS) { |
| 45 | + const retryAfter = Math.ceil( |
| 46 | + (window.windowStart + this.TIME_WINDOW_MS - now) / 1000, |
| 47 | + ); |
| 48 | + throw new HttpException( |
| 49 | + { |
| 50 | + statusCode: HttpStatus.TOO_MANY_REQUESTS, |
| 51 | + message: 'Too many requests. Please try again later.', |
| 52 | + retryAfter, |
| 53 | + }, |
| 54 | + HttpStatus.TOO_MANY_REQUESTS, |
| 55 | + { |
| 56 | + cause: { retryAfter }, |
| 57 | + }, |
| 58 | + ); |
| 59 | + } |
| 60 | + |
| 61 | + window.count++; |
| 62 | + return true; |
| 63 | + } |
| 64 | + |
| 65 | + private extractIP(request: Request): string { |
| 66 | + const forwarded = request.headers['x-forwarded-for']; |
| 67 | + if (typeof forwarded === 'string') { |
| 68 | + return forwarded.split(',')[0].trim(); |
| 69 | + } |
| 70 | + return request.ip ?? request.socket.remoteAddress ?? 'unknown'; |
| 71 | + } |
| 72 | +} |
0 commit comments