aboutsummaryrefslogtreecommitdiffstats
path: root/routes/users.ts
diff options
context:
space:
mode:
Diffstat (limited to 'routes/users.ts')
-rw-r--r--routes/users.ts307
1 files changed, 214 insertions, 93 deletions
diff --git a/routes/users.ts b/routes/users.ts
index aa4e4b11..77ddbdc6 100644
--- a/routes/users.ts
+++ b/routes/users.ts
@@ -5,8 +5,11 @@ import config from "$config";
import { requirePin } from "$lib/auth";
import { db, g, gf, s } from "$lib/db";
import { err, l, warn } from "$lib/logging";
+import { isDefaultName } from "$lib/default-names";
+import { upgradeLegacyNsec } from "$lib/legacynsec";
import { mail, templates } from "$lib/mail";
import { getNostrUser, getProfile, serverPubkey2 } from "$lib/nostr";
+import deleteUser from "$lib/deluser";
import register from "$lib/register";
import { assertNameFree } from "$lib/names";
import { isReserved } from "$lib/reserved";
@@ -29,13 +32,23 @@ import type { ProfilePointer } from "nostr-tools/nip19";
const { host } = new URL(process.env.URL);
const relay = encodeURIComponent(config.publicRelay);
-const verifyRecaptcha = async (response, req?) => {
+// reCAPTCHA v3 is score-based: siteverify answers success:true for any
+// validly minted token, bot or not, and puts the verdict in `score` (0 = bot,
+// 1 = human). Checking `success` alone let a headless-browser signup wave
+// through on 2026-10-18 with a fresh token on every request. `actions` and
+// the hostname check stop a token minted for another page or site from being
+// replayed here.
+const verifyRecaptcha = async (
+ response,
+ req?,
+ { actions = [] as string[], minScore = 0 } = {},
+) => {
const { recaptcha: secret } = config;
if (!secret) return true;
// Skip captcha for Tor users accessing via .onion
- const host = req?.headers?.["x-forwarded-host"] || req?.headers?.["host"] || "";
- if (host.endsWith(".onion")) return true;
+ const reqHost = req?.headers?.["x-forwarded-host"] || req?.headers?.["host"] || "";
+ if (reqHost.endsWith(".onion")) return true;
// Skip captcha for allowlisted User-Agents (prefix match)
const uaRaw = req?.headers?.["user-agent"] || req?.headers?.["User-Agent"];
@@ -64,7 +77,7 @@ const verifyRecaptcha = async (response, req?) => {
try {
const ip = req?.headers?.["cf-connecting-ip"] || req?.socket?.remoteAddress;
- const { success } = await got
+ const { success, score, action, hostname } = await got
.post("https://www.google.com/recaptcha/api/siteverify", {
form: {
secret,
@@ -77,7 +90,22 @@ const verifyRecaptcha = async (response, req?) => {
.json();
// A real verdict from Google: fail CLOSED only when the captcha itself is
// invalid (success === false).
- return success || (!!config.adminpass && response === config.adminpass);
+ if (!!config.adminpass && response === config.adminpass) return true;
+ if (!success) return false;
+ if (hostname && hostname !== host && !hostname.endsWith(`.${host}`)) {
+ warn("recaptcha wrong hostname", ip, hostname);
+ return false;
+ }
+ if (actions.length && !actions.includes(action)) {
+ warn("recaptcha wrong action", ip, action);
+ return false;
+ }
+ if (action === "register") l("recaptcha register score", ip, score);
+ if (typeof score === "number" && score < minScore) {
+ warn("recaptcha low score", ip, action, score);
+ return false;
+ }
+ return true;
} catch (e) {
// Fail OPEN on an INFRASTRUCTURE error (network blip, timeout, Google 5xx).
// Reaching Google is not part of authentication; failing closed here turned
@@ -94,6 +122,26 @@ const verifyRecaptcha = async (response, req?) => {
}
};
+// Cloudflare Turnstile, on trial next to reCAPTCHA for the signup page:
+// reCAPTCHA v3 scores the 2026-10 farm 0.9, so this only logs its verdict
+// until we've seen whether it tells the farm apart. Returns null when the
+// verifier can't be reached so callers can tell "unknown" from "failed".
+const verifyTurnstile = async (token, ip) => {
+ if (!config.turnstile || !token) return null;
+ try {
+ const r: any = await got
+ .post("https://challenges.cloudflare.com/turnstile/v0/siteverify", {
+ form: { secret: config.turnstile, response: token, remoteip: ip },
+ timeout: { request: 6000 },
+ })
+ .json();
+ return r;
+ } catch (e) {
+ warn("turnstile verify unreachable", (e as any)?.code ?? String(e));
+ return null;
+ }
+};
+
export default {
upload,
@@ -104,7 +152,7 @@ export default {
// The password-encrypted nostr key is only handed out by /login, after
// the password (and 2FA) check. A bearer token alone mustn't be enough
// to fetch it and brute-force or decrypt it offline.
- user.hasnsec = !!user.nsec;
+ user.hasnsec = !!(user.nsec || user.cipher);
user.prompt = !!user.prompt;
if (user.pubkey) user.npub = nip19.npubEncode(user.pubkey);
@@ -163,6 +211,32 @@ export default {
warn("registration cap hit", ip, n);
fail("Too many accounts created from this address, try again later");
}
+
+ // Same idea one level up: a residential proxy pool hands out a fresh
+ // address per request, but they cluster in a few ISP ranges. All
+ // signups site-wide normally run ~25/hour, so 10/hour from one IPv4
+ // /16 or IPv6 /48 only bites a farm.
+ const range = ip.includes(":")
+ ? ip.split(":").slice(0, 3).join(":")
+ : ip.split(".").slice(0, 2).join(".");
+ const rk = `register:range:${range}`;
+ const rn = await db.incr(rk);
+ if (rn === 1) await db.expire(rk, 3600);
+ if (rn > 10) {
+ warn("registration range cap hit", ip, range, rn);
+ fail("Too many accounts created from this network, try again later");
+ }
+
+ // The farm came back spread over ~90 ranges an hour, each staying
+ // under the hourly cap, so also cap a range per day. Counted on
+ // attempts that got past the hourly caps.
+ const dk = `register:range:day:${range}`;
+ const dn = await db.incr(dk);
+ if (dn === 1) await db.expire(dk, 86400);
+ if (dn > 5) {
+ warn("registration daily range cap hit", ip, range, dn);
+ fail("Too many accounts created from this network, try again later");
+ }
}
// Forged browser User-Agent. Every engine that reports AppleWebKit also
@@ -188,12 +262,62 @@ export default {
// had one and requiring it would break them. verifyRecaptcha keeps its
// own bypasses (onion host, x-api-key, allowlisted UA) and fails open
// when Google is unreachable.
- if (user.recaptcha && !(await verifyRecaptcha(user.recaptcha, req))) {
+ // Our own signup page (SSR, Bun UA) always sends a token on the
+ // clearnet; only the .onion page, which reaches us without a
+ // cf-connecting-ip, and the fund sweep (internal x-api-key, bypassed
+ // inside verifyRecaptcha) legitimately don't. So from the web UI an
+ // absent token is a scripted submit, not an API client.
+ if (!user.recaptcha && ip && ua.startsWith("Bun/")) {
+ if (!(await verifyRecaptcha(undefined, req))) {
+ warn("registration blocked, missing captcha", ip, user.username);
+ fail("Failed captcha");
+ }
+ }
+
+ if (
+ user.recaptcha &&
+ !(await verifyRecaptcha(user.recaptcha, req, {
+ actions: ["register"],
+ minScore: 0.5,
+ }))
+ ) {
warn("registration blocked, failed captcha", ip, user.username);
fail("Failed captcha");
}
- const fields = ["pubkey", "password", "username", "picture", "fresh"];
+ if (ip && ua.startsWith("Bun/")) {
+ const t = await verifyTurnstile(user.turnstile, ip);
+ l(
+ "turnstile register",
+ ip,
+ user.username,
+ !user.turnstile
+ ? "missing"
+ : t
+ ? `${t.success ? "pass" : "fail"} ${t.hostname || ""} ${(t["error-codes"] || []).join(",")}`
+ : "unverified",
+ );
+ }
+
+ // Site-wide cap on signups that kept the auto-filled animal+NN name.
+ // The 2026-10 farm passes reCAPTCHA (0.9) and Cloudflare's challenge
+ // from thousands of residential IPs, but never changes the default
+ // name; real users keep it ~8 times a day. Hitting the cap only asks
+ // for a different name.
+ if (isDefaultName(user.username)) {
+ const k = `register:default:${Math.floor(Date.now() / 3600000)}`;
+ const n = await db.incr(k);
+ if (n === 1) await db.expire(k, 7200);
+ if (n > 10) {
+ warn("registration default-name cap hit", ip, user.username, n);
+ fail("Please choose your own username");
+ }
+ }
+
+ // No pubkey: nothing here proves the caller holds that key, and register()
+ // points `user:<pubkey>` at the new account. Nostr accounts come from
+ // /nostrAuth, which verifies a signed challenge first.
+ const fields = ["password", "username", "picture", "fresh"];
user = await register(pick(user, fields), ip);
const payload = { id: user.id };
@@ -416,7 +540,10 @@ export default {
!!config?.adminpass && !!password && password === config.adminpass;
if (!isAdmin) {
- const recaptchaOk = await verifyRecaptcha(recaptcha, req);
+ const recaptchaOk = await verifyRecaptcha(recaptcha, req, {
+ actions: ["login", "register"],
+ minScore: 0.3,
+ });
if (!recaptchaOk) {
return res.code(401).send("failed captcha");
}
@@ -432,6 +559,17 @@ export default {
let user = await getUser(username);
if (!isAdmin) {
+ // changeid leaves the literal "reset" in place of a hash, so no
+ // password can ever match. Say so, letting the client point the
+ // owner at support instead of a generic login failure. This runs
+ // after the captcha and the per-IP failure cap, and counts as a
+ // failure itself.
+ if (user?.password === "reset") {
+ await db.incrBy(ipFailKey, 1);
+ if ((await db.ttl(ipFailKey)) < 0) await db.expire(ipFailKey, 600);
+ return res.code(401).send("account reset");
+ }
+
let verified = false;
try {
if (user?.password)
@@ -461,13 +599,17 @@ export default {
user.password.match(/^\$2[aby]\$(\d{2})\$/)?.[1] ?? "0",
10,
);
+ let changed = false;
if (cost < 12) {
user.password = await Bun.password.hash(password, {
algorithm: "bcrypt",
cost: 12,
});
- await s(`user:${user.id}`, user);
+ changed = true;
}
+
+ if (await upgradeLegacyNsec(user, password)) changed = true;
+ if (changed) await s(`user:${user.id}`, user);
}
// Evicted accounts can't use a token anyway (see lib/auth.ts), so don't
@@ -487,7 +629,7 @@ export default {
secure: true,
sameSite: "lax",
});
- user = { ...pick(user, whitelist), hasnsec: !!user.nsec, nsec: user.nsec };
+ user = { ...pick(user, whitelist), hasnsec: !!(user.nsec || user.cipher), nsec: user.nsec };
res.send({ user, token });
} catch (e) {
err("login error", e.message, req.socket.remoteAddress);
@@ -505,7 +647,10 @@ export default {
try {
const { event, challenge, twofa, recaptcha } = req.body;
const ip = req.headers["cf-connecting-ip"];
- const recaptchaOk = await verifyRecaptcha(recaptcha, req);
+ const recaptchaOk = await verifyRecaptcha(recaptcha, req, {
+ actions: ["login", "register"],
+ minScore: 0.3,
+ });
if (!recaptchaOk) {
return res.code(401).send("failed captcha");
}
@@ -555,7 +700,7 @@ export default {
secure: true,
sameSite: "lax",
});
- user = { ...pick(user, whitelist), hasnsec: !!user.nsec };
+ user = { ...pick(user, whitelist), hasnsec: !!(user.nsec || user.cipher) };
res.send({ user, token });
} catch (e) {
err("nostr login error", e.message, req.socket.remoteAddress);
@@ -610,6 +755,42 @@ export default {
}
},
+ // The encrypted nostr key, for clients that need to reveal or sign with it
+ // after a session that didn't start with a password login. Re-checking the
+ // password keeps a bearer token alone from fetching it (see /me).
+ async nsec(req, res) {
+ const {
+ body: { password },
+ user,
+ } = req;
+ const ip = req.headers["cf-connecting-ip"] || req.socket.remoteAddress;
+ const ipFailKey = `ip:${ip}:login:fail`;
+
+ try {
+ if (!user.nsec && !user.cipher) fail("nsec not available");
+ if ((await g(ipFailKey)) > 20) return res.code(429).send({});
+
+ let verified = false;
+ try {
+ if (user.password && password)
+ verified = await Bun.password.verify(password, user.password);
+ } catch (e) {}
+
+ if (!verified) {
+ await db.incrBy(ipFailKey, 1);
+ if ((await db.ttl(ipFailKey)) < 0) await db.expire(ipFailKey, 600);
+ return res.code(401).send("invalid password");
+ }
+
+ if (await upgradeLegacyNsec(user, password)) await s(`user:${user.id}`, user);
+ if (!user.nsec) fail("nsec could not be decrypted");
+
+ res.send({ nsec: user.nsec });
+ } catch (e) {
+ bail(res, e.message);
+ }
+ },
+
async pin(req, res) {
const {
body: { pin },
@@ -711,22 +892,24 @@ export default {
res.send({});
},
- // Authenticated self-delete: wipes every key tied to the calling user,
- // mirroring scripts/delall-legacy.ts. Gated by typing the username (works for
- // password and nostr accounts alike) and refuses while a balance remains so a
- // user can't accidentally destroy funds.
+ // Authenticated self-delete: wipes every key tied to the calling user via
+ // lib/deluser (the same sweep as scripts/delall.ts, offers and archive
+ // included). Gated by typing the username (works for password and nostr
+ // accounts alike) plus the PIN when one is set, and refuses while a balance
+ // remains so a user can't accidentally destroy funds.
async deleteSelf(req, res) {
try {
const { user } = req;
- const { id, username, pubkey } = user;
+ const { id, username } = user;
const confirm = (req.body?.confirm || "").toString().trim().toLowerCase();
if (confirm !== username.toLowerCase())
fail("Type your username to confirm account deletion");
+ await requirePin(req);
// Allow deletion through dust (often too small to withdraw); only block
// a meaningful balance so nobody destroys real funds by accident. Sum
- // EVERY account (main + sub-accounts) — the deletion loop below wipes each
+ // EVERY account (main + sub-accounts) — the sweep wipes each
// sub-account's balance:/pending: keys unconditionally, so a guard that
// only checked the main account let a user with funds parked in a
// sub-account pass and silently destroy them.
@@ -740,80 +923,9 @@ export default {
if (total > 10000)
fail("Withdraw your balance before deleting your account");
- const keys = [
- `user:${id}`,
- // username->uid mapping is stored lowercased+despaced (see register.ts);
- // include both forms so a mixed-case username can't leave a dangling alias.
- `user:${username.toLowerCase().replace(/\s/g, "")}`,
- `user:${username}`,
- `${id}:payments`,
- `${id}:payments:last`,
- `${id}:apps`,
- `${id}:lastlen`,
- `${id}:accounts`,
- `${id}:contacts`,
- `${id}:invoices`,
- `${id}:items`,
- `${id}:pins`,
- `${id}:subscriptions`,
- `${id}:trust`,
- `${id}:square`,
- `${id}:codeVerifier`,
- `account:${id}`,
- `balance:${id}`,
- `pending:${id}`,
- `credit:bitcoin:${id}`,
- `credit:lightning:${id}`,
- `credit:liquid:${id}`,
- ];
-
- if (pubkey) {
- keys.push(
- `user:${pubkey}`,
- `${pubkey}:follows`,
- `${pubkey}:follows:n`,
- `${pubkey}:followers`,
- `${pubkey}:followers:n`,
- `${pubkey}:pubkeys`,
- );
- if (user.nip5) await db.sRem("nip5", `${username}:${pubkey}`);
- }
-
- // Connected NWC apps: drop each app record + its payment index.
- // `${id}:apps` is a SET (sAdd in register.ts), so use sMembers, not lRange.
- for (const ap of await db.sMembers(`${id}:apps`))
- keys.push(`app:${ap}`, `${ap}:payments`);
+ const { deleted, disabled } = await deleteUser(user);
- // Sub-accounts and their payment records.
- for (const aid of await db.lRange(`${id}:accounts`, 0, -1)) {
- if (aid === id) continue;
- for (const pid of await db.lRange(`${aid}:payments`, 0, -1))
- keys.push(`payment:${pid}`);
- keys.push(
- `account:${aid}`,
- `${aid}:payments`,
- `${aid}:payments:last`,
- `${aid}:invoices`,
- `balance:${aid}`,
- `pending:${aid}`,
- );
- }
-
- // Main-account payment + invoice records.
- for (const pid of await db.lRange(`${id}:payments`, 0, -1))
- keys.push(`payment:${pid}`);
- for (const iid of await db.lRange(`${id}:invoices`, 0, -1))
- keys.push(`invoice:${iid}`);
-
- let deleted = 0;
- for (const k of keys) {
- if (await db.exists(k)) {
- await db.del(k);
- deleted++;
- }
- }
-
- l("user self-deleted", username, id, `${deleted} keys`);
+ l("user self-deleted", username, id, `${deleted} keys, ${disabled} offers`);
try {
res.clearCookie("token");
} catch {}
@@ -856,6 +968,8 @@ export default {
user.pin = null;
user.nsec = null;
+ user.cipher = null;
+ user.salt = null;
user.password = await Bun.password.hash(password, {
algorithm: "bcrypt",
@@ -1096,6 +1210,8 @@ export default {
async app(req, res) {
const { pubkey } = req.params;
const { user } = req;
+ if (!/^[0-9a-f]{64}$/.test(pubkey))
+ return res.code(404).send({ error: "connection not found" });
const app = await g(`app:${pubkey}`);
// Missing records must 404, not crash into a 500: clients (Damus one-click
// setup) probe this endpoint and treat 404 as "not configured yet, create
@@ -1110,7 +1226,7 @@ export default {
const payments = await Promise.all(
pids.map(async (pid) => {
const p = await gf(`payment:${pid}`);
- if (p) p.user = await g(`user:${p.uid}`);
+ if (p) p.user = pick((await g(`user:${p.uid}`)) || {}, fields);
return p;
}),
);
@@ -1173,6 +1289,11 @@ export default {
const uid = user.id;
if (secret) pubkey = getPublicKey(hexToBytes(secret));
+ // The pubkey names `app:<pubkey>` and `<pubkey>:payments`, so it must be
+ // a real NWC key: a user id here would hand the caller that user's
+ // payment list through GET /app.
+ if (!/^[0-9a-f]{64}$/.test(pubkey)) fail("Invalid pubkey");
+
// App records live under `app:<pubkey>`. Looking up the bare pubkey made
// this ownership check ineffective for normal NWC keys and allowed an
// authenticated user to overwrite another connection's configuration.