|
| 1 | +/** |
| 2 | + * Minimal in-memory fixed-window rate limiter, shared by the unauthenticated |
| 3 | + * `/api/logs` ingest endpoints (browser + anonymous CLI). Per-instance and |
| 4 | + * best-effort — good enough to blunt abuse/cost on a single Render instance, |
| 5 | + * not a distributed guarantee. Kept dependency-free and `now`-injectable so the |
| 6 | + * window logic is unit-testable. |
| 7 | + */ |
| 8 | +export interface FixedWindowRateLimiter { |
| 9 | + /** Returns true if `key` has exceeded the window's request budget. */ |
| 10 | + limited(key: string, now: number): boolean |
| 11 | +} |
| 12 | + |
| 13 | +export function createFixedWindowRateLimiter(opts: { |
| 14 | + windowMs: number |
| 15 | + max: number |
| 16 | + /** Prune expired entries once the map grows past this. Defaults to 10k. */ |
| 17 | + maxKeys?: number |
| 18 | +}): FixedWindowRateLimiter { |
| 19 | + const { windowMs, max, maxKeys = 10_000 } = opts |
| 20 | + const hits = new Map<string, { count: number; resetAt: number }>() |
| 21 | + let lastPruneAt = 0 |
| 22 | + |
| 23 | + return { |
| 24 | + limited(key: string, now: number): boolean { |
| 25 | + const entry = hits.get(key) |
| 26 | + if (!entry || now >= entry.resetAt) { |
| 27 | + hits.set(key, { count: 1, resetAt: now + windowMs }) |
| 28 | + // Bound map growth: prune expired entries, but at most once per window |
| 29 | + // so a steady stream of live keys can't trigger an O(n) scan per call. |
| 30 | + if (hits.size > maxKeys && now - lastPruneAt >= windowMs) { |
| 31 | + lastPruneAt = now |
| 32 | + for (const [k, v] of hits) if (now >= v.resetAt) hits.delete(k) |
| 33 | + } |
| 34 | + return false |
| 35 | + } |
| 36 | + entry.count++ |
| 37 | + return entry.count > max |
| 38 | + }, |
| 39 | + } |
| 40 | +} |
| 41 | + |
| 42 | +/** |
| 43 | + * Best-effort client IP for per-IP rate limiting on the unauthenticated ingest |
| 44 | + * endpoints. Prefers the proxy-set `x-real-ip` (harder to spoof than the |
| 45 | + * left-most `x-forwarded-for` token). Accepts any Headers-like object so it |
| 46 | + * works with `NextRequest.headers` without a Next dependency here. |
| 47 | + */ |
| 48 | +export function extractClientIp(headers: { |
| 49 | + get(name: string): string | null |
| 50 | +}): string { |
| 51 | + return ( |
| 52 | + headers.get('x-real-ip')?.trim() || |
| 53 | + headers.get('x-forwarded-for')?.split(',')[0]?.trim() || |
| 54 | + 'unknown' |
| 55 | + ) |
| 56 | +} |
0 commit comments