customer/src/modules/accounts/rate-limit.ts
Peppa 4acc7f5ea6
All checks were successful
peppa/lint lint: success за 0с
peppa/typecheck typecheck: success за 1с
peppa/test test: success за 14с
peppa/build build: success за 1с
ci / checks (pull_request) Successful in 25s
deploy / deploy (pull_request) Successful in 3s
CLT-2: Postgres, миграции, учётные записи, сессии, CSRF, rate-limit, удаление аккаунта
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-15 13:24:05 +05:00

35 lines
1.0 KiB
TypeScript

/** Счётчики в памяти процесса: окно windowMs, ключи не пишутся ни в БД, ни в логи. */
export class RateLimiter {
private readonly hits = new Map<string, number[]>();
private readonly max: number;
private readonly windowMs: number;
private readonly now: () => number;
constructor(max: number, windowMs = 15 * 60 * 1000, now: () => number = Date.now) {
this.max = max;
this.windowMs = windowMs;
this.now = now;
}
private recent(key: string): number[] {
const cutoff = this.now() - this.windowMs;
const list = (this.hits.get(key) ?? []).filter((t) => t > cutoff);
if (list.length) this.hits.set(key, list);
else this.hits.delete(key);
return list;
}
/** true, если лимит уже исчерпан. */
blocked(key: string): boolean {
return this.recent(key).length >= this.max;
}
hit(key: string): void {
this.hits.set(key, [...this.recent(key), this.now()]);
}
reset(key: string): void {
this.hits.delete(key);
}
}