@getalby/lightning-tools 7.0.2 → 8.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/README.md +108 -28
  2. package/dist/cjs/402/l402.cjs +55 -0
  3. package/dist/cjs/402/l402.cjs.map +1 -0
  4. package/dist/cjs/402/mpp.cjs +179 -0
  5. package/dist/cjs/402/mpp.cjs.map +1 -0
  6. package/dist/cjs/402/x402.cjs +1313 -0
  7. package/dist/cjs/402/x402.cjs.map +1 -0
  8. package/dist/cjs/402.cjs +1585 -0
  9. package/dist/cjs/402.cjs.map +1 -0
  10. package/dist/cjs/bolt11.cjs +8 -0
  11. package/dist/cjs/bolt11.cjs.map +1 -1
  12. package/dist/cjs/index.cjs +301 -53
  13. package/dist/cjs/index.cjs.map +1 -1
  14. package/dist/cjs/lnurl.cjs +8 -0
  15. package/dist/cjs/lnurl.cjs.map +1 -1
  16. package/dist/esm/402/l402.js +53 -0
  17. package/dist/esm/402/l402.js.map +1 -0
  18. package/dist/esm/402/mpp.js +177 -0
  19. package/dist/esm/402/mpp.js.map +1 -0
  20. package/dist/esm/402/x402.js +1311 -0
  21. package/dist/esm/402/x402.js.map +1 -0
  22. package/dist/esm/402.js +1579 -0
  23. package/dist/esm/402.js.map +1 -0
  24. package/dist/esm/bolt11.js +8 -0
  25. package/dist/esm/bolt11.js.map +1 -1
  26. package/dist/esm/index.js +298 -50
  27. package/dist/esm/index.js.map +1 -1
  28. package/dist/esm/lnurl.js +8 -0
  29. package/dist/esm/lnurl.js.map +1 -1
  30. package/dist/lightning-tools.umd.js +2 -2
  31. package/dist/lightning-tools.umd.js.map +1 -1
  32. package/dist/types/402/l402.d.ts +13 -0
  33. package/dist/types/402/mpp.d.ts +26 -0
  34. package/dist/types/402/x402.d.ts +13 -0
  35. package/dist/types/402.d.ts +41 -0
  36. package/dist/types/bolt11.d.ts +4 -0
  37. package/dist/types/index.d.ts +38 -28
  38. package/dist/types/lnurl.d.ts +2 -0
  39. package/package.json +20 -5
  40. package/dist/cjs/l402.cjs +0 -93
  41. package/dist/cjs/l402.cjs.map +0 -1
  42. package/dist/esm/l402.js +0 -87
  43. package/dist/esm/l402.js.map +0 -1
  44. package/dist/types/l402.d.ts +0 -35
package/dist/esm/index.js CHANGED
@@ -832,8 +832,12 @@ const decodeInvoice = (paymentRequest) => {
832
832
  return null;
833
833
  const paymentHash = hashTag.value;
834
834
  let satoshi = 0;
835
+ let millisatoshi = 0;
836
+ let amountRaw = "0";
835
837
  const amountTag = decoded.sections.find((value) => value.name === "amount");
836
838
  if (amountTag?.name === "amount" && amountTag.value) {
839
+ amountRaw = amountTag.value;
840
+ millisatoshi = parseInt(amountTag.value);
837
841
  satoshi = parseInt(amountTag.value) / 1000; // millisats
838
842
  }
839
843
  const timestampTag = decoded.sections.find((value) => value.name === "timestamp");
@@ -852,6 +856,8 @@ const decodeInvoice = (paymentRequest) => {
852
856
  return {
853
857
  paymentHash,
854
858
  satoshi,
859
+ millisatoshi,
860
+ amountRaw,
855
861
  timestamp,
856
862
  expiry,
857
863
  description,
@@ -1181,6 +1187,8 @@ class Invoice {
1181
1187
  }
1182
1188
  this.paymentHash = decodedInvoice.paymentHash;
1183
1189
  this.satoshi = decodedInvoice.satoshi;
1190
+ this.millisatoshi = decodedInvoice.millisatoshi;
1191
+ this.amountRaw = decodedInvoice.amountRaw;
1184
1192
  this.timestamp = decodedInvoice.timestamp;
1185
1193
  this.expiry = decodedInvoice.expiry;
1186
1194
  this.createdDate = new Date(this.timestamp * 1000);
@@ -1657,24 +1665,18 @@ class LightningAddress {
1657
1665
  }
1658
1666
  }
1659
1667
 
1660
- class MemoryStorage {
1661
- constructor(initial) {
1662
- this.storage = initial || {};
1663
- }
1664
- getItem(key) {
1665
- return this.storage[key];
1666
- }
1667
- setItem(key, value) {
1668
- this.storage[key] = value;
1669
- }
1670
- }
1671
- class NoStorage {
1672
- constructor(initial) { }
1673
- getItem(key) {
1674
- return null;
1675
- }
1676
- setItem(key, value) { }
1668
+ function createGuardedWallet(wallet, maxAmountSats) {
1669
+ return {
1670
+ payInvoice: async (args) => {
1671
+ const invoice = new Invoice({ pr: args.invoice });
1672
+ if (invoice.satoshi > maxAmountSats) {
1673
+ throw new Error(`Invoice amount (${invoice.satoshi} sats) exceeds maxAmount (${maxAmountSats} sats)`);
1674
+ }
1675
+ return wallet.payInvoice(args);
1676
+ },
1677
+ };
1677
1678
  }
1679
+
1678
1680
  const parseL402 = (input) => {
1679
1681
  // Remove the L402 and LSAT identifiers
1680
1682
  const string = input.replace("L402", "").replace("LSAT", "").trim();
@@ -1691,55 +1693,301 @@ const parseL402 = (input) => {
1691
1693
  }
1692
1694
  return keyValuePairs;
1693
1695
  };
1694
- const makeAuthenticateHeader = (args) => {
1695
- const key = args.key || "L402";
1696
- return `${key} macaroon="${args.macaroon}", invoice="${args.invoice}"`;
1697
- };
1698
1696
 
1699
- const memoryStorage = new MemoryStorage();
1700
- const HEADER_KEY = "L402";
1701
- const fetchWithL402 = async (url, fetchArgs, options) => {
1702
- if (!options) {
1703
- options = {};
1697
+ const handleL402Payment = async (l402Header, url, fetchArgs, headers, wallet) => {
1698
+ const details = parseL402(l402Header);
1699
+ const token = details.token || details.macaroon;
1700
+ const invoice = details.invoice;
1701
+ if (!token) {
1702
+ throw new Error("L402: missing token/macaroon in WWW-Authenticate header");
1703
+ }
1704
+ if (!invoice) {
1705
+ throw new Error("L402: missing invoice in WWW-Authenticate header");
1704
1706
  }
1705
- const headerKey = options.headerKey || HEADER_KEY;
1707
+ const invResp = await wallet.payInvoice({ invoice });
1708
+ headers.set("Authorization", `L402 ${token}:${invResp.preimage}`);
1709
+ return fetch(url, fetchArgs);
1710
+ };
1711
+ const fetchWithL402 = async (url, fetchArgs, options) => {
1706
1712
  const wallet = options.wallet;
1707
1713
  if (!wallet) {
1708
1714
  throw new Error("wallet is missing");
1709
1715
  }
1710
- const store = options.store || memoryStorage;
1711
1716
  if (!fetchArgs) {
1712
1717
  fetchArgs = {};
1713
1718
  }
1714
1719
  fetchArgs.cache = "no-store";
1715
1720
  fetchArgs.mode = "cors";
1716
- if (!fetchArgs.headers) {
1717
- fetchArgs.headers = {};
1721
+ const headers = new Headers(fetchArgs.headers ?? undefined);
1722
+ fetchArgs.headers = headers;
1723
+ const initResp = await fetch(url, fetchArgs);
1724
+ const header = initResp.headers.get("www-authenticate");
1725
+ if (!header) {
1726
+ return initResp;
1727
+ }
1728
+ return handleL402Payment(header, url, fetchArgs, headers, wallet);
1729
+ };
1730
+
1731
+ const buildX402PaymentSignature = (scheme, network, invoice, requirements) => {
1732
+ const json = JSON.stringify({
1733
+ x402Version: 2,
1734
+ scheme,
1735
+ network,
1736
+ payload: { invoice },
1737
+ accepted: requirements,
1738
+ });
1739
+ // btoa only handles latin1; encode via UTF-8 to be safe
1740
+ return btoa(unescape(encodeURIComponent(json)));
1741
+ };
1742
+
1743
+ const handleX402Payment = async (x402Header, url, fetchArgs, headers, wallet) => {
1744
+ let parsed;
1745
+ try {
1746
+ parsed = JSON.parse(decodeURIComponent(escape(atob(x402Header))));
1718
1747
  }
1719
- const cachedL402Data = store.getItem(url);
1720
- if (cachedL402Data) {
1721
- const data = JSON.parse(cachedL402Data);
1722
- fetchArgs.headers["Authorization"] =
1723
- `${headerKey} ${data.token}:${data.preimage}`;
1724
- return await fetch(url, fetchArgs);
1748
+ catch (_) {
1749
+ throw new Error("x402: invalid PAYMENT-REQUIRED header (not valid base64-encoded JSON)");
1750
+ }
1751
+ if (!Array.isArray(parsed.accepts) || parsed.accepts.length === 0) {
1752
+ throw new Error("x402: PAYMENT-REQUIRED header contains no payment options");
1753
+ }
1754
+ const requirements = parsed.accepts.find((e) => {
1755
+ return e.extra?.paymentMethod === "lightning";
1756
+ });
1757
+ if (!requirements) {
1758
+ throw new Error("x402: unsupported x402 network, only Bitcoin lightning network is supported.");
1759
+ }
1760
+ if (!requirements.extra?.invoice) {
1761
+ throw new Error("x402: payment requirements missing lightning invoice");
1762
+ }
1763
+ const invoice = new Invoice({ pr: requirements.extra.invoice });
1764
+ if (invoice.amountRaw != requirements.amount) {
1765
+ throw new Error(`Invalid invoice amount: ${invoice.amountRaw}. expected ${requirements.amount}`);
1766
+ }
1767
+ await wallet.payInvoice({ invoice: invoice.paymentRequest });
1768
+ headers.set("payment-signature", buildX402PaymentSignature(requirements.scheme, requirements.network, invoice.paymentRequest, requirements));
1769
+ return fetch(url, fetchArgs);
1770
+ };
1771
+ const fetchWithX402 = async (url, fetchArgs, options) => {
1772
+ const wallet = options.wallet;
1773
+ if (!fetchArgs) {
1774
+ fetchArgs = {};
1725
1775
  }
1726
- fetchArgs.headers["Accept-Authenticate"] = headerKey;
1776
+ fetchArgs.cache = "no-store";
1777
+ fetchArgs.mode = "cors";
1778
+ const headers = new Headers(fetchArgs.headers ?? undefined);
1779
+ fetchArgs.headers = headers;
1727
1780
  const initResp = await fetch(url, fetchArgs);
1728
- const header = initResp.headers.get("www-authenticate");
1781
+ const header = initResp.headers.get("PAYMENT-REQUIRED");
1729
1782
  if (!header) {
1730
1783
  return initResp;
1731
1784
  }
1732
- const details = parseL402(header);
1733
- const token = details.token || details.macaroon;
1734
- const inv = details.invoice;
1735
- const invResp = await wallet.sendPayment(inv);
1736
- store.setItem(url, JSON.stringify({
1737
- token: token,
1738
- preimage: invResp.preimage,
1739
- }));
1740
- fetchArgs.headers["Authorization"] =
1741
- `${headerKey} ${token}:${invResp.preimage}`;
1742
- return await fetch(url, fetchArgs);
1785
+ return handleX402Payment(header, url, fetchArgs, headers, wallet);
1786
+ };
1787
+
1788
+ /**
1789
+ * Parse a `WWW-Authenticate: Payment …` header produced by a
1790
+ * draft-lightning-charge-00 server. Expected format:
1791
+ *
1792
+ * Payment id="<id>", realm="<realm>", method="lightning",
1793
+ * intent="charge", request="<base64url>" [, expires="<rfc3339>"]
1794
+ *
1795
+ * Returns null when the header is not a Payment lightning/charge challenge.
1796
+ */
1797
+ const parseMppChallenge = (header) => {
1798
+ if (!header.trimStart().toLowerCase().startsWith("payment")) {
1799
+ return null;
1800
+ }
1801
+ const rest = header
1802
+ .slice(header.toLowerCase().indexOf("payment") + "payment".length)
1803
+ .trim();
1804
+ const result = {};
1805
+ const regex = /(\w+)=("([^"]*)"|'([^']*)'|([^,\s]*))/g;
1806
+ let match;
1807
+ while ((match = regex.exec(rest)) !== null) {
1808
+ result[match[1]] = match[3] ?? match[4] ?? match[5] ?? "";
1809
+ }
1810
+ if (result.method !== "lightning" ||
1811
+ result.intent !== "charge" ||
1812
+ !result.id ||
1813
+ !result.realm ||
1814
+ !result.request) {
1815
+ return null;
1816
+ }
1817
+ return {
1818
+ id: result.id,
1819
+ realm: result.realm,
1820
+ method: result.method,
1821
+ intent: result.intent,
1822
+ request: result.request,
1823
+ ...(result.expires ? { expires: result.expires } : {}),
1824
+ };
1825
+ };
1826
+ /** Decode a base64url string (no padding required) to a UTF-8 string. */
1827
+ const decodeBase64url = (input) => {
1828
+ const base64 = input.replace(/-/g, "+").replace(/_/g, "/");
1829
+ const binary = atob(base64);
1830
+ const bytes = new Uint8Array(binary.length);
1831
+ for (let i = 0; i < binary.length; i++) {
1832
+ bytes[i] = binary.charCodeAt(i);
1833
+ }
1834
+ return new TextDecoder("utf-8").decode(bytes);
1835
+ };
1836
+ /** Encode a UTF-8 string to base64url without padding. */
1837
+ const encodeBase64url = (input) => {
1838
+ const bytes = new TextEncoder().encode(input);
1839
+ let binary = "";
1840
+ for (let i = 0; i < bytes.length; i++) {
1841
+ binary += String.fromCharCode(bytes[i]);
1842
+ }
1843
+ return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, "");
1844
+ };
1845
+ /**
1846
+ * JSON Canonicalization Scheme (RFC 8785).
1847
+ * Produces compact JSON with object keys sorted lexicographically.
1848
+ */
1849
+ const jcs = (value) => {
1850
+ if (value === null || typeof value !== "object") {
1851
+ return JSON.stringify(value);
1852
+ }
1853
+ if (Array.isArray(value)) {
1854
+ return "[" + value.map(jcs).join(",") + "]";
1855
+ }
1856
+ const keys = Object.keys(value).sort();
1857
+ return ("{" +
1858
+ keys
1859
+ .map((k) => JSON.stringify(k) + ":" + jcs(value[k]))
1860
+ .join(",") +
1861
+ "}");
1862
+ };
1863
+ /**
1864
+ * Build the base64url-encoded credential token for the `Authorization` header.
1865
+ *
1866
+ * Per the spec the credential is a JCS-serialised JSON object that echoes all
1867
+ * challenge auth-params (id, realm, method, intent, request, expires) and
1868
+ * carries the HTLC preimage that proves payment:
1869
+ *
1870
+ * {
1871
+ * "challenge": { "id": "…", "intent": "charge",
1872
+ * "method": "lightning", "realm": "…", "request": "…" },
1873
+ * "payload": { "preimage": "<64-char lowercase hex>" }
1874
+ * }
1875
+ *
1876
+ * Keys are sorted lexicographically at every level per JCS.
1877
+ */
1878
+ const buildMppCredential = (challenge, preimage, source) => {
1879
+ const challengeEcho = {
1880
+ id: challenge.id,
1881
+ intent: challenge.intent,
1882
+ method: challenge.method,
1883
+ realm: challenge.realm,
1884
+ request: challenge.request,
1885
+ };
1886
+ if (challenge.expires) {
1887
+ challengeEcho.expires = challenge.expires;
1888
+ }
1889
+ const credential = {
1890
+ challenge: challengeEcho,
1891
+ payload: { preimage },
1892
+ };
1893
+ return encodeBase64url(jcs(credential));
1894
+ };
1895
+
1896
+ /**
1897
+ * Handle a `WWW-Authenticate: Payment …` challenge produced by a
1898
+ * draft-lightning-charge-00 server.
1899
+ *
1900
+ * Flow:
1901
+ * 1. Parse the challenge from the header.
1902
+ * 2. Decode the `request` auth-param to find the BOLT11 invoice.
1903
+ * 3. Pay the invoice via the wallet; receive the HTLC preimage.
1904
+ * 4. Build the `Authorization: Payment <credential>` header.
1905
+ * 5. Retry the original request with the credential.
1906
+ */
1907
+ const handleMppChargePayment = async (wwwAuthHeader, url, fetchArgs, headers, wallet) => {
1908
+ const challenge = parseMppChallenge(wwwAuthHeader);
1909
+ if (!challenge) {
1910
+ throw new Error("mpp: invalid or unsupported WWW-Authenticate challenge (expected Payment method=lightning intent=charge)");
1911
+ }
1912
+ let request;
1913
+ try {
1914
+ request = JSON.parse(decodeBase64url(challenge.request));
1915
+ }
1916
+ catch (_) {
1917
+ throw new Error("mpp: invalid request auth-param (not valid base64url-encoded JSON)");
1918
+ }
1919
+ const invoice = request.methodDetails?.invoice;
1920
+ if (!invoice) {
1921
+ throw new Error("mpp: missing invoice in charge request");
1922
+ }
1923
+ const invResp = await wallet.payInvoice({ invoice });
1924
+ // Per spec: Authorization: Payment <base64url-token> (single token, no wrapper)
1925
+ const credential = buildMppCredential(challenge, invResp.preimage);
1926
+ headers.set("Authorization", `Payment ${credential}`);
1927
+ return fetch(url, fetchArgs);
1928
+ };
1929
+ /**
1930
+ * Fetch a resource protected by the draft-lightning-charge-00 payment
1931
+ * authentication protocol.
1932
+ *
1933
+ * On a `402 Payment Required` response that carries a
1934
+ * `WWW-Authenticate: Payment method="lightning" intent="charge" …` header
1935
+ * the function pays the embedded BOLT11 invoice and retries with the
1936
+ * resulting preimage as the credential.
1937
+ *
1938
+ * Note: lightning-charge uses consume-once challenge semantics – each
1939
+ * challenge embeds a fresh invoice, so paid credentials cannot be reused.
1940
+ * The `store` option is accepted for API consistency but is not used.
1941
+ */
1942
+ const fetchWithMpp = async (url, fetchArgs, options) => {
1943
+ const wallet = options.wallet;
1944
+ if (!wallet) {
1945
+ throw new Error("wallet is missing");
1946
+ }
1947
+ if (!fetchArgs) {
1948
+ fetchArgs = {};
1949
+ }
1950
+ fetchArgs.cache = "no-store";
1951
+ fetchArgs.mode = "cors";
1952
+ const headers = new Headers(fetchArgs.headers ?? undefined);
1953
+ fetchArgs.headers = headers;
1954
+ const initResp = await fetch(url, fetchArgs);
1955
+ const wwwAuthHeader = initResp.headers.get("www-authenticate");
1956
+ if (!wwwAuthHeader ||
1957
+ !wwwAuthHeader.trimStart().toLowerCase().startsWith("payment")) {
1958
+ return initResp;
1959
+ }
1960
+ return handleMppChargePayment(wwwAuthHeader, url, fetchArgs, headers, wallet);
1961
+ };
1962
+
1963
+ const fetch402 = async (url, fetchArgs, options) => {
1964
+ const wallet = options.maxAmount
1965
+ ? createGuardedWallet(options.wallet, options.maxAmount)
1966
+ : options.wallet;
1967
+ if (!fetchArgs) {
1968
+ fetchArgs = {};
1969
+ }
1970
+ fetchArgs.cache = "no-store";
1971
+ fetchArgs.mode = "cors";
1972
+ const headers = new Headers(fetchArgs.headers ?? undefined);
1973
+ fetchArgs.headers = headers;
1974
+ const initResp = await fetch(url, fetchArgs);
1975
+ const wwwAuthHeader = initResp.headers.get("www-authenticate");
1976
+ if (wwwAuthHeader) {
1977
+ const trimmed = wwwAuthHeader.trimStart().toLowerCase();
1978
+ if (trimmed.startsWith("payment")) {
1979
+ return handleMppChargePayment(wwwAuthHeader, url, fetchArgs, headers, wallet);
1980
+ }
1981
+ if (trimmed.startsWith("l402") || trimmed.startsWith("lsat")) {
1982
+ return handleL402Payment(wwwAuthHeader, url, fetchArgs, headers, wallet);
1983
+ }
1984
+ throw new Error(`fetch402: unsupported WWW-Authenticate scheme: ${wwwAuthHeader}`);
1985
+ }
1986
+ const x402Header = initResp.headers.get("PAYMENT-REQUIRED");
1987
+ if (x402Header) {
1988
+ return handleX402Payment(x402Header, url, fetchArgs, headers, wallet);
1989
+ }
1990
+ return initResp;
1743
1991
  };
1744
1992
 
1745
1993
  const numSatsInBtc = 100000000;
@@ -1791,5 +2039,5 @@ const getFormattedFiatValue = async ({ satoshi, currency, locale, }) => {
1791
2039
  });
1792
2040
  };
1793
2041
 
1794
- export { DEFAULT_PROXY, Invoice, LN_ADDRESS_REGEX, LightningAddress, MemoryStorage, NoStorage, decodeInvoice, fetchWithL402, fromHexString, generateZapEvent, getEventHash, getFiatBtcRate, getFiatCurrencies, getFiatValue, getFormattedFiatValue, getSatoshiValue, isUrl, isValidAmount, makeAuthenticateHeader, parseKeysendResponse, parseL402, parseLnUrlPayResponse, parseNostrResponse, sendBoostagram, serializeEvent, validateEvent };
2042
+ export { DEFAULT_PROXY, Invoice, LN_ADDRESS_REGEX, LightningAddress, createGuardedWallet, decodeInvoice, fetch402, fetchWithL402, fetchWithMpp, fetchWithX402, fromHexString, generateZapEvent, getEventHash, getFiatBtcRate, getFiatCurrencies, getFiatValue, getFormattedFiatValue, getSatoshiValue, isUrl, isValidAmount, parseKeysendResponse, parseLnUrlPayResponse, parseNostrResponse, sendBoostagram, serializeEvent, validateEvent };
1795
2043
  //# sourceMappingURL=index.js.map