rateLimiter.ts
| 1 | import config from "../config.ts"; |
| 2 | |
| 3 | interface Bucket { |
| 4 | count: number; |
| 5 | resetAt: number; |
| 6 | } |
| 7 | |
| 8 | const buckets = new Map<string, Bucket>(); |
| 9 | |
| 10 | export function checkRateLimit( |
| 11 | ip: string | null, |
| 12 | maxRequests: number, |
| 13 | windowMs: number, |
| 14 | ): boolean { |
| 15 | if (config.RATE_LIMIT_DISABLED || !ip) return true; |
| 16 | const now = Date.now(); |
| 17 | const bucket = buckets.get(ip); |
| 18 | if (!bucket || now > bucket.resetAt) { |
| 19 | buckets.set(ip, { count: 1, resetAt: now + windowMs }); |
| 20 | return true; |
| 21 | } |
| 22 | if (bucket.count >= maxRequests) return false; |
| 23 | bucket.count++; |
| 24 | return true; |
| 25 | } |
| 26 | |
| 27 | export function getClientIp( |
| 28 | request: Request, |
| 29 | server: Bun.Server<unknown> | null, |
| 30 | ): string | null { |
| 31 | if (config.TRUSTED_PROXY) { |
| 32 | return ( |
| 33 | request.headers.get("x-forwarded-for")?.split(",")[0]?.trim() ?? |
| 34 | null |
| 35 | ); |
| 36 | } |
| 37 | return server?.requestIP(request)?.address ?? null; |
| 38 | } |
| 39 |