diff options
Diffstat (limited to 'lib')
| -rw-r--r-- | lib/adminip.ts | 31 | ||||
| -rw-r--r-- | lib/app.ts | 50 | ||||
| -rw-r--r-- | lib/auth.ts | 54 | ||||
| -rw-r--r-- | lib/changeid.ts | 22 | ||||
| -rw-r--r-- | lib/db.ts | 25 | ||||
| -rw-r--r-- | lib/default-names.ts | 63 | ||||
| -rw-r--r-- | lib/deluser.ts | 154 | ||||
| -rw-r--r-- | lib/hold.ts | 70 | ||||
| -rw-r--r-- | lib/invoices.ts | 15 | ||||
| -rw-r--r-- | lib/legacynsec.ts | 62 | ||||
| -rw-r--r-- | lib/lightning.ts | 65 | ||||
| -rw-r--r-- | lib/lnquote.ts | 29 | ||||
| -rw-r--r-- | lib/lnurl-payload.ts | 60 | ||||
| -rw-r--r-- | lib/names.ts | 35 | ||||
| -rw-r--r-- | lib/nostr.ts | 10 | ||||
| -rw-r--r-- | lib/notifier.ts | 35 | ||||
| -rw-r--r-- | lib/nwc.ts | 10 | ||||
| -rw-r--r-- | lib/payments.ts | 209 | ||||
| -rw-r--r-- | lib/register.ts | 11 | ||||
| -rw-r--r-- | lib/registration-limit.ts | 19 | ||||
| -rw-r--r-- | lib/safe-fetch.ts | 53 | ||||
| -rw-r--r-- | lib/types.ts | 2 | ||||
| -rw-r--r-- | lib/utils.ts | 2 | ||||
| -rw-r--r-- | lib/v3forward.ts | 9 | ||||
| -rw-r--r-- | lib/webhooks.ts | 28 | ||||
| -rw-r--r-- | lib/whitelist.ts | 2 |
26 files changed, 1044 insertions, 81 deletions
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", |
