diff options
Diffstat (limited to 'routes/payments.ts')
| -rw-r--r-- | routes/payments.ts | 126 |
1 files changed, 95 insertions, 31 deletions
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; |
