|
| 1 | +import { Elysia } from "elysia"; |
| 2 | + |
| 3 | +interface RateLimitConfig { |
| 4 | + /** |
| 5 | + * Maximum number of requests allowed within the duration window |
| 6 | + */ |
| 7 | + max: number; |
| 8 | + |
| 9 | + /** |
| 10 | + * Time window in milliseconds |
| 11 | + */ |
| 12 | + duration: number; |
| 13 | + |
| 14 | + /** |
| 15 | + * Optional custom key generator function |
| 16 | + * Defaults to using IP address |
| 17 | + */ |
| 18 | + generator?: (context: { |
| 19 | + request: Request; |
| 20 | + headers: Record<string, string | undefined>; |
| 21 | + }) => string; |
| 22 | + |
| 23 | + /** |
| 24 | + * Error message when rate limit is exceeded |
| 25 | + */ |
| 26 | + message?: string; |
| 27 | + |
| 28 | + /** |
| 29 | + * Skip rate limiting based on custom logic |
| 30 | + */ |
| 31 | + skip?: (context: { request: Request }) => boolean; |
| 32 | +} |
| 33 | + |
| 34 | +interface RateLimitEntry { |
| 35 | + count: number; |
| 36 | + resetTime: number; |
| 37 | +} |
| 38 | + |
| 39 | +class RateLimiter { |
| 40 | + private store: Map<string, RateLimitEntry> = new Map(); |
| 41 | + private cleanupInterval: Timer; |
| 42 | + |
| 43 | + constructor() { |
| 44 | + // Clean up expired entries every minute |
| 45 | + this.cleanupInterval = setInterval(() => { |
| 46 | + const now = Date.now(); |
| 47 | + for (const [key, entry] of this.store.entries()) { |
| 48 | + if (entry.resetTime < now) { |
| 49 | + this.store.delete(key); |
| 50 | + } |
| 51 | + } |
| 52 | + }, 60000); |
| 53 | + } |
| 54 | + |
| 55 | + public check( |
| 56 | + key: string, |
| 57 | + max: number, |
| 58 | + duration: number |
| 59 | + ): { allowed: boolean; remaining: number; resetTime: number } { |
| 60 | + const now = Date.now(); |
| 61 | + const entry = this.store.get(key); |
| 62 | + |
| 63 | + // No existing entry or entry has expired |
| 64 | + if (!entry || entry.resetTime < now) { |
| 65 | + const resetTime = now + duration; |
| 66 | + this.store.set(key, { count: 1, resetTime }); |
| 67 | + return { |
| 68 | + allowed: true, |
| 69 | + remaining: max - 1, |
| 70 | + resetTime, |
| 71 | + }; |
| 72 | + } |
| 73 | + |
| 74 | + // Increment count and check if limit exceeded |
| 75 | + entry.count++; |
| 76 | + this.store.set(key, entry); |
| 77 | + |
| 78 | + return { |
| 79 | + allowed: entry.count <= max, |
| 80 | + remaining: Math.max(0, max - entry.count), |
| 81 | + resetTime: entry.resetTime, |
| 82 | + }; |
| 83 | + } |
| 84 | + |
| 85 | + public destroy() { |
| 86 | + clearInterval(this.cleanupInterval); |
| 87 | + this.store.clear(); |
| 88 | + } |
| 89 | +} |
| 90 | + |
| 91 | +// Global rate limiter instance |
| 92 | +const rateLimiter = new RateLimiter(); |
| 93 | + |
| 94 | +/** |
| 95 | + * Rate limiting middleware for Elysia |
| 96 | + * |
| 97 | + * @example |
| 98 | + * ```ts |
| 99 | + * app.use(rateLimit({ |
| 100 | + * max: 5, // 5 requests |
| 101 | + * duration: 60000, // per minute |
| 102 | + * })) |
| 103 | + * ``` |
| 104 | + */ |
| 105 | +export function rateLimit(config: RateLimitConfig) { |
| 106 | + const { max, duration, generator, message, skip } = config; |
| 107 | + |
| 108 | + return new Elysia({ name: "rate-limit" }).onBeforeHandle(({ request, set, headers }) => { |
| 109 | + // Skip rate limiting if custom skip function returns true |
| 110 | + if (skip && skip({ request })) { |
| 111 | + return; |
| 112 | + } |
| 113 | + |
| 114 | + // Generate unique key for this client |
| 115 | + const key = generator ? generator({ request, headers }) : getClientIdentifier(request, headers); |
| 116 | + |
| 117 | + // Check rate limit |
| 118 | + const result = rateLimiter.check(key, max, duration); |
| 119 | + |
| 120 | + // Set rate limit headers |
| 121 | + set.headers["X-RateLimit-Limit"] = max.toString(); |
| 122 | + set.headers["X-RateLimit-Remaining"] = result.remaining.toString(); |
| 123 | + set.headers["X-RateLimit-Reset"] = new Date(result.resetTime).toISOString(); |
| 124 | + |
| 125 | + // If limit exceeded, return 429 Too Many Requests |
| 126 | + if (!result.allowed) { |
| 127 | + set.status = 429; |
| 128 | + const retryAfter = Math.ceil((result.resetTime - Date.now()) / 1000); |
| 129 | + set.headers["Retry-After"] = retryAfter.toString(); |
| 130 | + |
| 131 | + throw new Error(message || `Too many requests. Please try again in ${retryAfter} seconds.`); |
| 132 | + } |
| 133 | + }); |
| 134 | +} |
| 135 | + |
| 136 | +/** |
| 137 | + * Get client identifier from request |
| 138 | + * Tries to use IP address from various headers, falls back to random identifier |
| 139 | + */ |
| 140 | +function getClientIdentifier( |
| 141 | + request: Request, |
| 142 | + headers: Record<string, string | undefined> |
| 143 | +): string { |
| 144 | + // Try to get IP from common headers |
| 145 | + const forwardedFor = headers["x-forwarded-for"]; |
| 146 | + if (forwardedFor) { |
| 147 | + return forwardedFor.split(",")[0]?.trim() || "unknown"; |
| 148 | + } |
| 149 | + |
| 150 | + const realIp = headers["x-real-ip"]; |
| 151 | + if (realIp) { |
| 152 | + return realIp; |
| 153 | + } |
| 154 | + |
| 155 | + const cfConnectingIp = headers["cf-connecting-ip"]; |
| 156 | + if (cfConnectingIp) { |
| 157 | + return cfConnectingIp; |
| 158 | + } |
| 159 | + |
| 160 | + // Fallback to URL+User-Agent combo if no IP available |
| 161 | + const userAgent = headers["user-agent"] || "unknown"; |
| 162 | + return `${request.url}-${userAgent}`; |
| 163 | +} |
| 164 | + |
| 165 | +/** |
| 166 | + * Predefined rate limit configurations |
| 167 | + */ |
| 168 | +export const rateLimitPresets = { |
| 169 | + /** |
| 170 | + * Strict rate limit for sensitive operations (auth, password reset, etc.) |
| 171 | + * 5 requests per minute |
| 172 | + */ |
| 173 | + strict: { max: 5, duration: 60000 }, |
| 174 | + |
| 175 | + /** |
| 176 | + * Moderate rate limit for API endpoints |
| 177 | + * 30 requests per minute |
| 178 | + */ |
| 179 | + moderate: { max: 30, duration: 60000 }, |
| 180 | + |
| 181 | + /** |
| 182 | + * Relaxed rate limit for public endpoints |
| 183 | + * 100 requests per minute |
| 184 | + */ |
| 185 | + relaxed: { max: 100, duration: 60000 }, |
| 186 | +}; |
0 commit comments