|
| 1 | +import { decodeJwt } from "jose"; |
| 2 | + |
| 3 | +const WINDOW_MS = 60_000; // 1-minute window |
| 4 | +const MAX_REQUESTS_PER_PLATFORM = |
| 5 | + Number(process.env.RATE_LIMIT_PER_PLATFORM) || 250; |
| 6 | +const MAX_REQUESTS_PER_IP = Number(process.env.RATE_LIMIT_PER_IP) || 500; |
| 7 | + |
| 8 | +interface RateRecord { |
| 9 | + count: number; |
| 10 | + windowStart: number; |
| 11 | +} |
| 12 | + |
| 13 | +const platformRecords = new Map<string, RateRecord>(); |
| 14 | +const ipRecords = new Map<string, RateRecord>(); |
| 15 | + |
| 16 | +function check( |
| 17 | + map: Map<string, RateRecord>, |
| 18 | + key: string, |
| 19 | + limit: number, |
| 20 | +): { allowed: boolean; retryAfterSeconds: number } { |
| 21 | + const now = Date.now(); |
| 22 | + let rec = map.get(key); |
| 23 | + |
| 24 | + if (!rec || now - rec.windowStart > WINDOW_MS) { |
| 25 | + rec = { count: 0, windowStart: now }; |
| 26 | + map.set(key, rec); |
| 27 | + } |
| 28 | + |
| 29 | + rec.count++; |
| 30 | + |
| 31 | + if (rec.count > limit) { |
| 32 | + const retryAfterSeconds = Math.ceil( |
| 33 | + (rec.windowStart + WINDOW_MS - now) / 1000, |
| 34 | + ); |
| 35 | + return { allowed: false, retryAfterSeconds }; |
| 36 | + } |
| 37 | + |
| 38 | + return { allowed: true, retryAfterSeconds: 0 }; |
| 39 | +} |
| 40 | + |
| 41 | +function extractPlatform(token: string): string | null { |
| 42 | + try { |
| 43 | + const payload = decodeJwt(token); |
| 44 | + return (payload as any).platform ?? null; |
| 45 | + } catch { |
| 46 | + return null; |
| 47 | + } |
| 48 | +} |
| 49 | + |
| 50 | +export function checkGlobalRateLimit( |
| 51 | + token: string | null, |
| 52 | + ip: string, |
| 53 | +): { allowed: boolean; retryAfterSeconds: number } { |
| 54 | + if (token) { |
| 55 | + const platform = extractPlatform(token); |
| 56 | + if (platform) { |
| 57 | + const result = check( |
| 58 | + platformRecords, |
| 59 | + platform, |
| 60 | + MAX_REQUESTS_PER_PLATFORM, |
| 61 | + ); |
| 62 | + if (!result.allowed) return result; |
| 63 | + } |
| 64 | + } |
| 65 | + |
| 66 | + return check(ipRecords, ip, MAX_REQUESTS_PER_IP); |
| 67 | +} |
| 68 | + |
| 69 | +// Periodically clean up stale entries to prevent memory growth |
| 70 | +setInterval(() => { |
| 71 | + const now = Date.now(); |
| 72 | + for (const [key, rec] of platformRecords) { |
| 73 | + if (now - rec.windowStart > WINDOW_MS) platformRecords.delete(key); |
| 74 | + } |
| 75 | + for (const [key, rec] of ipRecords) { |
| 76 | + if (now - rec.windowStart > WINDOW_MS) ipRecords.delete(key); |
| 77 | + } |
| 78 | +}, 60_000); |
0 commit comments