SPB Git

Repository Public

ratelimit.ts 3.5 KB 73 lines typescript

1/**2 * =============================================================================3 *                  SP BOUCHER | INFRASTRUCTURE & AUTOMATION4 *             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project          : MacLustr SMS Gateway8 * File             : backend/src/security/ratelimit.ts9 * Module           : security10 * Repository       : https://git.spboucher.ai/maclustr-sms11 * Project Website  : https://sms.spboucher.ai12 * Created          : 2026-11-3013 * Last Modified    : 2026-11-3014 *15 * Author           : Simon-Pierre Boucher16 * Position         : Professor of Finance17 * Institution      : Université du Québec en Outaouais (UQO)18 * Organization     : SP Boucher19 * Website          : https://spboucher.ai20 * Git              : https://git.spboucher.ai21 *22 * Preferred Contact: admin@spboucher.ai23 * Technical Contact: dev@spboucher.ai24 * Security/Admin   : admin@spboucher.ai25 *26 * Copyright (c) 202627 * Simon-Pierre Boucher28 * All rights reserved where applicable. This file is governed by the29 * applicable project license, copyright notices and relevant law.30 * Existing third-party rights and notices remain unaffected.31 *32 * License          : None specified (no license file in this repository)33 *34 * Do not embed credentials, private keys, access tokens,35 * certificates or confidential personal information.36 *37 * =============================================================================38 * END OF SP BOUCHER SOURCE HEADER39 * =============================================================================40 */4142import { ApiError } from "../util.ts"4344interface Bucket { tokens: number; at: number }45/** Seau à jetons en mémoire (un processus). Les quotas durables (journaliers) sont en base. */46export class RateLimiter {47  private buckets = new Map<string, Bucket>()48  constructor() { setInterval(() => this.sweep(), 60_000).unref() }49  take(key: string, perMinute: number, burst = Math.max(Math.ceil(perMinute / 4), 1)): boolean {50    if (perMinute <= 0) return false51    const now = Date.now(), cap = Math.max(burst, 1)52    const b = this.buckets.get(key) ?? { tokens: cap, at: now }53    b.tokens = Math.min(cap, b.tokens + ((now - b.at) / 60_000) * perMinute)54    b.at = now55    if (b.tokens < 1) { this.buckets.set(key, b); return false }56    b.tokens -= 157    this.buckets.set(key, b)58    return true59  }60  private sweep() { const cut = Date.now() - 600_000; for (const [k, b] of this.buckets) if (b.at < cut) this.buckets.delete(k) }61}62export const limiter = new RateLimiter()63// SMS_RATE_SCALE desserre les limites par adresse IP (tests d'intégration) ; les limites par application ne sont jamais desserrées.64const SCALE = Number(process.env.SMS_RATE_SCALE ?? 1)65export function enforceApp(key: string, perMinute: number) {66  // Rafale : la moitié du débit par minute (au moins 5, jamais plus que le débit lui-même).67  const burst = Math.min(perMinute, Math.max(Math.ceil(perMinute / 2), 5))68  if (!limiter.take(key, perMinute, burst)) throw new ApiError(429, "rate_limited", "limite de débit de l'application atteinte, réessayez plus tard", undefined, Math.max(1, Math.ceil(60 / Math.max(perMinute, 1))))69}70export function enforce(key: string, perMinute: number, burst?: number) {71  if (!limiter.take(key, perMinute * SCALE, burst === undefined ? undefined : burst * SCALE)) throw new ApiError(429, "rate_limited", "trop de requêtes, réessayez plus tard", undefined, Math.max(1, Math.ceil(60 / Math.max(perMinute * SCALE, 1))))72}73
Files main
Menu

Theme