diff options
Diffstat (limited to 'lib')
| -rw-r--r-- | lib/changeid.ts | 22 | ||||
| -rw-r--r-- | lib/default-names.ts | 63 | ||||
| -rw-r--r-- | lib/deluser.ts | 154 | ||||
| -rw-r--r-- | lib/invoices.ts | 9 | ||||
| -rw-r--r-- | lib/legacynsec.ts | 62 | ||||
| -rw-r--r-- | lib/lnquote.ts | 29 | ||||
| -rw-r--r-- | lib/payments.ts | 26 | ||||
| -rw-r--r-- | lib/register.ts | 11 |
8 files changed, 368 insertions, 8 deletions
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; } 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/invoices.ts b/lib/invoices.ts index 0028dc91..835b1247 100644 --- a/lib/invoices.ts +++ b/lib/invoices.ts @@ -91,6 +91,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/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/payments.ts b/lib/payments.ts index 09cf2cf6..407e5eac 100644 --- a/lib/payments.ts +++ b/lib/payments.ts @@ -469,6 +469,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); @@ -824,6 +830,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 +850,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"); @@ -1011,6 +1027,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 +1043,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 +1062,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")) 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; |
