import type { Env } from '../env'; import { hmacHex, now } from './util'; /** Fixed-window counter in D1. Returns true while the caller is within the limit. */ export async function rateLimit(env: Env, key: string, limit: number, windowSec: number): Promise { const window = Math.floor(now() / windowSec); const row = await env.DB.prepare( `INSERT INTO rate_limits (key, window, count) VALUES (?, ?, 1) ON CONFLICT(key, window) DO UPDATE SET count = count + 1 RETURNING count`, ) .bind(`${key}:${windowSec}`, window) .first<{ count: number }>(); return (row?.count ?? 1) <= limit; } export async function pruneRateLimits(env: Env): Promise { // Windows are at most a week long, so anything older than 8 days of hour-windows is dead. await env.DB.prepare(`DELETE FROM rate_limits WHERE (key LIKE '%:60' AND window < ?) OR (key LIKE '%:3600' AND window < ?) OR (key LIKE '%:86400' AND window < ?) OR (key LIKE '%:604800' AND window < ?)`) .bind(Math.floor(now() / 60) - 5, Math.floor(now() / 3600) - 3, Math.floor(now() / 86400) - 2, Math.floor(now() / 604800) - 2) .run(); } /** Rate-limit key for a network address. The address itself is never stored, only a keyed hash. */ export async function ipKey(env: Env, ip: string | undefined): Promise { return (await hmacHex(env.SESSION_SECRET ?? 'skillfarm', `ip|${ip ?? 'local'}`)).slice(0, 24); }