diff options
Diffstat (limited to 'routes/users.ts')
| -rw-r--r-- | routes/users.ts | 313 |
1 files changed, 211 insertions, 102 deletions
diff --git a/routes/users.ts b/routes/users.ts index 684f361b..af195153 100644 --- a/routes/users.ts +++ b/routes/users.ts @@ -2,12 +2,17 @@ import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import { join } from "node:path"; import config from "$config"; -import { requirePin } from "$lib/auth"; +import { checkPin, requirePin } from "$lib/auth"; +import { adminIpAllowed } from "$lib/adminip"; 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 { allowTorRegistration } from "$lib/registration-limit"; import { assertNameFree } from "$lib/names"; import { isReserved } from "$lib/reserved"; import { emit } from "$lib/sockets"; @@ -29,13 +34,22 @@ 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; + if (req?.isTor) return true; // Skip captcha for allowlisted User-Agents (prefix match) const uaRaw = req?.headers?.["user-agent"] || req?.headers?.["User-Agent"]; @@ -64,7 +78,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 +91,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 +123,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 +153,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); @@ -146,6 +195,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 @@ -163,6 +213,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 +264,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 }; @@ -262,6 +388,12 @@ export default { l("updating user", user.username, tokid); if (user.id !== tokid) fail("unauthorized"); + // Kill switch for the v3 migration hand-off (`migrate:disabled`). The + // UI's migrate action marks the account here before it asks the + // registrar to grant the name, so failing this stops the grant. + if (typeof body.migrated !== "undefined" && (await db.get("migrate:disabled"))) + fail("Migration is temporarily unavailable"); + const { confirm, password, pin, newpin } = body; const username = body?.username?.toLowerCase().replace(/\s/g, ""); const valid = /^[\p{L}\p{N}]{2,24}$/u; @@ -281,10 +413,10 @@ export default { const existingUsername = exists?.username ?.toLowerCase() .replace(/\s/g, ""); + const takeAnon = exists && un !== existingUsername && exists.anon; if (exists && un !== existingUsername) { warn("key in use", pubkey, username, existingUsername); - if (exists.anon) await db.del(`user:${pubkey}`); - else fail("Key in use by another account"); + if (!exists.anon) fail("Key in use by another account"); } const event = JSON.parse(body.event); @@ -302,12 +434,15 @@ export default { pubkey = pubkey.replace(/\s*/g, ""); if (pubkey.length !== 64) fail(`Invalid pubkey ${pubkey}`); + // Only unlink an anon account's key once the caller has proven they + // hold it (signed challenge above). + if (takeAnon) await db.del(`user:${pubkey}`); await db.del(`user:${user.pubkey}`); user.pubkey = pubkey; user.nsec = undefined; } - if (user.pin && !(pin === user.pin)) fail("Pin required"); + if (!(await checkPin(user, pin))) fail("Pin required"); if (typeof newpin !== "undefined" && newpin.length === 6) user.pin = newpin; if (user.pin === "delete") user.pin = undefined; @@ -352,8 +487,6 @@ export default { "push", "reserve", "seed", - "shopifyStore", - "shopifyToken", "threshold", "tip", "tokens", @@ -369,6 +502,12 @@ export default { if (typeof body[a] !== "undefined") user[a] = body[a]; } + // A v3 hand-off from the /migrate action. Not the same thing as + // `migrated`, which every account has carried since 2023. Only the + // server sets this, and the names registrar grants the name to a v3 + // key only while it is fresh. + if (body.migrated === true) user.v3migrated = Date.now(); + user.fresh = false; user.tip = Math.max(0, Math.min(1000, Number.parseInt(user.tip))); @@ -413,10 +552,14 @@ export default { // undefined). Both the configured value and the supplied one must be // non-empty and match exactly. const isAdmin = - !!config?.adminpass && !!password && password === config.adminpass; + !!config?.adminpass && !!password && password === config.adminpass && + adminIpAllowed(req); // the master password only works from Adam's addresses 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 +575,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 +615,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 +645,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 +663,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"); } @@ -524,6 +685,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); @@ -555,7 +717,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); @@ -622,7 +784,7 @@ export default { const ipFailKey = `ip:${ip}:login:fail`; try { - if (!user.nsec) fail("nsec not available"); + if (!user.nsec && !user.cipher) fail("nsec not available"); if ((await g(ipFailKey)) > 20) return res.code(429).send({}); let verified = false; @@ -637,6 +799,9 @@ export default { 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); @@ -648,7 +813,11 @@ export default { body: { pin }, user, } = req; - res.send(!user.pin || user.pin === pin); + try { + res.send(await checkPin(user, pin)); + } catch (e) { + res.code(429).send(e.message); + } }, async otpsecret(req, res) { @@ -744,22 +913,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. @@ -773,80 +944,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}`, - ]; + const { deleted, disabled } = await deleteUser(user); - 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`); - - // 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 {} @@ -889,6 +989,8 @@ export default { user.pin = null; user.nsec = null; + user.cipher = null; + user.salt = null; user.password = await Bun.password.hash(password, { algorithm: "bcrypt", @@ -1129,6 +1231,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 @@ -1143,7 +1247,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; }), ); @@ -1206,6 +1310,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. |
