aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorAdam Soltys <[email protected]>2026-12-02 13:45:44 -0700
committerAdam Soltys <[email protected]>2026-12-02 13:45:44 -0700
commit5b7881f3195d9c1479cfffc207014540a9db4d9a (patch)
tree1316b495e207db65001c120c0ef3ff48c26c59f4
parent796999cb8a6fc7abbfb9dc2643e372795fed9882 (diff)
downloadcoinos-server-5b7881f3195d9c1479cfffc207014540a9db4d9a.tar.gz
coinos-server-5b7881f3195d9c1479cfffc207014540a9db4d9a.zip
register: cap account creation over Tor at five an hour
Onion clients all arrive from the Tor gateway's address, so the per-IP and per-range signup caps either let them create unlimited accounts or would count unrelated internal traffic. Mark requests that came through Tor (including ones the UI's server-side rendering relays, which forward the client address in cf-connecting-ip) with req.isTor, and give them one shared quota of five new accounts an hour for /register and first-time nostr logins. The recaptcha bypass for onion users now uses the same flag instead of trusting the Host header. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01VMan6SSfVopM1ZzXKZmLYU
-rw-r--r--lib/app.ts20
-rw-r--r--lib/registration-limit.ts19
-rw-r--r--routes/users.ts6
-rw-r--r--test/registration-limit.test.ts50
4 files changed, 91 insertions, 4 deletions
diff --git a/lib/app.ts b/lib/app.ts
index e349f1ee..b4595fc9 100644
--- a/lib/app.ts
+++ b/lib/app.ts
@@ -14,6 +14,12 @@ import * as path from "path";
import { jwtStrategy } from "$lib/auth";
+declare module "fastify" {
+ interface FastifyRequest {
+ isTor: boolean;
+ }
+}
+
const app = fastify({
logger: true,
logController: new fastify.LogController({ disableRequestLogging: true }),
@@ -80,6 +86,7 @@ const redactHeaders = (headers: any) => {
// rate limiter so its keyGenerator sees the rewritten header.
const UNTRUSTED_PEERS = ["tor"];
let untrusted = new Set<string>();
+let uiPeers = new Set<string>();
const resolveUntrusted = async () => {
const next = new Set<string>();
for (const host of UNTRUSTED_PEERS) {
@@ -89,10 +96,15 @@ const resolveUntrusted = async () => {
} catch {}
}
if (next.size) untrusted = next;
+ try {
+ uiPeers = new Set((await dns.promises.lookup("ui", { all: true }))
+ .map(({ address }) => address));
+ } catch {}
};
await resolveUntrusted();
setInterval(resolveUntrusted, 30000).unref();
+app.decorateRequest("isTor", false);
app.addHook("onRequest", async (req) => {
const peer = (req.socket.remoteAddress || "").replace(/^::ffff:/, "");
// The onion service points at lb, not at us, so the peer is usually lb.
@@ -102,9 +114,13 @@ app.addHook("onRequest", async (req) => {
const hop = (Array.isArray(xff) ? xff.at(-1) : xff?.split(",").at(-1))
?.trim()
.replace(/^::ffff:/, "");
- const viaTor = untrusted.has(peer) || (hop && untrusted.has(hop));
+ // SSR forwards the client IP in cf-connecting-ip without x-forwarded-for.
+ const forwarded = req.headers["cf-connecting-ip"];
+ const viaUi = uiPeers.has(peer) && typeof forwarded === "string" && untrusted.has(forwarded);
+ const viaTor = untrusted.has(peer) || (hop && untrusted.has(hop)) || viaUi;
if (!viaTor) return;
- req.headers["cf-connecting-ip"] = untrusted.has(peer) ? peer : hop;
+ req.isTor = true;
+ req.headers["cf-connecting-ip"] = untrusted.has(peer) ? peer : viaUi ? forwarded : hop;
delete req.headers["x-forwarded-for"];
delete req.headers["rate-limit-by"];
});
diff --git a/lib/registration-limit.ts b/lib/registration-limit.ts
new file mode 100644
index 00000000..2550e37f
--- /dev/null
+++ b/lib/registration-limit.ts
@@ -0,0 +1,19 @@
+import { db } from "$lib/db";
+
+// Onion clients share the Tor gateway's private IP. Keep a separate quota:
+// exempting private IPs lets onion clients create unlimited accounts, while
+// applying the public /16 quota would also count unrelated internal traffic.
+export const allowTorRegistration = async (req, res, store = db) => {
+ if (!req.isTor) return true;
+ const [count, ttl] = (await store.eval(
+ `local n = redis.call('INCR', KEYS[1])
+ if n == 1 then redis.call('EXPIRE', KEYS[1], 3600) end
+ return {n, redis.call('TTL', KEYS[1])}`,
+ { keys: ["register:tor:hour"], arguments: [] },
+ )) as number[];
+ if (count <= 5) return true;
+ res.header("Retry-After", Math.max(1, ttl)).code(429).send({
+ message: "Too many accounts created over Tor, try again later",
+ });
+ return false;
+};
diff --git a/routes/users.ts b/routes/users.ts
index 17bf5026..cfa41b8b 100644
--- a/routes/users.ts
+++ b/routes/users.ts
@@ -11,6 +11,7 @@ import { mail, templates } from "$lib/mail";
import { getNostrUser, getProfile, serverPubkey2 } from "$lib/nostr";
import deleteUser from "$lib/deluser";
import register from "$lib/register";
+import { allowTorRegistration } from "$lib/registration-limit";
import { assertNameFree } from "$lib/names";
import { isReserved } from "$lib/reserved";
import { emit } from "$lib/sockets";
@@ -47,8 +48,7 @@ const verifyRecaptcha = async (
if (!secret) return true;
// Skip captcha for Tor users accessing via .onion
- const reqHost = req?.headers?.["x-forwarded-host"] || req?.headers?.["host"] || "";
- if (reqHost.endsWith(".onion")) return true;
+ if (req?.isTor) return true;
// Skip captcha for allowlisted User-Agents (prefix match)
const uaRaw = req?.headers?.["user-agent"] || req?.headers?.["User-Agent"];
@@ -194,6 +194,7 @@ export default {
try {
const ip = headers["cf-connecting-ip"];
if (!body.user) fail("no user object provided");
+ if (!(await allowTorRegistration(req, res))) return;
let { user } = body;
// Per-IP registration cap. Nothing else throttles /register (the
@@ -679,6 +680,7 @@ export default {
let user = await getUser(key);
if (!user) {
+ if (!(await allowTorRegistration(req, res))) return;
const k0 = await getProfile(key);
let username = k0?.name?.replace(/[^a-zA-Z0-9 ]/g, "");
const exists = await getUser(username);
diff --git a/test/registration-limit.test.ts b/test/registration-limit.test.ts
new file mode 100644
index 00000000..2e75e512
--- /dev/null
+++ b/test/registration-limit.test.ts
@@ -0,0 +1,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);
+});