Repository Public
1/**2 * =============================================================================3 * SP BOUCHER | SOFTWARE & RESEARCH4 * ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project : ORIX App Universe8 * File : src/lib/security/ratelimit.ts9 * Module : lib10 * Repository : https://git.spboucher.ai/orix-spboucher-ai11 * Project Website : https://www.orixlab.dev12 * Created : 2026-11-2113 * Last Modified : 2026-11-2114 *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: support@spboucher.ai23 * Development : dev@spboucher.ai24 * Support : support@spboucher.ai25 * Security/Admin : admin@spboucher.ai26 *27 * Copyright (c) 202628 * Simon-Pierre Boucher29 * All rights reserved where applicable. This file is governed by the30 * applicable project license, copyright notices and relevant law.31 * Existing third-party rights and notices remain unaffected.32 *33 * License : None specified (no license file in this repository)34 *35 * Do not embed credentials, private keys, access tokens,36 * certificates or confidential personal information.37 *38 * =============================================================================39 * END OF SP BOUCHER SOURCE HEADER40 * =============================================================================41 */4243import { ApiError } from "./http";4445type Bucket = { n: number; reset: number };46const g = globalThis as typeof globalThis & { __orixRl?: Map<string, Bucket> };47const buckets = (g.__orixRl ??= new Map());4849/** Fixed-window limiter kept in memory (single process). Throws 429 with Retry-After when exceeded. */50export function rateLimit(scope: string, key: string, max: number, windowSec: number): void {51 const k = `${scope}:${key}`, t = Date.now();52 let b = buckets.get(k);53 if (!b || b.reset <= t) { b = { n: 0, reset: t + windowSec * 1000 }; buckets.set(k, b); }54 if (++b.n > max) throw new ApiError(429, "rate_limited", "Too many requests", { retryAfterSeconds: Math.ceil((b.reset - t) / 1000) });55 if (buckets.size > 20_000) for (const [bk, bv] of buckets) if (bv.reset <= t) buckets.delete(bk);56}57export const resetRateLimits = () => buckets.clear();58