xytara 3.1.13 → 3.1.14

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 (55) hide show
  1. package/.env.example +8 -1
  2. package/BSV_TERANODE_PLATFORM_DISCONTINUITY_RUNBOOK.md +126 -126
  3. package/RELEASE_NOTES.md +6 -4
  4. package/lib/a2a_rpc.js +280 -280
  5. package/lib/account_auth.js +585 -585
  6. package/lib/agent_identity.js +162 -162
  7. package/lib/bolt_adapter.js +187 -187
  8. package/lib/bolt_payment_front.js +224 -224
  9. package/lib/checkout_processor_adapter.js +217 -217
  10. package/lib/command_flow.js +722 -722
  11. package/lib/commerce_artifacts.js +591 -591
  12. package/lib/commerce_bridge.js +274 -274
  13. package/lib/commerce_cases.js +399 -399
  14. package/lib/commerce_client.js +7694 -7694
  15. package/lib/commerce_quotes.js +29 -0
  16. package/lib/commerce_runtime.js +322 -322
  17. package/lib/execution_dedupe.js +86 -86
  18. package/lib/external_credit_bridge.js +142 -142
  19. package/lib/http_transport.js +81 -81
  20. package/lib/l402_adapter.js +241 -241
  21. package/lib/l402_payment_front.js +265 -265
  22. package/lib/mpp_adapter.js +237 -237
  23. package/lib/payment_config.js +253 -253
  24. package/lib/payment_verification.js +357 -357
  25. package/lib/provider_payout_execution.js +155 -155
  26. package/lib/provider_registry.js +842 -842
  27. package/lib/rate_limiter.js +81 -81
  28. package/lib/runtime_state_store.js +491 -369
  29. package/lib/settlement_bsv_live.js +600 -600
  30. package/lib/settlement_bsv_teranode.js +117 -117
  31. package/lib/stripe_mpp_payment_front.js +258 -258
  32. package/lib/x402_facilitator.js +191 -191
  33. package/package.json +5 -3
  34. package/scripts/state_backup_offsite.js +196 -0
  35. package/scripts/verify_a2a_rpc.js +105 -105
  36. package/scripts/verify_agent_identity.js +153 -153
  37. package/scripts/verify_all.js +1 -1
  38. package/scripts/verify_bolt_adapter.js +128 -128
  39. package/scripts/verify_cdp_facilitator.js +110 -110
  40. package/scripts/verify_checkout_processor.js +109 -109
  41. package/scripts/verify_commerce_bridge.js +177 -177
  42. package/scripts/verify_execution_dedupe.js +189 -189
  43. package/scripts/verify_execution_surfacing.js +76 -76
  44. package/scripts/verify_final_activation.js +191 -191
  45. package/scripts/verify_l402_adapter.js +86 -86
  46. package/scripts/verify_mpp_adapter.js +128 -128
  47. package/scripts/verify_production_readiness.js +268 -268
  48. package/scripts/verify_rate_limiter.js +52 -52
  49. package/scripts/verify_refund_credit.js +106 -106
  50. package/scripts/verify_release_candidate.js +81 -81
  51. package/scripts/verify_runtime_state_guard.js +117 -0
  52. package/scripts/verify_service.js +15421 -15421
  53. package/scripts/verify_verify_execute_settle.js +208 -208
  54. package/scripts/verify_x402_facilitator.js +286 -286
  55. package/server.js +11976 -11974
@@ -1,241 +1,241 @@
1
- "use strict";
2
-
3
- // Provider-agnostic Lightning (L402) adapter.
4
- //
5
- // Makes the L402 lane a REAL Lightning rail: it creates bolt11 invoices through a
6
- // configured Lightning provider and verifies payment CRYPTOGRAPHICALLY
7
- // (preimage -> sha256 -> payment_hash). The macaroon is an HMAC-signed token that
8
- // binds the invoice's payment_hash; the runtime issues and verifies it, and the
9
- // client treats it as opaque and echoes it back with the preimage (standard L402
10
- // flow). Preimage verification needs no node — only invoice creation does.
11
- //
12
- // Engages only when env configures a provider; otherwise every function reports
13
- // not-configured and the caller preserves the existing bespoke token behavior.
14
- // Dependency-free (node http/https + crypto).
15
- //
16
- // Env:
17
- // XYTARA_L402_PROVIDER = "lnbits" | "generic" (unset => not configured)
18
- // XYTARA_L402_ROOT_KEY (HMAC key for macaroons)
19
- // XYTARA_L402_PRICE_SATS (default invoice amount, sats)
20
- // XYTARA_L402_MACAROON_TTL_SECONDS (default 900)
21
- // lnbits: XYTARA_LNBITS_URL, XYTARA_LNBITS_INVOICE_KEY
22
- // generic: XYTARA_L402_INVOICE_URL, XYTARA_L402_INVOICE_AUTH_HEADER ("Header: value")
23
-
24
- // SECURITY / LIMITATIONS (harden before enabling in production):
25
- // - FLAT-RATE lane: each call is priced at a flat XYTARA_L402_PRICE_SATS, not
26
- // the per-request USD quote amount (sats cannot be derived from USD without a
27
- // rate oracle). Use for flat-priced calls.
28
- // - DoS surface: each UNPAID request triggers a live invoice creation against
29
- // the configured Lightning provider. Deploy the L402 routes behind rate
30
- // limiting / a cheap pre-challenge gate so an unauthenticated flood cannot
31
- // amplify into unbounded outbound invoice creation.
32
-
33
- const https = require("https");
34
- const http = require("http");
35
- const crypto = require("crypto");
36
- const { URL } = require("url");
37
-
38
- function env(name) {
39
- const v = process.env[name];
40
- return typeof v === "string" && v.trim() ? v.trim() : "";
41
- }
42
-
43
- function loadL402Config() {
44
- const provider = env("XYTARA_L402_PROVIDER").toLowerCase();
45
- if (provider !== "lnbits" && provider !== "generic") return { provider: null };
46
- return {
47
- provider,
48
- rootKey: env("XYTARA_L402_ROOT_KEY") || env("XYTARA_L402_SHARED_SECRET"),
49
- priceSats: Number(env("XYTARA_L402_PRICE_SATS") || "") || null,
50
- macaroonTtlSeconds: Math.max(60, Number(env("XYTARA_L402_MACAROON_TTL_SECONDS") || 900) || 900),
51
- lnbitsUrl: env("XYTARA_LNBITS_URL"),
52
- lnbitsInvoiceKey: env("XYTARA_LNBITS_INVOICE_KEY"),
53
- genericInvoiceUrl: env("XYTARA_L402_INVOICE_URL"),
54
- genericAuthHeader: env("XYTARA_L402_INVOICE_AUTH_HEADER")
55
- };
56
- }
57
-
58
- function isConfigured(config) {
59
- return Boolean(config && config.provider);
60
- }
61
-
62
- function httpPostJson(urlStr, headers, bodyObj, timeoutMs) {
63
- return new Promise((resolve, reject) => {
64
- let u;
65
- try {
66
- u = new URL(urlStr);
67
- } catch (e) {
68
- return reject(new Error("invalid_url"));
69
- }
70
- const body = JSON.stringify(bodyObj || {});
71
- const lib = u.protocol === "http:" ? http : https;
72
- const req = lib.request(
73
- {
74
- method: "POST",
75
- hostname: u.hostname,
76
- port: u.port || (u.protocol === "http:" ? 80 : 443),
77
- path: u.pathname + u.search,
78
- headers: { "Content-Type": "application/json", "Content-Length": Buffer.byteLength(body), ...(headers || {}) }
79
- },
80
- (res) => {
81
- let d = "";
82
- res.on("data", (c) => (d += c));
83
- res.on("end", () => {
84
- let j = null;
85
- try {
86
- j = d ? JSON.parse(d) : null;
87
- } catch (_) {
88
- j = null;
89
- }
90
- resolve({ status: res.statusCode, json: j, raw: d });
91
- });
92
- }
93
- );
94
- req.on("error", reject);
95
- req.setTimeout(timeoutMs || 15000, () => req.destroy(new Error("l402_invoice_timeout")));
96
- req.write(body);
97
- req.end();
98
- });
99
- }
100
-
101
- // Create a real bolt11 invoice. Returns { ok, payment_request, payment_hash } | { ok:false, reason, detail? }.
102
- async function createLightningInvoice(config, options) {
103
- if (!isConfigured(config)) return { ok: false, reason: "l402_provider_not_configured" };
104
- const sats = Number((options && options.amountSats) || config.priceSats);
105
- if (!Number.isFinite(sats) || sats <= 0) return { ok: false, reason: "invalid_amount_sats" };
106
- const memo = (options && options.memo) || "naxytra L402";
107
- if (config.provider === "lnbits") {
108
- if (!config.lnbitsUrl || !config.lnbitsInvoiceKey) return { ok: false, reason: "lnbits_not_configured" };
109
- let res;
110
- try {
111
- res = await httpPostJson(
112
- config.lnbitsUrl.replace(/\/$/, "") + "/api/v1/payments",
113
- { "X-Api-Key": config.lnbitsInvoiceKey },
114
- { out: false, amount: Math.round(sats), memo },
115
- 15000
116
- );
117
- } catch (e) {
118
- return { ok: false, reason: "lnbits_unreachable", detail: e && e.message ? e.message : "request_error" };
119
- }
120
- if (!res.json || res.status >= 400) {
121
- return { ok: false, reason: "lnbits_invoice_failed", detail: (res.json && (res.json.detail || res.json.message)) || `HTTP ${res.status}` };
122
- }
123
- const pr = res.json.payment_request || res.json.bolt11;
124
- const ph = res.json.payment_hash || res.json.checking_id;
125
- if (!pr || !ph) return { ok: false, reason: "lnbits_invoice_missing_fields" };
126
- return { ok: true, payment_request: pr, payment_hash: ph };
127
- }
128
- if (config.provider === "generic") {
129
- if (!config.genericInvoiceUrl) return { ok: false, reason: "generic_invoice_url_missing" };
130
- const headers = {};
131
- if (config.genericAuthHeader) {
132
- const i = config.genericAuthHeader.indexOf(":");
133
- if (i > 0) headers[config.genericAuthHeader.slice(0, i).trim()] = config.genericAuthHeader.slice(i + 1).trim();
134
- }
135
- let res;
136
- try {
137
- res = await httpPostJson(config.genericInvoiceUrl, headers, { amount_sats: Math.round(sats), memo }, 15000);
138
- } catch (e) {
139
- return { ok: false, reason: "generic_invoice_unreachable", detail: e && e.message ? e.message : "request_error" };
140
- }
141
- if (!res.json || res.status >= 400) return { ok: false, reason: "generic_invoice_failed", detail: `HTTP ${res.status}` };
142
- const pr = res.json.payment_request || res.json.bolt11 || res.json.invoice;
143
- const ph = res.json.payment_hash;
144
- if (!pr || !ph) return { ok: false, reason: "generic_invoice_missing_fields" };
145
- return { ok: true, payment_request: pr, payment_hash: ph };
146
- }
147
- return { ok: false, reason: "unsupported_provider" };
148
- }
149
-
150
- function b64url(buf) {
151
- return Buffer.from(buf).toString("base64").replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
152
- }
153
- function b64urlDecode(s) {
154
- s = String(s).replace(/-/g, "+").replace(/_/g, "/");
155
- while (s.length % 4) s += "=";
156
- return Buffer.from(s, "base64");
157
- }
158
-
159
- // Issue an HMAC-signed macaroon binding a payment_hash. Returns "<payload>.<sig>" or null.
160
- function issueL402Macaroon(config, options) {
161
- if (!config || !config.rootKey) return null;
162
- const payload = {
163
- ph: String(options && options.payment_hash),
164
- exp: Math.floor(Date.now() / 1000) + config.macaroonTtlSeconds,
165
- nonce: b64url(crypto.randomBytes(12)),
166
- amt: (options && options.amountSats) || null
167
- };
168
- const encoded = b64url(JSON.stringify(payload));
169
- const sig = crypto.createHmac("sha256", config.rootKey).update(encoded, "utf8").digest("hex");
170
- return `${encoded}.${sig}`;
171
- }
172
-
173
- // Verify macaroon integrity + expiry. Returns { ok, payment_hash } | { ok:false, reason }.
174
- function verifyL402Macaroon(config, macaroon) {
175
- if (!config || !config.rootKey) return { ok: false, reason: "l402_root_key_missing" };
176
- const parts = String(macaroon || "").split(".");
177
- if (parts.length !== 2) return { ok: false, reason: "l402_macaroon_malformed" };
178
- const [encoded, sig] = parts;
179
- const expected = crypto.createHmac("sha256", config.rootKey).update(encoded, "utf8").digest("hex");
180
- let ok = false;
181
- try {
182
- ok = sig.length === expected.length && crypto.timingSafeEqual(Buffer.from(sig, "hex"), Buffer.from(expected, "hex"));
183
- } catch (_) {
184
- ok = false;
185
- }
186
- if (!ok) return { ok: false, reason: "l402_macaroon_signature_invalid" };
187
- let payload;
188
- try {
189
- payload = JSON.parse(b64urlDecode(encoded).toString("utf8"));
190
- } catch (_) {
191
- return { ok: false, reason: "l402_macaroon_payload_invalid" };
192
- }
193
- if (!payload.ph) return { ok: false, reason: "l402_macaroon_no_payment_hash" };
194
- if (payload.exp && Math.floor(Date.now() / 1000) > Number(payload.exp)) return { ok: false, reason: "l402_macaroon_expired" };
195
- return { ok: true, payment_hash: String(payload.ph) };
196
- }
197
-
198
- // Does preimage (hex) hash (sha256) to payment_hash (hex)? This is the real proof of payment.
199
- function verifyPreimage(preimageHex, paymentHashHex) {
200
- try {
201
- const h = crypto.createHash("sha256").update(Buffer.from(String(preimageHex), "hex")).digest("hex");
202
- return h.toLowerCase() === String(paymentHashHex).toLowerCase();
203
- } catch (_) {
204
- return false;
205
- }
206
- }
207
-
208
- // Parse "L402 <macaroon>:<preimage>" (also tolerates the legacy "LSAT" scheme).
209
- function parseL402Header(authorization) {
210
- const m = String(authorization || "").match(/^(?:L402|LSAT)\s+([^:\s]+):([0-9a-fA-F]+)\s*$/);
211
- if (!m) return null;
212
- return { macaroon: m[1], preimage: m[2] };
213
- }
214
-
215
- function buildWwwAuthenticate(macaroon, invoice) {
216
- return `L402 macaroon="${macaroon}", invoice="${invoice}"`;
217
- }
218
-
219
- // Full verification of an L402 Authorization header.
220
- // Returns { ok, payment_hash, preimage } | { ok:false, reason }.
221
- function verifyL402Authorization(config, authorization) {
222
- if (!isConfigured(config)) return { ok: false, reason: "l402_provider_not_configured" };
223
- const parsed = parseL402Header(authorization);
224
- if (!parsed) return { ok: false, reason: "l402_authorization_malformed" };
225
- const mac = verifyL402Macaroon(config, parsed.macaroon);
226
- if (!mac.ok) return mac;
227
- if (!verifyPreimage(parsed.preimage, mac.payment_hash)) return { ok: false, reason: "l402_preimage_mismatch" };
228
- return { ok: true, payment_hash: mac.payment_hash, preimage: parsed.preimage };
229
- }
230
-
231
- module.exports = {
232
- loadL402Config,
233
- isConfigured,
234
- createLightningInvoice,
235
- issueL402Macaroon,
236
- verifyL402Macaroon,
237
- verifyPreimage,
238
- parseL402Header,
239
- buildWwwAuthenticate,
240
- verifyL402Authorization
241
- };
1
+ "use strict";
2
+
3
+ // Provider-agnostic Lightning (L402) adapter.
4
+ //
5
+ // Makes the L402 lane a REAL Lightning rail: it creates bolt11 invoices through a
6
+ // configured Lightning provider and verifies payment CRYPTOGRAPHICALLY
7
+ // (preimage -> sha256 -> payment_hash). The macaroon is an HMAC-signed token that
8
+ // binds the invoice's payment_hash; the runtime issues and verifies it, and the
9
+ // client treats it as opaque and echoes it back with the preimage (standard L402
10
+ // flow). Preimage verification needs no node — only invoice creation does.
11
+ //
12
+ // Engages only when env configures a provider; otherwise every function reports
13
+ // not-configured and the caller preserves the existing bespoke token behavior.
14
+ // Dependency-free (node http/https + crypto).
15
+ //
16
+ // Env:
17
+ // XYTARA_L402_PROVIDER = "lnbits" | "generic" (unset => not configured)
18
+ // XYTARA_L402_ROOT_KEY (HMAC key for macaroons)
19
+ // XYTARA_L402_PRICE_SATS (default invoice amount, sats)
20
+ // XYTARA_L402_MACAROON_TTL_SECONDS (default 900)
21
+ // lnbits: XYTARA_LNBITS_URL, XYTARA_LNBITS_INVOICE_KEY
22
+ // generic: XYTARA_L402_INVOICE_URL, XYTARA_L402_INVOICE_AUTH_HEADER ("Header: value")
23
+
24
+ // SECURITY / LIMITATIONS (harden before enabling in production):
25
+ // - FLAT-RATE lane: each call is priced at a flat XYTARA_L402_PRICE_SATS, not
26
+ // the per-request USD quote amount (sats cannot be derived from USD without a
27
+ // rate oracle). Use for flat-priced calls.
28
+ // - DoS surface: each UNPAID request triggers a live invoice creation against
29
+ // the configured Lightning provider. Deploy the L402 routes behind rate
30
+ // limiting / a cheap pre-challenge gate so an unauthenticated flood cannot
31
+ // amplify into unbounded outbound invoice creation.
32
+
33
+ const https = require("https");
34
+ const http = require("http");
35
+ const crypto = require("crypto");
36
+ const { URL } = require("url");
37
+
38
+ function env(name) {
39
+ const v = process.env[name];
40
+ return typeof v === "string" && v.trim() ? v.trim() : "";
41
+ }
42
+
43
+ function loadL402Config() {
44
+ const provider = env("XYTARA_L402_PROVIDER").toLowerCase();
45
+ if (provider !== "lnbits" && provider !== "generic") return { provider: null };
46
+ return {
47
+ provider,
48
+ rootKey: env("XYTARA_L402_ROOT_KEY") || env("XYTARA_L402_SHARED_SECRET"),
49
+ priceSats: Number(env("XYTARA_L402_PRICE_SATS") || "") || null,
50
+ macaroonTtlSeconds: Math.max(60, Number(env("XYTARA_L402_MACAROON_TTL_SECONDS") || 900) || 900),
51
+ lnbitsUrl: env("XYTARA_LNBITS_URL"),
52
+ lnbitsInvoiceKey: env("XYTARA_LNBITS_INVOICE_KEY"),
53
+ genericInvoiceUrl: env("XYTARA_L402_INVOICE_URL"),
54
+ genericAuthHeader: env("XYTARA_L402_INVOICE_AUTH_HEADER")
55
+ };
56
+ }
57
+
58
+ function isConfigured(config) {
59
+ return Boolean(config && config.provider);
60
+ }
61
+
62
+ function httpPostJson(urlStr, headers, bodyObj, timeoutMs) {
63
+ return new Promise((resolve, reject) => {
64
+ let u;
65
+ try {
66
+ u = new URL(urlStr);
67
+ } catch (e) {
68
+ return reject(new Error("invalid_url"));
69
+ }
70
+ const body = JSON.stringify(bodyObj || {});
71
+ const lib = u.protocol === "http:" ? http : https;
72
+ const req = lib.request(
73
+ {
74
+ method: "POST",
75
+ hostname: u.hostname,
76
+ port: u.port || (u.protocol === "http:" ? 80 : 443),
77
+ path: u.pathname + u.search,
78
+ headers: { "Content-Type": "application/json", "Content-Length": Buffer.byteLength(body), ...(headers || {}) }
79
+ },
80
+ (res) => {
81
+ let d = "";
82
+ res.on("data", (c) => (d += c));
83
+ res.on("end", () => {
84
+ let j = null;
85
+ try {
86
+ j = d ? JSON.parse(d) : null;
87
+ } catch (_) {
88
+ j = null;
89
+ }
90
+ resolve({ status: res.statusCode, json: j, raw: d });
91
+ });
92
+ }
93
+ );
94
+ req.on("error", reject);
95
+ req.setTimeout(timeoutMs || 15000, () => req.destroy(new Error("l402_invoice_timeout")));
96
+ req.write(body);
97
+ req.end();
98
+ });
99
+ }
100
+
101
+ // Create a real bolt11 invoice. Returns { ok, payment_request, payment_hash } | { ok:false, reason, detail? }.
102
+ async function createLightningInvoice(config, options) {
103
+ if (!isConfigured(config)) return { ok: false, reason: "l402_provider_not_configured" };
104
+ const sats = Number((options && options.amountSats) || config.priceSats);
105
+ if (!Number.isFinite(sats) || sats <= 0) return { ok: false, reason: "invalid_amount_sats" };
106
+ const memo = (options && options.memo) || "naxytra L402";
107
+ if (config.provider === "lnbits") {
108
+ if (!config.lnbitsUrl || !config.lnbitsInvoiceKey) return { ok: false, reason: "lnbits_not_configured" };
109
+ let res;
110
+ try {
111
+ res = await httpPostJson(
112
+ config.lnbitsUrl.replace(/\/$/, "") + "/api/v1/payments",
113
+ { "X-Api-Key": config.lnbitsInvoiceKey },
114
+ { out: false, amount: Math.round(sats), memo },
115
+ 15000
116
+ );
117
+ } catch (e) {
118
+ return { ok: false, reason: "lnbits_unreachable", detail: e && e.message ? e.message : "request_error" };
119
+ }
120
+ if (!res.json || res.status >= 400) {
121
+ return { ok: false, reason: "lnbits_invoice_failed", detail: (res.json && (res.json.detail || res.json.message)) || `HTTP ${res.status}` };
122
+ }
123
+ const pr = res.json.payment_request || res.json.bolt11;
124
+ const ph = res.json.payment_hash || res.json.checking_id;
125
+ if (!pr || !ph) return { ok: false, reason: "lnbits_invoice_missing_fields" };
126
+ return { ok: true, payment_request: pr, payment_hash: ph };
127
+ }
128
+ if (config.provider === "generic") {
129
+ if (!config.genericInvoiceUrl) return { ok: false, reason: "generic_invoice_url_missing" };
130
+ const headers = {};
131
+ if (config.genericAuthHeader) {
132
+ const i = config.genericAuthHeader.indexOf(":");
133
+ if (i > 0) headers[config.genericAuthHeader.slice(0, i).trim()] = config.genericAuthHeader.slice(i + 1).trim();
134
+ }
135
+ let res;
136
+ try {
137
+ res = await httpPostJson(config.genericInvoiceUrl, headers, { amount_sats: Math.round(sats), memo }, 15000);
138
+ } catch (e) {
139
+ return { ok: false, reason: "generic_invoice_unreachable", detail: e && e.message ? e.message : "request_error" };
140
+ }
141
+ if (!res.json || res.status >= 400) return { ok: false, reason: "generic_invoice_failed", detail: `HTTP ${res.status}` };
142
+ const pr = res.json.payment_request || res.json.bolt11 || res.json.invoice;
143
+ const ph = res.json.payment_hash;
144
+ if (!pr || !ph) return { ok: false, reason: "generic_invoice_missing_fields" };
145
+ return { ok: true, payment_request: pr, payment_hash: ph };
146
+ }
147
+ return { ok: false, reason: "unsupported_provider" };
148
+ }
149
+
150
+ function b64url(buf) {
151
+ return Buffer.from(buf).toString("base64").replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
152
+ }
153
+ function b64urlDecode(s) {
154
+ s = String(s).replace(/-/g, "+").replace(/_/g, "/");
155
+ while (s.length % 4) s += "=";
156
+ return Buffer.from(s, "base64");
157
+ }
158
+
159
+ // Issue an HMAC-signed macaroon binding a payment_hash. Returns "<payload>.<sig>" or null.
160
+ function issueL402Macaroon(config, options) {
161
+ if (!config || !config.rootKey) return null;
162
+ const payload = {
163
+ ph: String(options && options.payment_hash),
164
+ exp: Math.floor(Date.now() / 1000) + config.macaroonTtlSeconds,
165
+ nonce: b64url(crypto.randomBytes(12)),
166
+ amt: (options && options.amountSats) || null
167
+ };
168
+ const encoded = b64url(JSON.stringify(payload));
169
+ const sig = crypto.createHmac("sha256", config.rootKey).update(encoded, "utf8").digest("hex");
170
+ return `${encoded}.${sig}`;
171
+ }
172
+
173
+ // Verify macaroon integrity + expiry. Returns { ok, payment_hash } | { ok:false, reason }.
174
+ function verifyL402Macaroon(config, macaroon) {
175
+ if (!config || !config.rootKey) return { ok: false, reason: "l402_root_key_missing" };
176
+ const parts = String(macaroon || "").split(".");
177
+ if (parts.length !== 2) return { ok: false, reason: "l402_macaroon_malformed" };
178
+ const [encoded, sig] = parts;
179
+ const expected = crypto.createHmac("sha256", config.rootKey).update(encoded, "utf8").digest("hex");
180
+ let ok = false;
181
+ try {
182
+ ok = sig.length === expected.length && crypto.timingSafeEqual(Buffer.from(sig, "hex"), Buffer.from(expected, "hex"));
183
+ } catch (_) {
184
+ ok = false;
185
+ }
186
+ if (!ok) return { ok: false, reason: "l402_macaroon_signature_invalid" };
187
+ let payload;
188
+ try {
189
+ payload = JSON.parse(b64urlDecode(encoded).toString("utf8"));
190
+ } catch (_) {
191
+ return { ok: false, reason: "l402_macaroon_payload_invalid" };
192
+ }
193
+ if (!payload.ph) return { ok: false, reason: "l402_macaroon_no_payment_hash" };
194
+ if (payload.exp && Math.floor(Date.now() / 1000) > Number(payload.exp)) return { ok: false, reason: "l402_macaroon_expired" };
195
+ return { ok: true, payment_hash: String(payload.ph) };
196
+ }
197
+
198
+ // Does preimage (hex) hash (sha256) to payment_hash (hex)? This is the real proof of payment.
199
+ function verifyPreimage(preimageHex, paymentHashHex) {
200
+ try {
201
+ const h = crypto.createHash("sha256").update(Buffer.from(String(preimageHex), "hex")).digest("hex");
202
+ return h.toLowerCase() === String(paymentHashHex).toLowerCase();
203
+ } catch (_) {
204
+ return false;
205
+ }
206
+ }
207
+
208
+ // Parse "L402 <macaroon>:<preimage>" (also tolerates the legacy "LSAT" scheme).
209
+ function parseL402Header(authorization) {
210
+ const m = String(authorization || "").match(/^(?:L402|LSAT)\s+([^:\s]+):([0-9a-fA-F]+)\s*$/);
211
+ if (!m) return null;
212
+ return { macaroon: m[1], preimage: m[2] };
213
+ }
214
+
215
+ function buildWwwAuthenticate(macaroon, invoice) {
216
+ return `L402 macaroon="${macaroon}", invoice="${invoice}"`;
217
+ }
218
+
219
+ // Full verification of an L402 Authorization header.
220
+ // Returns { ok, payment_hash, preimage } | { ok:false, reason }.
221
+ function verifyL402Authorization(config, authorization) {
222
+ if (!isConfigured(config)) return { ok: false, reason: "l402_provider_not_configured" };
223
+ const parsed = parseL402Header(authorization);
224
+ if (!parsed) return { ok: false, reason: "l402_authorization_malformed" };
225
+ const mac = verifyL402Macaroon(config, parsed.macaroon);
226
+ if (!mac.ok) return mac;
227
+ if (!verifyPreimage(parsed.preimage, mac.payment_hash)) return { ok: false, reason: "l402_preimage_mismatch" };
228
+ return { ok: true, payment_hash: mac.payment_hash, preimage: parsed.preimage };
229
+ }
230
+
231
+ module.exports = {
232
+ loadL402Config,
233
+ isConfigured,
234
+ createLightningInvoice,
235
+ issueL402Macaroon,
236
+ verifyL402Macaroon,
237
+ verifyPreimage,
238
+ parseL402Header,
239
+ buildWwwAuthenticate,
240
+ verifyL402Authorization
241
+ };