aboutsummaryrefslogtreecommitdiffstats
path: root/test/registration-limit.test.ts
blob: 2e75e512755adcdb86f0935eef83fc7ed08a0f9b (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
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);
});