From cdd086afc3044d9c8beefb0cc1abc307d1e4557e Mon Sep 17 00:00:00 2001 From: Adam Soltys Date: Wed, 25 Nov 2026 09:25:18 -0700 Subject: webhooks, zaps: send user-supplied URLs through the SSRF guard Invoice webhooks must be plain http(s) strings and are posted with safePost (checked, pinned address, no redirects). Zap requests resolve the recipient lud16/lud06 and callback through safeGot instead of fetching them as-is. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01VMan6SEnsbshZrUDtTsxAX --- lib/invoices.ts | 6 +++++- lib/safe-fetch.ts | 36 ++++++++++++++++++++++++++++++++++++ lib/webhooks.ts | 28 ++++++++++++++-------------- routes/nostr.ts | 36 +++++++++++++++++++++++++++--------- 4 files changed, 82 insertions(+), 24 deletions(-) diff --git a/lib/invoices.ts b/lib/invoices.ts index 835b1247..1de1f95b 100644 --- a/lib/invoices.ts +++ b/lib/invoices.ts @@ -47,9 +47,13 @@ export const generate = async ({ invoice, user }) => { single_use, type = PaymentType.lightning, usePreimage, - webhook, secret, } = invoice; + // Only a plain http(s) URL is a webhook; anything else is dropped. + const webhook = + typeof invoice.webhook === "string" && /^https?:\/\//i.test(invoice.webhook) + ? invoice.webhook.slice(0, 2048) + : undefined; amount = Number.parseInt(amount || 0); tip = tip == null ? null : Number.parseInt(tip); diff --git a/lib/safe-fetch.ts b/lib/safe-fetch.ts index 2a9c7870..b1d082f6 100644 --- a/lib/safe-fetch.ts +++ b/lib/safe-fetch.ts @@ -165,6 +165,42 @@ const fetchOnce = (url: string, redirectsLeft: number): Promise => // body. Throws on a bad scheme/URL or a host that resolves into a blocked range. export const safeGot = async (url: string): Promise => fetchOnce(url, MAX_REDIRECTS); +// POST JSON to a user-supplied URL (merchant webhooks) with the same +// protections as safeGot: http(s) only, the socket pinned to an address that +// was checked, and no redirects at all (a redirect could turn a public URL +// into an internal one). The response body is discarded; resolves with the +// status code. +export const safePost = (url: unknown, json: unknown): Promise => + new Promise((resolve, reject) => { + if (typeof url !== "string" || url.length > 2048) + return reject(new Error("invalid url")); + let u: URL; + try { u = new URL(url); } catch { return reject(new Error("invalid url")); } + if (u.protocol !== "http:" && u.protocol !== "https:") + return reject(new Error("unsupported scheme")); + const literal = u.hostname.replace(/^\[|\]$/g, ""); + if (net.isIP(literal) && isBlockedIp(literal)) + return reject(new Error(`blocked host ${literal}`)); + + const body = Buffer.from(JSON.stringify(json)); + const mod = u.protocol === "https:" ? https : http; + const req = mod.request( + url, + { + method: "POST", + lookup: pinnedLookup as any, + headers: { "content-type": "application/json", "content-length": body.length }, + }, + (res) => { + res.resume(); + resolve(res.statusCode || 0); + }, + ); + req.setTimeout(TIMEOUT_MS, () => req.destroy(new Error("request timed out"))); + req.on("error", reject); + req.end(body); + }); + // 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 diff --git a/lib/webhooks.ts b/lib/webhooks.ts index d724ccdf..ef9b43b1 100644 --- a/lib/webhooks.ts +++ b/lib/webhooks.ts @@ -1,5 +1,5 @@ import config from "$config"; -import got from "got"; +import { safePost } from "$lib/safe-fetch"; import { l, err } from "$lib/logging"; export const callWebhook = async (invoice, payment) => { @@ -8,7 +8,10 @@ export const callWebhook = async (invoice, payment) => { const { address, received, text, webhook, secret } = invoice; - if (webhook) { + // The webhook URL is whatever the invoice's creator typed, so it goes + // through the SSRF guard and must be a plain string: an object here would + // be read as a full set of request options (headers, credentials, ...). + if (typeof webhook === "string" && webhook) { const { amount, confirmed, hash, memo } = payment; l("calling webhook", webhook, amount, hash, address, text); @@ -19,19 +22,16 @@ export const callWebhook = async (invoice, payment) => { // "payment received" callbacks to that merchant. A merchant on a // self-signed cert now fails here instead, which the catch below logs; // the payment itself is unaffected. - const res = await got.post(webhook, { - json: { - address, - amount, - confirmed, - hash, - memo, - received, - text, - secret, - }, + return await safePost(webhook, { + address, + amount, + confirmed, + hash, + memo, + received, + text, + secret, }); - return res; } } catch (e) { err("problem calling webhook", e.message); diff --git a/routes/nostr.ts b/routes/nostr.ts index 3b28076a..023b656f 100644 --- a/routes/nostr.ts +++ b/routes/nostr.ts @@ -1,5 +1,6 @@ import config from "$config"; import { db, g, s } from "$lib/db"; +import { holderBlocked } from "$lib/names"; import ln from "$lib/ln"; import { EX, @@ -15,11 +16,12 @@ import { import { parseContent } from "$lib/notes"; import { scan } from "$lib/strfry"; import { bail, fail, fields, getUser } from "$lib/utils"; -import got from "got"; +import { safeGot } from "$lib/safe-fetch"; +import { bech32 } from "bech32"; import type { Event } from "nostr-tools"; import { decode } from "nostr-tools/nip19"; import type { ProfilePointer } from "nostr-tools/nip19"; -import { getZapEndpoint, makeZapRequest } from "nostr-tools/nip57"; +import { makeZapRequest } from "nostr-tools/nip57"; // Amount and payer of a zap receipt. NIP-57 kind 9735: amount comes from // decoding the paid bolt11, payer from the embedded 9734 zap request in the @@ -351,6 +353,7 @@ export default { // v3 registrar first: a claimed name's NIP-05 belongs to its wallet key. // Legacy accounts answer as before when the registrar doesn't know it. try { + if (await holderBlocked(name)) throw new Error("blocked holder"); const r = await fetch( `${process.env.NAMES_URL || "https://names.coinos.io"}/.well-known/nostr.json?name=${encodeURIComponent(name)}`, { signal: AbortSignal.timeout(3000) }, @@ -408,13 +411,28 @@ export default { const { event } = req.body; const amount = event.tags.find((t) => t[0] === "amount")[1]; const pubkey = event.tags.find((t) => t[0] === "p")[1]; - const content = JSON.stringify(await getProfile(pubkey)); - const callback = await getZapEndpoint({ content } as Event); - if (!callback || callback === "null") fail("Lightning address not found"); - - const encodedEvent = encodeURI(JSON.stringify(event)); - const url = `${callback}?amount=${amount}&nostr=${encodedEvent}`; - const json = await got(url).json(); + // The recipient's profile is whatever they published, so its lightning + // address and the callback it leads to are fetched through the SSRF + // guard (nostr-tools' getZapEndpoint and got would fetch them as-is). + const { lud06, lud16 } = (await getProfile(pubkey)) || {}; + let lnurl: string; + if (typeof lud16 === "string" && /^[^@\s/?#]+@[^@\s/?#]+$/.test(lud16)) { + const [name, domain] = lud16.split("@"); + lnurl = `https://${domain}/.well-known/lnurlp/${encodeURIComponent(name)}`; + } else if (typeof lud06 === "string" && lud06) { + lnurl = Buffer.from( + bech32.fromWords(bech32.decode(lud06, 2000).words), + ).toString(); + } else fail("Lightning address not found"); + + const pay = await safeGot(lnurl); + if (!pay?.allowsNostr || !pay.nostrPubkey || typeof pay.callback !== "string") + fail("Lightning address not found"); + + const u = new URL(pay.callback); + u.searchParams.set("amount", String(amount)); + u.searchParams.set("nostr", JSON.stringify(event)); + const json = await safeGot(u.toString()); res.send(json); } catch (e) { -- cgit v1.2.3