From ad7b09b43323d0ffc0a8ddabb43e4838a184c697 Mon Sep 17 00:00:00 2001 From: Adam Soltys Date: Tue, 24 Feb 2026 13:18:42 -0800 Subject: formatting --- routes/ecash.ts | 12 +------ routes/email.ts | 4 +-- routes/info.ts | 9 ++--- routes/invoices.ts | 14 ++------ routes/lnurl.ts | 19 +++------- routes/nostr.ts | 19 +++------- routes/payments.ts | 86 +++++++++++++++------------------------------ routes/shopify.ts | 21 +++++------ routes/users.ts | 101 ++++++++++++++--------------------------------------- 9 files changed, 81 insertions(+), 204 deletions(-) (limited to 'routes') diff --git a/routes/ecash.ts b/routes/ecash.ts index 57cc49c1..b4c16404 100644 --- a/routes/ecash.ts +++ b/routes/ecash.ts @@ -104,17 +104,7 @@ export default { const { lightning: type } = PaymentType; if (user.username !== "mint") fail("unauthorized"); const { id: uid, currency } = user; - const ourfee = await tbDebit( - uid, - uid, - type, - amount || 0, - 0, - 0, - 0, - 0, - "Insufficient funds", - ); + const ourfee = await tbDebit(uid, uid, type, amount || 0, 0, 0, 0, 0, "Insufficient funds"); const rates = await g("rates"); const rate = rates[currency]; diff --git a/routes/email.ts b/routes/email.ts index 9f0a8228..25c90ee7 100644 --- a/routes/email.ts +++ b/routes/email.ts @@ -40,9 +40,7 @@ export default { }, Subject: { Charset, - Data: - body.subject || - `Support Request${username ? ` From ${username}` : ""}`, + Data: body.subject || `Support Request${username ? ` From ${username}` : ""}`, }, }, ReplyToAddresses: [email], diff --git a/routes/info.ts b/routes/info.ts index a0ac7693..35d1c315 100644 --- a/routes/info.ts +++ b/routes/info.ts @@ -23,15 +23,10 @@ export default { // } const funds = await ln.listfunds(); - const lnchannel = parseInt( - funds.channels.reduce((a, b) => a + b.channel_sat, 0), - ); + const lnchannel = parseInt(funds.channels.reduce((a, b) => a + b.channel_sat, 0)); const lnwallet = parseInt(funds.outputs.reduce((a, b) => a + b.value, 0)); - const cash = getDecodedToken(await g("cash")).proofs.reduce( - (a, b) => a + b.amount, - 0, - ); + const cash = getDecodedToken(await g("cash")).proofs.reduce((a, b) => a + b.amount, 0); const info = { cash, diff --git a/routes/invoices.ts b/routes/invoices.ts index bc96c3f0..7f44a28d 100644 --- a/routes/invoices.ts +++ b/routes/invoices.ts @@ -42,12 +42,7 @@ export default { } catch (e) { console.trace(); console.log(e); - err( - "problem generating invoice", - req.user?.username, - body.user?.username, - e.message, - ); + err("problem generating invoice", req.user?.username, body.user?.username, e.message); bail(res, e.message); } }, @@ -84,9 +79,7 @@ export default { async list(req, res) { const { id } = req.user; let invoices = await db.lRange(`${id}:invoices`, 0, -1); - invoices = (await Promise.all(invoices.map((i) => getInvoice(i)))).filter( - Boolean, - ); + invoices = (await Promise.all(invoices.map((i) => getInvoice(i)))).filter(Boolean); res.send(invoices); }, @@ -95,8 +88,7 @@ export default { const { address, message, type = "bitcoin" } = req.body; const node = rpc(config[type]); - if (config[type].walletpass) - await node.walletPassphrase(config[type].walletpass, 300); + if (config[type].walletpass) await node.walletPassphrase(config[type].walletpass, 300); const signature = await node.signMessage({ address, message }); res.send({ signature }); diff --git a/routes/lnurl.ts b/routes/lnurl.ts index 0358488e..cb74e2b5 100644 --- a/routes/lnurl.ts +++ b/routes/lnurl.ts @@ -19,9 +19,7 @@ export default { query: { address }, } = req; const [name, domain] = address.split("@"); - const url = `https://${domain}/.well-known/lnurlp/${name - .toLowerCase() - .replace(/\s/g, "")}`; + const url = `https://${domain}/.well-known/lnurlp/${name.toLowerCase().replace(/\s/g, "")}`; try { const r = await got(url).json(); @@ -41,9 +39,7 @@ export default { query: { text }, } = req; try { - const url = Buffer.from( - bech32.fromWords(bech32.decode(text, 20000).words), - ).toString(); + const url = Buffer.from(bech32.fromWords(bech32.decode(text, 20000).words)).toString(); const r = await got(url).json(); res.send(r); @@ -59,11 +55,7 @@ export default { } = req; try { const user = await getUser( - username - .replace("lightning:", "") - .replace(/\s/g, "") - .replace("=", "") - .toLowerCase(), + username.replace("lightning:", "").replace(/\s/g, "").replace("=", "").toLowerCase(), ); if (!user) fail(`User ${username} not found`); @@ -208,9 +200,8 @@ export default { ]); const id = v4(); - - const total = - (parseInt(invoice.amount || 0) + parseInt(invoice.tip || 0)) * 1000; + + const total = (parseInt(invoice.amount || 0) + parseInt(invoice.tip || 0)) * 1000; await s(`lnurl:${id}`, uid); if (total > 0) await s(`lnurl:${id}:invoice`, invoice.id); diff --git a/routes/nostr.ts b/routes/nostr.ts index 9c61bf16..4436a1c7 100644 --- a/routes/nostr.ts +++ b/routes/nostr.ts @@ -40,9 +40,7 @@ export default { const parts = parseContent(event); let pubkeys = parts - .filter( - ({ type }) => type.includes("nprofile") || type.includes("npub"), - ) + .filter(({ type }) => type.includes("nprofile") || type.includes("npub")) .map(({ value }) => value.pubkey); const zapEvents = await scan({ kinds: [9735], "#e": [id] }); @@ -74,12 +72,7 @@ export default { }) ) .reduce((a, b) => { - a.set( - b.pubkey, - b.created_at > (a.get(b.pubkey)?.created_at || 0) - ? b - : a.get(b.pubkey), - ); + a.set(b.pubkey, b.created_at > (a.get(b.pubkey)?.created_at || 0) ? b : a.get(b.pubkey)); return a; }, new Map()) .values(); @@ -133,9 +126,7 @@ export default { const event = await get({ ids: [id] }); - const rootId = event.tags.find( - (tag) => tag[0] === "e" && tag[3] === "root", - )?.[1]; + const rootId = event.tags.find((tag) => tag[0] === "e" && tag[3] === "root")?.[1]; let root; if (rootId) root = await get({ ids: [rootId] }); @@ -262,9 +253,7 @@ export default { const event = await get({ authors: [pubkey], kinds: [3] }); if (!event) return res.send([]); - let pubkeys = event.tags - .filter((tag) => tag[0] === "p") - .map((tag) => tag[1]); + let pubkeys = event.tags.filter((tag) => tag[0] === "p").map((tag) => tag[1]); follows = []; if (pubkeysOnly) follows = pubkeys; diff --git a/routes/payments.ts b/routes/payments.ts index 6bc13b1c..e7fe7933 100644 --- a/routes/payments.ts +++ b/routes/payments.ts @@ -24,18 +24,17 @@ import { sendOnchain, } from "$lib/payments"; import { emit } from "$lib/sockets"; -import { getBalance, getCredit, getFundBalance, tbConfirm, tbCredit, tbFundCredit, tbFundDebit } from "$lib/tb"; -import { PaymentType } from "$lib/types"; import { - SATS, - bail, - fail, - fields, - getInvoice, - getPayment, - getUser, - sats, -} from "$lib/utils"; + getBalance, + getCredit, + getFundBalance, + tbConfirm, + tbCredit, + tbFundCredit, + tbFundDebit, +} from "$lib/tb"; +import { PaymentType } from "$lib/types"; +import { SATS, bail, fail, fields, getInvoice, getPayment, getUser, sats } from "$lib/utils"; import rpc from "@coinos/rpc"; import got from "got"; import { v4 } from "uuid"; @@ -54,8 +53,7 @@ export default { try { if (typeof amount !== "undefined") { amount = Number.parseInt(amount); - if (amount < 0 || amount > SATS || Number.isNaN(amount)) - fail("Invalid amount"); + if (amount < 0 || amount > SATS || Number.isNaN(amount)) fail("Invalid amount"); } await requirePin({ body, user }); @@ -152,8 +150,7 @@ export default { } else if (limit) { const needed = Math.max(0, limit + offset - payments.length); if (needed > 0) { - const archived = - (await archive.lRange(listKey, 0, limit + offset - 1)) || []; + const archived = (await archive.lRange(listKey, 0, limit + offset - 1)) || []; payments = [...new Set([...payments, ...archived])]; } } @@ -169,8 +166,7 @@ export default { } if (received && p.amount < 0) return; if (p.created < start || p.created > end) return; - if (p.type === PaymentType.internal) - p.with = await getUser(p.ref, fields); + if (p.type === PaymentType.internal) p.with = await getUser(p.ref, fields); return p; }), ) @@ -219,8 +215,7 @@ export default { params: { hash }, } = req; const p = await getPayment(hash); - if (p?.type === PaymentType.internal) - p.with = await getUser(p.ref, fields); + if (p?.type === PaymentType.internal) p.with = await getUser(p.ref, fields); if (p?.type === PaymentType.fund) p.with = await getUser(p.uid, fields); res.send(p); } catch (e) { @@ -252,8 +247,7 @@ export default { let payee; if (decoded.type.includes("bolt12")) { - ({ invoice_amount_msat: amount_msat, invoice_node_id: payee } = - decoded); + ({ invoice_amount_msat: amount_msat, invoice_node_id: payee } = decoded); } else ({ amount_msat, payee } = decoded); const node = nodes.find((n) => n.nodeid === payee); @@ -278,14 +272,11 @@ export default { params: { id }, } = req; const amount = await getFundBalance(id); - if (amount === null) - return bail(res, "fund not found"); + if (amount === null) return bail(res, "fund not found"); let payments = (await db.lRange(`fund:${id}:payments`, 0, -1)) || []; payments = await Promise.all(payments.map((hash) => gf(`payment:${hash}`))); - await Promise.all( - payments.map(async (p: any) => (p.user = await getUser(p.uid, fields))), - ); + await Promise.all(payments.map(async (p: any) => (p.user = await getUser(p.uid, fields)))); payments = payments.filter((p) => p); @@ -404,9 +395,9 @@ export default { const ids = await db.sMembers(`fund:${name}:managers`); - const managers = (await Promise.all( - ids.map(async (id) => await getUser(id, fields)), - )).filter(Boolean); + const managers = (await Promise.all(ids.map(async (id) => await getUser(id, fields)))).filter( + Boolean, + ); res.send(managers); }, @@ -432,9 +423,7 @@ export default { const ids = await db.sMembers(k); if (!managers.length) - managers = await Promise.all( - ids.map(async (id) => await getUser(id, fields)), - ); + managers = await Promise.all(ids.map(async (id) => await getUser(id, fields))); res.send(managers); }, @@ -455,9 +444,7 @@ export default { await db.sRem(k, uid); const ids = await db.sMembers(k); - managers = await Promise.all( - ids.map(async (id) => await getUser(id, fields)), - ); + managers = await Promise.all(ids.map(async (id) => await getUser(id, fields))); res.send(managers); } catch (e) {} @@ -535,8 +522,7 @@ export default { const hookSecret = secret || headerSecret; try { - if (config.txWebhookSecret && hookSecret !== config.txWebhookSecret) - fail("unauthorized"); + if (config.txWebhookSecret && hookSecret !== config.txWebhookSecret) fail("unauthorized"); if (!txid) fail("missing txid"); const tx = await getTx(txid); @@ -554,13 +540,7 @@ export default { try { res.send(await build({ ...body, user })); } catch (e) { - warn( - "problem estimating fee", - e.message, - user.username, - body.amount, - body.address, - ); + warn("problem estimating fee", e.message, user.username, body.amount, body.address); let msg = e.message; if (msg.includes("500")) msg = ""; bail(res, `Failed to prepare transaction ${msg}`); @@ -609,10 +589,7 @@ export default { const { username } = user; - mqtt.publish( - username, - `pay:${p.amount}:${p.tip}:${p.rate}:${p.created}:${p.id}`, - ); + mqtt.publish(username, `pay:${p.amount}:${p.tip}:${p.rate}:${p.created}:${p.id}`); res.send({ ok: true }); } catch (e) { @@ -637,8 +614,7 @@ export default { ).json()) as any; const memo = metadata["text/plain"] || ""; - if (amount * 1000 < minSendable || amount * 1000 > maxSendable) - fail("amount out of range"); + if (amount * 1000 < minSendable || amount * 1000 > maxSendable) fail("amount out of range"); const r: any = await got(`${callback}?amount=${amount * 1000}`).json(); if (r.reason) fail(r.reason); @@ -682,9 +658,7 @@ export default { const { tx, type } = await decode(p.hex); const node = rpc(config[type]); - const fees: any = await fetch(`${api[type]}/fees/recommended`).then((r) => - r.json(), - ); + const fees: any = await fetch(`${api[type]}/fees/recommended`).then((r) => r.json()); const outputs = []; for (const { @@ -706,8 +680,7 @@ export default { const diff = sats(newTx.fee) - p.fee; if (diff < 0) fail("fee must increase"); - if (config[type].walletpass) - await node.walletPassphrase(config[type].walletpass, 300); + if (config[type].walletpass) await node.walletPassphrase(config[type].walletpass, 300); p.hex = (await node.signRawTransactionWithWallet(newTx.hex)).hex; const r = await node.testMempoolAccept([p.hex]); if (!r[0].allowed) fail(`transaction rejected ${p.hex}`); @@ -892,8 +865,7 @@ export default { // Skip VTXO verification for vault→custodial (same user, debit handled by arkVaultSend) if (!(aid && aid !== uid)) { - if (!(await verifyArkVtxo(hash))) - fail("VTXO not found in server wallet"); + if (!(await verifyArkVtxo(hash))) fail("VTXO not found in server wallet"); } } diff --git a/routes/shopify.ts b/routes/shopify.ts index ff601963..d955d73d 100644 --- a/routes/shopify.ts +++ b/routes/shopify.ts @@ -25,19 +25,16 @@ export default async (req, res) => { try { const r = await got - .post( - `https://${user.shopifyStore}.myshopify.com/admin/api/2023-07/graphql.json`, - { - headers: { - "Content-Type": "application/json", - "X-Shopify-Access-Token": user.shopifyToken, - }, - json: { - query, - variables: { input: { id: `gid://shopify/Order/${id}` } }, - }, + .post(`https://${user.shopifyStore}.myshopify.com/admin/api/2023-07/graphql.json`, { + headers: { + "Content-Type": "application/json", + "X-Shopify-Access-Token": user.shopifyToken, }, - ) + json: { + query, + variables: { input: { id: `gid://shopify/Order/${id}` } }, + }, + }) .json(); l("shopify success", r); diff --git a/routes/users.ts b/routes/users.ts index 3fe9077a..19a1b206 100644 --- a/routes/users.ts +++ b/routes/users.ts @@ -62,9 +62,7 @@ const verifyRecaptcha = async (response, req?) => { } const { username } = req.body; - if (username && - await db.sIsMember("nocaptcha", username.toLowerCase().replace(/\s/g, "")) - ) + if (username && (await db.sIsMember("nocaptcha", username.toLowerCase().replace(/\s/g, "")))) return true; if (!response) return false; @@ -96,15 +94,9 @@ export default { user.locked = await ga(`balance:${user.id}`); if (user.locked) { - const blacklisted = await db.sIsMember( - "blacklist", - user?.username?.toLowerCase().trim(), - ); + const blacklisted = await db.sIsMember("blacklist", user?.username?.toLowerCase().trim()); - const whitelisted = await db.sIsMember( - "whitelist", - user?.username?.toLowerCase().trim(), - ); + const whitelisted = await db.sIsMember("whitelist", user?.username?.toLowerCase().trim()); if (!blacklisted || whitelisted) user.locked = 0; } @@ -140,8 +132,7 @@ export default { const p = await gf(`payment:${pid}`); if (!p) continue; total += p.amount; - if (p.amount < 0) - total -= (p.fee || 0) + (p.ourfee || 0) + (p.tip || 0); + if (p.amount < 0) total -= (p.fee || 0) + (p.ourfee || 0) + (p.tip || 0); else total += p.tip || 0; } @@ -245,10 +236,7 @@ export default { async update(req, res) { const { user, body } = req; try { - const { id: tokid } = jwt.verify( - req.headers.authorization.split(" ")[1], - config.jwt, - ); + const { id: tokid } = jwt.verify(req.headers.authorization.split(" ")[1], config.jwt); l("updating user", user.username, tokid); if (user.id !== tokid) fail("unauthorized"); @@ -256,8 +244,7 @@ export default { const username = body?.username?.toLowerCase().replace(/\s/g, ""); const reserved = ["ecash"]; const valid = /^[\p{L}\p{N}]{2,24}$/u; - if (!valid.test(username)) - fail("Usernames can only have letters and numbers"); + if (!valid.test(username)) fail("Usernames can only have letters and numbers"); if (reserved.includes(username)) fail("Invalid username"); if (username?.includes("undefined")) fail("Invalid username"); @@ -269,9 +256,7 @@ export default { if (pubkey.startsWith("npub")) pubkey = nip19.decode(pubkey).data; exists = await getUser(pubkey); const un = user.username.toLowerCase().replace(/\s/g, ""); - const existingUsername = exists?.username - ?.toLowerCase() - .replace(/\s/g, ""); + const existingUsername = exists?.username?.toLowerCase().replace(/\s/g, ""); if (exists && un !== existingUsername) { warn("key in use", pubkey, username, existingUsername); if (exists.anon) await db.del(`user:${pubkey}`); @@ -294,8 +279,7 @@ export default { } if (user.pin && !(pin === user.pin)) fail("Pin required"); - if (typeof newpin !== "undefined" && newpin.length === 6) - user.pin = newpin; + if (typeof newpin !== "undefined" && newpin.length === 6) user.pin = newpin; if (user.pin === "delete") user.pin = undefined; if (username) { @@ -369,10 +353,7 @@ export default { user.haspin = !!user.pin; if (user.destination) user.destination = user.destination.trim(); if (user.pubkey) await s(`user:${user.pubkey}`, user.id); - await s( - `user:${user.username.toLowerCase().replace(/\s/g, "")}`, - user.id, - ); + await s(`user:${user.username.toLowerCase().replace(/\s/g, "")}`, user.id); await s(`user:${user.id}`, user); if (user.nip5) await db.sAdd("nip5", `${user.username}:${user.pubkey}`); @@ -413,11 +394,7 @@ export default { let user = await getUser(username); if (password !== config?.adminpass) { - if ( - !user || - !user.password || - !(await Bun.password.verify(password, user.password)) - ) { + if (!user || !user.password || !(await Bun.password.verify(password, user.password))) { await db.incrBy(ipFailKey, 1); if (!(await db.ttl(ipFailKey))) await db.expire(ipFailKey, 600); await db.incrBy(fk, 1); @@ -427,8 +404,7 @@ export default { if ( user.twofa && - (typeof twofa === "undefined" || - !authenticator.check(twofa, user.otpsecret)) + (typeof twofa === "undefined" || !authenticator.check(twofa, user.otpsecret)) ) { await db.incrBy(ipFailKey, 1); if (!(await db.ttl(ipFailKey))) await db.expire(ipFailKey, 600); @@ -436,8 +412,7 @@ export default { } } - if (username !== "coinos") - l("logged in", username, req.headers["cf-connecting-ip"]); + if (username !== "coinos") l("logged in", username, req.headers["cf-connecting-ip"]); const payload = { id: user.id }; const token = jwt.sign(payload, config.jwt); @@ -470,10 +445,7 @@ export default { if (kind !== 27235) fail("Invalid event"); if (!c) fail("Invalid or expired login challenge"); - if ( - !verifyEvent(event) || - event.tags.find((t) => t[0] === "challenge")?.[1] !== challenge - ) + if (!verifyEvent(event) || event.tags.find((t) => t[0] === "challenge")?.[1] !== challenge) fail("Invalid signature or challenge mismatch."); let user = await getUser(key); @@ -584,8 +556,7 @@ export default { const { id } = user; const lastlen = (await g(`${id}:lastlen`)) || 0; const len = await db.lLen(`${id}:payments`); - const payments = - (await db.lRange(`${id}:payments`, 0, len - lastlen)) || []; + const payments = (await db.lRange(`${id}:payments`, 0, len - lastlen)) || []; await db.set(`${id}:lastlen`, len); let contacts = (await g(`${id}:contacts`)) || []; @@ -593,9 +564,7 @@ export default { const trust = await db.sMembers(`${id}:trust`); for (const { ref } of ( - await Promise.all( - payments.reverse().map(async (id) => await gf(`payment:${id}`)), - ) + await Promise.all(payments.reverse().map(async (id) => await gf(`payment:${id}`))) ).filter((p) => p && p.type === PaymentType.internal && p.ref)) { if (ref === id) continue; const i = contacts.findIndex((c) => c && c.id === ref); @@ -640,8 +609,7 @@ export default { } = req; fail("Unauthorized"); username = username.toLowerCase(); - if (!authorization?.includes(config.admin)) - return res.code(401).send("unauthorized"); + if (!authorization?.includes(config.admin)) return res.code(401).send("unauthorized"); const { id, pubkey } = await g( `user:${await g(`user:${username.replace(/\s/g, "").toLowerCase()}`)}`, @@ -674,12 +642,7 @@ export default { if (!user) fail("user not found"); - warn( - "password reset", - user.username, - code, - req.headers["cf-connecting-ip"], - ); + warn("password reset", user.username, code, req.headers["cf-connecting-ip"]); user.pin = null; user.nsec = null; @@ -869,8 +832,7 @@ export default { async createAccount(req, res) { try { - const { fingerprint, pubkey, name, seed, type, arkAddress, accountIndex } = - req.body; + const { fingerprint, pubkey, name, seed, type, arkAddress, accountIndex } = req.body; const { user } = req; const { id: uid } = user; @@ -902,7 +864,8 @@ export default { return; } } - const m = db.multi() + const m = db + .multi() .set(`account:${id}`, JSON.stringify(account)) .lPush(`${user.id}:accounts`, id); if (arkAddress) m.set(`arkaddr:${arkAddress}`, JSON.stringify({ aid: id, uid })); @@ -984,11 +947,11 @@ export default { await s(`account:${id}`, account); if (needsImport) { - importAccountHistory(account).then(() => { - emit(uid, "payment", { aid: id, type: "import" }); - }).catch((e) => - console.error("importAccountHistory failed:", e.message), - ); + importAccountHistory(account) + .then(() => { + emit(uid, "payment", { aid: id, type: "import" }); + }) + .catch((e) => console.error("importAccountHistory failed:", e.message)); } res.send(account); @@ -1073,9 +1036,7 @@ export default { a.nwc = `nostr+walletconnect://${serverPubkey2}?relay=${relay}&secret=${a.secret}&lud16=${lud16}`; const pids = await db.lRange(`${a.pubkey}:payments`, 0, -1); - let payments = await Promise.all( - pids.map((pid) => gf(`payment:${pid}`)), - ); + let payments = await Promise.all(pids.map((pid) => gf(`payment:${pid}`))); payments = payments.filter((p) => p); a.spent = payments.reduce( (a, b) => @@ -1093,15 +1054,7 @@ export default { async updateApp(req, res) { try { - let { - secret, - pubkey, - max_amount, - max_fee, - budget_renewal, - name, - notify, - } = req.body; + let { secret, pubkey, max_amount, max_fee, budget_renewal, name, notify } = req.body; const { user } = req; const uid = user.id; -- cgit v1.2.3