diff --git a/server/src/middleware/rate-limit.ts b/server/src/middleware/rate-limit.ts index 9754305..ce61b01 100644 --- a/server/src/middleware/rate-limit.ts +++ b/server/src/middleware/rate-limit.ts @@ -2,14 +2,22 @@ import type { Context, Next } from 'hono' const isDev = process.env.NODE_ENV !== 'production' +const MAX_MAP_SIZE = 10_000 + const hitCounts = new Map() -// Cleanup stale entries every 5 minutes +// Cleanup stale entries every 5 minutes + evict oldest if over MAX_MAP_SIZE export const cleanupInterval = setInterval(() => { const now = Date.now() for (const [key, entry] of hitCounts) { if (now > entry.resetAt) hitCounts.delete(key) } + // Evict oldest entries from botHitCounts if over limit + if (botHitCounts.size > MAX_MAP_SIZE) { + const sorted = [...botHitCounts.entries()].sort((a, b) => a[1] - b[1]) + const toRemove = sorted.slice(0, botHitCounts.size - MAX_MAP_SIZE) + for (const [key] of toRemove) botHitCounts.delete(key) + } }, 5 * 60 * 1000) export function rateLimit(windowMs: number, maxHits: number) {