import { afterAll, expect, test } from "bun:test"; import { db } from "../lib/db"; import { allowTorRegistration } from "../lib/registration-limit"; // Exercise the actual atomic Redis script under an isolated key; never consume // the production signup quota. Run inside app, where the configured DB resolves. const key = `test:register:tor:${crypto.randomUUID()}`; const store = { eval: (script, options) => db.eval(script, { ...options, keys: [key] }), } as typeof db; const reply = () => ({ status: 200, headers: {}, body: null, header(name, value) { this.headers[name] = value; return this; }, code(value) { this.status = value; return this; }, send(value) { this.body = value; return this; }, }); afterAll(async () => { await db.del(key); }); test("clearnet requests do not consume the shared Tor quota", async () => { expect(await allowTorRegistration({ isTor: false }, reply(), store)).toBe(true); expect(await db.exists(key)).toBe(0); }); test("concurrent onion signups allow five and reject the rest regardless of headers", async () => { const responses = Array.from({ length: 12 }, reply); const results = await Promise.all(responses.map((res, i) => allowTorRegistration({ isTor: true, headers: { "cf-connecting-ip": `198.51.100.${i}`, "user-agent": `rotating-${i}`, "rate-limit-by": "ua", } }, res, store), )); expect(results.filter(Boolean)).toHaveLength(5); expect(results.filter((allowed) => !allowed)).toHaveLength(7); for (const res of responses.filter((r) => r.status === 429)) { expect(res.headers["Retry-After"]).toBeGreaterThan(0); expect(res.headers["Retry-After"]).toBeLessThanOrEqual(3600); } expect(await db.ttl(key)).toBeGreaterThan(0); }); test("quota permits signups again after expiry", async () => { await db.del(key); expect(await allowTorRegistration({ isTor: true }, reply(), store)).toBe(true); expect(await db.get(key)).toBe("1"); expect(await db.ttl(key)).toBeGreaterThan(0); });