neireva-contact/lib/rateLimit.ts

21 lines
658 B
TypeScript

// In-memory rate limiter: 5 submissions per IP per hour.
// Adequate for a single-instance, time-boxed deployment. If this ever runs on
// multiple instances it would need a shared store (Redis); not needed here.
const WINDOW_MS = 60 * 60 * 1000;
const MAX_PER_WINDOW = 5;
const hits = new Map<string, number[]>();
export function rateLimit(ip: string): { allowed: boolean } {
const now = Date.now();
const recent = (hits.get(ip) ?? []).filter((t) => now - t < WINDOW_MS);
if (recent.length >= MAX_PER_WINDOW) {
hits.set(ip, recent);
return { allowed: false };
}
recent.push(now);
hits.set(ip, recent);
return { allowed: true };
}