From 47d2d02c445b03a056b705a5ba534741b998994a Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Wed, 19 Aug 2026 10:40:53 -0500 Subject: [PATCH] Validate zap invoice amounts in the nwc skill MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The LNURL-pay endpoint is chosen by the recipient, so a hostile author decides what invoice their zappers are handed — including how much it charges. Nothing in the old flow ever read the invoice: `useZaps` passed the string straight to `sendPayment` or WebLN, so a user who approved 776 sats could be billed 5,000,000 with no indication anything was off. Decode the BOLT11 and require it to charge exactly the approved amount before any wallet is touched, and re-assert in `sendPayment` so no future caller can bypass the check. Amountless invoices are rejected outright. Resolving the endpoint moves off `nip57.getZapEndpoint`, which discards the `minSendable`/`maxSendable` bounds and the `metadata` string needed to confirm the invoice was issued for this request; `lib/lnurlPay.ts` keeps them and pins both the LNURL and its callback to HTTPS. Building the callback query with `URLSearchParams` also fixes comments containing `&`, `+` or `#` corrupting the request under `encodeURI`. --- .agents/skills/nwc/SKILL.md | 30 ++- .agents/skills/nwc/files/hooks/useNWC.ts | 12 +- .agents/skills/nwc/files/hooks/useZaps.ts | 68 +++++- .agents/skills/nwc/files/lib/bolt11.ts | 257 ++++++++++++++++++++++ .agents/skills/nwc/files/lib/lnurlPay.ts | 136 ++++++++++++ 5 files changed, 492 insertions(+), 11 deletions(-) create mode 100644 .agents/skills/nwc/files/lib/bolt11.ts create mode 100644 .agents/skills/nwc/files/lib/lnurlPay.ts diff --git a/.agents/skills/nwc/SKILL.md b/.agents/skills/nwc/SKILL.md index 8533459..39b2705 100644 --- a/.agents/skills/nwc/SKILL.md +++ b/.agents/skills/nwc/SKILL.md @@ -24,6 +24,8 @@ All files live under `.agents/skills/nwc/files/` and must be copied into `src/` | `files/hooks/useNWCContext.ts` | `src/hooks/useNWCContext.ts` | | `files/hooks/useWallet.ts` | `src/hooks/useWallet.ts` | | `files/hooks/useZaps.ts` | `src/hooks/useZaps.ts` | +| `files/lib/bolt11.ts` | `src/lib/bolt11.ts` | +| `files/lib/lnurlPay.ts` | `src/lib/lnurlPay.ts` | | `files/contexts/NWCContext.tsx` | `src/contexts/NWCContext.tsx` | | `files/components/WalletModal.tsx` | `src/components/WalletModal.tsx` | | `files/components/ZapDialog.tsx` | `src/components/ZapDialog.tsx` | @@ -122,7 +124,7 @@ function MyComponent() { removeConnection, // (connectionString: string) => void setActiveConnection,// (connectionString: string) => void getActiveConnection,// () => NWCConnection | null - sendPayment, // (connection, invoice) => Promise<{ preimage: string }> + sendPayment, // (connection, invoice, expectedAmountMsat) => Promise<{ preimage: string }> } = useNWC(); } ``` @@ -160,8 +162,28 @@ The `zap(amount, comment)` function will: 1. Look up the author's LNURL endpoint from their profile's `lud16`/`lud06` 2. Create and sign a NIP-57 zap request 3. Fetch a Lightning invoice from the LNURL service -4. Try to pay it via NWC (preferred), then WebLN, then expose the invoice for QR/manual payment -5. Show toast feedback and invalidate zap query caches on success +4. **Decode the invoice and reject it unless it charges exactly the requested amount** +5. Try to pay it via NWC (preferred), then WebLN, then expose the invoice for QR/manual payment +6. Show toast feedback and invalidate zap query caches on success + +### Never pay an invoice you haven't read + +Step 4 is not optional. The LNURL endpoint is chosen by the **recipient**, so the +invoice it returns is attacker-controlled whenever the recipient is hostile: +anyone who posts a note and runs their own pay server otherwise decides how much +their victims spend, *after* the victim has approved a figure. A user who +approves 776 sats can be charged 5,000,000, and — since the wallet is handed only +the invoice string — nothing downstream will notice. + +`lib/bolt11.ts` provides `assertInvoiceAmount(invoice, expectedMsat)`, which +decodes the BOLT11 and throws unless the amount matches exactly. Amountless +invoices are rejected outright, since they let the wallet or payee pick the sum. +`useNWC.sendPayment` takes the approved amount and re-checks it, so no caller can +hand a wallet an unvetted invoice. + +If you add another payment path, put the check in front of it. Do not use a +regex on the human-readable part for this — that is a display heuristic, not an +authentication check. ## Components @@ -223,7 +245,7 @@ Errors at each stage fall through to the next method, with a toast explaining wh - **NIP-47 (NWC)** — wallet connection strings start with `nostr+walletconnect://` (or legacy `nostrwalletconnect://`). The `@getalby/sdk` `LN` client handles the underlying encrypted request/response events with the wallet service pubkey over relays defined in the URI. - **NIP-57 (Zaps)** — `nip57.makeZapRequest` builds the kind-9734 zap request. For addressable events (kinds 30000–39999) the skill passes the event object (so an `a` tag is included); for all other kinds it passes just the event id (so an `e` tag is included). The zap request is **signed but not published** — it's sent directly to the LNURL endpoint in the query string, which returns a BOLT11 invoice. -- **LNURL** — resolved from the author's `lud16` (email-style) or `lud06` (bech32) metadata field via `nip57.getZapEndpoint`. +- **LNURL** — resolved from the author's `lud16` (email-style) or `lud06` (bech32) metadata field by `lib/lnurlPay.ts`. It does not use `nip57.getZapEndpoint`, which returns only the callback URL and discards the `minSendable`/`maxSendable` bounds and the `metadata` string needed to validate the response. HTTPS is required for both the LNURL and the callback it names. - **Zap receipts** — kind 9735 events published by the LNURL service after payment. The skill queries them by `#e` (regular events) or `#a` (addressable events) and sums sats from the `amount` tag, BOLT11 invoice, or zap request description (in that order of preference). ## Tips diff --git a/.agents/skills/nwc/files/hooks/useNWC.ts b/.agents/skills/nwc/files/hooks/useNWC.ts index d1643e5..22c0899 100644 --- a/.agents/skills/nwc/files/hooks/useNWC.ts +++ b/.agents/skills/nwc/files/hooks/useNWC.ts @@ -2,6 +2,7 @@ import { useState, useCallback } from 'react'; import { useLocalStorage } from '@/hooks/useLocalStorage'; import { useToast } from '@/hooks/useToast'; import { LN } from '@getalby/sdk'; +import { assertInvoiceAmount } from '@/lib/bolt11'; export interface NWCConnection { connectionString: string; @@ -159,12 +160,21 @@ export function useNWCInternal() { // Send payment using the SDK const sendPayment = useCallback(async ( connection: NWCConnection, - invoice: string + invoice: string, + /** + * Amount in millisatoshis the user approved. The wallet is handed only the + * invoice, so this is the last point at which the sum the user agreed to + * and the sum the invoice charges can be compared — without it, whoever + * issued the invoice decides how much leaves the wallet. + */ + expectedAmountMsat: number, ): Promise<{ preimage: string }> => { if (!connection.connectionString) { throw new Error('Invalid connection: missing connection string'); } + assertInvoiceAmount(invoice, expectedAmountMsat); + let client: LN; try { client = new LN(connection.connectionString); diff --git a/.agents/skills/nwc/files/hooks/useZaps.ts b/.agents/skills/nwc/files/hooks/useZaps.ts index d3b810a..e92b0eb 100644 --- a/.agents/skills/nwc/files/hooks/useZaps.ts +++ b/.agents/skills/nwc/files/hooks/useZaps.ts @@ -11,6 +11,8 @@ import type { WebLNProvider } from '@webbtc/webln-types'; import { useQuery, useQueryClient } from '@tanstack/react-query'; import { useNostr } from '@nostrify/react'; import type { NostrEvent } from '@nostrify/nostrify'; +import { assertInvoiceAmount, invoiceCommitsTo } from '@/lib/bolt11'; +import { resolveLnurlPay, type LnurlPayParams } from '@/lib/lnurlPay'; export function useZaps( target: Event | Event[], @@ -180,12 +182,29 @@ export function useZaps( return; } - // Get zap endpoint using the old reliable method - const zapEndpoint = await nip57.getZapEndpoint(author.data.event); - if (!zapEndpoint) { + // Resolve the recipient's LNURL-pay endpoint. `nip57.getZapEndpoint` + // returns only the callback URL and discards the `minSendable` / + // `maxSendable` bounds and the `metadata` string needed to check that + // the invoice we get back is the one we asked for. + let lnurlParams: LnurlPayParams; + try { + lnurlParams = await resolveLnurlPay({ lud06, lud16 }); + } catch (endpointError) { toast({ title: 'Zap endpoint not found', - description: 'Could not find a zap endpoint for the author.', + description: endpointError instanceof Error + ? endpointError.message + : 'Could not find a zap endpoint for the author.', + variant: 'destructive', + }); + setIsZapping(false); + return; + } + + if (!lnurlParams.allowsNostr || !lnurlParams.nostrPubkey) { + toast({ + title: 'Zaps not supported', + description: "This author's lightning address does not support zaps.", variant: 'destructive', }); setIsZapping(false); @@ -201,6 +220,20 @@ export function useZaps( const zapAmount = amount * 1000; // convert to millisats + // The endpoint advertises what it will accept; asking for anything + // outside that range can only produce an invoice we'd have to reject. + if (zapAmount < lnurlParams.minSendable || zapAmount > lnurlParams.maxSendable) { + toast({ + title: 'Amount out of range', + description: + `This lightning address accepts between ${Math.ceil(lnurlParams.minSendable / 1000)} and ` + + `${Math.floor(lnurlParams.maxSendable / 1000)} sats.`, + variant: 'destructive', + }); + setIsZapping(false); + return; + } + const zapRequest = nip57.makeZapRequest({ profile: actualTarget.pubkey, event: event, @@ -214,9 +247,17 @@ export function useZaps( throw new Error('No signer available'); } const signedZapRequest = await user.signer.signEvent(zapRequest); + const zapRequestJson = JSON.stringify(signedZapRequest); try { - const res = await fetch(`${zapEndpoint}?amount=${zapAmount}&nostr=${encodeURI(JSON.stringify(signedZapRequest))}`); + // Build the query with URLSearchParams: `encodeURI` leaves `&`, `+` + // and `#` alone, so a comment containing any of them corrupted the + // request. + const zapUrl = new URL(lnurlParams.callback); + zapUrl.searchParams.set('amount', String(zapAmount)); + zapUrl.searchParams.set('nostr', zapRequestJson); + + const res = await fetch(zapUrl.toString()); const responseData = await res.json(); if (!res.ok) { @@ -228,13 +269,28 @@ export function useZaps( throw new Error('Lightning service did not return a valid invoice'); } + // The endpoint that produced this invoice is chosen by the + // recipient, so the invoice is not trusted: decode it and require + // that it charges exactly what the user approved. Without this the + // recipient — not the sender — decides how much the sender pays, + // and nothing downstream ever reads the invoice. Throwing here + // aborts before any wallet is touched, on every payment path. + const decodedInvoice = assertInvoiceAmount(newInvoice, zapAmount); + + // LUD-06 binds the invoice to the endpoint's `metadata`; NIP-57 + // binds it to the zap request instead. Either is fine, anything + // else means the invoice was not issued for this request. + if (!invoiceCommitsTo(decodedInvoice, [zapRequestJson, lnurlParams.metadata])) { + throw new Error('Lightning service returned an invoice for a different request. Payment cancelled.'); + } + // Get the current active NWC connection dynamically const currentNWCConnection = getActiveConnection(); // Try NWC first if available and properly connected if (currentNWCConnection && currentNWCConnection.connectionString && currentNWCConnection.isConnected) { try { - await sendPayment(currentNWCConnection, newInvoice); + await sendPayment(currentNWCConnection, newInvoice, zapAmount); // Clear states immediately on success setIsZapping(false); diff --git a/.agents/skills/nwc/files/lib/bolt11.ts b/.agents/skills/nwc/files/lib/bolt11.ts new file mode 100644 index 0000000..e37c03b --- /dev/null +++ b/.agents/skills/nwc/files/lib/bolt11.ts @@ -0,0 +1,257 @@ +/** + * BOLT11 lightning invoice decoding. + * + * This is an *authentication* decoder, not a display heuristic: before any + * wallet is asked to pay an invoice we have to know exactly what that invoice + * commits to. The regex in `LightningInvoiceCard` reads the human-readable + * part of a string that is assumed to already be an invoice — it will happily + * report an amount for a string that is not a valid invoice at all, and it + * cannot see the tagged fields. Use {@link decodeBolt11} for anything that + * moves money. + * + * Built on `@scure/base` + `@noble/hashes`, both already in the entry bundle + * via `nostr-tools`, so this adds no new dependency. + * + * Reference: BOLT 11, "Invoice Protocol for Lightning Payments". + */ +import { bech32 } from '@scure/base'; +import { sha256 } from '@noble/hashes/sha256'; +import { bytesToHex } from '@noble/hashes/utils'; + +/** A decoded BOLT11 invoice. Only the fields we need are surfaced. */ +export interface DecodedInvoice { + /** + * Amount in millisatoshis, or `null` when the invoice is *amountless* — + * meaning the payer or the payee chooses the sum. Never pay an amountless + * invoice on the user's behalf. + */ + amountMsat: number | null; + /** Network prefix from the human-readable part: `bc`, `tb`, `bcrt`, `sb`. */ + network: string; + /** Hex 32-byte payment hash (`p` field). */ + paymentHash?: string; + /** Hex 32-byte description hash (`h` field), if the invoice carries one. */ + descriptionHash?: string; + /** Plain-text description (`d` field), if the invoice carries one. */ + description?: string; + /** Hex 33-byte payee node id (`n` field), if the invoice carries one. */ + payee?: string; + /** Invoice creation time, in Unix seconds. */ + timestamp: number; + /** Seconds after {@link timestamp} that the invoice expires. */ + expiry: number; +} + +/** Millisatoshis in one bitcoin. */ +const MSAT_PER_BTC = 100_000_000_000n; + +/** + * BOLT11 amount multipliers, as the divisor applied to {@link MSAT_PER_BTC}. + * `p` (pico) divides to 1/10 msat, so pico amounts must be a multiple of 10. + */ +const MULTIPLIERS: Record = { + m: 1_000n, + u: 1_000_000n, + n: 1_000_000_000n, + p: 1_000_000_000_000n, +}; + +/** `ln` + network + optional amount. Longer prefixes first (`bcrt` vs `bc`). */ +const HRP_RE = /^ln(bcrt|bc|tbs|tb|sb)(?:(\d+)([munp])?)?$/; + +/** BOLT11 tagged-field types, as bech32 word values. */ +const TAG_PAYMENT_HASH = 1; // 'p' +const TAG_DESCRIPTION = 13; // 'd' +const TAG_PAYEE = 19; // 'n' +const TAG_DESCRIPTION_HASH = 23; // 'h' +const TAG_EXPIRY = 6; // 'x' + +/** Words occupied by the trailing signature (65 bytes = 520 bits). */ +const SIGNATURE_WORDS = 104; +/** Words occupied by the leading timestamp (35 bits). */ +const TIMESTAMP_WORDS = 7; + +/** BOLT11's default expiry when no `x` field is present. */ +const DEFAULT_EXPIRY = 3600; + +/** + * Pack 5-bit bech32 words into bytes, discarding any trailing bits that do + * not complete a byte. BOLT11 fields are not all byte-aligned (a 32-byte hash + * occupies 52 words = 260 bits), so `bech32.fromWords` — which rejects + * leftover bits — cannot be used here. + */ +function wordsToBytes(words: number[]): Uint8Array { + const out = new Uint8Array(Math.floor((words.length * 5) / 8)); + let acc = 0; + let bits = 0; + let i = 0; + for (const word of words) { + acc = (acc << 5) | word; + bits += 5; + while (bits >= 8) { + bits -= 8; + out[i++] = (acc >> bits) & 0xff; + } + } + return out; +} + +/** Read a big-endian integer out of 5-bit words. */ +function wordsToInt(words: number[]): number { + let value = 0; + for (const word of words) { + value = value * 32 + word; + } + return value; +} + +/** Parse the amount out of a BOLT11 human-readable part, in millisatoshis. */ +function parseHrpAmount(digits: string | undefined, multiplier: string | undefined): number | null { + if (!digits) return null; + + const value = BigInt(digits); + const divisor = multiplier ? MULTIPLIERS[multiplier] : 1n; + const numerator = value * MSAT_PER_BTC; + + if (numerator % divisor !== 0n) { + // Sub-millisatoshi precision. BOLT11 forbids it, and we can't pay it. + throw new Error('Invalid BOLT11 invoice: amount is not a whole number of millisatoshis'); + } + + const msat = numerator / divisor; + if (msat > BigInt(Number.MAX_SAFE_INTEGER)) { + throw new Error('Invalid BOLT11 invoice: amount is implausibly large'); + } + + return Number(msat); +} + +/** + * Decode a BOLT11 invoice, verifying its bech32 checksum and structure. + * + * Throws on anything that is not a well-formed invoice. The signature is not + * checked — verifying it would only prove the invoice was signed by whoever + * the invoice itself names as payee, which tells us nothing we didn't already + * decide by choosing to talk to that endpoint. What matters to callers is the + * *amount* and the *description hash*, both of which are covered here. + */ +export function decodeBolt11(invoice: string): DecodedInvoice { + const trimmed = invoice.trim().replace(/^lightning:/i, ''); + const lowered = trimmed.toLowerCase(); + + if (!lowered.startsWith('ln')) { + throw new Error('Invalid BOLT11 invoice: missing "ln" prefix'); + } + + // `false` disables bech32's 90-character limit, which invoices exceed. + const { prefix, words } = bech32.decode(lowered as `${Lowercase}1${string}`, false); + + const hrp = HRP_RE.exec(prefix); + if (!hrp) { + throw new Error('Invalid BOLT11 invoice: unrecognized prefix'); + } + + const [, network, digits, multiplier] = hrp; + const amountMsat = parseHrpAmount(digits, multiplier); + + if (words.length < TIMESTAMP_WORDS + SIGNATURE_WORDS) { + throw new Error('Invalid BOLT11 invoice: truncated'); + } + + const timestamp = wordsToInt(words.slice(0, TIMESTAMP_WORDS)); + const tagged = words.slice(TIMESTAMP_WORDS, words.length - SIGNATURE_WORDS); + + const decoded: DecodedInvoice = { amountMsat, network, timestamp, expiry: DEFAULT_EXPIRY }; + + for (let i = 0; i + 3 <= tagged.length;) { + const type = tagged[i]; + const length = tagged[i + 1] * 32 + tagged[i + 2]; + const start = i + 3; + const end = start + length; + if (end > tagged.length) { + throw new Error('Invalid BOLT11 invoice: tagged field overruns the invoice'); + } + const data = tagged.slice(start, end); + i = end; + + switch (type) { + case TAG_PAYMENT_HASH: + if (length === 52) decoded.paymentHash = bytesToHex(wordsToBytes(data)); + break; + case TAG_DESCRIPTION_HASH: + if (length === 52) decoded.descriptionHash = bytesToHex(wordsToBytes(data)); + break; + case TAG_PAYEE: + if (length === 53) decoded.payee = bytesToHex(wordsToBytes(data)); + break; + case TAG_DESCRIPTION: + decoded.description = new TextDecoder().decode(wordsToBytes(data)); + break; + case TAG_EXPIRY: + decoded.expiry = wordsToInt(data); + break; + } + } + + return decoded; +} + +/** + * Assert that `invoice` is payable for exactly `expectedMsat`. + * + * LNURL-pay endpoints are chosen by the *recipient*, so the invoice they hand + * back is attacker-controlled whenever the recipient is hostile. Without this + * check the recipient — not the sender — decides how much the sender pays. + * + * Returns the decoded invoice so callers can report the amount they actually + * paid rather than the one they asked for. + */ +export function assertInvoiceAmount( + invoice: string, + expectedMsat: number, +): DecodedInvoice & { amountMsat: number } { + let decoded: DecodedInvoice; + try { + decoded = decodeBolt11(invoice); + } catch (error) { + throw new Error( + `Lightning service returned an unreadable invoice: ${ + error instanceof Error ? error.message : 'unknown error' + }`, + ); + } + + if (decoded.amountMsat === null) { + throw new Error( + 'Lightning service returned an invoice with no amount, which would let it charge any sum. Payment cancelled.', + ); + } + + if (decoded.amountMsat !== expectedMsat) { + throw new Error( + `Lightning service returned an invoice for ${Math.round(decoded.amountMsat / 1000)} sats, ` + + `but ${Math.round(expectedMsat / 1000)} sats was requested. Payment cancelled.`, + ); + } + + return { ...decoded, amountMsat: decoded.amountMsat }; +} + +/** + * Check an invoice's `h` field against the strings it is allowed to commit to. + * + * LUD-06 binds the invoice to the LNURL endpoint's `metadata`; NIP-57 replaces + * that with the zap request JSON. Providers implement one or the other, so any + * match is accepted. An invoice with no `h` field at all is accepted too — + * plenty of providers use a plain `d` description — because the amount check + * is what actually stops an overcharge; this is defence in depth against a + * substituted invoice on an otherwise honest response. + */ +export function invoiceCommitsTo(decoded: DecodedInvoice, candidates: string[]): boolean { + if (!decoded.descriptionHash) return true; + + const encoder = new TextEncoder(); + return candidates.some( + (candidate) => bytesToHex(sha256(encoder.encode(candidate))) === decoded.descriptionHash, + ); +} diff --git a/.agents/skills/nwc/files/lib/lnurlPay.ts b/.agents/skills/nwc/files/lib/lnurlPay.ts new file mode 100644 index 0000000..5da5302 --- /dev/null +++ b/.agents/skills/nwc/files/lib/lnurlPay.ts @@ -0,0 +1,136 @@ +/** + * LNURL-pay (LUD-06 / LUD-16) resolution for zaps. + * + * `nostr-tools`' `nip57.getZapEndpoint` returns only the `callback` URL and + * throws away everything else the endpoint said — including the `minSendable` + * / `maxSendable` bounds and the `metadata` string that LUD-06 uses to bind an + * invoice to the endpoint that issued it. Both are needed to check that the + * invoice we get back is the one we asked for, so resolution lives here + * instead. + * + * Everything in an LNURL-pay response is chosen by the payment *recipient*, so + * none of it is trusted: it is validated for shape, the transport is pinned to + * HTTPS, and the caller re-checks the resulting invoice against the amount the + * user actually approved (see `assertInvoiceAmount` in `@/lib/bolt11`). + */ +import { bech32 } from '@scure/base'; + +/** A validated LNURL-pay response. */ +export interface LnurlPayParams { + /** URL to request the invoice from. Always `https:`. */ + callback: string; + /** Smallest payable amount, in millisatoshis. */ + minSendable: number; + /** Largest payable amount, in millisatoshis. */ + maxSendable: number; + /** LUD-06 metadata string. The invoice's description hash may commit to it. */ + metadata: string; + /** Whether the endpoint accepts a NIP-57 zap request. */ + allowsNostr: boolean; + /** Pubkey the endpoint signs zap receipts with, when it supports zaps. */ + nostrPubkey?: string; +} + +/** Shape of the JSON an LNURL-pay endpoint returns. */ +interface LnurlPayResponse { + tag?: unknown; + callback?: unknown; + minSendable?: unknown; + maxSendable?: unknown; + metadata?: unknown; + allowsNostr?: unknown; + nostrPubkey?: unknown; + reason?: unknown; +} + +/** A lightning address (`name@domain`) or a bech32 `lnurl1…` string. */ +export interface LnurlSource { + lud06?: string; + lud16?: string; +} + +/** + * Turn a `lud06` / `lud16` pointer into the URL to fetch LNURL-pay params + * from. Returns `null` when neither is usable. + * + * HTTPS is required. A `lud06` may encode any URL at all, and plaintext HTTP + * would let anyone on the network path swap the invoice for one of their own — + * which is the entire attack this module exists to prevent. + */ +export function lnurlToUrl({ lud06, lud16 }: LnurlSource): string | null { + let raw: string; + + if (lud06?.trim()) { + const { words } = bech32.decode(lud06.trim().toLowerCase() as `${Lowercase}1${string}`, false); + raw = new TextDecoder().decode(bech32.fromWords(words)); + } else if (lud16?.trim()) { + const [name, domain] = lud16.trim().split('@'); + if (!name || !domain) return null; + raw = new URL(`/.well-known/lnurlp/${encodeURIComponent(name)}`, `https://${domain}`).toString(); + } else { + return null; + } + + const url = new URL(raw); + if (url.protocol !== 'https:') { + throw new Error('Lightning address must use HTTPS'); + } + return url.toString(); +} + +/** Coerce a JSON value to a non-negative integer, or `null` if it isn't one. */ +function toCount(value: unknown): number | null { + return typeof value === 'number' && Number.isFinite(value) && value >= 0 ? Math.floor(value) : null; +} + +/** + * Fetch and validate the LNURL-pay parameters for a payment pointer. + * + * Throws with a user-presentable message when the endpoint is unreachable or + * its response doesn't conform. + */ +export async function resolveLnurlPay(source: LnurlSource, signal?: AbortSignal): Promise { + const url = lnurlToUrl(source); + if (!url) { + throw new Error('No lightning address configured'); + } + + const res = await fetch(url, { signal }); + if (!res.ok) { + throw new Error(`Lightning service returned HTTP ${res.status}`); + } + + const body: LnurlPayResponse = await res.json(); + + if (typeof body.reason === 'string' && !body.callback) { + throw new Error(body.reason); + } + if (body.tag !== 'payRequest') { + throw new Error('Lightning address does not support payments'); + } + if (typeof body.callback !== 'string') { + throw new Error('Lightning service returned no payment callback'); + } + + // The callback is a second, separate URL the endpoint gets to choose. Pin it + // to HTTPS for the same reason as the LNURL itself. + const callback = new URL(body.callback); + if (callback.protocol !== 'https:') { + throw new Error('Lightning service requested an insecure payment callback'); + } + + const minSendable = toCount(body.minSendable); + const maxSendable = toCount(body.maxSendable); + if (minSendable === null || maxSendable === null || minSendable > maxSendable) { + throw new Error('Lightning service returned invalid payment limits'); + } + + return { + callback: callback.toString(), + minSendable, + maxSendable, + metadata: typeof body.metadata === 'string' ? body.metadata : '', + allowsNostr: body.allowsNostr === true, + nostrPubkey: typeof body.nostrPubkey === 'string' ? body.nostrPubkey : undefined, + }; +}