UNPKG

@paroicms/server

Version:
37 lines 1.15 kB
import { ApiError } from "@paroicms/public-server-lib"; const rateLimitMap = new Map(); const INITIAL_LIMIT = 50; const WINDOW_LIMIT = 10; const WINDOW_DURATION = 30000; setInterval(() => { const now = Date.now(); const expiredThreshold = now - WINDOW_DURATION * 2; for (const [sessionId, entry] of rateLimitMap.entries()) { if (entry.windowStart < expiredThreshold) { rateLimitMap.delete(sessionId); } } }, WINDOW_DURATION * 3).unref(); export function checkRateLimit(sessionId) { const now = Date.now(); const entry = rateLimitMap.get(sessionId); if (!entry) { rateLimitMap.set(sessionId, { count: 1, windowStart: now }); return; } if (entry.count < INITIAL_LIMIT) { ++entry.count; return; } const timeSinceWindowStart = now - entry.windowStart; if (timeSinceWindowStart >= WINDOW_DURATION) { entry.count = 1; entry.windowStart = now; return; } if (entry.count >= WINDOW_LIMIT) { throw new ApiError("Rate limit exceeded", 400); } ++entry.count; } //# sourceMappingURL=naive-rate-limiter.js.map