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);
+25
View File
@@ -0,0 +1,25 @@
import { describe, it, expect } from 'vitest';
import { RateLimiter } from '$lib/server/rate-limit';
describe('rate-limit', () => {
it('allows requests under the limit', () => {
const limiter = new RateLimiter(3, 60000);
expect(limiter.check('ip1')).toBe(true);
expect(limiter.check('ip1')).toBe(true);
expect(limiter.check('ip1')).toBe(true);
});
it('blocks requests over the limit', () => {
const limiter = new RateLimiter(2, 60000);
expect(limiter.check('ip1')).toBe(true);
expect(limiter.check('ip1')).toBe(true);
expect(limiter.check('ip1')).toBe(false);
});
it('tracks different keys independently', () => {
const limiter = new RateLimiter(1, 60000);
expect(limiter.check('ip1')).toBe(true);
expect(limiter.check('ip2')).toBe(true);
expect(limiter.check('ip1')).toBe(false);
});
});