chat-dev / server /rateLimiter.js
incognitolm's picture
Initial
5383ef0 verified
raw
history blame contribute delete
667 Bytes
// Simple sliding window rate limiter
const windows = new Map();
export function rateLimiter(key, maxRequests, windowMs) {
const now = Date.now();
if (!windows.has(key)) {
windows.set(key, { count: 1, resetAt: now + windowMs });
return true;
}
const entry = windows.get(key);
if (now > entry.resetAt) {
entry.count = 1;
entry.resetAt = now + windowMs;
return true;
}
if (entry.count >= maxRequests) return false;
entry.count++;
return true;
}
// Cleanup every 5 minutes
setInterval(() => {
const now = Date.now();
for (const [k, v] of windows.entries()) {
if (now > v.resetAt) windows.delete(k);
}
}, 5 * 60 * 1000);