import { g, s } from "$lib/db"; import { err, warn } from "$lib/logging"; import { bail, getUser, fail } from "$lib/utils"; import { v4 } from "uuid"; import got from "got"; import { generate } from "$lib/invoices"; import { bech32 } from "bech32"; import { types } from "$lib/payments"; import { serverPubkey } from "$lib/nostr"; const { URL } = process.env; const host = URL.split("/").at(-1); export default { async encode(req, res) { const { query: { address }, } = req; const [name, domain] = address.split("@"); const url = `https://${domain}/.well-known/lnurlp/${name}`; try { const r = await got(url).json(); if (r.tag !== "payRequest") fail("not an ln address"); } catch (e) { const m = `failed to lookup lightning address ${address}`; warn(m); return bail(res, m); } const enc = bech32.encode("lnurl", bech32.toWords(Buffer.from(url)), 20000); res.send(enc); }, async decode(req, res) { const { query: { text }, } = req; try { const url = Buffer.from( bech32.fromWords(bech32.decode(text, 20000).words), ).toString(); res.send(await got(url).json()); } catch (e) { bail(res, e.message); } }, async lnurlp(req, res) { const { params: { username }, query: { minSendable = 1000, maxSendable = 100000000000 }, } = req; try { const { id: uid } = await getUser(username); const metadata = JSON.stringify([ ["text/plain", `Paying ${username}@${host}`], ["text/identifier", `${username}@${host}`], ]); const id = v4(); await s(`lnurl:${id}`, uid); res.send({ allowsNostr: true, minSendable, maxSendable, metadata, nostrPubkey: serverPubkey, commentAllowed: 512, callback: `${URL}/api/lnurl/${id}`, tag: "payRequest", }); } catch (e) { warn("problem generating lnurlp request", username, e.message); bail(res, e.message); } }, async lnurl(req, res) { const { params: { id }, query: { amount, comment, nostr }, } = req; try { const uid = await g(`lnurl:${id}`); const user = await getUser(uid); if (!user) fail("user not found"); let { username } = user; username = username.replace(/\s/g, "").toLowerCase(); const memo = `Paying ${username}@${host}`; let metadata = JSON.stringify([ ["text/plain", memo], ["text/identifier", `${username}@${host}`], ]); if (nostr) { try { const event = JSON.parse(decodeURIComponent(nostr)); // TODO: validate the event await s(`zap:${id}`, event); metadata = nostr; } catch (e) { err("problem handling zap", e.message); } } const { id: iid, text: pr } = await generate({ invoice: { amount: Math.round(amount / 1000), memo: metadata, type: types.lightning, }, user, }); res.send({ pr, routes: [], verify: `${URL}/api/lnurl/verify/${iid}` }); } catch (e) { bail(res, e.message); } }, async verify(req, res) { const { params: { id }, } = req; const inv = await g(`invoice:${id}`); if (!inv) return res.send({ status: "ERROR", reason: "Not found" }); const { received, amount, preimage } = inv; const settled = received >= amount; res.send({ status: "OK", settled, preimage }); }, };