diff options
43 files changed, 1993 insertions, 325 deletions
@@ -37,3 +37,6 @@ req* # peerswap runtime artifacts /peerswap/ + +# runtime logs written by the app (contain usernames and IPs) +logs/ diff --git a/docker/bun-distrust.ts b/docker/bun-distrust.ts index 5137883a..df27f619 100644 --- a/docker/bun-distrust.ts +++ b/docker/bun-distrust.ts @@ -1,40 +1,41 @@ -// Bun compiles Mozilla's root store into its binary, and NODE_USE_SYSTEM_CA +// Bun (1.4+) compiles Mozilla's root store into its binary as DER, and NODE_USE_SYSTEM_CA // only adds to it. Until a Bun release drops a distrusted root, overwrite its // DER in place with a same-length self-signed placeholder whose key was thrown // away (zeroing it instead makes every TLS handshake fail). // -// emSign ECC Root CA - G3: eMudhra intermediate key compromise, CVE-2026-111943. +// Usage: bun bun-distrust.ts <path to a bun binary> (not the one running it) import { readFileSync, writeFileSync } from "node:fs"; -import { getCACertificates } from "node:tls"; -import { X509Certificate } from "node:crypto"; -const distrust = { - "emSign ECC Root CA - G3": - "MIICTjCCAdSgAwIBAgIUfFrc+EjEsB3lBo+k60ijjiGPT/IwCgYIKoZIzj0EAwIwXjEfMB0GA1UEAwwWeHh4eHh4eHh4eHh4eHh4eHh4eHh4eDE7MDkGA1UECgwyY29pbm9zIHJldm9rZWQgZW1TaWduIEVDQyBSb290IENBIC0gRzMgcGxhY2Vob2xkZXIwHhcNMjYxMDIxMTI1NjQzWhcNMzYxMDE4MTI1NjQzWjBeMR8wHQYDVQQDDBZ4eHh4eHh4eHh4eHh4eHh4eHh4eHh4MTswOQYDVQQKDDJjb2lub3MgcmV2b2tlZCBlbVNpZ24gRUNDIFJvb3QgQ0EgLSBHMyBwbGFjZWhvbGRlcjB2MBAGByqGSM49AgEGBSuBBAAiA2IABBBYruwA2K1haT213dKQAOYRE5Gdy1PMXpM7V57BH6VwUToz9hkWTCXqeOr7/NctfY1fpqbT+tcKl0/OnTVwZuO3ePtUkTvREL/fuVKd9LTU/eTMT1Pqf2GQfVTmkS8C76NTMFEwHQYDVR0OBBYEFARKTDRI5W1qeguIYelguHqh3gvBMB8GA1UdIwQYMBaAFARKTDRI5W1qeguIYelguHqh3gvBMA8GA1UdEwEB/wQFMAMBAf8wCgYIKoZIzj0EAwIDaAAwZQIwIW/6zsZDBk7LGTetfJJzKqXbhsvMo+4ykb8JSHjLn5zoIsuyBPGvox71gdDPcttgAjEAu3xr0zjPLGQnlM4cwgv6mKTgiiXbt7HneYNN2hu/DvSuCj99c0KuGKEyfHGqotCL", -}; +const distrust = [ + { + // eMudhra intermediate key compromise, CVE-2026-111943. + // sha256 86:A1:EC:BA:08:9C:4A:8D:3B:BE:27:34:C6:12:BA:34:1D:81:3E:04:3C:F9:E8:A8:62:CD:5C:57:A3:6B:BE:6B + name: "emSign ECC Root CA - G3", + der: "MIICTjCCAdOgAwIBAgIKPPYHqWhwDtqLhDAKBggqhkjOPQQDAzBrMQswCQYDVQQGEwJJTjETMBEGA1UECxMKZW1TaWduIFBLSTElMCMGA1UEChMcZU11ZGhyYSBUZWNobm9sb2dpZXMgTGltaXRlZDEgMB4GA1UEAxMXZW1TaWduIEVDQyBSb290IENBIC0gRzMwHhcNMTgwMjE4MTgzMDAwWhcNNDMwMjE4MTgzMDAwWjBrMQswCQYDVQQGEwJJTjETMBEGA1UECxMKZW1TaWduIFBLSTElMCMGA1UEChMcZU11ZGhyYSBUZWNobm9sb2dpZXMgTGltaXRlZDEgMB4GA1UEAxMXZW1TaWduIEVDQyBSb290IENBIC0gRzMwdjAQBgcqhkjOPQIBBgUrgQQAIgNiAAQjpQy4LRL1KPOxst3iAhKAnjlfSU2fySU0WXTsuwYc58Byr+iuL+FBVIcUqEqy6HyC5ltqtdyzdc6LBtCGI79G1Y4PPwT01xySfvalY8L1X44uT6EYGQIrMgqCZH0Wk9GjQjBAMB0GA1UdDgQWBBR8XQKEE9TMipuBzhccLikenEhjQjAOBgNVHQ8BAf8EBAMCAQYwDwYDVR0TAQH/BAUwAwEB/zAKBggqhkjOPQQDAwNpADBmAjEAvvNhzwIQHWSVB7gYboiFBS+DCBeQyh+KTOgNG3qxrdWBCUfvO6wIBHxcmbHtRwfSAjEAnbpV/KlK6O3t5nYBQnvI+GDZjVGLVTv7jHvrZQnD+JbNR6iC8hZVdyR+EhCVBCyj", + placeholder: + "MIICTjCCAdSgAwIBAgIUfFrc+EjEsB3lBo+k60ijjiGPT/IwCgYIKoZIzj0EAwIwXjEfMB0GA1UEAwwWeHh4eHh4eHh4eHh4eHh4eHh4eHh4eDE7MDkGA1UECgwyY29pbm9zIHJldm9rZWQgZW1TaWduIEVDQyBSb290IENBIC0gRzMgcGxhY2Vob2xkZXIwHhcNMjYxMDIxMTI1NjQzWhcNMzYxMDE4MTI1NjQzWjBeMR8wHQYDVQQDDBZ4eHh4eHh4eHh4eHh4eHh4eHh4eHh4MTswOQYDVQQKDDJjb2lub3MgcmV2b2tlZCBlbVNpZ24gRUNDIFJvb3QgQ0EgLSBHMyBwbGFjZWhvbGRlcjB2MBAGByqGSM49AgEGBSuBBAAiA2IABBBYruwA2K1haT213dKQAOYRE5Gdy1PMXpM7V57BH6VwUToz9hkWTCXqeOr7/NctfY1fpqbT+tcKl0/OnTVwZuO3ePtUkTvREL/fuVKd9LTU/eTMT1Pqf2GQfVTmkS8C76NTMFEwHQYDVR0OBBYEFARKTDRI5W1qeguIYelguHqh3gvBMB8GA1UdIwQYMBaAFARKTDRI5W1qeguIYelguHqh3gvBMA8GA1UdEwEB/wQFMAMBAf8wCgYIKoZIzj0EAwIDaAAwZQIwIW/6zsZDBk7LGTetfJJzKqXbhsvMo+4ykb8JSHjLn5zoIsuyBPGvox71gdDPcttgAjEAu3xr0zjPLGQnlM4cwgv6mKTgiiXbt7HneYNN2hu/DvSuCj99c0KuGKEyfHGqotCL", + }, +]; const bin = process.argv[2]; const buf = readFileSync(bin); let patched = false; -for (const [cn, placeholder] of Object.entries(distrust)) { - const pem = getCACertificates("bundled").find( - (p) => new X509Certificate(p).subject.split("\n").includes(`CN=${cn}`), - ); - if (!pem) { - console.log(`${cn}: not in bun's root store, nothing to do`); - continue; - } - const der = new X509Certificate(pem).raw; +for (const { name, der: d, placeholder } of distrust) { + const der = Buffer.from(d, "base64"); const repl = Buffer.from(placeholder, "base64"); if (repl.length !== der.length) - throw new Error(`${cn}: placeholder is ${repl.length} bytes, need ${der.length}`); + throw new Error(`${name}: placeholder is ${repl.length} bytes, need ${der.length}`); const at = buf.indexOf(der); - if (at < 0 || buf.indexOf(der, at + 1) >= 0) - throw new Error(`${cn}: expected exactly one copy in ${bin}`); + if (at < 0) { + console.log(`${name}: not in ${bin}, nothing to do`); + continue; + } + if (buf.indexOf(der, at + 1) >= 0) + throw new Error(`${name}: more than one copy in ${bin}`); repl.copy(buf, at); patched = true; - console.log(`${cn}: replaced at offset ${at}`); + console.log(`${name}: replaced at offset ${at}`); } if (patched) writeFileSync(bin, buf); diff --git a/docker/bun.Dockerfile b/docker/bun.Dockerfile new file mode 100644 index 00000000..8ca4aefb --- /dev/null +++ b/docker/bun.Dockerfile @@ -0,0 +1,9 @@ +# oven/bun with distrusted roots taken out of its built-in store (bun-distrust.ts) +# docker build -f docker/bun.Dockerfile --build-arg BUN_VERSION=1.4.3 -t ghcr.io/coinos/bun:1.4.3 docker/ +ARG BUN_VERSION=1.4.3 +FROM oven/bun:${BUN_VERSION} + +COPY bun-distrust.ts /tmp/ +RUN cp /usr/local/bin/bun /tmp/bun \ + && /tmp/bun /tmp/bun-distrust.ts /usr/local/bin/bun \ + && rm /tmp/bun /tmp/bun-distrust.ts @@ -20,10 +20,23 @@ import nostr from "$routes/nostr"; import payments from "$routes/payments"; import preimages from "$routes/preimages"; import rates from "$routes/rates"; -import shopify from "$routes/shopify"; import square from "$routes/square"; import users from "$routes/users"; +// Per-account limit. Runs at preHandler, after auth (preValidation) has set +// req.user, so the bucket is the real user id. Keying on a slice of the +// Authorization header doesn't work: every token starts with the same JWT +// header + `{"id":"` prefix, so all users would share one bucket. +const perUser = (name: string, max: number, timeWindow: number) => ({ + rateLimit: { + max, + timeWindow, + hook: "preHandler", + keyGenerator: (req) => + `${name}:${req.user?.id || (req.headers["cf-connecting-ip"] as string) || req.ip}`, + }, +}); + try { getLocations(); getFx(); @@ -47,7 +60,7 @@ app.get("/rates", rates.index); app.get("/locations", locations.list); -app.get("/invoice/:id", { config: { rateLimit: { max: 30, timeWindow: 10000, keyGenerator: (req) => { const ip = (req.headers["cf-connecting-ip"] as string) || req.ip; const token = (req.headers.authorization || "").slice(0, 50); return token ? `invoice:${token}` : `invoice:${ip}`; } } } }, invoices.get); +app.get("/invoice/:id", { config: { rateLimit: { max: 30, timeWindow: 10000, keyGenerator: (req) => `invoice:${(req.headers["cf-connecting-ip"] as string) || req.ip}` } } }, invoices.get); app.get("/invoices", auth, invoices.list); app.post("/invoice", { ...optional, config: { rateLimit: { max: 30, timeWindow: 10000, keyGenerator: (req) => `invoicecreate:${(req.headers["cf-connecting-ip"] as string) || req.ip}` } } }, invoices.create); app.post("/invoice/:id", { ...optional, config: { rateLimit: { max: 30, timeWindow: 10000, keyGenerator: (req) => `invoiceupdate:${(req.headers["cf-connecting-ip"] as string) || req.ip}` } } }, invoices.update); @@ -95,13 +108,7 @@ app.post( "/lightning/quote", { ...auth, - config: { - rateLimit: { - max: 20, - timeWindow: 10000, - keyGenerator: (req) => `lnquote:${(req.headers.authorization || "").slice(0, 50) || (req.headers["cf-connecting-ip"] as string) || req.ip}`, - }, - }, + config: perUser("lnquote", 20, 10000), }, payments.quote, ); @@ -125,8 +132,8 @@ app.get("/pay/:username/:amount", lnurl.pay); app.post("/freeze", payments.freeze); app.post("/confirm", payments.confirm); -app.post("/bitcoin/fee", auth, payments.fee); -app.post("/bitcoin/send", auth, payments.send); +app.post("/bitcoin/fee", { ...auth, config: perUser("btcfee", 10, 60000) }, payments.fee); +app.post("/bitcoin/send", { ...auth, config: perUser("btcsend", 10, 60000) }, payments.send); app.get("/account/:id", auth, users.account); app.post("/account/:id", auth, users.updateAccount); @@ -194,8 +201,6 @@ app.post("/items", auth, items.create); app.post("/items/delete", auth, items.del); app.post("/items/sort", auth, items.sort); -app.post("/shopify/:id", shopify); - app.get("/bolt12", fixBolt12); app.get("/cash/:id/:version", ecash.get); diff --git a/lib/adminip.ts b/lib/adminip.ts new file mode 100644 index 00000000..c870af8b --- /dev/null +++ b/lib/adminip.ts @@ -0,0 +1,31 @@ +// The admin account and the admin password only work from Adam's own +// addresses (2026-12-04: after the desk breach the JWT secret was kept, so a +// copied or forged admin session must be useless from anywhere else). +// config.adminIps: exact IPs and/or IPv4 CIDR ranges. Unset or empty: no +// restriction (so a config without it behaves as before). +import config from "$config"; + +const v4 = (ip: string) => + ip.split(".").reduce((a, o) => a * 256 + Number(o), 0); +const isV4 = (ip: string) => /^\d{1,3}(\.\d{1,3}){3}$/.test(ip); + +// The real client: Cloudflare's header (the app is only reachable through the +// tunnel and Caddy). Tor pages carry a placeholder address, never allowed. +export const clientIp = (req: any): string => + String(req.headers?.["cf-connecting-ip"] || req.ip || "").replace(/^::ffff:/, ""); + +export const adminIpAllowed = (req: any): boolean => { + const list: string[] = (config as any).adminIps; + if (!Array.isArray(list) || !list.length) return true; + if (req.isTor) return false; + const ip = clientIp(req); + return list.some((entry) => { + const [net, bits] = String(entry).split("/"); + if (bits === undefined) return ip === net; + if (!isV4(ip) || !isV4(net)) return false; + const n = Number(bits); + if (!(n >= 0 && n <= 32)) return false; + const block = 2 ** (32 - n); // addresses per network at this prefix length + return Math.floor(v4(ip) / block) === Math.floor(v4(net) / block); + }); +}; @@ -13,6 +13,13 @@ import dns from "node:dns"; import * as path from "path"; import { jwtStrategy } from "$lib/auth"; +import { adminIpAllowed, clientIp } from "$lib/adminip"; + +declare module "fastify" { + interface FastifyRequest { + isTor: boolean; + } +} const app = fastify({ logger: true, @@ -80,6 +87,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,14 +97,43 @@ 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:/, ""); - if (!untrusted.has(peer)) return; - req.headers["cf-connecting-ip"] = peer; + // The onion service points at lb, not at us, so the peer is usually lb. + // lb (Caddy, no trusted_proxies) overwrites x-forwarded-for with its own + // peer, so a tor address there means the request came in over the onion. + const xff = req.headers["x-forwarded-for"]; + const hop = (Array.isArray(xff) ? xff.at(-1) : xff?.split(",").at(-1)) + ?.trim() + .replace(/^::ffff:/, ""); + // SSR forwards the client IP in cf-connecting-ip without x-forwarded-for. + // Onion pages never pass Cloudflare, so the UI has no client IP to forward + // for them; it does forward the page's Host as x-forwarded-host. Only the + // ui peer is believed on that, and clearnet pages always reach ui with a + // coinos.io Host. + const forwarded = req.headers["cf-connecting-ip"]; + const fwdHost = String(req.headers["x-forwarded-host"] || ""); + const viaUi = + uiPeers.has(peer) && + ((typeof forwarded === "string" && untrusted.has(forwarded)) || + fwdHost.endsWith(".onion")); + const viaTor = untrusted.has(peer) || (hop && untrusted.has(hop)) || viaUi; + if (!viaTor) return; + req.isTor = true; + req.headers["cf-connecting-ip"] = untrusted.has(peer) + ? peer + : hop && untrusted.has(hop) + ? hop + : [...untrusted][0]; delete req.headers["x-forwarded-for"]; delete req.headers["rate-limit-by"]; }); @@ -210,4 +247,13 @@ app.setNotFoundHandler((_, reply) => reply.code(404).type("text/html").send("Not Found"), ); +// Admin sessions only from config.adminIps (lib/adminip.ts). preHandler runs +// after each route's auth, so req.user is set for every authenticated route. +app.addHook("preHandler", async (req: any, reply) => { + if (req.user?.username && req.user.username === config.admin && !adminIpAllowed(req)) { + req.log?.warn?.({ ip: clientIp(req), url: req.url }, "admin session refused: address not allowed"); + return reply.code(403).send("forbidden"); + } +}); + export default app; diff --git a/lib/auth.ts b/lib/auth.ts index 107c44f4..d9cfc484 100644 --- a/lib/auth.ts +++ b/lib/auth.ts @@ -1,9 +1,14 @@ import config from "$config"; import { db } from "$lib/db"; import { fail, getUser } from "$lib/utils"; -import { quiet, suppressed } from "$lib/logging"; +import { quiet } from "$lib/logging"; import fastifyPassport from "@fastify/passport"; import jwt from "passport-jwt"; +import { mkdirSync } from "node:fs"; +import pino from "pino"; + +mkdirSync("logs", { recursive: true }); +const evictedAudit = pino(pino.destination("logs/evicted-auth.jsonl")); export const optional = { preValidation: fastifyPassport.authenticate( @@ -22,8 +27,31 @@ export const auth = { }), }; +// Wrong PINs per account. Without a limit, anyone holding a stolen session +// can try all 10^6 PINs from rotating IPs, since every PIN check answers +// right/wrong. After PIN_MAX wrong guesses in PIN_WINDOW seconds, every PIN +// check fails, the right PIN included, until the window runs out. +const PIN_MAX = 10; +const PIN_WINDOW = 3600; + +// true if the account has no PIN or `pin` is right. A missing pin is not a +// guess and doesn't count; a wrong one does. +export const checkPin = async (user, pin) => { + if (!user?.pin) return true; + const k = `pinfail:${user.id}`; + const n = Number(await db.get(k)) || 0; + if (n >= PIN_MAX) fail("Too many wrong PINs, try again in an hour"); + if (pin === undefined || pin === null || pin === "") return false; + if (pin === user.pin) { + if (n) await db.del(k); + return true; + } + if ((await db.incr(k)) === 1) await db.expire(k, PIN_WINDOW); + return false; +}; + export const requirePin = async ({ body, user }) => { - if (!user || (user.pin && user.pin !== body.pin)) fail("Invalid pin"); + if (!user || !(await checkPin(user, body?.pin))) fail("Invalid pin"); }; // A caller-supplied `aid` decides which account's node wallet composes and @@ -69,19 +97,19 @@ export const jwtStrategy = new jwt.Strategy( ((await db.sIsMember("evicted", user.id)) || (await db.sIsMember("evicted", user.username?.toLowerCase?.().trim()))) ) { - // Distinctive, greppable line carrying the real source IP so the realtime - // auto-banner (scripts/atk-autoban.sh) can insta-ban it at Cloudflare. - // Throttled per account. An evicted JWT replayed from a rotating proxy - // pool otherwise emits one line per request and - // has atk-autoban.sh place a Cloudflare block on every residential IP it - // sees, which protects nothing. First hit logs with its IP; afterwards - // one summary per 10 minutes, worded so the auto-banner ignores it. + // Preserve evidence in a separate audit file, without flooding container + // stderr when a script replays tokens for many disabled accounts. + // Throttle per account, summarizing repeats every ten minutes. const n = quiet(`evicted:${user.id}`); if (n !== null) - console.error( - n - ? `evicted-auth ${user.username} ${suppressed(n)}` - : `EVICTED_AUTH ${user.username} ${req.headers["cf-connecting-ip"] || req.ip}`, + evictedAudit.warn( + { + event: "EVICTED_AUTH", + username: user.username, + ip: req.headers["cf-connecting-ip"] || req.ip, + suppressed: n, + }, + "Rejected authentication for disabled account", ); return next(null, false); } diff --git a/lib/changeid.ts b/lib/changeid.ts index 1c6a6688..c7343ab3 100644 --- a/lib/changeid.ts +++ b/lib/changeid.ts @@ -16,9 +16,16 @@ export default async function changeid(un: string) { user.id = nid; user.password = "reset"; + // A rekey assumes the account's credentials are compromised, nostr key + // included. Drop the pubkey's login mapping rather than pointing it at the + // new id, and revoke the key so nostr login can't register a fresh account + // with it either. user.pubkey stays on the record so an admin can re-link. if (user.pubkey) { - await s(user.pubkey, nid); - await sa(user.pubkey, nid); + for (const k of [`user:${user.pubkey}`, user.pubkey]) { + await db.del(k); + await arc.del(k); + } + await db.sAdd("revoked:pubkeys", user.pubkey); } await s(`user:${un}`, nid); await sa(`user:${un}`, nid); @@ -33,6 +40,12 @@ export default async function changeid(un: string) { `pending:${id}`, `${id}:lastlen`, `${id}:contacts`, + `${id}:offer`, + `${id}:trust`, + `${id}:subscriptions`, + `${id}:items`, + `${id}:pins`, + `${id}:square`, `${id}:accounts`, `${id}:payments`, `account:${id}`, @@ -116,6 +129,11 @@ export default async function changeid(un: string) { } catch (e) {} } + // Freezes and evictions are keyed by uid, so carry them to the new id or a + // rekey (which the blocked-address check triggers on its own) lifts them. + for (const set of ["blacklist", "evicted"]) + if (await db.sIsMember(set, id)) await db.sAdd(set, nid); + l(`SECURITY: rekeyed ${un} from ${id} to ${nid}`); return nid; } @@ -12,20 +12,39 @@ local tip = tonumber(ARGV[2]) local fee = tonumber(ARGV[3]) local ourfee = tonumber(ARGV[4]) local frozen = tonumber(ARGV[5]) +-- Optional deposit hold (see lib/hold.ts). Held sats can leave over Lightning +-- or internally but not on-chain; spending them releases the hold, and the +-- amount released is returned so the receiver of an internal send inherits it. +local heldKey = ARGV[6] +local onchain = ARGV[7] == '1' +local held = 0 +if heldKey and heldKey ~= '' then held = tonumber(redis.call('get', heldKey) or '0') end local balance = tonumber(redis.call('get', balanceKey) or '0') local credit = tonumber(redis.call('get', creditKey) or '0') local covered = math.min(credit, ourfee) ourfee = ourfee - covered +local total = amount + tip + fee + ourfee -if balance - frozen < amount + tip + fee + ourfee then - return {err = insufficientString .. ' ⚡️' .. balance - frozen .. ' / ' .. amount + tip + fee + ourfee} +if balance - frozen < total then + return {err = insufficientString .. ' ⚡️' .. balance - frozen .. ' / ' .. total} +end +if onchain and held > 0 and balance - math.max(frozen, held) < total then + return {err = 'HELD:' .. held .. ':' .. math.max(0, balance - math.max(frozen, held))} end redis.call('decrby', creditKey, tostring(math.floor(covered))) -redis.call('decrby', balanceKey, tostring(math.floor(amount + tip + fee + ourfee))) +redis.call('decrby', balanceKey, tostring(math.floor(total))) +if heldKey and heldKey ~= '' then + local used = 0 + if not onchain and held > 0 then + used = math.min(held, math.floor(total)) + redis.call('decrby', heldKey, tostring(used)) + end + return {ourfee, used} +end return ourfee `; diff --git a/lib/default-names.ts b/lib/default-names.ts new file mode 100644 index 00000000..e36dcde0 --- /dev/null +++ b/lib/default-names.ts @@ -0,0 +1,63 @@ +// Usernames the web signup page fills in by default: an animal from +// unique-names-generator plus a number 10-99 (coinos-ui src/lib/random.ts). +// Real users rarely keep one (~8/day); signup farms always do. +const animals = new Set([ + "aardvark", "aardwolf", "albatross", "alligator", "alpaca", "amphibian", + "anaconda", "angelfish", "anglerfish", "ant", "anteater", "antelope", + "antlion", "ape", "aphid", "armadillo", "asp", "baboon", "badger", + "bandicoot", "barnacle", "barracuda", "basilisk", "bass", "bat", "bear", + "beaver", "bedbug", "bee", "beetle", "bird", "bison", "blackbird", "boa", + "boar", "bobcat", "bobolink", "bonobo", "booby", "bovid", "bug", + "butterfly", "buzzard", "camel", "canid", "canidae", "capybara", + "cardinal", "caribou", "carp", "cat", "caterpillar", "catfish", "catshark", + "cattle", "centipede", "cephalopod", "chameleon", "cheetah", "chickadee", + "chicken", "chimpanzee", "chinchilla", "chipmunk", "cicada", "clam", + "clownfish", "cobra", "cockroach", "cod", "condor", "constrictor", "coral", + "cougar", "cow", "coyote", "crab", "crane", "crawdad", "crayfish", + "cricket", "crocodile", "crow", "cuckoo", "damselfly", "deer", "dingo", + "dinosaur", "dog", "dolphin", "donkey", "dormouse", "dove", "dragon", + "dragonfly", "duck", "eagle", "earthworm", "earwig", "echidna", "eel", + "egret", "elephant", "elk", "emu", "ermine", "falcon", "felidae", "ferret", + "finch", "firefly", "fish", "flamingo", "flea", "fly", "flyingfish", + "fowl", "fox", "frog", "galliform", "gamefowl", "gayal", "gazelle", + "gecko", "gerbil", "gibbon", "giraffe", "goat", "goldfish", "goose", + "gopher", "gorilla", "grasshopper", "grouse", "guan", "guanaco", + "guineafowl", "gull", "guppy", "haddock", "halibut", "hamster", "hare", + "harrier", "hawk", "hedgehog", "heron", "herring", "hippopotamus", + "hookworm", "hornet", "horse", "hoverfly", "hummingbird", "hyena", + "iguana", "impala", "jackal", "jaguar", "jay", "jellyfish", "junglefowl", + "kangaroo", "kingfisher", "kite", "kiwi", "koala", "koi", "krill", + "ladybug", "lamprey", "landfowl", "lark", "leech", "lemming", "lemur", + "leopard", "leopon", "limpet", "lion", "lizard", "llama", "lobster", + "locust", "loon", "louse", "lungfish", "lynx", "macaw", "mackerel", + "magpie", "mammal", "manatee", "mandrill", "marlin", "marmoset", "marmot", + "marsupial", "marten", "mastodon", "meadowlark", "meerkat", "mink", + "minnow", "mite", "mockingbird", "mole", "mollusk", "mongoose", "monkey", + "moose", "mosquito", "moth", "mouse", "mule", "muskox", "narwhal", "newt", + "nightingale", "ocelot", "octopus", "opossum", "orangutan", "orca", + "ostrich", "otter", "owl", "ox", "panda", "panther", "parakeet", "parrot", + "parrotfish", "partridge", "peacock", "peafowl", "pelican", "penguin", + "perch", "pheasant", "pig", "pigeon", "pike", "pinniped", "piranha", + "planarian", "platypus", "pony", "porcupine", "porpoise", "possum", + "prawn", "primate", "ptarmigan", "puffin", "puma", "python", "quail", + "quelea", "quokka", "rabbit", "raccoon", "rat", "rattlesnake", "raven", + "reindeer", "reptile", "rhinoceros", "roadrunner", "rodent", "rook", + "rooster", "roundworm", "sailfish", "salamander", "salmon", "sawfish", + "scallop", "scorpion", "seahorse", "shark", "sheep", "shrew", "shrimp", + "silkworm", "silverfish", "skink", "skunk", "sloth", "slug", "smelt", + "snail", "snake", "snipe", "sole", "sparrow", "spider", "spoonbill", + "squid", "squirrel", "starfish", "stingray", "stoat", "stork", "sturgeon", + "swallow", "swan", "swift", "swordfish", "swordtail", "tahr", "takin", + "tapir", "tarantula", "tarsier", "termite", "tern", "thrush", "tick", + "tiger", "tiglon", "toad", "tortoise", "toucan", "trout", "tuna", "turkey", + "turtle", "tyrannosaurus", "unicorn", "urial", "vicuna", "viper", "vole", + "vulture", "wallaby", "walrus", "warbler", "wasp", "weasel", "whale", + "whippet", "whitefish", "wildcat", "wildebeest", "wildfowl", "wolf", + "wolverine", "wombat", "woodpecker", "worm", "wren", "xerinae", "yak", + "zebra", +]); + +export const isDefaultName = (username: string) => { + const m = /^([a-z]+)\d\d$/.exec(String(username || "").toLowerCase()); + return !!m && animals.has(m[1]); +}; diff --git a/lib/deluser.ts b/lib/deluser.ts new file mode 100644 index 00000000..55d05386 --- /dev/null +++ b/lib/deluser.ts @@ -0,0 +1,154 @@ +import { archive, db, g } from "$lib/db"; +import ln from "$lib/ln"; + +// Delete an account and everything hanging off it — the same sweep as +// scripts/delall.ts on the prod host. Beyond the plain keys this also: +// - disables the account's bolt12 offers on the node, so a payer (e.g. an +// OCEAN payout) fails instead of settling into the house wallet; +// - removes the invoice pointer keys (invoice:<bolt11|bolt12|offer_id>) so a +// late settlement resolves to "no invoice" and is skipped; +// - deletes the same keys from the archive, which gf()/getUser fall back +// to, so nothing resurrects from there. +// Without those, a deleted user's offer kept receiving and wedged the lightning +// listener for two hours on 2026-09-05 (pay_index 1068006). +// +// Offers are disabled before any key is deleted, so if the node can't be +// reached this throws with the account still intact. +export default async function deleteUser(user) { + const { id, username, pubkey } = user; + + // Fail up front rather than halfway through the sweep. + await archive.ping(); + + const ga = async (k: string) => { + const v = await archive.get(k); + try { + return JSON.parse(v); + } catch { + return v; + } + }; + const getInv = async (iid: string) => + (await g(`invoice:${iid}`)) ?? (await ga(`invoice:${iid}`)); + + const aids = [ + id, + ...(await db.lRange(`${id}:accounts`, 0, -1)).filter((a) => a !== id), + ]; + const keys = new Set<string>(); + const add = (...ks: (string | false | undefined | null)[]) => + ks.forEach((k) => k && keys.add(k)); + + // username->uid mapping is stored lowercased+despaced (see register.ts); + // include both forms so a mixed-case username can't leave a dangling alias. + add( + `user:${id}`, + `user:${username}`, + `user:${username.toLowerCase().replace(/\s/g, "")}`, + ); + add( + ...[ + "payments", + "payments:last", + "apps", + "lastlen", + "accounts", + "contacts", + "invoices", + "items", + "pins", + "subscriptions", + "trust", + "square", + "codeVerifier", + ].map((s) => `${id}:${s}`), + ); + add( + `account:${id}`, + `balance:${id}`, + `pending:${id}`, + `credit:bitcoin:${id}`, + `credit:lightning:${id}`, + `credit:liquid:${id}`, + ); + if (pubkey) + add( + `user:${pubkey}`, + `${pubkey}:follows`, + `${pubkey}:follows:n`, + `${pubkey}:followers`, + `${pubkey}:followers:n`, + `${pubkey}:pubkeys`, + ); + + // Connected NWC apps. `${id}:apps` is a SET (sAdd in register.ts). + for (const ap of await db.sMembers(`${id}:apps`)) + add(`app:${ap}`, `${ap}:payments`); + + // Invoices and payments for the main account and every sub-account. + const invoiceIds = new Set<string>(); + const bolt12s = new Set<string>(); + for (const aid of aids) { + if (aid !== id) + add( + `account:${aid}`, + `${aid}:payments`, + `${aid}:payments:last`, + `${aid}:invoices`, + `balance:${aid}`, + `pending:${aid}`, + ); + for (const pid of await db.lRange(`${aid}:payments`, 0, -1)) + add(`payment:${pid}`); + for (const iid of await db.lRange(`${aid}:invoices`, 0, -1)) { + invoiceIds.add(iid); + add(`invoice:${iid}`); + const inv = await getInv(iid); + if (!inv) continue; + add(inv.hash && `invoice:${inv.hash}`, inv.text && `invoice:${inv.text}`); + if (inv.type === "bolt12" && inv.hash) bolt12s.add(inv.hash); + } + } + + // bolt12 offers: match by bolt12 string, or through the invoice:<offer_id> + // pointer (which also catches offers whose :invoices entry is already gone). + const { offers } = await ln.call("listoffers", {}); + let disabled = 0; + for (const o of offers) { + let mine = bolt12s.has(o.bolt12); + if (!mine) { + let iid = await g(`invoice:${o.offer_id}`); + if (iid && typeof iid === "object") iid = iid.id; + if (iid) { + if (invoiceIds.has(iid)) mine = true; + else { + const inv = await getInv(iid); + if (inv && aids.includes(inv.uid)) { + mine = true; + add(`invoice:${iid}`, inv.hash && `invoice:${inv.hash}`); + } + } + } + } + if (!mine) continue; + add(`invoice:${o.offer_id}`); + if (o.active) { + await ln.call("disableoffer", { offer_id: o.offer_id }); + disabled++; + } + } + + if (pubkey && user.nip5) await db.sRem("nip5", `${username}:${pubkey}`); + + let deleted = 0; + for (const k of keys) { + const inDb = await db.exists(k); + const inArc = await archive.exists(k); + if (!inDb && !inArc) continue; + deleted++; + if (inDb) await db.del(k); + if (inArc) await archive.del(k); + } + + return { deleted, disabled }; +} diff --git a/lib/hold.ts b/lib/hold.ts new file mode 100644 index 00000000..9404d0c8 --- /dev/null +++ b/lib/hold.ts @@ -0,0 +1,70 @@ +// Deposit holds. +// +// While `hold:enabled` is set, every Lightning (and bolt12) deposit adds to +// the receiving account's `held:<id>`. Held sats can still be spent over +// Lightning or sent to another coinos account, but not withdrawn on-chain +// (bitcoin, liquid) or over Lightning into our own on-chain liquidity (the +// nodes in `hold:exit_nodes`). Spending held sats over Lightning releases +// that much of the hold. An internal transfer of held sats moves the hold to +// the receiver, so passing funds through a second account doesn't clear it. +// The check and the release happen inside the atomic debit script in +// lib/db.ts. A failed send that's reversed gets its hold back. +// +// The first `hold:free_sat` (default 50k) of Lightning deposits per account +// in any 24h aren't held at all, and holds older than `hold:expire_hours` +// (default 72h) are released by `holds.ts expire` (hourly cron) unless the +// account is frozen. Big recent deposits are what we want to look at; small +// ones were mostly false positives. +// +// Accounts with a hold are listed in the `held` set, and each account keeps a +// short log of what added to or lifted its hold (`held:log:<id>`). Review and +// lift holds with scripts/holds.ts. +import { db } from "$lib/db"; + +export const holdKey = (id: string) => `held:${id}`; +const LOG_MAX = 100; + +// Add to a hold inside the caller's MULTI so the balance and the hold change +// together. +export const addHold = (m: any, id: string, amount: number, entry: Record<string, any>) => { + m.incrBy(holdKey(id), amount) + .sAdd("held", id) + .lPush(`held:log:${id}`, JSON.stringify({ at: Date.now(), amount, ...entry })) + .lTrim(`held:log:${id}`, 0, LOG_MAX - 1); +}; + +export const HOLD_FREE_SAT = 50_000; +export const HOLD_EXPIRE_HOURS = 72; + +// How much of a Lightning deposit falls inside the account's daily free +// allowance. Counts the deposit against the allowance as a side effect. +export const holdAllowance = async (id: string, amount: number) => { + const cap = Number(await db.get("hold:free_sat") ?? HOLD_FREE_SAT); + if (!(cap > 0) || !(amount > 0)) return 0; + const k = `holdfree:${id}`; + const used = await db.incrBy(k, amount); + if (used === amount) await db.expire(k, 86400); + return Math.max(0, Math.min(amount, cap - (used - amount))); +}; + +export const logHold = async (id: string, entry: Record<string, any>) => { + await db + .multi() + .lPush(`held:log:${id}`, JSON.stringify({ at: Date.now(), ...entry })) + .lTrim(`held:log:${id}`, 0, LOG_MAX - 1) + .exec(); +}; + +// Lightning destinations that are really our own on-chain liquidity (the +// swap/Ark node). Cached briefly: it's checked on every Lightning send. +let exitNodes = { at: 0, set: new Set<string>() }; +export const isExitNode = async (pubkey?: string) => { + if (!pubkey) return false; + if (Date.now() - exitNodes.at > 60_000) + exitNodes = { at: Date.now(), set: new Set(await db.sMembers("hold:exit_nodes")) }; + return exitNodes.set.has(pubkey); +}; + +export const heldMessage = (held: number, available: number) => + `⚡️${held} of your balance came from recent Lightning deposits and can't be withdrawn on-chain right now. ` + + `You can still send it over Lightning. Available for on-chain withdrawal: ⚡️${available}.`; diff --git a/lib/invoices.ts b/lib/invoices.ts index 0028dc91..1de1f95b 100644 --- a/lib/invoices.ts +++ b/lib/invoices.ts @@ -47,9 +47,13 @@ export const generate = async ({ invoice, user }) => { single_use, type = PaymentType.lightning, usePreimage, - webhook, secret, } = invoice; + // Only a plain http(s) URL is a webhook; anything else is dropped. + const webhook = + typeof invoice.webhook === "string" && /^https?:\/\//i.test(invoice.webhook) + ? invoice.webhook.slice(0, 2048) + : undefined; amount = Number.parseInt(amount || 0); tip = tip == null ? null : Number.parseInt(tip); @@ -91,6 +95,15 @@ export const generate = async ({ invoice, user }) => { if (!id) id = v4(); else { + // An internal invoice's id becomes its hash, and credit() writes + // `payment:<hash>`. A free-form id like "<txid>:<vout>" therefore lets a + // payer overwrite an on-chain deposit's dedup pointer, so ids must be the + // uuids we hand out. + if ( + typeof id !== "string" || + !/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(id) + ) + fail("invoice not found"); // A caller-supplied id re-uses an existing record (tip/webhook update, // repeated bolt12 offer create). It must be the caller's own: the write // below replaces `invoice:<id>` wholesale with uid = this user, and the diff --git a/lib/legacynsec.ts b/lib/legacynsec.ts new file mode 100644 index 00000000..0d0a2e6a --- /dev/null +++ b/lib/legacynsec.ts @@ -0,0 +1,62 @@ +import { warn } from "$lib/logging"; +import { bech32m, hex } from "@scure/base"; +import { entropyToMnemonic } from "@scure/bip39"; +import { wordlist } from "@scure/bip39/wordlists/english.js"; +import { getPublicKey } from "nostr-tools"; +import { privateKeyFromSeedWords } from "nostr-tools/nip06"; +import { encrypt as nip49encrypt } from "nostr-tools/nip49"; + +// Accounts created before the switch to NIP-49 (Dec 2024) hold their nostr key +// as `cipher` + `salt`: BIP-39 entropy, AES-GCM encrypted under +// PBKDF2-SHA256(password, salt, 100k) with an all-zero 16-byte IV, bech32m +// encoded with the "en" prefix. The key is the NIP-06 derivation of the +// mnemonic. Returns the secret key, or undefined if the password doesn't open +// it (e.g. it was changed after the UI stopped re-encrypting the cipher). +const decryptLegacy = async ({ cipher, salt }, password: string) => { + try { + const key = await crypto.subtle.deriveKey( + { name: "PBKDF2", salt: hex.decode(salt), iterations: 100000, hash: "SHA-256" }, + await crypto.subtle.importKey( + "raw", + new TextEncoder().encode(password), + { name: "PBKDF2" }, + false, + ["deriveKey"], + ), + { name: "AES-GCM", length: 256 }, + false, + ["decrypt"], + ); + + const entropy = await crypto.subtle.decrypt( + { name: "AES-GCM", iv: new Uint8Array(16) }, + key, + Uint8Array.from(bech32m.fromWords(bech32m.decode(cipher, 180).words)), + ); + + return privateKeyFromSeedWords( + entropyToMnemonic(new Uint8Array(entropy), wordlist), + ); + } catch (e) {} +}; + +// Given a verified password, convert a legacy cipher into a NIP-49 nsec on the +// user record so the normal reveal/sign paths work. Only adopts the key if it +// still matches the account's pubkey. Returns true if the user was changed. +export const upgradeLegacyNsec = async (user, password: string) => { + if (user.nsec || !user.cipher || !user.salt || !password) return false; + + const sk = await decryptLegacy(user, password); + if (!sk) { + warn("legacy nsec: password doesn't open cipher", user.username); + return false; + } + + if (getPublicKey(sk) !== user.pubkey) { + warn("legacy nsec: cipher key doesn't match pubkey", user.username); + return false; + } + + user.nsec = nip49encrypt(sk, password); + return true; +}; diff --git a/lib/lightning.ts b/lib/lightning.ts index 6c37ddf1..34c698cb 100644 --- a/lib/lightning.ts +++ b/lib/lightning.ts @@ -142,6 +142,15 @@ export async function listenForLightning() { } } + // Note which peer the deposit came in from, for reviewing deposit holds + // (lib/hold.ts). Peers in `freeze:inbound_peers` are flagged. + let holdNote; + try { + holdNote = await inboundNote(payment_hash); + } catch (e) { + warn("inbound peer lookup failed", payment_hash, e.message); + } + const paymentRequest = bolt11 || bolt12; await credit({ hash: paymentRequest, @@ -152,6 +161,7 @@ export async function listenForLightning() { ref: preimage, type: bolt12 ? PaymentType.bolt12 : PaymentType.lightning, payment_hash, + holdNote, }); // credit() may decline a duplicate idempotency claim. Only advance the @@ -402,3 +412,58 @@ export const fixBolt12 = async (_, res) => { res.send({}); }; + +// --- inbound peer lookup (see the listener) --- +// HTLCs are read incrementally by created index, so each lookup only fetches +// what arrived since the last one. +let htlcCursor = 0; +const inboundByHash = new Map<string, Set<string>>(); +let peers: { at: number; scid: Map<string, string>; watched: Set<string> } = { at: 0, scid: new Map(), watched: new Set() }; +const aliases = new Map<string, string>(); + +async function refreshPeers() { + if (Date.now() - peers.at < 60_000) return peers; + const { channels } = await ln.listpeerchannels(); + const scid = new Map<string, string>(); + for (const c of channels || []) if (c.short_channel_id) scid.set(c.short_channel_id, c.peer_id); + const watched = new Set<string>(await db.sMembers("freeze:inbound_peers")); + peers = { at: Date.now(), scid, watched }; + return peers; +} + +async function alias(id: string) { + if (!aliases.has(id)) { + try { + const { nodes } = await ln.listnodes(id); + aliases.set(id, nodes?.[0]?.alias || id.slice(0, 16)); + } catch { + return id.slice(0, 16); + } + } + return aliases.get(id)!; +} + +async function inboundNote(hash: string): Promise<string | undefined> { + if (!hash) return; + const { scid, watched } = await refreshPeers(); + if (!htlcCursor) { + const { created } = await ln.call("wait", { subsystem: "htlcs", indexname: "created", nextvalue: 0 }); + htlcCursor = Math.max(1, Number(created) - 5000); + } + for (;;) { + const { htlcs } = await ln.call("listhtlcs", { index: "created", start: htlcCursor, limit: 1000 }); + for (const h of htlcs || []) { + htlcCursor = Math.max(htlcCursor, Number(h.created_index) + 1); + if (h.direction !== "in") continue; + if (!inboundByHash.has(h.payment_hash)) inboundByHash.set(h.payment_hash, new Set()); + inboundByHash.get(h.payment_hash)!.add(h.short_channel_id); + } + if (!htlcs || htlcs.length < 1000) break; + } + if (inboundByHash.size > 50_000) + for (const k of [...inboundByHash.keys()].slice(0, 25_000)) inboundByHash.delete(k); + const ids = [...new Set([...(inboundByHash.get(hash) || [])].map((c) => scid.get(c)).filter(Boolean))] as string[]; + if (!ids.length) return; + const names = await Promise.all(ids.map(async (id) => `${await alias(id)}${watched.has(id) ? " (watched)" : ""}`)); + return `via ${names.join(", ")}`; +} diff --git a/lib/lnquote.ts b/lib/lnquote.ts index de96f69a..bc34b3fb 100644 --- a/lib/lnquote.ts +++ b/lib/lnquote.ts @@ -22,6 +22,9 @@ const FAKE_NODE = const XPAY_MAXDELAY = 2016; // xpay's default maxdelay +// How long a quote layer outlives a getroutes call that timed out on our side +const LAYER_REMOVE_DELAY = 10 * 60_000; + // Extra layers sendLightning passes to xpay. xpay forwards user layers to // getroutes verbatim, and getroutes rejects an unknown layer outright, so only // pass the ones that actually exist on this node (prod has prefer-kappa, @@ -173,6 +176,12 @@ export const quoteRoutingFee = async ({ } const layer = `quote-${v4()}`; + // True while a getroutes on this layer may still be queued inside askrene. + // askrene runs at most 4 route computations at once and checks layer names + // only on arrival; a queued request whose layer was removed in the meantime + // trips an assert in apply_layers that aborts lightningd. When our RPC times + // out the request is still in that queue, so the layer has to outlive it. + let routing = false; try { await ln.call("askrene-create-layer", { layer, persistent: false }); for (const f of fakes) { @@ -195,6 +204,7 @@ export const quoteRoutingFee = async ({ }); } + routing = true; const r = await ln.call("getroutes", { source: me, destination, @@ -211,7 +221,12 @@ export const quoteRoutingFee = async ({ maxfee_msat: cap, final_cltv: finalCltv, maxdelay: XPAY_MAXDELAY, + }).catch((e) => { + // Any reply from askrene, error or not, means it is done with the layer + if (e?.code !== "ETIMEDOUT") routing = false; + throw e; }); + routing = false; const routes: any[] = r?.routes ?? []; if (!routes.length) fail("No route found"); @@ -232,11 +247,15 @@ export const quoteRoutingFee = async ({ const feeMsat = Math.max(0, sent - delivered); return { fee: Math.ceil(feeMsat / 1000), feeMsat, parts: routes.length }; } finally { - try { - await ln.call("askrene-remove-layer", { layer }); - } catch (e: any) { - warn("askrene-remove-layer failed", layer, e?.message ?? String(e)); - } + const remove = async () => { + try { + await ln.call("askrene-remove-layer", { layer }); + } catch (e: any) { + warn("askrene-remove-layer failed", layer, e?.message ?? String(e)); + } + }; + if (routing) setTimeout(remove, LAYER_REMOVE_DELAY); + else await remove(); } }; diff --git a/lib/lnurl-payload.ts b/lib/lnurl-payload.ts new file mode 100644 index 00000000..6248d213 --- /dev/null +++ b/lib/lnurl-payload.ts @@ -0,0 +1,60 @@ +import { bech32 } from "bech32"; + +const invalid = (): never => { throw new Error("Invalid LNURL response"); }; +const object = (v: any) => v !== null && typeof v === "object" && !Array.isArray(v); +const amount = (v: any, min: number) => Number.isSafeInteger(v) && v >= min; +const callback = (v: any) => { + if (typeof v !== "string") return invalid(); + const u = new URL(v); + if (!["http:", "https:"].includes(u.protocol) || u.username || u.password) invalid(); + return v; +}; + +// Return only protocol fields: never relay an arbitrary upstream JSON object. +export function lnurlPayload(v: any): any { + if (!object(v)) return invalid(); + if (v.status === "ERROR" && typeof v.reason === "string") + return { status: "ERROR", reason: "LNURL service returned an error" }; + if (v.status === "OK" && !v.tag && !v.pr) return { status: "OK" }; + if (v.tag === "payRequest") { + if (!amount(v.minSendable, 1) || !amount(v.maxSendable, v.minSendable) || typeof v.metadata !== "string") invalid(); + let metadata: any; + try { metadata = JSON.parse(v.metadata); } catch { return invalid(); } + if (!Array.isArray(metadata) || !metadata.every((e: any) => Array.isArray(e) && e.length >= 2 && typeof e[0] === "string") || + metadata.filter((e: any) => e[0] === "text/plain" && typeof e[1] === "string").length !== 1) invalid(); + const out: any = { tag: v.tag, callback: callback(v.callback), minSendable: v.minSendable, maxSendable: v.maxSendable, metadata: v.metadata }; + if (amount(v.commentAllowed, 0)) out.commentAllowed = v.commentAllowed; + if (v.allowsNostr === true && typeof v.nostrPubkey === "string" && /^[a-f0-9]{64}$/i.test(v.nostrPubkey)) { + out.allowsNostr = true; out.nostrPubkey = v.nostrPubkey; + } + return out; + } + if (v.tag === "withdrawRequest") { + if (typeof v.k1 !== "string" || !v.k1 || typeof v.defaultDescription !== "string" || + !amount(v.minWithdrawable, 0) || !amount(v.maxWithdrawable, v.minWithdrawable)) invalid(); + return { tag: v.tag, callback: callback(v.callback), k1: v.k1, defaultDescription: v.defaultDescription, + minWithdrawable: v.minWithdrawable, maxWithdrawable: v.maxWithdrawable }; + } + if (typeof v.pr === "string") { + let decoded: any; + try { decoded = bech32.decode(v.pr, 20000); } catch { return invalid(); } + if (!/^ln(bc|tb|bcrt|sb)[0-9]*[munp]?$/.test(decoded.prefix) || decoded.words.length < 111 || + !Array.isArray(v.routes) || v.routes.length !== 0) invalid(); + const out: any = { pr: v.pr, routes: [] }; + if (v.disposable === false || v.disposable === true) out.disposable = v.disposable; + if (typeof v.verify === "string") out.verify = callback(v.verify); + const a = v.successAction; + if (object(a)) { + if (a.tag === "message" && typeof a.message === "string" && a.message.length <= 144) + out.successAction = { tag: a.tag, message: a.message }; + else if (a.tag === "url" && typeof a.description === "string" && a.description.length <= 144) + out.successAction = { tag: a.tag, description: a.description, url: callback(a.url) }; + else if (a.tag === "aes" && typeof a.description === "string" && a.description.length <= 144 && + typeof a.ciphertext === "string" && a.ciphertext.length <= 4096 && typeof a.iv === "string" && /^[A-Za-z0-9+/]{22}==$/.test(a.iv)) + out.successAction = { tag: a.tag, description: a.description, ciphertext: a.ciphertext, iv: a.iv }; + else invalid(); + } + return out; + } + return invalid(); +} diff --git a/lib/names.ts b/lib/names.ts index 284c595d..e170b3ca 100644 --- a/lib/names.ts +++ b/lib/names.ts @@ -1,3 +1,4 @@ +import { db } from "$lib/db"; import { warn } from "$lib/logging"; import { fail } from "$lib/utils"; @@ -35,3 +36,37 @@ export const assertNameFree = async (username: string, ownPubkey?: string) => { fail(`Username ${name} taken`); } }; + +// Registrar holders we refuse to honour (valkey set `names:blocked_holders`, +// full hex pubkeys). A name whose v3 record belongs to one of them is treated +// as unclaimed: its lightning address, NIP-05 and legacy forwarding all stay +// with the local account. This is the containment for a name hijack on the +// registrar side; it needs no deploy there. Fails open: if the registrar or +// the db can't answer, callers behave as they did before. +const blockedCache = new Map<string, { at: number; blocked: boolean }>(); +export const holderBlocked = async (username: string): Promise<boolean> => { + const name = String(username || "").toLowerCase(); + if (!name) return false; + const hit = blockedCache.get(name); + if (hit && Date.now() - hit.at < 60_000) return hit.blocked; + try { + if (!(await db.sCard("names:blocked_holders"))) return false; + const r = await fetch( + `${NAMES_URL}/name/${encodeURIComponent(name)}?domain=${DOMAIN}`, + { signal: AbortSignal.timeout(3000) }, + ); + if (!r.ok) return false; + const body: any = await r.json(); + const pk = body?.taken && typeof body.pubkey === "string" ? body.pubkey : null; + const mgr = typeof body?.manager === "string" ? body.manager : null; + const blocked = + (!!pk && (await db.sIsMember("names:blocked_holders", pk))) || + (!!mgr && (await db.sIsMember("names:blocked_holders", mgr))); + blockedCache.set(name, { at: Date.now(), blocked }); + if (blocked) warn("registrar holder blocked, serving local account for", name); + return blocked; + } catch (e: any) { + warn("holderBlocked check failed for", name, e?.message); + return false; + } +}; diff --git a/lib/nostr.ts b/lib/nostr.ts index ed1b2f42..63199bf8 100644 --- a/lib/nostr.ts +++ b/lib/nostr.ts @@ -1,4 +1,5 @@ import config from "$config"; +import { safeRelayUrl } from "$lib/safe-fetch"; import { db, g, s } from "$lib/db"; import { l, warn } from "$lib/logging"; import { scan } from "$lib/strfry"; @@ -125,7 +126,14 @@ export async function handleZap(invoice, sender = undefined) { l("sending receipt"); - const relays = relays_tag.slice(1).filter((r) => r?.startsWith("ws")); + // Relay URLs come from the zap request, i.e. from whoever asked for the + // invoice; don't let them point our server at internal hosts. + const requested = relays_tag + .slice(1) + .filter((r) => typeof r === "string" && r.startsWith("ws")) + .slice(0, 10); + const relays = []; + for (const r of requested) if (await safeRelayUrl(r)) relays.push(r); relays.push(config.nostr); relays.map(async (url) => { try { diff --git a/lib/notifier.ts b/lib/notifier.ts new file mode 100644 index 00000000..adc09457 --- /dev/null +++ b/lib/notifier.ts @@ -0,0 +1,35 @@ +import config from "$config"; +import dns from "node:dns"; + +// POST /confirm credits deposits, so only the wallet-notify scripts may call +// it. They run inside the bitcoin and liquid node containers and connect to +// us directly, so the TCP peer is one of those nodes (or ourselves, for the +// catch-up sweep in lib/payments.ts). Checking the peer address, rather than +// the absence of proxy headers, also stops requests relayed by another +// internal service such as the UI's server-side forwarding routes. +const hosts = [config.bitcoin?.host, config.liquid?.host].filter( + (h): h is string => typeof h === "string" && h.length > 0, +); + +let notifiers = new Set<string>(); +const resolve = async () => { + const next = new Set<string>(); + for (const host of hosts) { + try { + for (const { address } of await dns.promises.lookup(host.split(":")[0], { + all: true, + })) + next.add(address); + } catch {} + } + if (next.size) notifiers = next; +}; +await resolve(); +setInterval(resolve, 30000).unref(); + +const loopback = (ip: string) => ip === "::1" || ip.startsWith("127."); + +export const isNotifier = (req): boolean => { + const peer = (req.socket?.remoteAddress || "").replace(/^::ffff:/, ""); + return loopback(peer) || notifiers.has(peer); +}; @@ -59,6 +59,12 @@ const methods = [ ]; const week = 7 * 24 * 60 * 60; + +// Fee cap for a connection with no max fee of its own: 1% of the amount, but +// never under 5 sats. Plain 1% rounds to 0 below 50 sats, and a 0 cap rejects +// any zap whose route costs a single sat. Unused fee is refunded. +const defaultMaxFee = (amount: number) => + Math.max(5, Math.ceil(amount * 0.01)); const nwcEventMaxAgeSeconds = 5 * 60; // Tolerated clock skew for future-dated events. Events further ahead than this // are rejected so a captured, future-dated signed event can't be replayed later. @@ -704,7 +710,7 @@ const handle = (method, params, ev, app, user) => // payment had settled; see issue #80). const p = await sendLightning({ amount, - fee: max_fee || Math.round(amount * 0.01), + fee: max_fee || defaultMaxFee(amount), user, pr, memo: JSON.stringify(metadata), @@ -877,7 +883,7 @@ const handle = (method, params, ev, app, user) => try { const p = await sendLightning({ amount, - fee: app.max_fee || Math.round(amount * 0.01), + fee: app.max_fee || defaultMaxFee(amount), user, pr, memo: metadata ? JSON.stringify(metadata) : undefined, diff --git a/lib/payments.ts b/lib/payments.ts index 09cf2cf6..6cde225c 100644 --- a/lib/payments.ts +++ b/lib/payments.ts @@ -1,4 +1,5 @@ import config from "$config"; +import { safeGot } from "$lib/safe-fetch"; import { existsSync } from "fs"; import api from "$lib/api"; import { requireAccount } from "$lib/auth"; @@ -41,6 +42,7 @@ import { } from "$lib/utils"; import { callWebhook } from "$lib/webhooks"; import { maybeForwardToV3, retryV3Forwards } from "$lib/v3forward"; +import { addHold, heldMessage, holdAllowance, holdKey, isExitNode } from "$lib/hold"; import changeid from "$lib/changeid"; import rpc from "@coinos/rpc"; import { bech32 } from "bech32"; @@ -103,6 +105,13 @@ const { URL } = process.env; const dust = 547; +// Freeze matches on EITHER the current username OR the uid. The uid never +// changes, so renaming the account can't shake the freeze — add the uid to the +// `blacklist` set to freeze a compromised account durably. +export const isBlacklisted = async (user) => + (await db.sIsMember("blacklist", user?.username?.toLowerCase().trim())) || + (!!user?.id && (await db.sIsMember("blacklist", user.id))); + export const debit = async ({ aid = undefined, hash, @@ -115,6 +124,9 @@ export const debit = async ({ // a v3 bridge forward (lib/v3forward.ts) costs routing only exempt = false, maxTotal = undefined, + // a Lightning send that lands in our own on-chain liquidity (see + // isExitNode), which deposit holds treat like an on-chain withdrawal + exitNode = false, }) => { amount = Number.parseInt(amount); @@ -122,13 +134,7 @@ export const debit = async ({ "whitelist", user?.username?.toLowerCase().trim(), ); - - // Blacklist (freeze) matches on EITHER the current username OR the uid. The - // uid never changes, so renaming the account can't shake the freeze — add the - // uid to the `blacklist` set to freeze a compromised account durably. - const blacklisted = - (await db.sIsMember("blacklist", user?.username?.toLowerCase().trim())) || - (!!user?.id && (await db.sIsMember("blacklist", user.id))); + const blacklisted = await isBlacklisted(user); if (hash && await db.sIsMember("blocked_addresses", hash)) { err(`SECURITY: blocked send to ${hash} by ${user.username}`); @@ -265,18 +271,44 @@ export const debit = async ({ const frozenBalance = !blacklisted || whitelisted ? 0 : await g(`balance:${uid}`); - ourfee = await db.debit( - `balance:${aid}`, - `credit:${creditType}:${aid !== uid ? 0 : uid}`, - t(user).insufficientFunds, - amount || 0, - tip || 0, - fee || 0, - ourfee || 0, - frozenBalance || 0, - ); + // Deposit hold: held sats can't leave on-chain (or into our own on-chain + // liquidity over Lightning). v3 bridge forwards and whitelisted accounts are + // not restricted. + const onchain = + !exempt && + !whitelisted && + ([PaymentType.bitcoin, PaymentType.liquid].includes(type) || exitNode) && + !(await db.sIsMember("hold:exempt", aid)); - if (ourfee.err) fail(ourfee.err); + let heldUsed = 0; + let r: any; + try { + r = await db.debit( + `balance:${aid}`, + `credit:${creditType}:${aid !== uid ? 0 : uid}`, + t(user).insufficientFunds, + amount || 0, + tip || 0, + fee || 0, + ourfee || 0, + frozenBalance || 0, + holdKey(aid), + onchain ? 1 : 0, + ); + } catch (e: any) { + r = { err: e?.message }; + } + if (r?.err) { + const m = String(r.err).match(/HELD:(\d+):(\d+)/); + if (m) { + const n = quiet(`block:${aid}:held`, 5 * 60 * 1000); + if (n !== null) warn("Blocking", user.username, amount, hash, aid, type, "held", m[1], suppressed(n)); + fail(heldMessage(Number(m[1]), Number(m[2]))); + } + fail(r.err); + } + if (Array.isArray(r)) [ourfee, heldUsed] = r.map(Number); + else ourfee = r; // Defense-in-depth: the DEBIT lua rejects overdrafts, so a negative balance // here means the invariant was violated by a mismatched input or a non-lua @@ -313,6 +345,7 @@ export const debit = async ({ type, ref, tip, + held: heldUsed || undefined, created: Date.now(), }; @@ -341,8 +374,18 @@ export const credit = async ({ payment_hash = undefined, created = undefined, tip = undefined, + // held sats the sender of an internal transfer spent (debit's p.held) + held = 0, + // where a Lightning deposit came from, for the hold review log + holdNote = undefined, }) => { amount = Number.parseInt(amount) || 0; + // type drives the one-time credit guards below; anything but a known + // string (e.g. ["bitcoin"] from a request body) would skip them. + if (!Object.values(PaymentType).includes(type as any)) { + warn("credit with invalid type", JSON.stringify(type), hash, amount, ref); + return; + } // Kill switch (see routes/payments.ts confirm): no Liquid credits at all // while `liquid:deposits:disabled` is set. @@ -469,6 +512,12 @@ export const credit = async ({ let balanceKey = "balance"; if ([PaymentType.bitcoin, PaymentType.liquid].includes(type)) { const [txid, vout] = ref.split(":").slice(-2); + // Permanent first-credit claim per output. Unlike `payment:<txid>:<vout>`, + // nothing else writes or deletes this key. + if (!(await db.set(`credited:${txid}:${vout}`, id, { NX: true }))) { + warn("duplicate credit blocked", hash, ref); + return; + } p.confirmed = false; balanceKey = "pending"; await s(`payment:${txid}:${vout}`, id); @@ -521,6 +570,23 @@ export const credit = async ({ ); } + // Deposit hold: Lightning deposits, and internal transfers of sats that + // were themselves held, can't be withdrawn on-chain until reviewed. + const holdExempt = await db.sIsMember("hold:exempt", aid || uid); + const holdAmt = holdExempt + ? 0 + : [PaymentType.lightning, PaymentType.bolt12].includes(type) + ? ((await g("hold:enabled")) ? amount - (await holdAllowance(aid || uid, amount)) : 0) + : type === PaymentType.internal + ? Math.min(Number(held) || 0, amount) + : 0; + if (holdAmt > 0) + addHold(m, aid || uid, holdAmt, { + type, + pid: p.id, + from: holdNote || (type === PaymentType.internal ? `internal from ${ref}` : undefined), + }); + await m.set(`invoice:${inv.id}`, JSON.stringify(inv)) .set(`payment:${p.id}`, JSON.stringify(p)) .lPush(`${aid || uid}:payments`, p.id) @@ -597,6 +663,8 @@ const pay = async ({ aid = undefined, amount, to, user }) => { let pr; if (to.includes("@") && to.includes(".")) { const [name, domain] = to.split("@"); + if (!name || /[\/\\?#%@\s]|\.\./u.test(name) || !/^[a-z0-9.-]+(:\d+)?$/i.test(domain || "")) + fail("Invalid lightning address"); if (URL.includes(domain)) to = name; lnurl = `https://${domain}/.well-known/lnurlp/${name}`; } else if (to.startsWith("lnurl")) { @@ -625,8 +693,8 @@ const pay = async ({ aid = undefined, amount, to, user }) => { const fee = Math.max(5, Math.round(amount * 0.02)); if (lnurl) { amount -= fee; - const { callback } = (await got(lnurl).json()) as any; - ({ pr } = (await got(`${callback}?amount=${amount * 1000}`).json()) as any); + const { callback } = (await safeGot(lnurl)) as any; + ({ pr } = (await safeGot(`${callback}?amount=${amount * 1000}`)) as any); } else if (to.startsWith("ln")) { amount -= fee; pr = to; @@ -660,6 +728,22 @@ const inflight = {}; export const sendOnchain = async (params) => { let { aid, hex, rate, user, signed } = params; aid = await requireAccount({ aid, user }); + + // A frozen account's debit is going to fail anyway, but only after we've + // built the tx and locked its inputs. Frozen throwaways retry every few + // seconds, so each attempt holds hot-wallet UTXOs and legit withdrawals fail + // with "output already locked". Refuse before touching the wallet; the + // message matches what debit() would have said. + if ( + (await isBlacklisted(user)) && + !(await db.sIsMember("whitelist", user?.username?.toLowerCase().trim())) + ) { + const n = quiet(`block:${user.id}:frozen-onchain`, 5 * 60 * 1000); + if (n !== null) + warn("Blocking frozen on-chain send", user.username, user.id, suppressed(n)); + fail(`${t(user).insufficientFunds} ⚡️0`); + } + const supplied = !!hex; if (!hex) ({ hex } = await build(params)); @@ -731,10 +815,40 @@ export const sendOnchain = async (params) => { // fund fresh throwaway accounts and sweep each one on-chain to the same // address, so freezing accounts is a treadmill while the destination is // constant. + // + // The list feeds itself through the `mules` set: an account caught + // sending to a marked address is frozen and recorded as a mule, and a + // mule's withdrawal attempts mark their destinations (mules are funded + // fresh and sweep to the same exit, so this catches each one on its first + // withdrawal instead of hours later). A plain `blacklist` freeze does NOT + // feed the list: those are often takeover victims, and their real owner's + // own withdrawal address must not get blocked. Add a + // uid to `mules` by hand to mark a known drain account. + const uname = user?.username?.toLowerCase().trim(); + const exempt = !!uname && (await db.sIsMember("whitelist", uname)); + const dests: string[] = []; for (const { scriptPubKey: { address }, } of tx.vout) { - if (address && (await db.sIsMember("blocked_addresses", address))) { + if (!address || (await node.getAddressInfo(address)).ismine) continue; + dests.push(address); + } + const markDests = async (why: string) => { + for (const address of dests) + if (await db.sAdd("blocked_addresses", address)) { + await db.hSet("blocked_addresses:source", address, JSON.stringify({ uid: user.id, username: user.username, at: Date.now() })); + err(`SECURITY: ${why} ${user.username} ${user.id} sent to ${address}, address blocked`); + } + }; + if (!exempt && user?.id && (await db.sIsMember("mules", user.id))) + await markDests("mule"); + for (const address of dests) { + if (await db.sIsMember("blocked_addresses", address)) { + if (!exempt && user?.id) { + if (await db.sAdd("blacklist", user.id)) + err(`SECURITY: froze ${user.username} ${user.id} for sending to blocked address ${address}`); + if (await db.sAdd("mules", user.id)) await markDests("mule"); + } const n = quiet(`blockedaddr:${user.id}`, 5 * 60 * 1000); if (n !== null) err( @@ -824,6 +938,15 @@ export const sendOnchain = async (params) => { } }; +// Ceiling on the routing fee a send may reserve: 5% of the amount or 1000 +// sats, whichever is larger. An invoice can carry route hints with arbitrary +// fees, and whoever controls those hints keeps the difference, so a caller- +// named fee must not be trusted past what real routes cost. +const checkRoutingFee = (amount, fee) => { + const max = Math.max(1000, Math.ceil(amount * 0.05)); + if (fee > max) fail(`Routing fee of ⚡️${fee} exceeds the ⚡️${max} limit`); +}; + export const sendKeysend = async ({ hash, amount, @@ -835,6 +958,7 @@ export const sendKeysend = async ({ maxTotal = undefined, }) => { fee = Math.max(Number.parseInt(fee || amount * 0.005), 5); + checkRoutingFee(amount, fee); let p = await gf(`payment:${hash}`); if (p) fail("duplicate keysend"); @@ -847,6 +971,7 @@ export const sendKeysend = async ({ user, type: PaymentType.lightning, maxTotal, + exitNode: await isExitNode(pubkey), }); let outcome = "unknown"; @@ -1011,6 +1136,11 @@ export const sendLightning = async ({ const amt = amount_msat ? Math.round(amount_msat / 1000) : amount; + // Bots retrying sends against an empty account would otherwise cost an + // askrene query each. debit() below is still the authoritative check. + if (amt > (Number.parseInt(await g(`balance:${user.id}`)) || 0)) + fail(t(user).insufficientFunds); + // Ask askrene up front what routing this will cost — the same query xpay // runs — so the maxfee we reserve is the real fee, not a guess. A caller // that names its own cap keeps it (finalize refunds whatever xpay doesn't @@ -1022,7 +1152,9 @@ export const sendLightning = async ({ try { ({ fee: quoted } = await quoteRoutingFee({ pr, amount: amt })); } catch (e: any) { - warn("route quote failed", pr.substr(-8), shortError(e?.message)); + const n = quiet(`quotefail:${user.id}`, 5 * 60 * 1000); + if (n !== null) + warn("route quote failed", user.username, pr.substr(-8), shortError(e?.message), suppressed(n)); } const explicit = Number.parseInt(fee); @@ -1039,6 +1171,7 @@ export const sendLightning = async ({ if (channels.some((c) => c.peer_id === payee)) minfee = 0; fee = minfee; } + checkRoutingFee(amt, fee); const { pays } = await ln.listpays(pr); if (pays.find((p) => p.status === "complete")) @@ -1067,6 +1200,7 @@ export const sendLightning = async ({ type: PaymentType.lightning, maxTotal, exempt, + exitNode: await isExitNode(payee), }); await db.sAdd("pending", pr); @@ -1229,7 +1363,7 @@ export const sendInternal = async ({ const { hash } = invoice; const p = await debit({ hash, amount, memo, user: sender, maxTotal }); - await credit({ hash, amount, memo, ref: sender.id, tip: p.tip }); + await credit({ hash, amount, memo, ref: sender.id, tip: p.tip, held: p.held }); if (invoice.memo?.includes("9734")) { const { invoices } = await ln.listinvoices({ invstring: hash }); @@ -1381,19 +1515,24 @@ export const catchUp = async () => { // Each chain is isolated: one being unreachable (e.g. lq when cs is down) // must not stop the other chain's deposit-recovery loop. for (const [type, n] of Object.entries({ bitcoin: bc, liquid: lq })) { - try { - txns.push( - ...(await n.listTransactions("*", 100)).filter((tx) => { - tx.type = type; - return tx.category === "receive" && tx.confirmations > 0; - }), - ); - } catch (e: any) { - warnThrottled(`catchUp ${type}`, e.message); + // the hot wallet, then any retired ones still receiving (legacyWallets) + const wallets = [[config[type]?.wallet, n], ...((config[type]?.legacyWallets || []).map((w) => [w, rpc({ ...config[type], wallet: w })]))]; + for (const [wallet, node] of wallets) { + try { + txns.push( + ...(await node.listTransactions("*", 100)).filter((tx) => { + tx.type = type; + tx.wallet = wallet; + return tx.category === "receive" && tx.confirmations > 0; + }), + ); + } catch (e: any) { + warnThrottled(`catchUp ${type} ${wallet}`, e.message); + } } } - for (const { txid, type } of txns) { + for (const { txid, type, wallet } of txns) { try { if (await db.zScore("seen", txid)) continue; // walletnotify is the primary path; catchUp is a safety net. The @@ -1401,7 +1540,7 @@ export const catchUp = async () => { // on cs's lq — now that's fixed, a single call suffices and avoids // contributing to /confirm race conditions. await got.post(`http://localhost:${process.env.PORT || 3119}/confirm`, { - json: { txid, wallet: config[type].wallet, type }, + json: { txid, wallet: wallet || config[type].wallet, type }, }); await db.zAdd("seen", { score: Date.now(), value: txid }); @@ -1592,6 +1731,8 @@ const reverse = async (p) => { credit, p.hash, ); + // give back any deposit hold the send released + if (p.held > 0) await db.incrBy(holdKey(p.aid || p.uid), p.held); warn("reversed", p.id); }; diff --git a/lib/register.ts b/lib/register.ts index a9e9d7f7..bb9ce4b8 100644 --- a/lib/register.ts +++ b/lib/register.ts @@ -24,6 +24,17 @@ export default async (user, ip) => { if (isReserved(username)) fail("Invalid username"); if (username.includes("undefined")) fail("Invalid username"); + // Keys revoked by changeid() belong to compromised accounts, and a key that + // already resolves to a live account must not be re-pointed at a new one. + if (pubkey) { + const holder = await db.get(`user:${pubkey}`); + if ( + (await db.sIsMember("revoked:pubkeys", pubkey)) || + (holder && (await db.exists(`user:${holder.replace(/"/g, "")}`))) + ) + fail("Key in use by another account"); + } + const id = v4(); user.id = id; 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/lib/safe-fetch.ts b/lib/safe-fetch.ts index 5b1059e9..b1d082f6 100644 --- a/lib/safe-fetch.ts +++ b/lib/safe-fetch.ts @@ -26,6 +26,7 @@ const blockedV4 = (ip: string): boolean => { if (a === 127) return true; // loopback if (a === 169 && b === 254) return true; // link-local + cloud metadata (169.254.169.254) if (a === 172 && b >= 16 && b <= 31) return true; // private + if (a === 172 && b === 42) return true; // cs Docker network uses 172.42.0.0/16 if (a === 192 && b === 168) return true; // private if (a === 100 && b >= 64 && b <= 127) return true; // CGNAT 100.64/10 (incl. tailscale) if (a >= 224) return true; // multicast / reserved @@ -163,3 +164,55 @@ const fetchOnce = (url: string, redirectsLeft: number): Promise<any> => // Fetch a user-supplied URL with SSRF protection and return the parsed JSON // body. Throws on a bad scheme/URL or a host that resolves into a blocked range. export const safeGot = async (url: string): Promise<any> => fetchOnce(url, MAX_REDIRECTS); + +// POST JSON to a user-supplied URL (merchant webhooks) with the same +// protections as safeGot: http(s) only, the socket pinned to an address that +// was checked, and no redirects at all (a redirect could turn a public URL +// into an internal one). The response body is discarded; resolves with the +// status code. +export const safePost = (url: unknown, json: unknown): Promise<number> => + new Promise((resolve, reject) => { + if (typeof url !== "string" || url.length > 2048) + return reject(new Error("invalid url")); + let u: URL; + try { u = new URL(url); } catch { return reject(new Error("invalid url")); } + if (u.protocol !== "http:" && u.protocol !== "https:") + return reject(new Error("unsupported scheme")); + const literal = u.hostname.replace(/^\[|\]$/g, ""); + if (net.isIP(literal) && isBlockedIp(literal)) + return reject(new Error(`blocked host ${literal}`)); + + const body = Buffer.from(JSON.stringify(json)); + const mod = u.protocol === "https:" ? https : http; + const req = mod.request( + url, + { + method: "POST", + lookup: pinnedLookup as any, + headers: { "content-type": "application/json", "content-length": body.length }, + }, + (res) => { + res.resume(); + resolve(res.statusCode || 0); + }, + ); + req.setTimeout(TIMEOUT_MS, () => req.destroy(new Error("request timed out"))); + req.on("error", reject); + req.end(body); + }); + +// For URLs we hand to a library that does its own connecting (nostr relays +// over WebSocket): allow only ws/wss to a host whose every resolved address +// is public. Not rebind-proof like safeGot, but keeps user-supplied relay +// lists from pointing us at internal services. +export const safeRelayUrl = async (raw: string): Promise<boolean> => { + let u: globalThis.URL; + try { u = new globalThis.URL(raw); } catch { return false; } + if (u.protocol !== "ws:" && u.protocol !== "wss:") return false; + const host = u.hostname.replace(/^\[|\]$/g, ""); + if (net.isIP(host)) return !isBlockedIp(host); + try { + const addrs = await dns.promises.lookup(host, { all: true }); + return addrs.length > 0 && addrs.every((a) => !isBlockedIp(a.address)); + } catch { return false; } +}; diff --git a/lib/types.ts b/lib/types.ts index 802fe995..553a50b5 100644 --- a/lib/types.ts +++ b/lib/types.ts @@ -35,8 +35,6 @@ export interface User { push: string; reserve: string; seed: string; - shopifyStore: string; - shopifyToken: string; theme: string; threshold: string; twofa: string; diff --git a/lib/utils.ts b/lib/utils.ts index 539258a4..c52c8a9c 100644 --- a/lib/utils.ts +++ b/lib/utils.ts @@ -181,5 +181,7 @@ export const fields = [ "prompt", "pubkey", "username", + // when this account last handed its name to v3 (see users.update) + "v3migrated", "website", ]; diff --git a/lib/v3forward.ts b/lib/v3forward.ts index 9a263acd..525c1be1 100644 --- a/lib/v3forward.ts +++ b/lib/v3forward.ts @@ -19,6 +19,7 @@ import { PaymentType } from "$lib/types"; // account's own session named in a migration grant (`granted`). A name that // merely exists on v3 is never forwarded to. +import { holderBlocked } from "$lib/names"; const NAMES_URL = process.env.NAMES_URL || "https://names.coinos.io"; const DOMAIN = "coinos.io"; const TYPES = [PaymentType.lightning, PaymentType.bolt12, PaymentType.bitcoin, PaymentType.liquid]; @@ -34,6 +35,13 @@ async function v3Holder(username: string): Promise<{ pk: string | null; granted: if (hit && Date.now() - hit.at < (hit.pk ? 60_000 : 600_000)) return hit; const r = await fetch(`${NAMES_URL}/name/${encodeURIComponent(name)}?domain=${DOMAIN}`, { signal: AbortSignal.timeout(2000) }); + // 404 is the registrar's answer for a name that can't exist on v3 (a legacy + // username with spaces, say), so nobody holds it + if (r.status === 404) { + const none = { at: Date.now(), pk: null, granted: false }; + holderCache.set(name, none); + return none; + } if (!r.ok) throw new Error(`registrar said ${r.status}`); const body: any = await r.json(); const pk = body?.taken && typeof body.pubkey === "string" ? body.pubkey : null; @@ -46,6 +54,7 @@ async function v3Holder(username: string): Promise<{ pk: string | null; granted: export async function v3Destination(user): Promise<string | null> { if (!user?.username || !user?.pubkey || user.username.length > 64) return null; const { pk, granted } = await v3Holder(user.username); + if (pk && (await holderBlocked(user.username))) return null; return pk && (granted || pk === user.pubkey) ? user.username.toLowerCase() : null; } diff --git a/lib/webhooks.ts b/lib/webhooks.ts index d724ccdf..ef9b43b1 100644 --- a/lib/webhooks.ts +++ b/lib/webhooks.ts @@ -1,5 +1,5 @@ import config from "$config"; -import got from "got"; +import { safePost } from "$lib/safe-fetch"; import { l, err } from "$lib/logging"; export const callWebhook = async (invoice, payment) => { @@ -8,7 +8,10 @@ export const callWebhook = async (invoice, payment) => { const { address, received, text, webhook, secret } = invoice; - if (webhook) { + // The webhook URL is whatever the invoice's creator typed, so it goes + // through the SSRF guard and must be a plain string: an object here would + // be read as a full set of request options (headers, credentials, ...). + if (typeof webhook === "string" && webhook) { const { amount, confirmed, hash, memo } = payment; l("calling webhook", webhook, amount, hash, address, text); @@ -19,19 +22,16 @@ export const callWebhook = async (invoice, payment) => { // "payment received" callbacks to that merchant. A merchant on a // self-signed cert now fails here instead, which the catch below logs; // the payment itself is unaffected. - const res = await got.post(webhook, { - json: { - address, - amount, - confirmed, - hash, - memo, - received, - text, - secret, - }, + return await safePost(webhook, { + address, + amount, + confirmed, + hash, + memo, + received, + text, + secret, }); - return res; } } catch (e) { err("problem calling webhook", e.message); diff --git a/lib/whitelist.ts b/lib/whitelist.ts index f305f516..96733984 100644 --- a/lib/whitelist.ts +++ b/lib/whitelist.ts @@ -37,8 +37,6 @@ export default [ "push", "reserve", "seed", - "shopifyStore", - "shopifyToken", "theme", "threshold", "tip", diff --git a/meltguard.ts b/meltguard.ts index c7195bb0..33b579bf 100644 --- a/meltguard.ts +++ b/meltguard.ts @@ -18,8 +18,28 @@ // Everything that is not POST /v1/pay|/v1/xpay is proxied through untouched, so mint // startup (getinfo, listinvoices, waitanyinvoice, invoice, listpays…) works normally. // -// Env: CL_URL (http://cl:3010), MELT_MAX_SAT, MELT_CUM_MAX_SAT, GUARD_DIR (/guard), -// PORT (3011). Run: GUARD_DIR=./guard bun meltguard.ts +// 3. ONE PAY PER PAYMENT HASH — refuse any pay for a hash the guard has +// already forwarded, and refuse partial (MPP, `partial_msat`) pays. The +// mint settles a melt by payment hash, so two melt quotes on one invoice +// let a failed (held) first attempt absorb the settlement of a second one +// that cl actually paid: the mint returns the proofs and the same ecash +// can be melted again. +// +// With MELT_WINDOW_SEC set, the cumulative cap is a rolling window and a pay +// over it is REJECTED rather than freezing the guard (for the live mint, where +// normal redemptions would otherwise trip a lifetime cap). +// +// A pay the guard refuses for an amount cap (per-melt or rolling window) never +// reaches cl, so cl's listpays has nothing for that hash. nutshell >= 0.22 reads +// an empty listpays as NOT_FOUND and keeps the melt quote PENDING forever, which +// locks the user's proofs. Such hashes are recorded in GUARD_DIR/rejected, and a +// listpays for one of them that cl answers with no pays is reported as a failed +// pay, so the mint marks the quote UNPAID and releases the proofs. When cl has a +// pay for the hash, cl's answer is passed through unchanged. Repeat-hash and +// partial-pay refusals are not recorded: another quote on that hash may be real. +// +// Env: CL_URL (http://cl:3010), MELT_MAX_SAT, MELT_CUM_MAX_SAT, MELT_WINDOW_SEC, +// GUARD_DIR (/guard), PORT (3011). Run: GUARD_DIR=./guard bun meltguard.ts import { readFileSync, writeFileSync, existsSync, appendFileSync, mkdirSync } from "fs"; const CL = process.env.CL_URL || "http://cl:3010"; @@ -31,6 +51,18 @@ mkdirSync(DIR, { recursive: true }); const CUM_FILE = `${DIR}/cumulative_sat`; const FROZEN_FILE = `${DIR}/FROZEN`; const LOG = `${DIR}/meltguard.log`; +const HASH_FILE = `${DIR}/hashes`; +const WINDOW_FILE = `${DIR}/window.json`; +const WINDOW = Number(process.env.MELT_WINDOW_SEC || 0) * 1000; +const seen = new Set(existsSync(HASH_FILE) ? readFileSync(HASH_FILE, "utf8").split("\n").filter(Boolean) : []); +const remember = (h: string) => { seen.add(h); appendFileSync(HASH_FILE, h + "\n"); }; +const REJECTED_FILE = `${DIR}/rejected`; +const loadRejected = () => new Set(existsSync(REJECTED_FILE) ? readFileSync(REJECTED_FILE, "utf8").split("\n").map((x) => x.trim()).filter(Boolean) : []); +let rejected = loadRejected(); +const markRejected = (h: string) => { if (rejected.has(h)) return; rejected.add(h); appendFileSync(REJECTED_FILE, h + "\n"); }; +type Spend = { ts: number; amt: number }; +let spends: Spend[] = existsSync(WINDOW_FILE) ? JSON.parse(readFileSync(WINDOW_FILE, "utf8") || "[]") : []; +const windowSum = () => { const cut = Date.now() - WINDOW; spends = spends.filter((x) => x.ts >= cut); return spends.reduce((a, x) => a + x.amt, 0); }; const readCum = () => (existsSync(CUM_FILE) ? Number(readFileSync(CUM_FILE, "utf8").trim()) || 0 : 0); const writeCum = (n: number) => writeFileSync(CUM_FILE, String(n)); @@ -39,16 +71,17 @@ const log = (m: string) => { try { appendFileSync(LOG, `${new Date().toISOString const freeze = (why: string) => { writeFileSync(FROZEN_FILE, why + "\n"); log(`FROZEN — ${why} — operator must review and clear ${FROZEN_FILE}`); }; const err = (status: number, message: string) => new Response(JSON.stringify({ error: message }), { status, headers: { "content-type": "application/json" } }); -async function decodeSat(bolt11: string, rune: string | null): Promise<number | null> { +async function decode(bolt11: string, rune: string | null): Promise<{ sat: number; hash: string } | null> { try { const r = await fetch(`${CL}/v1/decode`, { method: "POST", headers: { "content-type": "application/json", ...(rune ? { Rune: rune } : {}) }, body: JSON.stringify({ string: bolt11 }) }); const j: any = await r.json(); - if (j.amount_msat != null) return Math.ceil(Number(j.amount_msat) / 1000); - return null; // amountless invoice — no embedded amount to cap on; treat as undecidable + // amountless invoice — no embedded amount to cap on; treat as undecidable + if (j.amount_msat == null || typeof j.payment_hash !== "string") return null; + return { sat: Math.ceil(Number(j.amount_msat) / 1000), hash: j.payment_hash }; } catch { return null; } } -console.log(`meltguard on :${PORT} -> ${CL} | per-melt<=${PER} sat, cumulative freeze at ${CUM} sat | state ${DIR} | frozen=${isFrozen()} cum=${readCum()}`); +console.log(`meltguard on :${PORT} -> ${CL} | per-melt<=${PER} sat, ${WINDOW ? `rolling ${WINDOW / 1000}s cap ${CUM}` : `cumulative freeze at ${CUM}`} sat | state ${DIR} | frozen=${isFrozen()} cum=${readCum()} hashes=${seen.size}`); Bun.serve({ port: PORT, hostname: "0.0.0.0", idleTimeout: 0, @@ -86,11 +119,21 @@ Bun.serve({ for (const k of Object.keys(j)) if (k !== "invoice" && k !== "bolt11" && k !== "invstring") extra[k] = String(j[k]); } catch {} } - const amt = await decodeSat(invoice, rune); - if (amt == null) return err(400, "meltguard: could not determine invoice amount — refusing to forward"); - if (amt > PER) { log(`REJECT per-melt ${amt} > ${PER}`); return err(403, `meltguard: per-melt cap ${PER} sat exceeded (${amt})`); } - const cum = readCum(); - if (cum + amt > CUM) { freeze(`cumulative ${cum}+${amt} > ${CUM}`); return err(403, `meltguard: cumulative cap ${CUM} sat — FROZEN, operator review required`); } + const inv = await decode(invoice, rune); + if (!inv) return err(400, "meltguard: could not determine invoice amount — refusing to forward"); + const amt = inv.sat; + if (extra.partial_msat != null || extra.amount_msat != null) { log(`REJECT partial pay ${extra.partial_msat ?? extra.amount_msat} msat of ${amt} sat hash=${inv.hash}`); return err(403, "meltguard: partial payments are not allowed"); } + if (seen.has(inv.hash)) { log(`REJECT repeat pay hash=${inv.hash} ${amt} sat`); return err(403, "meltguard: this invoice has already been attempted"); } + if (amt > PER) { markRejected(inv.hash); log(`REJECT per-melt ${amt} > ${PER}`); return err(403, `meltguard: per-melt cap ${PER} sat exceeded (${amt})`); } + const cum = WINDOW ? windowSum() : readCum(); + if (cum + amt > CUM) { + if (WINDOW) { markRejected(inv.hash); log(`REJECT window ${cum}+${amt} > ${CUM}`); return err(403, `meltguard: rolling cap ${CUM} sat reached, try later`); } + freeze(`cumulative ${cum}+${amt} > ${CUM}`); return err(403, `meltguard: cumulative cap ${CUM} sat — FROZEN, operator review required`); + } + // Claim the hash and the window budget before forwarding, so concurrent + // or later pays for the same invoice are refused even if this one fails. + remember(inv.hash); + if (WINDOW) { spends.push({ ts: Date.now(), amt }); writeFileSync(WINDOW_FILE, JSON.stringify(spends)); } // forward to cl (official CLNREST) as FORM on the SAME endpoint the mint // called (`invstring` for xpay, `bolt11` for pay), preserving the mint's // other params (maxfee / maxfeepercent / exemptfee). Count cumulative only @@ -98,13 +141,32 @@ Bun.serve({ const fwd = new URLSearchParams(isXpay ? { invstring: invoice, ...extra } : { bolt11: invoice, ...extra }); const resp = await fetch(`${CL}${isXpay ? "/v1/xpay" : "/v1/pay"}`, { method: "POST", headers: { "content-type": "application/x-www-form-urlencoded", ...(rune ? { Rune: rune } : {}) }, body: fwd.toString() }); const text = await resp.text(); - if (resp.ok) { writeCum(cum + amt); log(`PAID ${amt} sat via ${isXpay ? "xpay" : "pay"} (cumulative ${cum + amt}/${CUM})`); } + if (resp.ok) { if (!WINDOW) writeCum(cum + amt); log(`PAID ${amt} sat via ${isXpay ? "xpay" : "pay"} hash=${inv.hash} (${WINDOW ? "window" : "cumulative"} ${cum + amt}/${CUM})`); } + else log(`FAILED ${amt} sat hash=${inv.hash} status=${resp.status} ${text.slice(0, 160)}`); return new Response(text, { status: resp.status, headers: { "content-type": "application/json" } }); } // transparent proxy for all other CLNRest calls const body = req.method === "GET" || req.method === "HEAD" ? undefined : await req.arrayBuffer(); const resp = await fetch(`${CL}${url.pathname}${url.search}`, { method: req.method, headers: { ...(req.headers.get("content-type") ? { "content-type": req.headers.get("content-type")! } : {}), ...(rune ? { Rune: rune } : {}) }, body }); + if (req.method === "POST" && url.pathname === "/v1/listpays" && body && resp.ok) { + const raw = new TextDecoder().decode(body); + let hash = ""; + try { hash = new URLSearchParams(raw).get("payment_hash") || ""; } catch {} + if (!hash) { try { hash = JSON.parse(raw).payment_hash || ""; } catch {} } + // re-read so an operator can add a hash without a restart + if (hash) rejected = loadRejected(); + if (hash && rejected.has(hash)) { + const text = await resp.text(); + let j: any = null; + try { j = JSON.parse(text); } catch {} + if (j && Array.isArray(j.pays) && j.pays.length === 0) { + log(`listpays ${hash}: refused by guard, cl has no pay -> reporting failed`); + return new Response(JSON.stringify({ pays: [{ payment_hash: hash, status: "failed" }] }), { status: 200, headers: { "content-type": "application/json" } }); + } + return new Response(text, { status: resp.status, headers: { "content-type": resp.headers.get("content-type") || "application/json" } }); + } + } return new Response(await resp.arrayBuffer(), { status: resp.status, headers: { "content-type": resp.headers.get("content-type") || "application/json" } }); }, }); diff --git a/mintdemux.ts b/mintdemux.ts index d961b05b..1b93970b 100644 --- a/mintdemux.ts +++ b/mintdemux.ts @@ -19,7 +19,8 @@ // executed on OLD, else NEW — so wallets can poll a recovery melt // - /v1/checkstate -> both mints, merged (spent if either says spent) // - /v1/ws -> websocket proxy to NEW (subscriptions) -// - everything else (swap, mint, restore, mint quote) -> NEW +// - /v1/restore -> split by keyset: old outputs to OLD, rest to NEW +// - everything else (swap, mint, mint quote) -> NEW // The OLD mint also stands alone at mintrecovery.coinos.io (direct). // // Client-IP forwarding: cloudflared stamps cf-connecting-ip on every request; @@ -35,6 +36,9 @@ // LOG_DIR (/demux), PORT (3341) import { createHash } from "crypto"; import { appendFileSync, mkdirSync, readFileSync, existsSync, writeFileSync } from "fs"; +import { Database } from "bun:sqlite"; +import { secp256k1 } from "@noble/curves/secp256k1.js"; +import { sha256 } from "@noble/hashes/sha2.js"; const NEW = process.env.NEW_MINT || "http://mint:3338"; const OLD = process.env.OLD_MINT || "http://mint-old:3338"; @@ -52,6 +56,62 @@ const J = { ...CORS, "content-type": "application/json" }; const log = (m: string) => { try { appendFileSync(`${DIR}/demux.log`, `${new Date().toISOString()} ${m}\n`); } catch {} console.log("demux:", m); }; const parse = (s: string) => { try { return JSON.parse(s); } catch { return null; } }; +// --- provenance gate for a compromised keyset --- +// Ecash in a GATED keyset is spendable (swap/melt) only if each input carries +// its NUT-12 DLEQ blinding factor `r`, so we can recompute the blinded message +// B_ = hash_to_curve(secret) + r*G and look up which mint operation signed it. +// Allowed: signed before GATE_CUTOFF, or minted from a mint quote that is not +// blacklisted. Refused (fail-closed): blacklisted quotes, swap/melt-change +// outputs after the cutoff, anything we can't trace. Refusals are logged to +// gate.jsonl for manual review. +const GATED = new Set((process.env.GATED_KEYSETS || "").split(",").map(s => s.trim()).filter(Boolean)); +const GATE_CUTOFF = Number(process.env.GATE_CUTOFF || 0); +const GATE_BL = new Set(existsSync(`${DIR}/gate-blacklist`) ? readFileSync(`${DIR}/gate-blacklist`, "utf8").split("\n").map(s => s.trim()).filter(Boolean) : []); +const RECOVER = process.env.GATE_RECOVER || "email [email protected] with the token"; +let mintdb: Database | null = null; +function promiseOf(b_: string): any { + if (!mintdb) mintdb = new Database(process.env.MINT_DB || "/mintdb/mint.sqlite3", { readonly: true }); + return mintdb.query("select amount, created, mint_quote, swap_id, melt_quote from promises where b_ = ?").get(b_); +} +const G = secp256k1.Point.BASE; +const DST = new TextEncoder().encode("Secp256k1_HashToCurve_Cashu_"); +const cat = (...a: Uint8Array[]) => { const o = new Uint8Array(a.reduce((n, x) => n + x.length, 0)); let i = 0; for (const x of a) { o.set(x, i); i += x.length; } return o; }; +function hashToCurve(msg: Uint8Array) { + const h = sha256(cat(DST, msg)); + for (let c = 0; c < 65536; c++) { + const ctr = new Uint8Array(4); new DataView(ctr.buffer).setUint32(0, c, true); + const x = Buffer.from(sha256(cat(h, ctr))).toString("hex"); + try { return secp256k1.Point.fromHex("02" + x); } catch {} + } + throw new Error("hash_to_curve: no point"); +} +function gateVerdict(p: any): string | null { + const r = String(p?.dleq?.r || ""); + if (!/^[0-9a-f]{64}$/i.test(r)) return "missing DLEQ blinding factor"; + let b_: string; + try { b_ = hashToCurve(new TextEncoder().encode(String(p.secret))).add(G.multiply(BigInt("0x" + r))).toHex(true); } + catch { return "invalid proof"; } + let row: any; + try { row = promiseOf(b_); } catch (e: any) { return `lookup failed: ${e?.message}`; } + if (!row) return "unknown signature"; + if (Number(row.amount) !== Number(p.amount)) return "amount mismatch"; + if (Number(row.created) < GATE_CUTOFF) return null; + if (row.mint_quote && !GATE_BL.has(row.mint_quote)) return null; + if (row.mint_quote) return "issued from a blacklisted quote"; + return row.swap_id ? "swap output after cutoff" : "melt change after cutoff"; +} +function gateInputs(body: any, path: string, ip: string): Response | null { + if (!GATED.size || !Array.isArray(body?.inputs)) return null; + const gated = body.inputs.filter((p: any) => GATED.has(String(p?.id))); + if (!gated.length) return null; + const bad = gated.map((p: any) => ({ p, why: gateVerdict(p) })).filter((x: any) => x.why); + if (!bad.length) { log(`gate pass ${gated.length} input(s) ${gated.reduce((a: number, p: any) => a + (p?.amount || 0), 0)} sat ${path} ip=${ip}`); return null; } + const sat = bad.reduce((a: number, x: any) => a + (x.p?.amount || 0), 0); + try { appendFileSync(`${DIR}/gate.jsonl`, JSON.stringify({ t: new Date().toISOString(), ip, path, refused: bad.map((x: any) => ({ why: x.why, amount: x.p?.amount, id: x.p?.id, secret: x.p?.secret, C: x.p?.C, r: x.p?.dleq?.r })) }) + "\n"); } catch {} + log(`gate REFUSED ${bad.length}/${gated.length} input(s) ${sat} sat (${[...new Set(bad.map((x: any) => x.why))].join("; ")}) ${path} ip=${ip}`); + return new Response(JSON.stringify({ detail: `Some of this ecash is from a retired keyset and could not be verified. To recover it, ${RECOVER}`, code: 12005 }), { status: 400, headers: J }); +} + // --- keyset ownership, refreshed hourly --- let newKeysets = new Set<string>(); let oldKeysets = new Set<string>(); @@ -100,6 +160,31 @@ function rememberQuote(id: string, info: QInfo) { try { writeFileSync(QFILE, JSON.stringify(quoteMem)); } catch {} } +// --- melt quote screening --- +// Refuse MPP/amountless quote options and quotes we can't parse. Repeat quotes +// for one invoice are allowed, as upstream: nutshell >= 0.22.0 handles repeat +// payment attempts on a hash itself. +const B32 = "qpzry9x8gf2tvdw0s3jn54khce6mua7l"; +function bolt11Hash(inv: string): string | null { + const s = (inv || "").trim().toLowerCase().replace(/^lightning:/, ""); + const sep = s.lastIndexOf("1"); + if (!s.startsWith("ln") || sep < 0) return null; + const words: number[] = []; + for (const c of s.slice(sep + 1, -6)) { const v = B32.indexOf(c); if (v < 0) return null; words.push(v); } + let i = 7; // skip timestamp; tags stop before the 104-word signature + while (i + 3 <= words.length - 104) { + const tag = words[i], len = words[i + 1] * 32 + words[i + 2]; + const data = words.slice(i + 3, i + 3 + len); + if (tag === 1 && len === 52) { + let acc = 0, bits = 0; const out: number[] = []; + for (const w of data) { acc = (acc << 5) | w; bits += 5; while (bits >= 8) { bits -= 8; out.push((acc >> bits) & 255); } } + return Buffer.from(out.slice(0, 32)).toString("hex"); + } + i += 3 + len; + } + return null; +} + // --- NEW-quote-id -> OLD-quote-id map for melts executed on OLD, so status // polls (GET /v1/melt/quote/bolt11/<id>) can be routed to the mint that ran // the melt. Kept long: a pending lightning payment can be polled much later. @@ -239,6 +324,8 @@ Bun.serve({ // --- POST routes --- const raw = await req.arrayBuffer(); const body = parse(new TextDecoder().decode(raw)); + const gateResp = gateInputs(body, path, req.headers.get("cf-connecting-ip") || ""); + if (gateResp) return gateResp; if (path === "/v1/checkstate") { const [rn, ro] = await Promise.all([ @@ -251,6 +338,12 @@ Bun.serve({ } if (path === "/v1/melt/quote/bolt11") { + if (body?.options && Object.keys(body.options).length) { + log(`melt quote refused: options ${JSON.stringify(body.options).slice(0, 80)} ip=${key}`); + return new Response(JSON.stringify({ detail: "Multi-path and amountless melts are not supported", code: 11000 }), { status: 400, headers: J }); + } + const ph = bolt11Hash(body?.request); + if (!ph) return new Response(JSON.stringify({ detail: "Invalid invoice", code: 11000 }), { status: 400, headers: J }); const r = await fetch(`${NEW}/v1/melt/quote/bolt11`, { method: "POST", headers: fwd(key, true), body: raw }); const txt = await r.text(); const j = parse(txt); if (r.ok && j?.quote && body?.request) rememberQuote(j.quote, { invoice: body.request, unit: body.unit || "sat", ts: Date.now() }); @@ -302,7 +395,27 @@ Bun.serve({ return proxy(NEW, "POST", ps, raw, fwd(key, true)); } - // swap, mint, mint/quote, restore, everything else -> NEW (normal ops) + // NUT-09 restore: a seed-only wallet asks for every keyset it sees in + // /v1/keysets, so old-keyset outputs go to OLD (whose panic mode admits + // restore) and the rest to NEW. Results are concatenated; wallets pair + // signatures with the returned outputs, not with request order. + if (path === "/v1/restore" && Array.isArray(body?.outputs) && body.outputs.some((o: any) => oldKeysets.has(String(o?.id)))) { + const isOld = (o: any) => oldKeysets.has(String(o?.id)); + const parts = [[OLD, body.outputs.filter(isOld)], [NEW, body.outputs.filter((o: any) => !isOld(o))]] as const; + const rs = await Promise.all(parts.filter(([, outs]) => outs.length).map(async ([base, outs]) => { + const r = await fetch(`${base}/v1/restore`, { method: "POST", headers: fwd(key, true), body: JSON.stringify({ outputs: outs }) }); + return { r, txt: await r.text() }; + })); + const bad = rs.find(({ r }) => !r.ok); + if (bad) return respond(bad.r, bad.txt); + const merged = { outputs: [] as any[], signatures: [] as any[] }; + for (const { txt } of rs) { const j = parse(txt); merged.outputs.push(...(j?.outputs || [])); merged.signatures.push(...(j?.signatures || [])); } + const found = merged.signatures.filter((s: any) => oldKeysets.has(String(s?.id))); + if (found.length) log(`restore->OLD found ${found.length} sig(s) worth ${found.reduce((a: number, s: any) => a + (s?.amount || 0), 0)} sat ip=${req.headers.get("cf-connecting-ip") || ""}`); + return new Response(JSON.stringify(merged), { headers: J }); + } + + // swap, mint, mint/quote, everything else -> NEW (normal ops) return proxy(NEW, "POST", ps, raw, fwd(key, true)); }, // --- /v1/ws: pipe each client websocket to its own upstream connection on diff --git a/package.json b/package.json index 01a3a5e4..734a21bf 100644 --- a/package.json +++ b/package.json @@ -26,6 +26,7 @@ "@fastify/websocket": "^11.3.0", "@noble/hashes": "^1.8.0", "@scure/base": "^1.2.6", + "@scure/bip39": "^2.0.1", "bech32": "^2.0.0", "buffer-crc32": "^0.2.13", "clightning-client": "github:asoltys/lightning-client-js#master", diff --git a/routes/ecash.ts b/routes/ecash.ts index 995a8dce..e9c1cfdf 100644 --- a/routes/ecash.ts +++ b/routes/ecash.ts @@ -28,7 +28,7 @@ export default { } = req; try { const token = await get(id); - if (!token) fail("Ecash not found"); + if (!token) return bail(res, "Ecash not found"); const status = await check(token); res.send({ token, status }); } catch (e) { diff --git a/routes/lnurl.ts b/routes/lnurl.ts index 7f04db5d..20d795c0 100644 --- a/routes/lnurl.ts +++ b/routes/lnurl.ts @@ -5,6 +5,7 @@ import { serverPubkey2 } from "$lib/nostr"; import { SATS, bail, fail, getInvoice, getUser } from "$lib/utils"; import { bech32 } from "bech32"; import { safeGot } from "$lib/safe-fetch"; +import { lnurlPayload } from "$lib/lnurl-payload"; import { verifyEvent } from "nostr-tools"; import { v4 } from "uuid"; @@ -36,6 +37,8 @@ const unauthInvoiceBudget = async (uid: string) => { fail("Too many payment requests for this user, try again later"); } }; +import { holderBlocked } from "$lib/names"; + // v3 payment addresses (coinos v3 / halwallet) are registered here. const NAMES_URL = process.env.NAMES_URL || "https://names.coinos.io"; @@ -99,7 +102,7 @@ export default { bech32.fromWords(bech32.decode(text, 20000).words), ).toString(); - const r = await safeGot(url); + const r = lnurlPayload(await safeGot(url)); res.send(r); } catch (e) { bail(res, e.message); @@ -134,7 +137,7 @@ export default { // registrar never queries this endpoint for those. If the registrar is // unreachable we fall through and serve the local account — a briefly // stale destination beats an unpayable address. - const v3 = await registrarLookup(name); + const v3 = (await holderBlocked(name)) ? null : await registrarLookup(name); if (v3) return res.send(v3); const user = await getUser(name); @@ -240,11 +243,12 @@ export default { const { url } = req.query; if (!url) return bail(res, "url required"); try { - const r = await safeGot(url); + const r = lnurlPayload(await safeGot(url)); res.send(r); } catch (e) { - warn("lnurl proxy failed", url, e.message); - bail(res, e.message); + const n = quiet("lnurl-proxy-failure", 5 * 60 * 1000); + if (n !== null) warn("lnurl proxy failed", url, e.message, suppressed(n)); + bail(res, "Unable to resolve a valid LNURL response"); } }, diff --git a/routes/nostr.ts b/routes/nostr.ts index 3b28076a..023b656f 100644 --- a/routes/nostr.ts +++ b/routes/nostr.ts @@ -1,5 +1,6 @@ import config from "$config"; import { db, g, s } from "$lib/db"; +import { holderBlocked } from "$lib/names"; import ln from "$lib/ln"; import { EX, @@ -15,11 +16,12 @@ import { import { parseContent } from "$lib/notes"; import { scan } from "$lib/strfry"; import { bail, fail, fields, getUser } from "$lib/utils"; -import got from "got"; +import { safeGot } from "$lib/safe-fetch"; +import { bech32 } from "bech32"; import type { Event } from "nostr-tools"; import { decode } from "nostr-tools/nip19"; import type { ProfilePointer } from "nostr-tools/nip19"; -import { getZapEndpoint, makeZapRequest } from "nostr-tools/nip57"; +import { makeZapRequest } from "nostr-tools/nip57"; // Amount and payer of a zap receipt. NIP-57 kind 9735: amount comes from // decoding the paid bolt11, payer from the embedded 9734 zap request in the @@ -351,6 +353,7 @@ export default { // v3 registrar first: a claimed name's NIP-05 belongs to its wallet key. // Legacy accounts answer as before when the registrar doesn't know it. try { + if (await holderBlocked(name)) throw new Error("blocked holder"); const r = await fetch( `${process.env.NAMES_URL || "https://names.coinos.io"}/.well-known/nostr.json?name=${encodeURIComponent(name)}`, { signal: AbortSignal.timeout(3000) }, @@ -408,13 +411,28 @@ export default { const { event } = req.body; const amount = event.tags.find((t) => t[0] === "amount")[1]; const pubkey = event.tags.find((t) => t[0] === "p")[1]; - const content = JSON.stringify(await getProfile(pubkey)); - const callback = await getZapEndpoint({ content } as Event); - if (!callback || callback === "null") fail("Lightning address not found"); + // The recipient's profile is whatever they published, so its lightning + // address and the callback it leads to are fetched through the SSRF + // guard (nostr-tools' getZapEndpoint and got would fetch them as-is). + const { lud06, lud16 } = (await getProfile(pubkey)) || {}; + let lnurl: string; + if (typeof lud16 === "string" && /^[^@\s/?#]+@[^@\s/?#]+$/.test(lud16)) { + const [name, domain] = lud16.split("@"); + lnurl = `https://${domain}/.well-known/lnurlp/${encodeURIComponent(name)}`; + } else if (typeof lud06 === "string" && lud06) { + lnurl = Buffer.from( + bech32.fromWords(bech32.decode(lud06, 2000).words), + ).toString(); + } else fail("Lightning address not found"); - const encodedEvent = encodeURI(JSON.stringify(event)); - const url = `${callback}?amount=${amount}&nostr=${encodedEvent}`; - const json = await got(url).json(); + const pay = await safeGot(lnurl); + if (!pay?.allowsNostr || !pay.nostrPubkey || typeof pay.callback !== "string") + fail("Lightning address not found"); + + const u = new URL(pay.callback); + u.searchParams.set("amount", String(amount)); + u.searchParams.set("nostr", JSON.stringify(event)); + const json = await safeGot(u.toString()); res.send(json); } catch (e) { diff --git a/routes/payments.ts b/routes/payments.ts index 66fd3386..69eb992e 100644 --- a/routes/payments.ts +++ b/routes/payments.ts @@ -8,6 +8,7 @@ import ln from "$lib/ln"; import { platformFee, quoteMax, quoteRoutingFee } from "$lib/lnquote"; import { err, l, quiet, shortError, suppressed, warn } from "$lib/logging"; import mqtt from "$lib/mqtt"; +import { isNotifier } from "$lib/notifier"; import { build, completePayment, @@ -32,7 +33,9 @@ import { } from "$lib/utils"; import rpc from "@coinos/rpc"; import got from "got"; +import { safeGot } from "$lib/safe-fetch"; import { v4 } from "uuid"; +import { adminIpAllowed } from "$lib/adminip"; // Funds are closed. The mechanism let a caller pull unbacked balance out of a // fund (the /take drain, 2026-08-25) and its deposit path never had a @@ -40,12 +43,12 @@ import { v4 } from "uuid"; // INTO funds they were then unable to withdraw from. Every value-moving entry // point — deposit (POST /payments with `fund`), withdrawal (POST /take) and // pre-authorization (POST /authorize) — now refuses unconditionally, rather -// than depending on a redis flag someone can clear by accident. +// than depending on a redis flag someone can clear by accident. Adding and +// removing managers is closed too, so nobody can claim a manager-less fund. // -// Read paths are deliberately left working: GET /fund/:id and the manager -// endpoints still serve existing funds so balances stay visible and can be -// settled out of band. -const fundsClosed = () => fail("Funds are no longer supported"); +// Read paths are deliberately left working: GET /fund/:id and the managers +// list still serve existing funds so their history stays visible. +const fundsClosed = () => fail("Funds have been discontinued"); export default { async info(_, res) { @@ -284,17 +287,14 @@ export default { let fid = id; // A rotated fund no longer exists at its OLD id (security fix 2026-08-25: - // fund secret uids were rotated to invalidate an exfiltrated id list). Serve - // the new fund ONLY to an authenticated MANAGER of it — never anonymously or - // to a non-owner. An open old->new redirect would defeat the rotation, since - // the attacker holds the leaked OLD ids; gating on manager membership means a - // replayed old id reveals nothing unless you already control the fund. The - // route's `optional` auth populates req.user without requiring it. Bearer - // funds (no managers) are intentionally not recoverable this way. + // fund secret uids were rotated to invalidate an exfiltrated id list). + // That rotation existed to stop a leaked id being used to withdraw; funds + // are now closed and every value-moving route refuses (fundsClosed), so + // the old id resolves to the rotated fund for anyone, read-only, to keep + // its history viewable. if (typeof amount === "undefined" || amount === null) { const rotatedTo = await g(`fund:rotated:${id}`); - const uid = req.user?.id; - if (rotatedTo && uid && (await db.sIsMember(`fund:${rotatedTo}:managers`, uid))) { + if (rotatedTo) { fid = rotatedTo; amount = await g(`fund:${rotatedTo}`); } @@ -303,15 +303,31 @@ export default { if (typeof amount === "undefined" || amount === null) return bail(res, "fund not found"); - let payments = (await db.lRange(`fund:${fid}:payments`, 0, -1)) || []; - payments = await Promise.all(payments.map((hash) => gf(`payment:${hash}`))); + // Older history was moved to the archive, and funds rotated on 2026-08-25 + // keep their archived history under the pre-rotation id + // (fund:rotatedFrom:<new> -> old, backfilled from fund:rotated:*). + const oldId = fid !== id ? id : await g(`fund:rotatedFrom:${fid}`); + const lists = await Promise.all([ + db.lRange(`fund:${fid}:payments`, 0, -1), + archive.lRange(`fund:${fid}:payments`, 0, -1), + ...(oldId + ? [ + db.lRange(`fund:${oldId}:payments`, 0, -1), + archive.lRange(`fund:${oldId}:payments`, 0, -1), + ] + : []), + ]); + let payments: any[] = [...new Set(lists.flatMap((l) => l || []))]; + payments = await Promise.all(payments.map((pid) => gf(`payment:${pid}`))); + + payments = payments + .filter((p) => p) + .sort((a, b) => b.created - a.created); await Promise.all( payments.map(async (p: any) => (p.user = await getUser(p.uid, fields))), ); - payments = payments.filter((p) => p); - const authorization = await g(`authorization:${fid}`); res.send({ amount, @@ -498,6 +514,8 @@ export default { }, async addManager(req, res) { + fundsClosed(); + const { id, username } = req.body; const { user } = req; @@ -525,6 +543,8 @@ export default { }, async deleteManager(req, res) { + fundsClosed(); + try { const { name } = req.params; const { id: uid } = req.body; @@ -550,13 +570,36 @@ export default { async confirm(req, res) { const { - body: { txid, wallet, type }, + body: { wallet, type }, } = req; + // Canonical lowercase txid. bitcoind accepts any hex case, but the + // credited:/payment: dedupe keys are case-sensitive, so a mixed-case txid + // would re-credit an already-credited output. + const txid = String(req.body?.txid ?? "").toLowerCase(); + if (!/^[0-9a-f]{64}$/.test(txid)) return res.code(400).send("invalid txid"); + // Only our own wallet notify scripts may call this (they hit app:3119 + // directly). Anything that came through Cloudflare or the onion carries + // cf-connecting-ip (set in lib/app.ts for tor) or x-forwarded-for. + if (req.headers["cf-connecting-ip"] || req.headers["x-forwarded-for"]) + return res.code(403).send("forbidden"); + // Headers alone are not enough: the UI's /post/<path> route relays to us + // without them. Require the TCP peer to be a node container or ourselves. + if (!isNotifier(req)) { + warn("confirm refused from", req.socket?.remoteAddress, txid, wallet); + return res.code(403).send("forbidden"); + } + if (type !== PaymentType.bitcoin && type !== PaymentType.liquid) + return res.code(400).send("invalid type"); + if (typeof wallet !== "string") return res.code(400).send("invalid wallet"); try { const node = rpc({ ...config[type], wallet }); const { confirmations, details } = await node.getTransaction(txid); - const hot = wallet === config[type].wallet; + // A retired hot wallet still receives deposits to the addresses it handed + // out (2026-12-04: the "coinos" wallet's keys were stolen; "coinos2" took + // over and the old one is loaded as config.bitcoin.legacyWallets). Its + // deposits are credited like the hot wallet's, by invoice address. + const hot = wallet === config[type].wallet || (config[type].legacyWallets || []).includes(wallet); let aid; if (!hot) aid = wallet; @@ -616,6 +659,18 @@ export default { const p = await getPayment(`${txid}:${vout}`); + // A pointer whose payment record is gone (account deleted, record + // overwritten) means this output was already credited once. Never + // treat it as a first sighting. + if ( + !p && + ((await db.exists(`payment:${txid}:${vout}`)) || + (await db.exists(`credited:${txid}:${vout}`))) + ) { + warn("blocked re-credit of seen output", txid, vout, sats(amount), address); + continue; + } + if (!p) { const invoice = await getInvoice(address); if (!hot && aid !== invoice?.aid) continue; @@ -697,13 +752,18 @@ export default { try { res.send(await build({ ...body, user })); } catch (e) { - warn( - "problem estimating fee", - e.message, - user.username, - body.amount, - body.address, - ); + // Bots retry the same doomed withdrawal every few seconds; log once + // per user per 10 minutes. + const n = quiet(`feefail:${user.id}`); + if (n !== null) + warn( + "problem estimating fee", + e.message, + user.username, + body.amount, + body.address, + suppressed(n), + ); let msg = e.message; if (msg.includes("500")) msg = ""; bail(res, `Failed to prepare transaction ${msg}`); @@ -732,7 +792,7 @@ export default { body: { secret }, } = req; try { - if (!config.adminpass || secret !== config.adminpass) fail("unauthorized"); + if (!config.adminpass || secret !== config.adminpass || !adminIpAllowed(req)) fail("unauthorized"); await s("freeze", true); res.send("ok"); } catch (e) { @@ -777,15 +837,19 @@ export default { await requirePin({ body, user }); const [username, domain] = lnaddress.split("@"); - const { minSendable, maxSendable, callback, metadata } = (await got( + // Coinos names are any letters/digits, so don't enforce LUD-16's + // charset; just refuse what could steer the URL we fetch. + if (!username || /[\/\\?#%@\s]|\.\./u.test(username) || !/^[a-z0-9.-]+(:\d+)?$/i.test(domain || "")) + fail("Invalid lightning address"); + const { minSendable, maxSendable, callback, metadata } = (await safeGot( `https://${domain}/.well-known/lnurlp/${username}`, - ).json()) as any; + )) as any; const memo = metadata["text/plain"] || ""; if (amount * 1000 < minSendable || amount * 1000 > maxSendable) fail("amount out of range"); - const r: any = await got(`${callback}?amount=${amount * 1000}`).json(); + const r: any = await safeGot(`${callback}?amount=${amount * 1000}`); if (r.reason) fail(r.reason); const { pr } = r; diff --git a/routes/shopify.ts b/routes/shopify.ts deleted file mode 100644 index ff601963..00000000 --- a/routes/shopify.ts +++ /dev/null @@ -1,49 +0,0 @@ -import got from "got"; -import { g } from "$lib/db"; -import { l, err } from "$lib/logging"; -import { getPayment } from "$lib/utils"; - -const query = `mutation orderMarkAsPaid($input: OrderMarkAsPaidInput!) { - orderMarkAsPaid(input: $input) { - order { id } - userErrors { - field - message - } - } -}`; - -export default async (req, res) => { - const { - body: { hash }, - params: { id }, - } = req; - const p = await getPayment(hash); - const user = await g(`user:${p.uid}`); - - l("marking shopify order paid", id, user.username, p.id, user.shopifyStore); - - try { - const r = await got - .post( - `https://${user.shopifyStore}.myshopify.com/admin/api/2023-07/graphql.json`, - { - headers: { - "Content-Type": "application/json", - "X-Shopify-Access-Token": user.shopifyToken, - }, - json: { - query, - variables: { input: { id: `gid://shopify/Order/${id}` } }, - }, - }, - ) - .json(); - - l("shopify success", r); - - res.send(r); - } catch (e) { - err("problem marking shopify order as paid", e.message); - } -}; 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. diff --git a/scripts/holds.ts b/scripts/holds.ts new file mode 100644 index 00000000..3de04a09 --- /dev/null +++ b/scripts/holds.ts @@ -0,0 +1,246 @@ +// Review and lift deposit holds (lib/hold.ts). +// +// bun scripts/holds.ts list accounts with held sats +// bun scripts/holds.ts show <user> hold log for one account +// bun scripts/holds.ts lift <user> [sats] lift all (or part) of a hold +// bun scripts/holds.ts set <user> <sats> set a hold by hand +// bun scripts/holds.ts backfill <iso time> hold Lightning deposits since then +// bun scripts/holds.ts expire [--dry] release holds older than hold:expire_hours +// bun scripts/holds.ts on|off start/stop holding new deposits +// +// Run inside the app container: docker exec -w /home/bun/app app bun scripts/holds.ts +import { db } from "$lib/db"; +import { HOLD_EXPIRE_HOURS, holdKey, logHold } from "$lib/hold"; +import ln from "$lib/ln"; + +const [cmd = "list", arg, arg2] = process.argv.slice(2); +const get = async (k: string) => { + const v = await db.get(k); + try { return v ? JSON.parse(v) : null; } catch { return v; } +}; +const uidOf = async (name: string) => { + if (/^[0-9a-f-]{36}$/.test(name)) return name; + const id = await get(`user:${name.toLowerCase()}`); + if (!id) throw new Error(`no user ${name}`); + return id; +}; +const userOf = async (id: string) => (await get(`user:${id}`)) || {}; +const frozen = async (id: string, u: any) => + (await db.sIsMember("blacklist", id)) || (!!u.username && (await db.sIsMember("blacklist", u.username.toLowerCase()))); +const sats = (n: number) => n.toLocaleString("en-US"); +const ago = (t: number) => { + const m = Math.round((Date.now() - t) / 60000); + return m < 60 ? `${m}m` : m < 2880 ? `${Math.round(m / 60)}h` : `${Math.round(m / 1440)}d`; +}; + +async function list() { + const ids = await db.sMembers("held"); + const rows: any[] = []; + for (const id of ids) { + const held = Number(await db.get(holdKey(id))) || 0; + if (held <= 0) continue; + const u = await userOf(id); + const log = (await db.lRange(`held:log:${id}`, 0, 49)).map((l) => JSON.parse(l)); + const sources = [...new Set(log.filter((e) => e.amount > 0 && e.from).map((e) => e.from))]; + rows.push({ + held, + user: u.username || id, + balance: Number(await db.get(`balance:${id}`)) || 0, + frozen: await frozen(id, u), + last: log[0]?.at, + watched: sources.some((s) => String(s).includes("(watched)")), + sources: sources.slice(0, 3).join("; "), + }); + } + rows.sort((a, b) => b.held - a.held); + const total = rows.reduce((a, r) => a + r.held, 0); + console.log(`holds ${(await db.get("hold:enabled")) ? "ON" : "OFF"} · ${rows.length} accounts · ${sats(total)} sats held · ! = came via a watched peer\n`); + console.log("held".padStart(12), "balance".padStart(12), " ", "user".padEnd(24), "last".padStart(5), " sources"); + for (const r of rows) + console.log( + sats(r.held).padStart(12), + sats(r.balance).padStart(12), + `${r.watched ? "!" : " "}${r.frozen ? "F" : " "}`, + String(r.user).slice(0, 24).padEnd(24), + (r.last ? ago(r.last) : "").padStart(5), + "", + r.sources, + ); +} + +async function show(name: string) { + const id = await uidOf(name); + const u = await userOf(id); + console.log(`${u.username} ${id}`); + console.log(`held ${sats(Number(await db.get(holdKey(id))) || 0)} · balance ${sats(Number(await db.get(`balance:${id}`)) || 0)}${(await frozen(id, u)) ? " · FROZEN" : ""}\n`); + for (const l of await db.lRange(`held:log:${id}`, 0, -1)) { + const e = JSON.parse(l); + console.log(new Date(e.at).toISOString().slice(0, 19), String(e.amount ?? "").padStart(10), e.type || e.action || "", e.from || e.note || ""); + } +} + +async function lift(name: string, amount?: string) { + const id = await uidOf(name); + const held = Number(await db.get(holdKey(id))) || 0; + const n = amount ? Math.min(held, Number.parseInt(amount)) : held; + if (!(n > 0)) return console.log("nothing held"); + const left = await db.decrBy(holdKey(id), n); + if (left <= 0) await db.multi().del(holdKey(id)).sRem("held", id).exec(); + await logHold(id, { amount: -n, action: "lift", note: "lifted by operator" }); + console.log(`lifted ${sats(n)}, ${sats(Math.max(0, left))} still held`); +} + +async function set(name: string, amount: string) { + const id = await uidOf(name); + const n = Math.max(0, Number.parseInt(amount) || 0); + await db.multi().set(holdKey(id), n).sAdd("held", id).exec(); + await logHold(id, { amount: n, action: "set", note: "set by operator" }); + console.log(`held set to ${sats(n)}`); +} + +// Hold Lightning deposits received since `since`, less what each account has +// since sent over Lightning or internally (held sats are spent first), capped +// at the current balance. Internal receipts count as held when the sender +// itself received Lightning in the window. Receipts come from cl's paid +// invoices (credit() doesn't index receipts globally); spends from the +// global `payments` list, which holds debits. +async function backfill(since: string) { + const cutoff = Date.parse(since); + if (!cutoff) throw new Error("backfill needs an ISO time"); + const recv = new Map<string, number>(); + const spent = new Map<string, number>(); + const internalIn: [string, string, number][] = []; + const add = (m: Map<string, number>, k: string, v: number) => m.set(k, (m.get(k) || 0) + v); + + // which peer each payment hash came in from, for the review log + const { channels } = await ln.listpeerchannels(); + const scidPeer = new Map<string, string>(); + for (const c of channels || []) if (c.short_channel_id) scidPeer.set(c.short_channel_id, c.peer_id); + const watched = new Set<string>(await db.sMembers("freeze:inbound_peers")); + const alias = new Map<string, string>(); + const name = async (id: string) => { + if (!alias.has(id)) { + const { nodes } = await ln.listnodes(id).catch(() => ({ nodes: [] })); + alias.set(id, `${nodes?.[0]?.alias || id.slice(0, 16)}${watched.has(id) ? " (watched)" : ""}`); + } + return alias.get(id)!; + }; + const hashPeers = new Map<string, Set<string>>(); + const { created } = await ln.call("wait", { subsystem: "htlcs", indexname: "created", nextvalue: 0 }); + for (let start = Math.max(1, Number(created) - 200_000); ; start += 5000) { + const { htlcs } = await ln.call("listhtlcs", { index: "created", start, limit: 5000 }); + for (const h of htlcs || []) { + if (h.direction !== "in" || !scidPeer.has(h.short_channel_id)) continue; + if (!hashPeers.has(h.payment_hash)) hashPeers.set(h.payment_hash, new Set()); + hashPeers.get(h.payment_hash)!.add(scidPeer.get(h.short_channel_id)!); + } + if (!htlcs || htlcs.length < 5000) break; + } + const via = new Map<string, Map<string, number>>(); + + const { updated } = await ln.call("wait", { subsystem: "invoices", indexname: "updated", nextvalue: 0 }); + for (let start = Math.max(1, Number(updated) - 300_000); ; start += 5000) { + const { invoices } = await ln.call("listinvoices", { index: "updated", start, limit: 5000 }); + for (const i of invoices || []) { + if (i.status !== "paid" || i.paid_at * 1000 < cutoff) continue; + const pid = await get(`payment:${i.bolt11 || i.bolt12}`); + const p = pid && (await get(`payment:${pid}`)); + if (p?.amount > 0) { + const acct = p.aid || p.uid; + add(recv, acct, p.amount + (p.tip || 0)); + if (!via.has(acct)) via.set(acct, new Map()); + for (const peer of hashPeers.get(i.payment_hash) || []) { + const n = await name(peer); + via.get(acct)!.set(n, (via.get(acct)!.get(n) || 0) + p.amount + (p.tip || 0)); + } + } + } + if (!invoices || invoices.length < 5000) break; + } + + let done = false; + for (let i = 0; !done; i += 1000) { + const ids = await db.lRange("payments", i, i + 999); + if (!ids.length) break; + for (const pid of ids) { + const p = await get(`payment:${pid}`); + if (!p?.created) continue; + if (p.created < cutoff) { done = true; break; } + if (p.amount >= 0 || !["lightning", "bolt12", "internal"].includes(p.type)) continue; + const from = p.aid || p.uid; + add(spent, from, -p.amount + (p.fee || 0) + (p.ourfee || 0) + (p.tip || 0)); + if (p.type === "internal" && p.iid) { + const inv = await get(`invoice:${p.iid}`); + const to = inv?.aid || inv?.uid; + if (to) internalIn.push([to, from, -p.amount + (p.tip || 0)]); + } + } + } + for (const [to, from, amt] of internalIn) if (recv.has(from)) add(recv, to, amt); + + let total = 0; + let count = 0; + for (const [id, r] of recv) { + const bal = Number(await db.get(`balance:${id}`)) || 0; + const n = Math.min(bal, Math.max(0, r - (spent.get(id) || 0))); + if (n <= 0) continue; + const cur = Number(await db.get(holdKey(id))) || 0; + if (n <= cur) continue; + await db.multi().set(holdKey(id), n).sAdd("held", id).exec(); + const from = [...(via.get(id) || new Map()).entries()].sort((a, b) => b[1] - a[1]).map(([k, v]) => `via ${k} ${v}`).join(", "); + await logHold(id, { amount: n - cur, action: "backfill", from: from || "internal", note: `Lightning deposits since ${since}` }); + total += n - cur; + count++; + } + console.log(`backfilled ${count} accounts, ${sats(total)} sats held`); +} + +// Release the part of each hold that's older than the expiry window: an +// account keeps held only what was added to its hold inside the window +// (from its hold log). Frozen accounts keep their holds. If the log was +// trimmed inside the window we can't tell how much is recent, so we skip. +async function expire(dry: boolean) { + const hours = Number((await db.get("hold:expire_hours")) ?? HOLD_EXPIRE_HOURS); + if (!(hours > 0)) return console.log("expiry off"); + const since = Date.now() - hours * 3600_000; + let total = 0; + let count = 0; + for (const id of await db.sMembers("held")) { + const held = Number(await db.get(holdKey(id))) || 0; + if (held <= 0) { + if (!dry) await db.multi().del(holdKey(id)).sRem("held", id).exec(); + continue; + } + const u = await userOf(id); + if (await frozen(id, u)) continue; + const log = (await db.lRange(`held:log:${id}`, 0, -1)).map((l) => JSON.parse(l)); + if (log.length >= 100 && log[log.length - 1].at >= since) continue; + const recent = log.filter((e) => e.at >= since && e.amount > 0).reduce((a, e) => a + e.amount, 0); + const n = held - recent; + if (n <= 0) continue; + total += n; + count++; + if (dry) { console.log(`${String(u.username || id).padEnd(24)} release ${sats(n)} of ${sats(held)}`); continue; } + const left = await db.decrBy(holdKey(id), n); + if (left <= 0) await db.multi().del(holdKey(id)).sRem("held", id).exec(); + await logHold(id, { amount: -n, action: "expire", note: `older than ${hours}h` }); + } + console.log(`${dry ? "would release" : "released"} ${sats(total)} sats on ${count} accounts`); +} + +try { + if (cmd === "list") await list(); + else if (cmd === "show") await show(arg); + else if (cmd === "lift") await lift(arg, arg2); + else if (cmd === "expire") await expire(arg === "--dry"); + else if (cmd === "set") await set(arg, arg2); + else if (cmd === "backfill") await backfill(arg); + else if (cmd === "exempt") { const id = await uidOf(arg); await db.sAdd("hold:exempt", id); await lift(arg); console.log(`${arg} exempt from holds`); } + else if (cmd === "unexempt") { const id = await uidOf(arg); await db.sRem("hold:exempt", id); console.log(`${arg} no longer exempt`); } + else if (cmd === "on") { await db.set("hold:enabled", "1"); console.log("holding new Lightning deposits"); } + else if (cmd === "off") { await db.del("hold:enabled"); console.log("no longer holding new deposits (existing holds stay)"); } + else console.log("usage: holds.ts [list|show <user>|lift <user> [sats]|set <user> <sats>|backfill <iso>|on|off]"); +} catch (e: any) { + console.error(e.message); +} +process.exit(0); diff --git a/test/lnurl-payload.test.ts b/test/lnurl-payload.test.ts new file mode 100644 index 00000000..01d1da9b --- /dev/null +++ b/test/lnurl-payload.test.ts @@ -0,0 +1,29 @@ +import { describe, expect, test } from "bun:test"; +import { bech32 } from "bech32"; +import { lnurlPayload } from "../lib/lnurl-payload"; +import { safeGot } from "../lib/safe-fetch"; +const pay = { tag: "payRequest", callback: "https://example.com/pay", minSendable: 1000, maxSendable: 2000, metadata: '[["text/plain","coffee"]]' }; +describe("LNURL response boundary", () => { + test("keeps supported pay fields and strips unrelated data", () => { + expect(lnurlPayload({ ...pay, secret: "internal data", commentAllowed: 100 })).toEqual({ ...pay, commentAllowed: 100 }); + }); + test("rejects unrelated and malformed JSON payloads", () => { + for (const v of [null, [], "hello", { version: "docker" }, { ...pay, minSendable: -1 }, { ...pay, maxSendable: 1 }, { ...pay, metadata: "{}" }, { ...pay, callback: "file:///etc/passwd" }, { ...pay, metadata: '[["image/png;base64","abc"]]' }]) + expect(() => lnurlPayload(v)).toThrow(); + }); + test("withdrawal and status responses expose only protocol fields", () => { + const w = { tag: "withdrawRequest", callback: "https://example.com/withdraw", k1: "challenge", defaultDescription: "withdraw", minWithdrawable: 0, maxWithdrawable: 1000 }; + expect(lnurlPayload({ ...w, secret: "hidden" })).toEqual(w); + expect(lnurlPayload({ status: "OK", secret: "hidden" })).toEqual({ status: "OK" }); + expect(lnurlPayload({ status: "ERROR", reason: "sensitive upstream error", secret: "hidden" }).reason).toBe("LNURL service returned an error"); + }); + test("requires a checksummed invoice and strips extras", () => { + expect(() => lnurlPayload({ pr: "not an invoice", routes: [] })).toThrow(); + const pr = bech32.encode("lnbc10n", Array(120).fill(0), 20000); + expect(lnurlPayload({ pr, routes: [], secret: "hidden", successAction: { tag: "message", message: "thanks", secret: "hidden" } })).toEqual({ pr, routes: [], successAction: { tag: "message", message: "thanks" } }); + }); + test("blocks internal literal targets before fetching", async () => { + for (const url of ["http://172.42.0.13:3119/health", "http://127.0.0.1", "http://169.254.169.254", "http://10.1.2.3", "http://[::1]", "http://[::ffff:127.0.0.1]", "file:///etc/passwd"]) + await expect(safeGot(url)).rejects.toThrow(); + }); +}); diff --git a/test/pin-limit.test.ts b/test/pin-limit.test.ts new file mode 100644 index 00000000..f8702c0b --- /dev/null +++ b/test/pin-limit.test.ts @@ -0,0 +1,40 @@ +import { afterAll, expect, test } from "bun:test"; +import { db } from "../lib/db"; +import { checkPin, requirePin } from "../lib/auth"; + +// Run inside app, where the configured DB resolves. Uses a throwaway user id, +// so only the pinfail:<id> key it creates is touched. +const user = { id: `test-${crypto.randomUUID()}`, pin: "123456" }; +const key = `pinfail:${user.id}`; +afterAll(async () => { await db.del(key); }); + +test("no PIN on the account: anything passes and nothing is counted", async () => { + expect(await checkPin({ id: user.id }, "000000")).toBe(true); + expect(await db.exists(key)).toBe(0); +}); + +test("a missing PIN is not a guess", async () => { + expect(await checkPin(user, undefined)).toBe(false); + expect(await checkPin(user, "")).toBe(false); + expect(await db.exists(key)).toBe(0); +}); + +test("the right PIN clears earlier wrong guesses", async () => { + expect(await checkPin(user, "000001")).toBe(false); + expect(Number(await db.get(key))).toBe(1); + expect(await db.ttl(key)).toBeGreaterThan(0); + expect(await checkPin(user, "123456")).toBe(true); + expect(await db.exists(key)).toBe(0); +}); + +test("ten wrong PINs lock every PIN check, the right one included", async () => { + for (let i = 0; i < 10; i++) expect(await checkPin(user, `9999${i}0`)).toBe(false); + await expect(checkPin(user, "123456")).rejects.toThrow("Too many wrong PINs"); + await expect(requirePin({ body: { pin: "123456" }, user })).rejects.toThrow("Too many wrong PINs"); +}); + +test("requirePin still refuses a wrong PIN and allows the right one", async () => { + await db.del(key); + await expect(requirePin({ body: { pin: "111111" }, user })).rejects.toThrow("Invalid pin"); + await requirePin({ body: { pin: "123456" }, user }); +}); 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); +}); |
