SPB Git

Repository Public

ratelimit.ts 3.2 KB 64 lines typescript

1/**2 * =============================================================================3 *                  SP BOUCHER | SOFTWARE & RESEARCH4 *             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project          : Chat SPBoucher AI8 * File             : src/lib/auth/ratelimit.ts9 * Module           : lib10 * Repository       : https://git.spboucher.ai/chat-spboucher-ai11 * Project Website  : https://chat.spboucher.ai12 * Created          : 2026-11-1713 * Last Modified    : 2026-11-1714 *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: contact@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 { sql } from "../db";4445/**46 * Fixed-window rate limiter stored in PostgreSQL: shared by every process and unaffected by restarts47 * (the 0.2 limiter lived in process memory and was reset by `pm2 restart`).48 */49export async function hit(bucket: string, limit: number, windowSec: number): Promise<{ limited: boolean; count: number; retryAfterSec: number }> {50  const now = Date.now(); const start = new Date(Math.floor(now / (windowSec * 1000)) * windowSec * 1000);51  const rows = await sql<{ count: number }[]>`INSERT INTO rate_limits (bucket, window_start, count) VALUES (${bucket.slice(0, 200)}, ${start}, 1)52    ON CONFLICT (bucket, window_start) DO UPDATE SET count = rate_limits.count + 1 RETURNING count`;53  const count = rows[0].count;54  if (Math.random() < 0.02) void sql`DELETE FROM rate_limits WHERE window_start < now() - interval '2 days'`.catch(() => {});55  return { limited: count > limit, count, retryAfterSec: Math.max(1, Math.ceil((start.getTime() + windowSec * 1000 - now) / 1000)) };56}5758/** Several limits at once; the first one exceeded wins. Every bucket is counted (no short-circuit) so a flood cannot hide behind one key. */59export async function hitAll(rules: { bucket: string; limit: number; windowSec: number }[]): Promise<{ limited: boolean; retryAfterSec: number; bucket?: string }> {60  const res = await Promise.all(rules.map(r => hit(r.bucket, r.limit, r.windowSec)));61  const i = res.findIndex(r => r.limited);62  return i >= 0 ? { limited: true, retryAfterSec: res[i].retryAfterSec, bucket: rules[i].bucket } : { limited: false, retryAfterSec: 0 };63}64
Files main
Menu

Theme