|
| 1 | +import { |
| 2 | + CanActivate, |
| 3 | + ExecutionContext, |
| 4 | + HttpException, |
| 5 | + HttpStatus, |
| 6 | + Injectable, |
| 7 | + SetMetadata, |
| 8 | +} from '@nestjs/common'; |
| 9 | +import { Reflector } from '@nestjs/core'; |
| 10 | +import { RateLimitService } from '../../auth/rate-limit.service'; |
| 11 | + |
| 12 | +export const USERS_ROUTE_LIMIT_KEY = 'users-route-limit'; |
| 13 | + |
| 14 | +export interface UsersRouteLimitOptions { |
| 15 | + /** Requests allowed per caller per window. */ |
| 16 | + max: number; |
| 17 | + windowMs: number; |
| 18 | +} |
| 19 | + |
| 20 | +/** Limit one Users route per authenticated caller. Apply after the JWT guard. */ |
| 21 | +export const UsersRouteLimit = (options: UsersRouteLimitOptions) => |
| 22 | + SetMetadata(USERS_ROUTE_LIMIT_KEY, options); |
| 23 | + |
| 24 | +/** |
| 25 | + * Per-caller rate limit for costly or abusable Users routes. The caller is the |
| 26 | + * authenticated user id (falling back to the client address), and each route has |
| 27 | + * its own counter, so heavy use of one route does not consume another's budget. |
| 28 | + * Over the limit the response is `429` with `Retry-After`. |
| 29 | + */ |
| 30 | +@Injectable() |
| 31 | +export class UsersRouteRateLimitGuard implements CanActivate { |
| 32 | + constructor( |
| 33 | + private readonly reflector: Reflector, |
| 34 | + private readonly rateLimitService: RateLimitService, |
| 35 | + ) {} |
| 36 | + |
| 37 | + async canActivate(context: ExecutionContext): Promise<boolean> { |
| 38 | + const options = this.reflector.get<UsersRouteLimitOptions | undefined>( |
| 39 | + USERS_ROUTE_LIMIT_KEY, |
| 40 | + context.getHandler(), |
| 41 | + ); |
| 42 | + if (!options) return true; |
| 43 | + |
| 44 | + const request = context.switchToHttp().getRequest(); |
| 45 | + const response = context.switchToHttp().getResponse(); |
| 46 | + const route = `${request.method} ${request.route?.path ?? request.url}`; |
| 47 | + const caller = String(request.authUser?.sub ?? request.user?.sub ?? request.ip ?? 'unknown'); |
| 48 | + |
| 49 | + const status = await this.rateLimitService.checkScopedRateLimit( |
| 50 | + `users-route:${route}`, |
| 51 | + caller, |
| 52 | + options.max, |
| 53 | + options.windowMs, |
| 54 | + ); |
| 55 | + |
| 56 | + if (status.isExceeded) { |
| 57 | + if (status.retryAfter !== undefined) response.setHeader('Retry-After', String(status.retryAfter)); |
| 58 | + throw new HttpException( |
| 59 | + { |
| 60 | + statusCode: HttpStatus.TOO_MANY_REQUESTS, |
| 61 | + message: 'Too many requests. Please try again later.', |
| 62 | + retryAfter: status.retryAfter, |
| 63 | + }, |
| 64 | + HttpStatus.TOO_MANY_REQUESTS, |
| 65 | + ); |
| 66 | + } |
| 67 | + return true; |
| 68 | + } |
| 69 | +} |
0 commit comments