diff options
Diffstat (limited to 'lib')
| -rw-r--r-- | lib/lnurl-payload.ts | 60 | ||||
| -rw-r--r-- | lib/nostr.ts | 10 | ||||
| -rw-r--r-- | lib/payments.ts | 7 | ||||
| -rw-r--r-- | lib/safe-fetch.ts | 17 |
4 files changed, 91 insertions, 3 deletions
diff --git a/lib/lnurl-payload.ts b/lib/lnurl-payload.ts new file mode 100644 index 00000000..6248d213 --- /dev/null +++ b/lib/lnurl-payload.ts @@ -0,0 +1,60 @@ +import { bech32 } from "bech32"; + +const invalid = (): never => { throw new Error("Invalid LNURL response"); }; +const object = (v: any) => v !== null && typeof v === "object" && !Array.isArray(v); +const amount = (v: any, min: number) => Number.isSafeInteger(v) && v >= min; +const callback = (v: any) => { + if (typeof v !== "string") return invalid(); + const u = new URL(v); + if (!["http:", "https:"].includes(u.protocol) || u.username || u.password) invalid(); + return v; +}; + +// Return only protocol fields: never relay an arbitrary upstream JSON object. +export function lnurlPayload(v: any): any { + if (!object(v)) return invalid(); + if (v.status === "ERROR" && typeof v.reason === "string") + return { status: "ERROR", reason: "LNURL service returned an error" }; + if (v.status === "OK" && !v.tag && !v.pr) return { status: "OK" }; + if (v.tag === "payRequest") { + if (!amount(v.minSendable, 1) || !amount(v.maxSendable, v.minSendable) || typeof v.metadata !== "string") invalid(); + let metadata: any; + try { metadata = JSON.parse(v.metadata); } catch { return invalid(); } + if (!Array.isArray(metadata) || !metadata.every((e: any) => Array.isArray(e) && e.length >= 2 && typeof e[0] === "string") || + metadata.filter((e: any) => e[0] === "text/plain" && typeof e[1] === "string").length !== 1) invalid(); + const out: any = { tag: v.tag, callback: callback(v.callback), minSendable: v.minSendable, maxSendable: v.maxSendable, metadata: v.metadata }; + if (amount(v.commentAllowed, 0)) out.commentAllowed = v.commentAllowed; + if (v.allowsNostr === true && typeof v.nostrPubkey === "string" && /^[a-f0-9]{64}$/i.test(v.nostrPubkey)) { + out.allowsNostr = true; out.nostrPubkey = v.nostrPubkey; + } + return out; + } + if (v.tag === "withdrawRequest") { + if (typeof v.k1 !== "string" || !v.k1 || typeof v.defaultDescription !== "string" || + !amount(v.minWithdrawable, 0) || !amount(v.maxWithdrawable, v.minWithdrawable)) invalid(); + return { tag: v.tag, callback: callback(v.callback), k1: v.k1, defaultDescription: v.defaultDescription, + minWithdrawable: v.minWithdrawable, maxWithdrawable: v.maxWithdrawable }; + } + if (typeof v.pr === "string") { + let decoded: any; + try { decoded = bech32.decode(v.pr, 20000); } catch { return invalid(); } + if (!/^ln(bc|tb|bcrt|sb)[0-9]*[munp]?$/.test(decoded.prefix) || decoded.words.length < 111 || + !Array.isArray(v.routes) || v.routes.length !== 0) invalid(); + const out: any = { pr: v.pr, routes: [] }; + if (v.disposable === false || v.disposable === true) out.disposable = v.disposable; + if (typeof v.verify === "string") out.verify = callback(v.verify); + const a = v.successAction; + if (object(a)) { + if (a.tag === "message" && typeof a.message === "string" && a.message.length <= 144) + out.successAction = { tag: a.tag, message: a.message }; + else if (a.tag === "url" && typeof a.description === "string" && a.description.length <= 144) + out.successAction = { tag: a.tag, description: a.description, url: callback(a.url) }; + else if (a.tag === "aes" && typeof a.description === "string" && a.description.length <= 144 && + typeof a.ciphertext === "string" && a.ciphertext.length <= 4096 && typeof a.iv === "string" && /^[A-Za-z0-9+/]{22}==$/.test(a.iv)) + out.successAction = { tag: a.tag, description: a.description, ciphertext: a.ciphertext, iv: a.iv }; + else invalid(); + } + return out; + } + return invalid(); +} diff --git a/lib/nostr.ts b/lib/nostr.ts index ed1b2f42..63199bf8 100644 --- a/lib/nostr.ts +++ b/lib/nostr.ts @@ -1,4 +1,5 @@ import config from "$config"; +import { safeRelayUrl } from "$lib/safe-fetch"; import { db, g, s } from "$lib/db"; import { l, warn } from "$lib/logging"; import { scan } from "$lib/strfry"; @@ -125,7 +126,14 @@ export async function handleZap(invoice, sender = undefined) { l("sending receipt"); - const relays = relays_tag.slice(1).filter((r) => r?.startsWith("ws")); + // Relay URLs come from the zap request, i.e. from whoever asked for the + // invoice; don't let them point our server at internal hosts. + const requested = relays_tag + .slice(1) + .filter((r) => typeof r === "string" && r.startsWith("ws")) + .slice(0, 10); + const relays = []; + for (const r of requested) if (await safeRelayUrl(r)) relays.push(r); relays.push(config.nostr); relays.map(async (url) => { try { diff --git a/lib/payments.ts b/lib/payments.ts index 407e5eac..43070843 100644 --- a/lib/payments.ts +++ b/lib/payments.ts @@ -1,4 +1,5 @@ import config from "$config"; +import { safeGot } from "$lib/safe-fetch"; import { existsSync } from "fs"; import api from "$lib/api"; import { requireAccount } from "$lib/auth"; @@ -603,6 +604,8 @@ const pay = async ({ aid = undefined, amount, to, user }) => { let pr; if (to.includes("@") && to.includes(".")) { const [name, domain] = to.split("@"); + if (!name || /[\/\\?#%@\s]|\.\./u.test(name) || !/^[a-z0-9.-]+(:\d+)?$/i.test(domain || "")) + fail("Invalid lightning address"); if (URL.includes(domain)) to = name; lnurl = `https://${domain}/.well-known/lnurlp/${name}`; } else if (to.startsWith("lnurl")) { @@ -631,8 +634,8 @@ const pay = async ({ aid = undefined, amount, to, user }) => { const fee = Math.max(5, Math.round(amount * 0.02)); if (lnurl) { amount -= fee; - const { callback } = (await got(lnurl).json()) as any; - ({ pr } = (await got(`${callback}?amount=${amount * 1000}`).json()) as any); + const { callback } = (await safeGot(lnurl)) as any; + ({ pr } = (await safeGot(`${callback}?amount=${amount * 1000}`)) as any); } else if (to.startsWith("ln")) { amount -= fee; pr = to; diff --git a/lib/safe-fetch.ts b/lib/safe-fetch.ts index 5b1059e9..2a9c7870 100644 --- a/lib/safe-fetch.ts +++ b/lib/safe-fetch.ts @@ -26,6 +26,7 @@ const blockedV4 = (ip: string): boolean => { if (a === 127) return true; // loopback if (a === 169 && b === 254) return true; // link-local + cloud metadata (169.254.169.254) if (a === 172 && b >= 16 && b <= 31) return true; // private + if (a === 172 && b === 42) return true; // cs Docker network uses 172.42.0.0/16 if (a === 192 && b === 168) return true; // private if (a === 100 && b >= 64 && b <= 127) return true; // CGNAT 100.64/10 (incl. tailscale) if (a >= 224) return true; // multicast / reserved @@ -163,3 +164,19 @@ const fetchOnce = (url: string, redirectsLeft: number): Promise<any> => // Fetch a user-supplied URL with SSRF protection and return the parsed JSON // body. Throws on a bad scheme/URL or a host that resolves into a blocked range. export const safeGot = async (url: string): Promise<any> => fetchOnce(url, MAX_REDIRECTS); + +// For URLs we hand to a library that does its own connecting (nostr relays +// over WebSocket): allow only ws/wss to a host whose every resolved address +// is public. Not rebind-proof like safeGot, but keeps user-supplied relay +// lists from pointing us at internal services. +export const safeRelayUrl = async (raw: string): Promise<boolean> => { + let u: globalThis.URL; + try { u = new globalThis.URL(raw); } catch { return false; } + if (u.protocol !== "ws:" && u.protocol !== "wss:") return false; + const host = u.hostname.replace(/^\[|\]$/g, ""); + if (net.isIP(host)) return !isBlockedIp(host); + try { + const addrs = await dns.promises.lookup(host, { all: true }); + return addrs.length > 0 && addrs.every((a) => !isBlockedIp(a.address)); + } catch { return false; } +}; |
