Skillfarm / website · skillfarm.ai / src / lib / ratelimit.ts
| 1 | import type { Env } from '../env'; |
| 2 | import { hmacHex, now } from './util'; |
| 3 | |
| 4 | /** Fixed-window counter in D1. Returns true while the caller is within the limit. */ |
| 5 | export async function rateLimit(env: Env, key: string, limit: number, windowSec: number): Promise<boolean> { |
| 6 | const window = Math.floor(now() / windowSec); |
| 7 | const row = await env.DB.prepare( |
| 8 | `INSERT INTO rate_limits (key, window, count) VALUES (?, ?, 1) |
| 9 | ON CONFLICT(key, window) DO UPDATE SET count = count + 1 RETURNING count`, |
| 10 | ) |
| 11 | .bind(`${key}:${windowSec}`, window) |
| 12 | .first<{ count: number }>(); |
| 13 | return (row?.count ?? 1) <= limit; |
| 14 | } |
| 15 | |
| 16 | export async function pruneRateLimits(env: Env): Promise<void> { |
| 17 | // Windows are at most a week long, so anything older than 8 days of hour-windows is dead. |
| 18 | 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 < ?)`) |
| 19 | .bind(Math.floor(now() / 60) - 5, Math.floor(now() / 3600) - 3, Math.floor(now() / 86400) - 2, Math.floor(now() / 604800) - 2) |
| 20 | .run(); |
| 21 | } |
| 22 | |
| 23 | /** Rate-limit key for a network address. The address itself is never stored, only a keyed hash. */ |
| 24 | export async function ipKey(env: Env, ip: string | undefined): Promise<string> { |
| 25 | return (await hmacHex(env.SESSION_SECRET ?? 'skillfarm', `ip|${ip ?? 'local'}`)).slice(0, 24); |
| 26 | } |