feat: add in-memory sliding window rate limiter

This commit is contained in:
2026-03-26 11:54:51 -05:00
parent af2e48347f
commit c5f1d2c993
2 changed files with 58 additions and 0 deletions
+33
View File
@@ -0,0 +1,33 @@
export class RateLimiter {
private windows = new Map<string, number[]>();
constructor(
private maxRequests: number,
private windowMs: number
) {}
check(key: string): boolean {
const now = Date.now();
const timestamps = this.windows.get(key) ?? [];
const valid = timestamps.filter((t) => now - t < this.windowMs);
if (valid.length >= this.maxRequests) {
this.windows.set(key, valid);
return false;
}
valid.push(now);
this.windows.set(key, valid);
return true;
}
reset(key: string): void {
this.windows.delete(key);
}
}
export const loginLimiter = new RateLimiter(5, 15 * 60 * 1000);
export const registrationLimiter = new RateLimiter(3, 60 * 60 * 1000);
export const apiLimiter = new RateLimiter(60, 60 * 1000);
export const nameGeneratorLimiter = new RateLimiter(10, 5 * 60 * 1000);