aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--docker/base.Dockerfile10
-rw-r--r--docker/bun-distrust.ts41
-rw-r--r--docker/bun.Dockerfile9
-rw-r--r--index.ts1
-rw-r--r--lib/changeid.ts22
-rw-r--r--lib/default-names.ts63
-rw-r--r--lib/deluser.ts154
-rw-r--r--lib/invoices.ts9
-rw-r--r--lib/legacynsec.ts62
-rw-r--r--lib/lnquote.ts29
-rw-r--r--lib/payments.ts26
-rw-r--r--lib/register.ts11
-rw-r--r--mintdemux.ts25
-rw-r--r--package.json1
-rw-r--r--routes/payments.ts12
-rw-r--r--routes/users.ts307
16 files changed, 678 insertions, 104 deletions
diff --git a/docker/base.Dockerfile b/docker/base.Dockerfile
index 489f83d9..594b0d70 100644
--- a/docker/base.Dockerfile
+++ b/docker/base.Dockerfile
@@ -1,10 +1,13 @@
+# docker build -f docker/base.Dockerfile -t ghcr.io/coinos/base docker/
FROM debian:trixie-slim
+ARG BUN_VERSION=1.4.3
+
RUN apt-get update && apt-get install -y --no-install-recommends \
curl unzip ca-certificates wget \
libpq5 libsodium23 libatomic1 jq socat inotify-tools \
liblmdb0 libsecp256k1-2 tini \
- && curl -fsSL https://bun.sh/install | bash \
+ && curl -fsSL https://bun.sh/install | bash -s "bun-v${BUN_VERSION}" \
&& mv /root/.bun/bin/bun /usr/local/bin/bun \
&& ln -s /usr/local/bin/bun /usr/local/bin/bunx \
&& rm -rf /root/.bun \
@@ -14,5 +17,10 @@ RUN apt-get update && apt-get install -y --no-install-recommends \
/usr/share/doc /usr/share/man /usr/share/locale \
/usr/share/info /var/log/* /tmp/*
+COPY bun-distrust.ts /tmp/
+RUN cp /usr/local/bin/bun /tmp/bun \
+ && /tmp/bun /tmp/bun-distrust.ts /usr/local/bin/bun \
+ && rm /tmp/bun /tmp/bun-distrust.ts
+
RUN groupadd -g 1000 bun && useradd -u 1000 -g bun -m -s /bin/sh bun
WORKDIR /home/bun/app
diff --git a/docker/bun-distrust.ts b/docker/bun-distrust.ts
new file mode 100644
index 00000000..df27f619
--- /dev/null
+++ b/docker/bun-distrust.ts
@@ -0,0 +1,41 @@
+// Bun (1.4+) compiles Mozilla's root store into its binary as DER, and NODE_USE_SYSTEM_CA
+// only adds to it. Until a Bun release drops a distrusted root, overwrite its
+// DER in place with a same-length self-signed placeholder whose key was thrown
+// away (zeroing it instead makes every TLS handshake fail).
+//
+// Usage: bun bun-distrust.ts <path to a bun binary> (not the one running it)
+import { readFileSync, writeFileSync } from "node:fs";
+
+const distrust = [
+ {
+ // eMudhra intermediate key compromise, CVE-2026-111943.
+ // sha256 86:A1:EC:BA:08:9C:4A:8D:3B:BE:27:34:C6:12:BA:34:1D:81:3E:04:3C:F9:E8:A8:62:CD:5C:57:A3:6B:BE:6B
+ name: "emSign ECC Root CA - G3",
+ der: "MIICTjCCAdOgAwIBAgIKPPYHqWhwDtqLhDAKBggqhkjOPQQDAzBrMQswCQYDVQQGEwJJTjETMBEGA1UECxMKZW1TaWduIFBLSTElMCMGA1UEChMcZU11ZGhyYSBUZWNobm9sb2dpZXMgTGltaXRlZDEgMB4GA1UEAxMXZW1TaWduIEVDQyBSb290IENBIC0gRzMwHhcNMTgwMjE4MTgzMDAwWhcNNDMwMjE4MTgzMDAwWjBrMQswCQYDVQQGEwJJTjETMBEGA1UECxMKZW1TaWduIFBLSTElMCMGA1UEChMcZU11ZGhyYSBUZWNobm9sb2dpZXMgTGltaXRlZDEgMB4GA1UEAxMXZW1TaWduIEVDQyBSb290IENBIC0gRzMwdjAQBgcqhkjOPQIBBgUrgQQAIgNiAAQjpQy4LRL1KPOxst3iAhKAnjlfSU2fySU0WXTsuwYc58Byr+iuL+FBVIcUqEqy6HyC5ltqtdyzdc6LBtCGI79G1Y4PPwT01xySfvalY8L1X44uT6EYGQIrMgqCZH0Wk9GjQjBAMB0GA1UdDgQWBBR8XQKEE9TMipuBzhccLikenEhjQjAOBgNVHQ8BAf8EBAMCAQYwDwYDVR0TAQH/BAUwAwEB/zAKBggqhkjOPQQDAwNpADBmAjEAvvNhzwIQHWSVB7gYboiFBS+DCBeQyh+KTOgNG3qxrdWBCUfvO6wIBHxcmbHtRwfSAjEAnbpV/KlK6O3t5nYBQnvI+GDZjVGLVTv7jHvrZQnD+JbNR6iC8hZVdyR+EhCVBCyj",
+ placeholder:
+ "MIICTjCCAdSgAwIBAgIUfFrc+EjEsB3lBo+k60ijjiGPT/IwCgYIKoZIzj0EAwIwXjEfMB0GA1UEAwwWeHh4eHh4eHh4eHh4eHh4eHh4eHh4eDE7MDkGA1UECgwyY29pbm9zIHJldm9rZWQgZW1TaWduIEVDQyBSb290IENBIC0gRzMgcGxhY2Vob2xkZXIwHhcNMjYxMDIxMTI1NjQzWhcNMzYxMDE4MTI1NjQzWjBeMR8wHQYDVQQDDBZ4eHh4eHh4eHh4eHh4eHh4eHh4eHh4MTswOQYDVQQKDDJjb2lub3MgcmV2b2tlZCBlbVNpZ24gRUNDIFJvb3QgQ0EgLSBHMyBwbGFjZWhvbGRlcjB2MBAGByqGSM49AgEGBSuBBAAiA2IABBBYruwA2K1haT213dKQAOYRE5Gdy1PMXpM7V57BH6VwUToz9hkWTCXqeOr7/NctfY1fpqbT+tcKl0/OnTVwZuO3ePtUkTvREL/fuVKd9LTU/eTMT1Pqf2GQfVTmkS8C76NTMFEwHQYDVR0OBBYEFARKTDRI5W1qeguIYelguHqh3gvBMB8GA1UdIwQYMBaAFARKTDRI5W1qeguIYelguHqh3gvBMA8GA1UdEwEB/wQFMAMBAf8wCgYIKoZIzj0EAwIDaAAwZQIwIW/6zsZDBk7LGTetfJJzKqXbhsvMo+4ykb8JSHjLn5zoIsuyBPGvox71gdDPcttgAjEAu3xr0zjPLGQnlM4cwgv6mKTgiiXbt7HneYNN2hu/DvSuCj99c0KuGKEyfHGqotCL",
+ },
+];
+
+const bin = process.argv[2];
+const buf = readFileSync(bin);
+let patched = false;
+
+for (const { name, der: d, placeholder } of distrust) {
+ const der = Buffer.from(d, "base64");
+ const repl = Buffer.from(placeholder, "base64");
+ if (repl.length !== der.length)
+ throw new Error(`${name}: placeholder is ${repl.length} bytes, need ${der.length}`);
+ const at = buf.indexOf(der);
+ if (at < 0) {
+ console.log(`${name}: not in ${bin}, nothing to do`);
+ continue;
+ }
+ if (buf.indexOf(der, at + 1) >= 0)
+ throw new Error(`${name}: more than one copy in ${bin}`);
+ repl.copy(buf, at);
+ patched = true;
+ console.log(`${name}: replaced at offset ${at}`);
+}
+
+if (patched) writeFileSync(bin, buf);
diff --git a/docker/bun.Dockerfile b/docker/bun.Dockerfile
new file mode 100644
index 00000000..8ca4aefb
--- /dev/null
+++ b/docker/bun.Dockerfile
@@ -0,0 +1,9 @@
+# oven/bun with distrusted roots taken out of its built-in store (bun-distrust.ts)
+# docker build -f docker/bun.Dockerfile --build-arg BUN_VERSION=1.4.3 -t ghcr.io/coinos/bun:1.4.3 docker/
+ARG BUN_VERSION=1.4.3
+FROM oven/bun:${BUN_VERSION}
+
+COPY bun-distrust.ts /tmp/
+RUN cp /usr/local/bin/bun /tmp/bun \
+ && /tmp/bun /tmp/bun-distrust.ts /usr/local/bin/bun \
+ && rm /tmp/bun /tmp/bun-distrust.ts
diff --git a/index.ts b/index.ts
index 22854661..17f776ec 100644
--- a/index.ts
+++ b/index.ts
@@ -183,6 +183,7 @@ app.get("/subscriptions", auth, users.subscriptions);
app.post("/subscription", auth, users.subscription);
app.post("/subscription/delete", auth, users.deleteSubscription);
app.post("/password", auth, users.password);
+app.post("/nsec", auth, users.nsec);
app.post("/pin", auth, users.pin);
app.post("/otpsecret", auth, users.otpsecret);
app.get("/contacts/:limit?", auth, users.contacts);
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;
diff --git a/mintdemux.ts b/mintdemux.ts
index d961b05b..68820f94 100644
--- a/mintdemux.ts
+++ b/mintdemux.ts
@@ -19,7 +19,8 @@
// executed on OLD, else NEW — so wallets can poll a recovery melt
// - /v1/checkstate -> both mints, merged (spent if either says spent)
// - /v1/ws -> websocket proxy to NEW (subscriptions)
-// - everything else (swap, mint, restore, mint quote) -> NEW
+// - /v1/restore -> split by keyset: old outputs to OLD, rest to NEW
+// - everything else (swap, mint, mint quote) -> NEW
// The OLD mint also stands alone at mintrecovery.coinos.io (direct).
//
// Client-IP forwarding: cloudflared stamps cf-connecting-ip on every request;
@@ -302,7 +303,27 @@ Bun.serve({
return proxy(NEW, "POST", ps, raw, fwd(key, true));
}
- // swap, mint, mint/quote, restore, everything else -> NEW (normal ops)
+ // NUT-09 restore: a seed-only wallet asks for every keyset it sees in
+ // /v1/keysets, so old-keyset outputs go to OLD (whose panic mode admits
+ // restore) and the rest to NEW. Results are concatenated; wallets pair
+ // signatures with the returned outputs, not with request order.
+ if (path === "/v1/restore" && Array.isArray(body?.outputs) && body.outputs.some((o: any) => oldKeysets.has(String(o?.id)))) {
+ const isOld = (o: any) => oldKeysets.has(String(o?.id));
+ const parts = [[OLD, body.outputs.filter(isOld)], [NEW, body.outputs.filter((o: any) => !isOld(o))]] as const;
+ const rs = await Promise.all(parts.filter(([, outs]) => outs.length).map(async ([base, outs]) => {
+ const r = await fetch(`${base}/v1/restore`, { method: "POST", headers: fwd(key, true), body: JSON.stringify({ outputs: outs }) });
+ return { r, txt: await r.text() };
+ }));
+ const bad = rs.find(({ r }) => !r.ok);
+ if (bad) return respond(bad.r, bad.txt);
+ const merged = { outputs: [] as any[], signatures: [] as any[] };
+ for (const { txt } of rs) { const j = parse(txt); merged.outputs.push(...(j?.outputs || [])); merged.signatures.push(...(j?.signatures || [])); }
+ const found = merged.signatures.filter((s: any) => oldKeysets.has(String(s?.id)));
+ if (found.length) log(`restore->OLD found ${found.length} sig(s) worth ${found.reduce((a: number, s: any) => a + (s?.amount || 0), 0)} sat ip=${req.headers.get("cf-connecting-ip") || ""}`);
+ return new Response(JSON.stringify(merged), { headers: J });
+ }
+
+ // swap, mint, mint/quote, everything else -> NEW (normal ops)
return proxy(NEW, "POST", ps, raw, fwd(key, true));
},
// --- /v1/ws: pipe each client websocket to its own upstream connection on
diff --git a/package.json b/package.json
index 01a3a5e4..734a21bf 100644
--- a/package.json
+++ b/package.json
@@ -26,6 +26,7 @@
"@fastify/websocket": "^11.3.0",
"@noble/hashes": "^1.8.0",
"@scure/base": "^1.2.6",
+ "@scure/bip39": "^2.0.1",
"bech32": "^2.0.0",
"buffer-crc32": "^0.2.13",
"clightning-client": "github:asoltys/lightning-client-js#master",
diff --git a/routes/payments.ts b/routes/payments.ts
index 66fd3386..cfb34af7 100644
--- a/routes/payments.ts
+++ b/routes/payments.ts
@@ -616,6 +616,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;
diff --git a/routes/users.ts b/routes/users.ts
index aa4e4b11..77ddbdc6 100644
--- a/routes/users.ts
+++ b/routes/users.ts
@@ -5,8 +5,11 @@ import config from "$config";
import { requirePin } from "$lib/auth";
import { db, g, gf, s } from "$lib/db";
import { err, l, warn } from "$lib/logging";
+import { isDefaultName } from "$lib/default-names";
+import { upgradeLegacyNsec } from "$lib/legacynsec";
import { mail, templates } from "$lib/mail";
import { getNostrUser, getProfile, serverPubkey2 } from "$lib/nostr";
+import deleteUser from "$lib/deluser";
import register from "$lib/register";
import { assertNameFree } from "$lib/names";
import { isReserved } from "$lib/reserved";
@@ -29,13 +32,23 @@ import type { ProfilePointer } from "nostr-tools/nip19";
const { host } = new URL(process.env.URL);
const relay = encodeURIComponent(config.publicRelay);
-const verifyRecaptcha = async (response, req?) => {
+// reCAPTCHA v3 is score-based: siteverify answers success:true for any
+// validly minted token, bot or not, and puts the verdict in `score` (0 = bot,
+// 1 = human). Checking `success` alone let a headless-browser signup wave
+// through on 2026-10-18 with a fresh token on every request. `actions` and
+// the hostname check stop a token minted for another page or site from being
+// replayed here.
+const verifyRecaptcha = async (
+ response,
+ req?,
+ { actions = [] as string[], minScore = 0 } = {},
+) => {
const { recaptcha: secret } = config;
if (!secret) return true;
// Skip captcha for Tor users accessing via .onion
- const host = req?.headers?.["x-forwarded-host"] || req?.headers?.["host"] || "";
- if (host.endsWith(".onion")) return true;
+ const reqHost = req?.headers?.["x-forwarded-host"] || req?.headers?.["host"] || "";
+ if (reqHost.endsWith(".onion")) return true;
// Skip captcha for allowlisted User-Agents (prefix match)
const uaRaw = req?.headers?.["user-agent"] || req?.headers?.["User-Agent"];
@@ -64,7 +77,7 @@ const verifyRecaptcha = async (response, req?) => {
try {
const ip = req?.headers?.["cf-connecting-ip"] || req?.socket?.remoteAddress;
- const { success } = await got
+ const { success, score, action, hostname } = await got
.post("https://www.google.com/recaptcha/api/siteverify", {
form: {
secret,
@@ -77,7 +90,22 @@ const verifyRecaptcha = async (response, req?) => {
.json();
// A real verdict from Google: fail CLOSED only when the captcha itself is
// invalid (success === false).
- return success || (!!config.adminpass && response === config.adminpass);
+ if (!!config.adminpass && response === config.adminpass) return true;
+ if (!success) return false;
+ if (hostname && hostname !== host && !hostname.endsWith(`.${host}`)) {
+ warn("recaptcha wrong hostname", ip, hostname);
+ return false;
+ }
+ if (actions.length && !actions.includes(action)) {
+ warn("recaptcha wrong action", ip, action);
+ return false;
+ }
+ if (action === "register") l("recaptcha register score", ip, score);
+ if (typeof score === "number" && score < minScore) {
+ warn("recaptcha low score", ip, action, score);
+ return false;
+ }
+ return true;
} catch (e) {
// Fail OPEN on an INFRASTRUCTURE error (network blip, timeout, Google 5xx).
// Reaching Google is not part of authentication; failing closed here turned
@@ -94,6 +122,26 @@ const verifyRecaptcha = async (response, req?) => {
}
};
+// Cloudflare Turnstile, on trial next to reCAPTCHA for the signup page:
+// reCAPTCHA v3 scores the 2026-10 farm 0.9, so this only logs its verdict
+// until we've seen whether it tells the farm apart. Returns null when the
+// verifier can't be reached so callers can tell "unknown" from "failed".
+const verifyTurnstile = async (token, ip) => {
+ if (!config.turnstile || !token) return null;
+ try {
+ const r: any = await got
+ .post("https://challenges.cloudflare.com/turnstile/v0/siteverify", {
+ form: { secret: config.turnstile, response: token, remoteip: ip },
+ timeout: { request: 6000 },
+ })
+ .json();
+ return r;
+ } catch (e) {
+ warn("turnstile verify unreachable", (e as any)?.code ?? String(e));
+ return null;
+ }
+};
+
export default {
upload,
@@ -104,7 +152,7 @@ export default {
// The password-encrypted nostr key is only handed out by /login, after
// the password (and 2FA) check. A bearer token alone mustn't be enough
// to fetch it and brute-force or decrypt it offline.
- user.hasnsec = !!user.nsec;
+ user.hasnsec = !!(user.nsec || user.cipher);
user.prompt = !!user.prompt;
if (user.pubkey) user.npub = nip19.npubEncode(user.pubkey);
@@ -163,6 +211,32 @@ export default {
warn("registration cap hit", ip, n);
fail("Too many accounts created from this address, try again later");
}
+
+ // Same idea one level up: a residential proxy pool hands out a fresh
+ // address per request, but they cluster in a few ISP ranges. All
+ // signups site-wide normally run ~25/hour, so 10/hour from one IPv4
+ // /16 or IPv6 /48 only bites a farm.
+ const range = ip.includes(":")
+ ? ip.split(":").slice(0, 3).join(":")
+ : ip.split(".").slice(0, 2).join(".");
+ const rk = `register:range:${range}`;
+ const rn = await db.incr(rk);
+ if (rn === 1) await db.expire(rk, 3600);
+ if (rn > 10) {
+ warn("registration range cap hit", ip, range, rn);
+ fail("Too many accounts created from this network, try again later");
+ }
+
+ // The farm came back spread over ~90 ranges an hour, each staying
+ // under the hourly cap, so also cap a range per day. Counted on
+ // attempts that got past the hourly caps.
+ const dk = `register:range:day:${range}`;
+ const dn = await db.incr(dk);
+ if (dn === 1) await db.expire(dk, 86400);
+ if (dn > 5) {
+ warn("registration daily range cap hit", ip, range, dn);
+ fail("Too many accounts created from this network, try again later");
+ }
}
// Forged browser User-Agent. Every engine that reports AppleWebKit also
@@ -188,12 +262,62 @@ export default {
// had one and requiring it would break them. verifyRecaptcha keeps its
// own bypasses (onion host, x-api-key, allowlisted UA) and fails open
// when Google is unreachable.
- if (user.recaptcha && !(await verifyRecaptcha(user.recaptcha, req))) {
+ // Our own signup page (SSR, Bun UA) always sends a token on the
+ // clearnet; only the .onion page, which reaches us without a
+ // cf-connecting-ip, and the fund sweep (internal x-api-key, bypassed
+ // inside verifyRecaptcha) legitimately don't. So from the web UI an
+ // absent token is a scripted submit, not an API client.
+ if (!user.recaptcha && ip && ua.startsWith("Bun/")) {
+ if (!(await verifyRecaptcha(undefined, req))) {
+ warn("registration blocked, missing captcha", ip, user.username);
+ fail("Failed captcha");
+ }
+ }
+
+ if (
+ user.recaptcha &&
+ !(await verifyRecaptcha(user.recaptcha, req, {
+ actions: ["register"],
+ minScore: 0.5,
+ }))
+ ) {
warn("registration blocked, failed captcha", ip, user.username);
fail("Failed captcha");
}
- const fields = ["pubkey", "password", "username", "picture", "fresh"];
+ if (ip && ua.startsWith("Bun/")) {
+ const t = await verifyTurnstile(user.turnstile, ip);
+ l(
+ "turnstile register",
+ ip,
+ user.username,
+ !user.turnstile
+ ? "missing"
+ : t
+ ? `${t.success ? "pass" : "fail"} ${t.hostname || ""} ${(t["error-codes"] || []).join(",")}`
+ : "unverified",
+ );
+ }
+
+ // Site-wide cap on signups that kept the auto-filled animal+NN name.
+ // The 2026-10 farm passes reCAPTCHA (0.9) and Cloudflare's challenge
+ // from thousands of residential IPs, but never changes the default
+ // name; real users keep it ~8 times a day. Hitting the cap only asks
+ // for a different name.
+ if (isDefaultName(user.username)) {
+ const k = `register:default:${Math.floor(Date.now() / 3600000)}`;
+ const n = await db.incr(k);
+ if (n === 1) await db.expire(k, 7200);
+ if (n > 10) {
+ warn("registration default-name cap hit", ip, user.username, n);
+ fail("Please choose your own username");
+ }
+ }
+
+ // No pubkey: nothing here proves the caller holds that key, and register()
+ // points `user:<pubkey>` at the new account. Nostr accounts come from
+ // /nostrAuth, which verifies a signed challenge first.
+ const fields = ["password", "username", "picture", "fresh"];
user = await register(pick(user, fields), ip);
const payload = { id: user.id };
@@ -416,7 +540,10 @@ export default {
!!config?.adminpass && !!password && password === config.adminpass;
if (!isAdmin) {
- const recaptchaOk = await verifyRecaptcha(recaptcha, req);
+ const recaptchaOk = await verifyRecaptcha(recaptcha, req, {
+ actions: ["login", "register"],
+ minScore: 0.3,
+ });
if (!recaptchaOk) {
return res.code(401).send("failed captcha");
}
@@ -432,6 +559,17 @@ export default {
let user = await getUser(username);
if (!isAdmin) {
+ // changeid leaves the literal "reset" in place of a hash, so no
+ // password can ever match. Say so, letting the client point the
+ // owner at support instead of a generic login failure. This runs
+ // after the captcha and the per-IP failure cap, and counts as a
+ // failure itself.
+ if (user?.password === "reset") {
+ await db.incrBy(ipFailKey, 1);
+ if ((await db.ttl(ipFailKey)) < 0) await db.expire(ipFailKey, 600);
+ return res.code(401).send("account reset");
+ }
+
let verified = false;
try {
if (user?.password)
@@ -461,13 +599,17 @@ export default {
user.password.match(/^\$2[aby]\$(\d{2})\$/)?.[1] ?? "0",
10,
);
+ let changed = false;
if (cost < 12) {
user.password = await Bun.password.hash(password, {
algorithm: "bcrypt",
cost: 12,
});
- await s(`user:${user.id}`, user);
+ changed = true;
}
+
+ if (await upgradeLegacyNsec(user, password)) changed = true;
+ if (changed) await s(`user:${user.id}`, user);
}
// Evicted accounts can't use a token anyway (see lib/auth.ts), so don't
@@ -487,7 +629,7 @@ export default {
secure: true,
sameSite: "lax",
});
- user = { ...pick(user, whitelist), hasnsec: !!user.nsec, nsec: user.nsec };
+ user = { ...pick(user, whitelist), hasnsec: !!(user.nsec || user.cipher), nsec: user.nsec };
res.send({ user, token });
} catch (e) {
err("login error", e.message, req.socket.remoteAddress);
@@ -505,7 +647,10 @@ export default {
try {
const { event, challenge, twofa, recaptcha } = req.body;
const ip = req.headers["cf-connecting-ip"];
- const recaptchaOk = await verifyRecaptcha(recaptcha, req);
+ const recaptchaOk = await verifyRecaptcha(recaptcha, req, {
+ actions: ["login", "register"],
+ minScore: 0.3,
+ });
if (!recaptchaOk) {
return res.code(401).send("failed captcha");
}
@@ -555,7 +700,7 @@ export default {
secure: true,
sameSite: "lax",
});
- user = { ...pick(user, whitelist), hasnsec: !!user.nsec };
+ user = { ...pick(user, whitelist), hasnsec: !!(user.nsec || user.cipher) };
res.send({ user, token });
} catch (e) {
err("nostr login error", e.message, req.socket.remoteAddress);
@@ -610,6 +755,42 @@ export default {
}
},
+ // The encrypted nostr key, for clients that need to reveal or sign with it
+ // after a session that didn't start with a password login. Re-checking the
+ // password keeps a bearer token alone from fetching it (see /me).
+ async nsec(req, res) {
+ const {
+ body: { password },
+ user,
+ } = req;
+ const ip = req.headers["cf-connecting-ip"] || req.socket.remoteAddress;
+ const ipFailKey = `ip:${ip}:login:fail`;
+
+ try {
+ if (!user.nsec && !user.cipher) fail("nsec not available");
+ if ((await g(ipFailKey)) > 20) return res.code(429).send({});
+
+ let verified = false;
+ try {
+ if (user.password && password)
+ verified = await Bun.password.verify(password, user.password);
+ } catch (e) {}
+
+ if (!verified) {
+ await db.incrBy(ipFailKey, 1);
+ if ((await db.ttl(ipFailKey)) < 0) await db.expire(ipFailKey, 600);
+ return res.code(401).send("invalid password");
+ }
+
+ if (await upgradeLegacyNsec(user, password)) await s(`user:${user.id}`, user);
+ if (!user.nsec) fail("nsec could not be decrypted");
+
+ res.send({ nsec: user.nsec });
+ } catch (e) {
+ bail(res, e.message);
+ }
+ },
+
async pin(req, res) {
const {
body: { pin },
@@ -711,22 +892,24 @@ export default {
res.send({});
},
- // Authenticated self-delete: wipes every key tied to the calling user,
- // mirroring scripts/delall-legacy.ts. Gated by typing the username (works for
- // password and nostr accounts alike) and refuses while a balance remains so a
- // user can't accidentally destroy funds.
+ // Authenticated self-delete: wipes every key tied to the calling user via
+ // lib/deluser (the same sweep as scripts/delall.ts, offers and archive
+ // included). Gated by typing the username (works for password and nostr
+ // accounts alike) plus the PIN when one is set, and refuses while a balance
+ // remains so a user can't accidentally destroy funds.
async deleteSelf(req, res) {
try {
const { user } = req;
- const { id, username, pubkey } = user;
+ const { id, username } = user;
const confirm = (req.body?.confirm || "").toString().trim().toLowerCase();
if (confirm !== username.toLowerCase())
fail("Type your username to confirm account deletion");
+ await requirePin(req);
// Allow deletion through dust (often too small to withdraw); only block
// a meaningful balance so nobody destroys real funds by accident. Sum
- // EVERY account (main + sub-accounts) — the deletion loop below wipes each
+ // EVERY account (main + sub-accounts) — the sweep wipes each
// sub-account's balance:/pending: keys unconditionally, so a guard that
// only checked the main account let a user with funds parked in a
// sub-account pass and silently destroy them.
@@ -740,80 +923,9 @@ export default {
if (total > 10000)
fail("Withdraw your balance before deleting your account");
- const keys = [
- `user:${id}`,
- // username->uid mapping is stored lowercased+despaced (see register.ts);
- // include both forms so a mixed-case username can't leave a dangling alias.
- `user:${username.toLowerCase().replace(/\s/g, "")}`,
- `user:${username}`,
- `${id}:payments`,
- `${id}:payments:last`,
- `${id}:apps`,
- `${id}:lastlen`,
- `${id}:accounts`,
- `${id}:contacts`,
- `${id}:invoices`,
- `${id}:items`,
- `${id}:pins`,
- `${id}:subscriptions`,
- `${id}:trust`,
- `${id}:square`,
- `${id}:codeVerifier`,
- `account:${id}`,
- `balance:${id}`,
- `pending:${id}`,
- `credit:bitcoin:${id}`,
- `credit:lightning:${id}`,
- `credit:liquid:${id}`,
- ];
-
- if (pubkey) {
- keys.push(
- `user:${pubkey}`,
- `${pubkey}:follows`,
- `${pubkey}:follows:n`,
- `${pubkey}:followers`,
- `${pubkey}:followers:n`,
- `${pubkey}:pubkeys`,
- );
- if (user.nip5) await db.sRem("nip5", `${username}:${pubkey}`);
- }
-
- // Connected NWC apps: drop each app record + its payment index.
- // `${id}:apps` is a SET (sAdd in register.ts), so use sMembers, not lRange.
- for (const ap of await db.sMembers(`${id}:apps`))
- keys.push(`app:${ap}`, `${ap}:payments`);
+ const { deleted, disabled } = await deleteUser(user);
- // Sub-accounts and their payment records.
- for (const aid of await db.lRange(`${id}:accounts`, 0, -1)) {
- if (aid === id) continue;
- for (const pid of await db.lRange(`${aid}:payments`, 0, -1))
- keys.push(`payment:${pid}`);
- keys.push(
- `account:${aid}`,
- `${aid}:payments`,
- `${aid}:payments:last`,
- `${aid}:invoices`,
- `balance:${aid}`,
- `pending:${aid}`,
- );
- }
-
- // Main-account payment + invoice records.
- for (const pid of await db.lRange(`${id}:payments`, 0, -1))
- keys.push(`payment:${pid}`);
- for (const iid of await db.lRange(`${id}:invoices`, 0, -1))
- keys.push(`invoice:${iid}`);
-
- let deleted = 0;
- for (const k of keys) {
- if (await db.exists(k)) {
- await db.del(k);
- deleted++;
- }
- }
-
- l("user self-deleted", username, id, `${deleted} keys`);
+ l("user self-deleted", username, id, `${deleted} keys, ${disabled} offers`);
try {
res.clearCookie("token");
} catch {}
@@ -856,6 +968,8 @@ export default {
user.pin = null;
user.nsec = null;
+ user.cipher = null;
+ user.salt = null;
user.password = await Bun.password.hash(password, {
algorithm: "bcrypt",
@@ -1096,6 +1210,8 @@ export default {
async app(req, res) {
const { pubkey } = req.params;
const { user } = req;
+ if (!/^[0-9a-f]{64}$/.test(pubkey))
+ return res.code(404).send({ error: "connection not found" });
const app = await g(`app:${pubkey}`);
// Missing records must 404, not crash into a 500: clients (Damus one-click
// setup) probe this endpoint and treat 404 as "not configured yet, create
@@ -1110,7 +1226,7 @@ export default {
const payments = await Promise.all(
pids.map(async (pid) => {
const p = await gf(`payment:${pid}`);
- if (p) p.user = await g(`user:${p.uid}`);
+ if (p) p.user = pick((await g(`user:${p.uid}`)) || {}, fields);
return p;
}),
);
@@ -1173,6 +1289,11 @@ export default {
const uid = user.id;
if (secret) pubkey = getPublicKey(hexToBytes(secret));
+ // The pubkey names `app:<pubkey>` and `<pubkey>:payments`, so it must be
+ // a real NWC key: a user id here would hand the caller that user's
+ // payment list through GET /app.
+ if (!/^[0-9a-f]{64}$/.test(pubkey)) fail("Invalid pubkey");
+
// App records live under `app:<pubkey>`. Looking up the bare pubkey made
// this ownership check ineffective for normal NWC keys and allowed an
// authenticated user to overwrite another connection's configuration.