diff --git a/package-lock.json b/package-lock.json index 2e99f28c..eb037af5 100644 --- a/package-lock.json +++ b/package-lock.json @@ -5052,6 +5052,7 @@ "cpu": [ "arm" ], + "dev": true, "license": "MIT", "optional": true, "os": [ @@ -5065,6 +5066,7 @@ "cpu": [ "arm64" ], + "dev": true, "license": "MIT", "optional": true, "os": [ @@ -5078,6 +5080,7 @@ "cpu": [ "arm64" ], + "dev": true, "license": "MIT", "optional": true, "os": [ @@ -5091,6 +5094,7 @@ "cpu": [ "x64" ], + "dev": true, "license": "MIT", "optional": true, "os": [ @@ -5104,6 +5108,7 @@ "cpu": [ "arm64" ], + "dev": true, "license": "MIT", "optional": true, "os": [ @@ -5117,6 +5122,7 @@ "cpu": [ "x64" ], + "dev": true, "license": "MIT", "optional": true, "os": [ @@ -5130,6 +5136,7 @@ "cpu": [ "arm" ], + "dev": true, "license": "MIT", "optional": true, "os": [ @@ -5143,6 +5150,7 @@ "cpu": [ "arm" ], + "dev": true, "license": "MIT", "optional": true, "os": [ @@ -5156,6 +5164,7 @@ "cpu": [ "arm64" ], + "dev": true, "license": "MIT", "optional": true, "os": [ @@ -5169,6 +5178,7 @@ "cpu": [ "arm64" ], + "dev": true, "license": "MIT", "optional": true, "os": [ @@ -5182,6 +5192,7 @@ "cpu": [ "loong64" ], + "dev": true, "license": "MIT", "optional": true, "os": [ @@ -5195,6 +5206,7 @@ "cpu": [ "loong64" ], + "dev": true, "license": "MIT", "optional": true, "os": [ @@ -5208,6 +5220,7 @@ "cpu": [ "ppc64" ], + "dev": true, "license": "MIT", "optional": true, "os": [ @@ -5221,6 +5234,7 @@ "cpu": [ "ppc64" ], + "dev": true, "license": "MIT", "optional": true, "os": [ @@ -5234,6 +5248,7 @@ "cpu": [ "riscv64" ], + "dev": true, "license": "MIT", "optional": true, "os": [ @@ -5247,6 +5262,7 @@ "cpu": [ "riscv64" ], + "dev": true, "license": "MIT", "optional": true, "os": [ @@ -5260,6 +5276,7 @@ "cpu": [ "s390x" ], + "dev": true, "license": "MIT", "optional": true, "os": [ @@ -5273,6 +5290,7 @@ "cpu": [ "x64" ], + "dev": true, "license": "MIT", "optional": true, "os": [ @@ -5286,6 +5304,7 @@ "cpu": [ "x64" ], + "dev": true, "license": "MIT", "optional": true, "os": [ @@ -5299,6 +5318,7 @@ "cpu": [ "x64" ], + "dev": true, "license": "MIT", "optional": true, "os": [ @@ -5312,6 +5332,7 @@ "cpu": [ "arm64" ], + "dev": true, "license": "MIT", "optional": true, "os": [ @@ -5325,6 +5346,7 @@ "cpu": [ "arm64" ], + "dev": true, "license": "MIT", "optional": true, "os": [ @@ -5338,6 +5360,7 @@ "cpu": [ "ia32" ], + "dev": true, "license": "MIT", "optional": true, "os": [ @@ -5351,6 +5374,7 @@ "cpu": [ "x64" ], + "dev": true, "license": "MIT", "optional": true, "os": [ @@ -5364,6 +5388,7 @@ "cpu": [ "x64" ], + "dev": true, "license": "MIT", "optional": true, "os": [ diff --git a/src/hooks/useNWC.ts b/src/hooks/useNWC.ts index 43b14c71..c80da04d 100644 --- a/src/hooks/useNWC.ts +++ b/src/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/src/hooks/useZaps.ts b/src/hooks/useZaps.ts index 138ae53b..5c91962c 100644 --- a/src/hooks/useZaps.ts +++ b/src/hooks/useZaps.ts @@ -11,6 +11,8 @@ import type { WebLNProvider } from 'webln'; 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,19 @@ 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 in-repo instead of via + // nip57.getZapEndpoint, which returns only the callback URL and discards + // the minSendable/maxSendable bounds and metadata needed to validate the + // invoice we get back. + 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); @@ -194,6 +203,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 writeRelays = config.relayMetadata.relays .filter(r => r.write) .map(r => r.url); @@ -209,9 +232,14 @@ 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))}`); + 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) { @@ -223,13 +251,31 @@ 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. 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.'); + } + + // Report what the invoice actually charges rather than what was asked + // for, so a success screen can never understate a spend. + const paidSats = Math.round(decodedInvoice.amountMsat / 1000); + // 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); @@ -237,7 +283,7 @@ export function useZaps( toast({ title: 'Zap successful!', - description: `You sent ${amount} sats via NWC to the author.`, + description: `You sent ${paidSats} sats via NWC to the author.`, }); // Invalidate zap queries to refresh counts @@ -269,7 +315,7 @@ export function useZaps( toast({ title: 'Zap successful!', - description: `You sent ${amount} sats to the author.`, + description: `You sent ${paidSats} sats to the author.`, }); // Invalidate zap queries to refresh counts diff --git a/src/lib/bolt11.test.ts b/src/lib/bolt11.test.ts new file mode 100644 index 00000000..e2fa2d07 --- /dev/null +++ b/src/lib/bolt11.test.ts @@ -0,0 +1,115 @@ +import { describe, it, expect } from 'vitest'; + +import { assertInvoiceAmount, decodeBolt11, invoiceCommitsTo } from './bolt11'; + +// BOLT 11 specification test vectors. +/** 2500u = 250,000,000 msat, with a plain-text description. */ +const INVOICE_2500U = + 'lnbc2500u1pvjluezpp5qqqsyqcyq5rqwzqfqqqsyqcyq5rqwzqfqqqsyqcyq5rqwzqfqypq' + + 'dq5xysxxatsyp3k7enxv4jsxqzpuaztrnwngzn3kdzw5hydlzf03qdgm2hdq27cqv3agm2aw' + + 'hz5se903vruatfhq77w3ls4evs3ch9zw97j25emudupq63nyw24cg27h2rspfj9srp'; + +/** No amount in the human-readable part — the payer or payee picks the sum. */ +const INVOICE_AMOUNTLESS = + 'lnbc1pvjluezpp5qqqsyqcyq5rqwzqfqqqsyqcyq5rqwzqfqqqsyqcyq5rqwzqfqypqdpl2p' + + 'kx2ctnv5sxxmmwwd5kgetjypeh2ursdae8g6twvus8g6rfwvs8qun0dfjkxaq8rkx3yf5tcs' + + 'yz3d73gafnh3cax9rn449d9p5uxz9ezhhypd0elx87sjle52x86fux2ypatgddc6k63n7erq' + + 'z25le42c4u4ecky03ylcqca784w'; + +/** 20m = 2,000,000,000 msat, carrying a description hash rather than text. */ +const INVOICE_20M_WITH_HASH = + 'lnbc20m1pvjluezpp5qqqsyqcyq5rqwzqfqqqsyqcyq5rqwzqfqqqsyqcyq5rqwzqfqypqhp' + + '58yjmdan79s6qqdhdzgynm4zwqd5d7xmw5fk98klysy043l2ahrqscc6gd6ql3jrc5yzme8v' + + '4ntcewwz5cnw92tz0pc8qcuufvq7khhr8wpald05e92xw006sq94mg8v2ndf4sefvf9sygks' + + 'hp5zfem29trqq2yxxz7'; + +/** The string whose sha256 is the description hash in {@link INVOICE_20M_WITH_HASH}. */ +const HASHED_DESCRIPTION = + 'One piece of chocolate cake, one icecream cone, one pickle, one slice of swiss cheese, ' + + 'one slice of salami, one lollypop, one piece of cherry pie, one sausage, one cupcake, ' + + 'and one slice of watermelon'; + +describe('decodeBolt11', () => { + it('decodes the amount from the human-readable part', () => { + expect(decodeBolt11(INVOICE_2500U).amountMsat).toBe(250_000_000); + expect(decodeBolt11(INVOICE_20M_WITH_HASH).amountMsat).toBe(2_000_000_000); + }); + + it('reports an amountless invoice as null rather than zero', () => { + expect(decodeBolt11(INVOICE_AMOUNTLESS).amountMsat).toBeNull(); + }); + + it('reads the network, timestamp and payment hash', () => { + const decoded = decodeBolt11(INVOICE_2500U); + expect(decoded.network).toBe('bc'); + expect(decoded.timestamp).toBe(1496314658); + expect(decoded.paymentHash).toBe( + '0001020304050607080900010203040506070809000102030405060708090102', + ); + }); + + it('reads the plain-text description', () => { + expect(decodeBolt11(INVOICE_2500U).description).toBe('1 cup coffee'); + }); + + it('reads the description hash', () => { + expect(decodeBolt11(INVOICE_20M_WITH_HASH).descriptionHash).toHaveLength(64); + }); + + it('tolerates a lightning: URI prefix, whitespace and uppercase', () => { + expect(decodeBolt11(` LIGHTNING:${INVOICE_2500U.toUpperCase()} `).amountMsat).toBe(250_000_000); + }); + + it('rejects a string that is not an invoice', () => { + expect(() => decodeBolt11('not-an-invoice')).toThrow(); + expect(() => decodeBolt11('')).toThrow(); + }); + + it('rejects an invoice whose checksum has been tampered with', () => { + // Flip the last character of the bech32 checksum. + const tampered = INVOICE_2500U.slice(0, -1) + (INVOICE_2500U.endsWith('p') ? 'q' : 'p'); + expect(() => decodeBolt11(tampered)).toThrow(); + }); +}); + +describe('assertInvoiceAmount', () => { + it('accepts an invoice for exactly the requested amount', () => { + expect(assertInvoiceAmount(INVOICE_2500U, 250_000_000).amountMsat).toBe(250_000_000); + }); + + it('rejects an invoice for more than was requested', () => { + // The reported attack: the user approves 776 sats and the recipient's own + // LNURL server answers with an invoice for 5,000,000 sats. + expect(() => assertInvoiceAmount(INVOICE_2500U, 776_000)).toThrow(/250000 sats.*776 sats/); + }); + + it('rejects an invoice for less than was requested', () => { + expect(() => assertInvoiceAmount(INVOICE_2500U, 250_000_001)).toThrow(); + }); + + it('rejects an amountless invoice, which would let the wallet pick the sum', () => { + expect(() => assertInvoiceAmount(INVOICE_AMOUNTLESS, 250_000_000)).toThrow(/no amount/); + }); + + it('rejects an unparseable invoice rather than passing it through', () => { + expect(() => assertInvoiceAmount('lnbc-garbage', 1000)).toThrow(/unreadable/); + }); +}); + +describe('invoiceCommitsTo', () => { + it('accepts an invoice whose description hash matches a candidate', () => { + const decoded = decodeBolt11(INVOICE_20M_WITH_HASH); + expect(invoiceCommitsTo(decoded, ['something else', HASHED_DESCRIPTION])).toBe(true); + }); + + it('rejects an invoice bound to a different request', () => { + const decoded = decodeBolt11(INVOICE_20M_WITH_HASH); + expect(invoiceCommitsTo(decoded, ['a different zap request'])).toBe(false); + }); + + it('accepts an invoice with no description hash at all', () => { + // Many providers use a plain `d` description; the amount check is what + // stops an overcharge, this is only defence in depth. + expect(invoiceCommitsTo(decodeBolt11(INVOICE_2500U), ['anything'])).toBe(true); + }); +}); diff --git a/src/lib/bolt11.ts b/src/lib/bolt11.ts new file mode 100644 index 00000000..d71c82bd --- /dev/null +++ b/src/lib/bolt11.ts @@ -0,0 +1,258 @@ +/** + * 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. `nip57.getSatoshisAmountFromBolt11` 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, utf8ToBytes } 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; + + // Use noble's own `utf8ToBytes` rather than `TextEncoder`: under jsdom the + // latter returns a Uint8Array from a different realm, which `sha256` rejects. + return candidates.some( + (candidate) => bytesToHex(sha256(utf8ToBytes(candidate))) === decoded.descriptionHash, + ); +} diff --git a/src/lib/lnurlPay.ts b/src/lib/lnurlPay.ts new file mode 100644 index 00000000..5da53020 --- /dev/null +++ b/src/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, + }; +}