39 lines
1006 B
TypeScript
39 lines
1006 B
TypeScript
// In-memory rate limiter – funktioniert pro Prozess (single Docker container).
|
||
// Erlaubt MAX_ATTEMPTS Versuche pro IP innerhalb WINDOW_MS Millisekunden.
|
||
|
||
const MAX_ATTEMPTS = 10;
|
||
const WINDOW_MS = 15 * 60 * 1000; // 15 Minuten
|
||
|
||
interface Entry {
|
||
count: number;
|
||
resetAt: number;
|
||
}
|
||
|
||
const store = new Map<string, Entry>();
|
||
|
||
// Aufräumen abgelaufener Einträge alle 5 Minuten
|
||
setInterval(() => {
|
||
const now = Date.now();
|
||
for (const [key, entry] of store) {
|
||
if (entry.resetAt < now) store.delete(key);
|
||
}
|
||
}, 5 * 60 * 1000);
|
||
|
||
export function checkRateLimit(ip: string): { allowed: boolean; remainingMs: number } {
|
||
const now = Date.now();
|
||
const entry = store.get(ip);
|
||
|
||
if (!entry || entry.resetAt < now) {
|
||
store.set(ip, { count: 1, resetAt: now + WINDOW_MS });
|
||
return { allowed: true, remainingMs: 0 };
|
||
}
|
||
|
||
entry.count += 1;
|
||
|
||
if (entry.count > MAX_ATTEMPTS) {
|
||
return { allowed: false, remainingMs: entry.resetAt - now };
|
||
}
|
||
|
||
return { allowed: true, remainingMs: 0 };
|
||
}
|