feat: add in-memory sliding window rate limiter
This commit is contained in:
@@ -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);
|
||||
Reference in New Issue
Block a user