import { beforeEach, describe, expect, mock, test } from "bun:test"; const env: Record = { PUBLIC_URL: "https://forge.example.com" }; mock.module("cloudflare:workers", () => ({ env })); mock.module("@tanstack/react-start/server", () => ({ getRequestHeader: () => null })); const hits = new Map(); const deletes: number[] = []; mock.module("./db", () => ({ first: async (_sql: string, key: string, window: number) => { const id = `${key}@${window}`; const next = (hits.get(id) ?? 0) + 1; hits.set(id, next); return { hits: next }; }, run: async (_sql: string, cutoff: number) => { deletes.push(cutoff); }, })); const { enforceHourlyLimit, pruneHourlyLimits } = await import("./limits"); const HOUR = 60 * 60 * 1000; const base = 1_000 * HOUR; beforeEach(() => { hits.clear(); deletes.length = 0; delete env.RATE_LIMITS_DISABLED; }); describe("enforceHourlyLimit", () => { test("allows up to max then rejects with 429", async () => { const max = 3; for (let i = 0; i < max; i++) await enforceHourlyLimit("sudo:u1", max, base); await expect(enforceHourlyLimit("sudo:u1", max, base)).rejects.toMatchObject({ status: 429 }); }); test("keys are independent", async () => { await enforceHourlyLimit("sudo:u1", 1, base); await enforceHourlyLimit("sudo:u2", 1, base); await expect(enforceHourlyLimit("sudo:u1", 1, base)).rejects.toMatchObject({ status: 429 }); }); test("a new clock hour resets the budget", async () => { await enforceHourlyLimit("2fa:u1", 1, base + 10); await expect(enforceHourlyLimit("2fa:u1", 1, base + HOUR - 1)).rejects.toMatchObject({ status: 429 }); await enforceHourlyLimit("2fa:u1", 1, base + HOUR); }); test("the e2e switch is ignored on a deployed forge", async () => { env.RATE_LIMITS_DISABLED = "true"; await expect(enforceHourlyLimit("k", 0, base)).rejects.toMatchObject({ status: 429 }); }); test("the e2e switch disables the limit on loopback", async () => { env.RATE_LIMITS_DISABLED = "true"; env.PUBLIC_URL = "http://localhost:5173"; await enforceHourlyLimit("k", 0, base); expect(hits.size).toBe(0); env.PUBLIC_URL = "https://forge.example.com"; }); test("prune drops windows older than two hours", async () => { await pruneHourlyLimits(base); expect(deletes).toEqual([base - 2 * HOUR]); }); });