@t402/core 2.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 (66) hide show
  1. package/README.md +293 -0
  2. package/dist/cjs/client/index.d.ts +103 -0
  3. package/dist/cjs/client/index.js +510 -0
  4. package/dist/cjs/client/index.js.map +1 -0
  5. package/dist/cjs/facilitator/index.d.ts +192 -0
  6. package/dist/cjs/facilitator/index.js +398 -0
  7. package/dist/cjs/facilitator/index.js.map +1 -0
  8. package/dist/cjs/http/index.d.ts +52 -0
  9. package/dist/cjs/http/index.js +763 -0
  10. package/dist/cjs/http/index.js.map +1 -0
  11. package/dist/cjs/index.d.ts +3 -0
  12. package/dist/cjs/index.js +31 -0
  13. package/dist/cjs/index.js.map +1 -0
  14. package/dist/cjs/mechanisms-CmrqNl1M.d.ts +238 -0
  15. package/dist/cjs/mechanisms-DsJn3ZiM.d.ts +238 -0
  16. package/dist/cjs/server/index.d.ts +2 -0
  17. package/dist/cjs/server/index.js +1241 -0
  18. package/dist/cjs/server/index.js.map +1 -0
  19. package/dist/cjs/t402HTTPClient-m6cjzTek.d.ts +243 -0
  20. package/dist/cjs/t402HTTPResourceServer-B-xmYMwj.d.ts +719 -0
  21. package/dist/cjs/t402HTTPResourceServer-Bcfxp2UO.d.ts +719 -0
  22. package/dist/cjs/types/index.d.ts +1 -0
  23. package/dist/cjs/types/index.js +19 -0
  24. package/dist/cjs/types/index.js.map +1 -0
  25. package/dist/cjs/types/v1/index.d.ts +1 -0
  26. package/dist/cjs/types/v1/index.js +19 -0
  27. package/dist/cjs/types/v1/index.js.map +1 -0
  28. package/dist/cjs/utils/index.d.ts +48 -0
  29. package/dist/cjs/utils/index.js +108 -0
  30. package/dist/cjs/utils/index.js.map +1 -0
  31. package/dist/esm/chunk-3IUBYRYG.mjs +78 -0
  32. package/dist/esm/chunk-3IUBYRYG.mjs.map +1 -0
  33. package/dist/esm/chunk-3VTYR43U.mjs +7 -0
  34. package/dist/esm/chunk-3VTYR43U.mjs.map +1 -0
  35. package/dist/esm/chunk-BJTO5JO5.mjs +11 -0
  36. package/dist/esm/chunk-BJTO5JO5.mjs.map +1 -0
  37. package/dist/esm/chunk-D5DYKKCZ.mjs +722 -0
  38. package/dist/esm/chunk-D5DYKKCZ.mjs.map +1 -0
  39. package/dist/esm/client/index.d.mts +103 -0
  40. package/dist/esm/client/index.mjs +356 -0
  41. package/dist/esm/client/index.mjs.map +1 -0
  42. package/dist/esm/facilitator/index.d.mts +192 -0
  43. package/dist/esm/facilitator/index.mjs +373 -0
  44. package/dist/esm/facilitator/index.mjs.map +1 -0
  45. package/dist/esm/http/index.d.mts +52 -0
  46. package/dist/esm/http/index.mjs +28 -0
  47. package/dist/esm/http/index.mjs.map +1 -0
  48. package/dist/esm/index.d.mts +3 -0
  49. package/dist/esm/index.mjs +8 -0
  50. package/dist/esm/index.mjs.map +1 -0
  51. package/dist/esm/mechanisms-CmrqNl1M.d.mts +238 -0
  52. package/dist/esm/server/index.d.mts +2 -0
  53. package/dist/esm/server/index.mjs +562 -0
  54. package/dist/esm/server/index.mjs.map +1 -0
  55. package/dist/esm/t402HTTPClient-C285YGCp.d.mts +243 -0
  56. package/dist/esm/t402HTTPResourceServer-k_l3d8ua.d.mts +719 -0
  57. package/dist/esm/types/index.d.mts +1 -0
  58. package/dist/esm/types/index.mjs +1 -0
  59. package/dist/esm/types/index.mjs.map +1 -0
  60. package/dist/esm/types/v1/index.d.mts +1 -0
  61. package/dist/esm/types/v1/index.mjs +1 -0
  62. package/dist/esm/types/v1/index.mjs.map +1 -0
  63. package/dist/esm/utils/index.d.mts +48 -0
  64. package/dist/esm/utils/index.mjs +20 -0
  65. package/dist/esm/utils/index.mjs.map +1 -0
  66. package/package.json +129 -0
@@ -0,0 +1,763 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/http/index.ts
21
+ var http_exports = {};
22
+ __export(http_exports, {
23
+ HTTPFacilitatorClient: () => HTTPFacilitatorClient,
24
+ RouteConfigurationError: () => RouteConfigurationError,
25
+ decodePaymentRequiredHeader: () => decodePaymentRequiredHeader,
26
+ decodePaymentResponseHeader: () => decodePaymentResponseHeader,
27
+ decodePaymentSignatureHeader: () => decodePaymentSignatureHeader,
28
+ encodePaymentRequiredHeader: () => encodePaymentRequiredHeader,
29
+ encodePaymentResponseHeader: () => encodePaymentResponseHeader,
30
+ encodePaymentSignatureHeader: () => encodePaymentSignatureHeader,
31
+ t402HTTPClient: () => t402HTTPClient,
32
+ t402HTTPResourceServer: () => t402HTTPResourceServer
33
+ });
34
+ module.exports = __toCommonJS(http_exports);
35
+
36
+ // src/utils/index.ts
37
+ var Base64EncodedRegex = /^[A-Za-z0-9+/]*={0,2}$/;
38
+ function safeBase64Encode(data) {
39
+ if (typeof globalThis !== "undefined" && typeof globalThis.btoa === "function") {
40
+ return globalThis.btoa(data);
41
+ }
42
+ return Buffer.from(data).toString("base64");
43
+ }
44
+ function safeBase64Decode(data) {
45
+ if (typeof globalThis !== "undefined" && typeof globalThis.atob === "function") {
46
+ return globalThis.atob(data);
47
+ }
48
+ return Buffer.from(data, "base64").toString("utf-8");
49
+ }
50
+
51
+ // src/index.ts
52
+ var t402Version = 2;
53
+
54
+ // src/http/t402HTTPResourceServer.ts
55
+ var RouteConfigurationError = class extends Error {
56
+ /**
57
+ * Creates a new RouteConfigurationError with the given validation errors.
58
+ *
59
+ * @param errors - The validation errors that caused this exception.
60
+ */
61
+ constructor(errors) {
62
+ const message = `t402 Route Configuration Errors:
63
+ ${errors.map((e) => ` - ${e.message}`).join("\n")}`;
64
+ super(message);
65
+ this.name = "RouteConfigurationError";
66
+ this.errors = errors;
67
+ }
68
+ };
69
+ var t402HTTPResourceServer = class {
70
+ /**
71
+ * Creates a new t402HTTPResourceServer instance.
72
+ *
73
+ * @param ResourceServer - The core t402ResourceServer instance to use
74
+ * @param routes - Route configuration for payment-protected endpoints
75
+ */
76
+ constructor(ResourceServer, routes) {
77
+ this.compiledRoutes = [];
78
+ this.ResourceServer = ResourceServer;
79
+ this.routesConfig = routes;
80
+ const normalizedRoutes = typeof routes === "object" && !("accepts" in routes) ? routes : { "*": routes };
81
+ for (const [pattern, config] of Object.entries(normalizedRoutes)) {
82
+ const parsed = this.parseRoutePattern(pattern);
83
+ this.compiledRoutes.push({
84
+ verb: parsed.verb,
85
+ regex: parsed.regex,
86
+ config
87
+ });
88
+ }
89
+ }
90
+ /**
91
+ * Initialize the HTTP resource server.
92
+ *
93
+ * This method initializes the underlying resource server (fetching facilitator support)
94
+ * and then validates that all route payment configurations have corresponding
95
+ * registered schemes and facilitator support.
96
+ *
97
+ * @throws RouteConfigurationError if any route's payment options don't have
98
+ * corresponding registered schemes or facilitator support
99
+ *
100
+ * @example
101
+ * ```typescript
102
+ * const httpServer = new t402HTTPResourceServer(server, routes);
103
+ * await httpServer.initialize();
104
+ * ```
105
+ */
106
+ async initialize() {
107
+ await this.ResourceServer.initialize();
108
+ const errors = this.validateRouteConfiguration();
109
+ if (errors.length > 0) {
110
+ throw new RouteConfigurationError(errors);
111
+ }
112
+ }
113
+ /**
114
+ * Register a custom paywall provider for generating HTML
115
+ *
116
+ * @param provider - PaywallProvider instance
117
+ * @returns This service instance for chaining
118
+ */
119
+ registerPaywallProvider(provider) {
120
+ this.paywallProvider = provider;
121
+ return this;
122
+ }
123
+ /**
124
+ * Process HTTP request and return response instructions
125
+ * This is the main entry point for framework middleware
126
+ *
127
+ * @param context - HTTP request context
128
+ * @param paywallConfig - Optional paywall configuration
129
+ * @returns Process result indicating next action for middleware
130
+ */
131
+ async processHTTPRequest(context, paywallConfig) {
132
+ const { adapter, path, method } = context;
133
+ const routeConfig = this.getRouteConfig(path, method);
134
+ if (!routeConfig) {
135
+ return { type: "no-payment-required" };
136
+ }
137
+ const paymentOptions = this.normalizePaymentOptions(routeConfig);
138
+ const paymentPayload = this.extractPayment(adapter);
139
+ const resourceInfo = {
140
+ url: routeConfig.resource || context.adapter.getUrl(),
141
+ description: routeConfig.description || "",
142
+ mimeType: routeConfig.mimeType || ""
143
+ };
144
+ const requirements = await this.ResourceServer.buildPaymentRequirementsFromOptions(
145
+ paymentOptions,
146
+ context
147
+ );
148
+ let extensions = routeConfig.extensions;
149
+ if (extensions) {
150
+ extensions = this.ResourceServer.enrichExtensions(extensions, context);
151
+ }
152
+ const paymentRequired = this.ResourceServer.createPaymentRequiredResponse(
153
+ requirements,
154
+ resourceInfo,
155
+ !paymentPayload ? "Payment required" : void 0,
156
+ extensions
157
+ );
158
+ if (!paymentPayload) {
159
+ const unpaidBody = routeConfig.unpaidResponseBody ? await routeConfig.unpaidResponseBody(context) : void 0;
160
+ return {
161
+ type: "payment-error",
162
+ response: this.createHTTPResponse(
163
+ paymentRequired,
164
+ this.isWebBrowser(adapter),
165
+ paywallConfig,
166
+ routeConfig.customPaywallHtml,
167
+ unpaidBody
168
+ )
169
+ };
170
+ }
171
+ try {
172
+ const matchingRequirements = this.ResourceServer.findMatchingRequirements(
173
+ paymentRequired.accepts,
174
+ paymentPayload
175
+ );
176
+ if (!matchingRequirements) {
177
+ const errorResponse = this.ResourceServer.createPaymentRequiredResponse(
178
+ requirements,
179
+ resourceInfo,
180
+ "No matching payment requirements",
181
+ routeConfig.extensions
182
+ );
183
+ return {
184
+ type: "payment-error",
185
+ response: this.createHTTPResponse(errorResponse, false, paywallConfig)
186
+ };
187
+ }
188
+ const verifyResult = await this.ResourceServer.verifyPayment(
189
+ paymentPayload,
190
+ matchingRequirements
191
+ );
192
+ if (!verifyResult.isValid) {
193
+ const errorResponse = this.ResourceServer.createPaymentRequiredResponse(
194
+ requirements,
195
+ resourceInfo,
196
+ verifyResult.invalidReason,
197
+ routeConfig.extensions
198
+ );
199
+ return {
200
+ type: "payment-error",
201
+ response: this.createHTTPResponse(errorResponse, false, paywallConfig)
202
+ };
203
+ }
204
+ return {
205
+ type: "payment-verified",
206
+ paymentPayload,
207
+ paymentRequirements: matchingRequirements
208
+ };
209
+ } catch (error) {
210
+ const errorResponse = this.ResourceServer.createPaymentRequiredResponse(
211
+ requirements,
212
+ resourceInfo,
213
+ error instanceof Error ? error.message : "Payment verification failed",
214
+ routeConfig.extensions
215
+ );
216
+ return {
217
+ type: "payment-error",
218
+ response: this.createHTTPResponse(errorResponse, false, paywallConfig)
219
+ };
220
+ }
221
+ }
222
+ /**
223
+ * Process settlement after successful response
224
+ *
225
+ * @param paymentPayload - The verified payment payload
226
+ * @param requirements - The matching payment requirements
227
+ * @returns ProcessSettleResultResponse - SettleResponse with headers if success or errorReason if failure
228
+ */
229
+ async processSettlement(paymentPayload, requirements) {
230
+ try {
231
+ const settleResponse = await this.ResourceServer.settlePayment(paymentPayload, requirements);
232
+ if (!settleResponse.success) {
233
+ return {
234
+ ...settleResponse,
235
+ success: false,
236
+ errorReason: settleResponse.errorReason || "Settlement failed"
237
+ };
238
+ }
239
+ return {
240
+ ...settleResponse,
241
+ success: true,
242
+ headers: this.createSettlementHeaders(settleResponse, requirements),
243
+ requirements
244
+ };
245
+ } catch (error) {
246
+ throw new Error(error instanceof Error ? error.message : "Settlement failed");
247
+ }
248
+ }
249
+ /**
250
+ * Check if a request requires payment based on route configuration
251
+ *
252
+ * @param context - HTTP request context
253
+ * @returns True if the route requires payment, false otherwise
254
+ */
255
+ requiresPayment(context) {
256
+ const routeConfig = this.getRouteConfig(context.path, context.method);
257
+ return routeConfig !== void 0;
258
+ }
259
+ /**
260
+ * Normalizes a RouteConfig's accepts field into an array of PaymentOptions
261
+ * Handles both single PaymentOption and array formats
262
+ *
263
+ * @param routeConfig - Route configuration
264
+ * @returns Array of payment options
265
+ */
266
+ normalizePaymentOptions(routeConfig) {
267
+ return Array.isArray(routeConfig.accepts) ? routeConfig.accepts : [routeConfig.accepts];
268
+ }
269
+ /**
270
+ * Validates that all payment options in routes have corresponding registered schemes
271
+ * and facilitator support.
272
+ *
273
+ * @returns Array of validation errors (empty if all routes are valid)
274
+ */
275
+ validateRouteConfiguration() {
276
+ const errors = [];
277
+ const normalizedRoutes = typeof this.routesConfig === "object" && !("accepts" in this.routesConfig) ? Object.entries(this.routesConfig) : [["*", this.routesConfig]];
278
+ for (const [pattern, config] of normalizedRoutes) {
279
+ const paymentOptions = this.normalizePaymentOptions(config);
280
+ for (const option of paymentOptions) {
281
+ if (!this.ResourceServer.hasRegisteredScheme(option.network, option.scheme)) {
282
+ errors.push({
283
+ routePattern: pattern,
284
+ scheme: option.scheme,
285
+ network: option.network,
286
+ reason: "missing_scheme",
287
+ message: `Route "${pattern}": No scheme implementation registered for "${option.scheme}" on network "${option.network}"`
288
+ });
289
+ continue;
290
+ }
291
+ const supportedKind = this.ResourceServer.getSupportedKind(
292
+ t402Version,
293
+ option.network,
294
+ option.scheme
295
+ );
296
+ if (!supportedKind) {
297
+ errors.push({
298
+ routePattern: pattern,
299
+ scheme: option.scheme,
300
+ network: option.network,
301
+ reason: "missing_facilitator",
302
+ message: `Route "${pattern}": Facilitator does not support scheme "${option.scheme}" on network "${option.network}"`
303
+ });
304
+ }
305
+ }
306
+ }
307
+ return errors;
308
+ }
309
+ /**
310
+ * Get route configuration for a request
311
+ *
312
+ * @param path - Request path
313
+ * @param method - HTTP method
314
+ * @returns Route configuration or undefined if no match
315
+ */
316
+ getRouteConfig(path, method) {
317
+ const normalizedPath = this.normalizePath(path);
318
+ const upperMethod = method.toUpperCase();
319
+ const matchingRoute = this.compiledRoutes.find(
320
+ (route) => route.regex.test(normalizedPath) && (route.verb === "*" || route.verb === upperMethod)
321
+ );
322
+ return matchingRoute?.config;
323
+ }
324
+ /**
325
+ * Extract payment from HTTP headers (handles v1 and v2)
326
+ *
327
+ * @param adapter - HTTP adapter
328
+ * @returns Decoded payment payload or null
329
+ */
330
+ extractPayment(adapter) {
331
+ const header = adapter.getHeader("payment-signature") || adapter.getHeader("PAYMENT-SIGNATURE");
332
+ if (header) {
333
+ try {
334
+ return decodePaymentSignatureHeader(header);
335
+ } catch (error) {
336
+ console.warn("Failed to decode PAYMENT-SIGNATURE header:", error);
337
+ }
338
+ }
339
+ return null;
340
+ }
341
+ /**
342
+ * Check if request is from a web browser
343
+ *
344
+ * @param adapter - HTTP adapter
345
+ * @returns True if request appears to be from a browser
346
+ */
347
+ isWebBrowser(adapter) {
348
+ const accept = adapter.getAcceptHeader();
349
+ const userAgent = adapter.getUserAgent();
350
+ return accept.includes("text/html") && userAgent.includes("Mozilla");
351
+ }
352
+ /**
353
+ * Create HTTP response instructions from payment required
354
+ *
355
+ * @param paymentRequired - Payment requirements
356
+ * @param isWebBrowser - Whether request is from browser
357
+ * @param paywallConfig - Paywall configuration
358
+ * @param customHtml - Custom HTML template
359
+ * @param unpaidResponse - Optional custom response (content type and body) for unpaid API requests
360
+ * @returns Response instructions
361
+ */
362
+ createHTTPResponse(paymentRequired, isWebBrowser, paywallConfig, customHtml, unpaidResponse) {
363
+ if (isWebBrowser) {
364
+ const html = this.generatePaywallHTML(paymentRequired, paywallConfig, customHtml);
365
+ return {
366
+ status: 402,
367
+ headers: { "Content-Type": "text/html" },
368
+ body: html,
369
+ isHtml: true
370
+ };
371
+ }
372
+ const response = this.createHTTPPaymentRequiredResponse(paymentRequired);
373
+ const contentType = unpaidResponse ? unpaidResponse.contentType : "application/json";
374
+ const body = unpaidResponse ? unpaidResponse.body : {};
375
+ return {
376
+ status: 402,
377
+ headers: {
378
+ "Content-Type": contentType,
379
+ ...response.headers
380
+ },
381
+ body
382
+ };
383
+ }
384
+ /**
385
+ * Create HTTP payment required response (v1 puts in body, v2 puts in header)
386
+ *
387
+ * @param paymentRequired - Payment required object
388
+ * @returns Headers and body for the HTTP response
389
+ */
390
+ createHTTPPaymentRequiredResponse(paymentRequired) {
391
+ return {
392
+ headers: {
393
+ "PAYMENT-REQUIRED": encodePaymentRequiredHeader(paymentRequired)
394
+ }
395
+ };
396
+ }
397
+ /**
398
+ * Create settlement response headers
399
+ *
400
+ * @param settleResponse - Settlement response
401
+ * @param requirements - Payment requirements that were settled
402
+ * @returns Headers to add to response
403
+ */
404
+ createSettlementHeaders(settleResponse, requirements) {
405
+ const encoded = encodePaymentResponseHeader({
406
+ ...settleResponse,
407
+ requirements
408
+ });
409
+ return { "PAYMENT-RESPONSE": encoded };
410
+ }
411
+ /**
412
+ * Parse route pattern into verb and regex
413
+ *
414
+ * @param pattern - Route pattern like "GET /api/*" or "/api/[id]"
415
+ * @returns Parsed pattern with verb and regex
416
+ */
417
+ parseRoutePattern(pattern) {
418
+ const [verb, path] = pattern.includes(" ") ? pattern.split(/\s+/) : ["*", pattern];
419
+ const regex = new RegExp(
420
+ `^${path.replace(/[$()+.?^{|}]/g, "\\$&").replace(/\*/g, ".*?").replace(/\[([^\]]+)\]/g, "[^/]+").replace(/\//g, "\\/")}$`,
421
+ "i"
422
+ );
423
+ return { verb: verb.toUpperCase(), regex };
424
+ }
425
+ /**
426
+ * Normalize path for matching
427
+ *
428
+ * @param path - Raw path from request
429
+ * @returns Normalized path
430
+ */
431
+ normalizePath(path) {
432
+ try {
433
+ const pathWithoutQuery = path.split(/[?#]/)[0];
434
+ const decodedPath = decodeURIComponent(pathWithoutQuery);
435
+ return decodedPath.replace(/\\/g, "/").replace(/\/+/g, "/").replace(/(.+?)\/+$/, "$1");
436
+ } catch {
437
+ return path;
438
+ }
439
+ }
440
+ /**
441
+ * Generate paywall HTML for browser requests
442
+ *
443
+ * @param paymentRequired - Payment required response
444
+ * @param paywallConfig - Optional paywall configuration
445
+ * @param customHtml - Optional custom HTML template
446
+ * @returns HTML string
447
+ */
448
+ generatePaywallHTML(paymentRequired, paywallConfig, customHtml) {
449
+ if (customHtml) {
450
+ return customHtml;
451
+ }
452
+ if (this.paywallProvider) {
453
+ return this.paywallProvider.generateHtml(paymentRequired, paywallConfig);
454
+ }
455
+ try {
456
+ const paywall = require("@t402/paywall");
457
+ const displayAmount2 = this.getDisplayAmount(paymentRequired);
458
+ const resource2 = paymentRequired.resource;
459
+ return paywall.getPaywallHtml({
460
+ amount: displayAmount2,
461
+ paymentRequired,
462
+ currentUrl: resource2?.url || paywallConfig?.currentUrl || "",
463
+ testnet: paywallConfig?.testnet ?? true,
464
+ appName: paywallConfig?.appName,
465
+ appLogo: paywallConfig?.appLogo,
466
+ sessionTokenEndpoint: paywallConfig?.sessionTokenEndpoint
467
+ });
468
+ } catch {
469
+ }
470
+ const resource = paymentRequired.resource;
471
+ const displayAmount = this.getDisplayAmount(paymentRequired);
472
+ return `
473
+ <!DOCTYPE html>
474
+ <html>
475
+ <head>
476
+ <title>Payment Required</title>
477
+ <meta charset="UTF-8">
478
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
479
+ </head>
480
+ <body>
481
+ <div style="max-width: 600px; margin: 50px auto; padding: 20px; font-family: system-ui, -apple-system, sans-serif;">
482
+ ${paywallConfig?.appLogo ? `<img src="${paywallConfig.appLogo}" alt="${paywallConfig.appName || "App"}" style="max-width: 200px; margin-bottom: 20px;">` : ""}
483
+ <h1>Payment Required</h1>
484
+ ${resource ? `<p><strong>Resource:</strong> ${resource.description || resource.url}</p>` : ""}
485
+ <p><strong>Amount:</strong> $${displayAmount.toFixed(2)} USDC</p>
486
+ <div id="payment-widget"
487
+ data-requirements='${JSON.stringify(paymentRequired)}'
488
+ data-app-name="${paywallConfig?.appName || ""}"
489
+ data-testnet="${paywallConfig?.testnet || false}">
490
+ <!-- Install @t402/paywall for full wallet integration -->
491
+ <p style="margin-top: 2rem; padding: 1rem; background: #fef3c7; border-radius: 0.5rem;">
492
+ <strong>Note:</strong> Install <code>@t402/paywall</code> for full wallet connection and payment UI.
493
+ </p>
494
+ </div>
495
+ </div>
496
+ </body>
497
+ </html>
498
+ `;
499
+ }
500
+ /**
501
+ * Extract display amount from payment requirements.
502
+ *
503
+ * @param paymentRequired - The payment required object
504
+ * @returns The display amount in decimal format
505
+ */
506
+ getDisplayAmount(paymentRequired) {
507
+ const accepts = paymentRequired.accepts;
508
+ if (accepts && accepts.length > 0) {
509
+ const firstReq = accepts[0];
510
+ if ("amount" in firstReq) {
511
+ return parseFloat(firstReq.amount) / 1e6;
512
+ }
513
+ }
514
+ return 0;
515
+ }
516
+ };
517
+
518
+ // src/http/httpFacilitatorClient.ts
519
+ var DEFAULT_FACILITATOR_URL = "https://t402.org/facilitator";
520
+ var HTTPFacilitatorClient = class {
521
+ /**
522
+ * Creates a new HTTPFacilitatorClient instance.
523
+ *
524
+ * @param config - Configuration options for the facilitator client
525
+ */
526
+ constructor(config) {
527
+ this.url = config?.url || DEFAULT_FACILITATOR_URL;
528
+ this._createAuthHeaders = config?.createAuthHeaders;
529
+ }
530
+ /**
531
+ * Verify a payment with the facilitator
532
+ *
533
+ * @param paymentPayload - The payment to verify
534
+ * @param paymentRequirements - The requirements to verify against
535
+ * @returns Verification response
536
+ */
537
+ async verify(paymentPayload, paymentRequirements) {
538
+ let headers = {
539
+ "Content-Type": "application/json"
540
+ };
541
+ if (this._createAuthHeaders) {
542
+ const authHeaders = await this.createAuthHeaders("verify");
543
+ headers = { ...headers, ...authHeaders.headers };
544
+ }
545
+ const response = await fetch(`${this.url}/verify`, {
546
+ method: "POST",
547
+ headers,
548
+ body: JSON.stringify({
549
+ t402Version: paymentPayload.t402Version,
550
+ paymentPayload: this.toJsonSafe(paymentPayload),
551
+ paymentRequirements: this.toJsonSafe(paymentRequirements)
552
+ })
553
+ });
554
+ if (!response.ok) {
555
+ const errorText = await response.text().catch(() => response.statusText);
556
+ throw new Error(`Facilitator verify failed (${response.status}): ${errorText}`);
557
+ }
558
+ return await response.json();
559
+ }
560
+ /**
561
+ * Settle a payment with the facilitator
562
+ *
563
+ * @param paymentPayload - The payment to settle
564
+ * @param paymentRequirements - The requirements for settlement
565
+ * @returns Settlement response
566
+ */
567
+ async settle(paymentPayload, paymentRequirements) {
568
+ let headers = {
569
+ "Content-Type": "application/json"
570
+ };
571
+ if (this._createAuthHeaders) {
572
+ const authHeaders = await this.createAuthHeaders("settle");
573
+ headers = { ...headers, ...authHeaders.headers };
574
+ }
575
+ const response = await fetch(`${this.url}/settle`, {
576
+ method: "POST",
577
+ headers,
578
+ body: JSON.stringify({
579
+ t402Version: paymentPayload.t402Version,
580
+ paymentPayload: this.toJsonSafe(paymentPayload),
581
+ paymentRequirements: this.toJsonSafe(paymentRequirements)
582
+ })
583
+ });
584
+ if (!response.ok) {
585
+ const errorText = await response.text().catch(() => response.statusText);
586
+ throw new Error(`Facilitator settle failed (${response.status}): ${errorText}`);
587
+ }
588
+ return await response.json();
589
+ }
590
+ /**
591
+ * Get supported payment kinds and extensions from the facilitator
592
+ *
593
+ * @returns Supported payment kinds and extensions
594
+ */
595
+ async getSupported() {
596
+ let headers = {
597
+ "Content-Type": "application/json"
598
+ };
599
+ if (this._createAuthHeaders) {
600
+ const authHeaders = await this.createAuthHeaders("supported");
601
+ headers = { ...headers, ...authHeaders.headers };
602
+ }
603
+ const response = await fetch(`${this.url}/supported`, {
604
+ method: "GET",
605
+ headers
606
+ });
607
+ if (!response.ok) {
608
+ const errorText = await response.text().catch(() => response.statusText);
609
+ throw new Error(`Facilitator getSupported failed (${response.status}): ${errorText}`);
610
+ }
611
+ return await response.json();
612
+ }
613
+ /**
614
+ * Creates authentication headers for a specific path.
615
+ *
616
+ * @param path - The path to create authentication headers for (e.g., "verify", "settle", "supported")
617
+ * @returns An object containing the authentication headers for the specified path
618
+ */
619
+ async createAuthHeaders(path) {
620
+ if (this._createAuthHeaders) {
621
+ const authHeaders = await this._createAuthHeaders();
622
+ return {
623
+ headers: authHeaders[path] ?? {}
624
+ };
625
+ }
626
+ return {
627
+ headers: {}
628
+ };
629
+ }
630
+ /**
631
+ * Helper to convert objects to JSON-safe format.
632
+ * Handles BigInt and other non-JSON types.
633
+ *
634
+ * @param obj - The object to convert
635
+ * @returns The JSON-safe representation of the object
636
+ */
637
+ toJsonSafe(obj) {
638
+ return JSON.parse(
639
+ JSON.stringify(obj, (_, value) => typeof value === "bigint" ? value.toString() : value)
640
+ );
641
+ }
642
+ };
643
+
644
+ // src/http/t402HTTPClient.ts
645
+ var t402HTTPClient = class {
646
+ /**
647
+ * Creates a new t402HTTPClient instance.
648
+ *
649
+ * @param client - The underlying t402Client for payment logic
650
+ */
651
+ constructor(client) {
652
+ this.client = client;
653
+ }
654
+ /**
655
+ * Encodes a payment payload into appropriate HTTP headers based on version.
656
+ *
657
+ * @param paymentPayload - The payment payload to encode
658
+ * @returns HTTP headers containing the encoded payment signature
659
+ */
660
+ encodePaymentSignatureHeader(paymentPayload) {
661
+ switch (paymentPayload.t402Version) {
662
+ case 2:
663
+ return {
664
+ "PAYMENT-SIGNATURE": encodePaymentSignatureHeader(paymentPayload)
665
+ };
666
+ case 1:
667
+ return {
668
+ "X-PAYMENT": encodePaymentSignatureHeader(paymentPayload)
669
+ };
670
+ default:
671
+ throw new Error(
672
+ `Unsupported t402 version: ${paymentPayload.t402Version}`
673
+ );
674
+ }
675
+ }
676
+ /**
677
+ * Extracts payment required information from HTTP response.
678
+ *
679
+ * @param getHeader - Function to retrieve header value by name (case-insensitive)
680
+ * @param body - Optional response body for v1 compatibility
681
+ * @returns The payment required object
682
+ */
683
+ getPaymentRequiredResponse(getHeader, body) {
684
+ const paymentRequired = getHeader("PAYMENT-REQUIRED");
685
+ if (paymentRequired) {
686
+ return decodePaymentRequiredHeader(paymentRequired);
687
+ }
688
+ if (body && body instanceof Object && "t402Version" in body && body.t402Version === 1) {
689
+ return body;
690
+ }
691
+ throw new Error("Invalid payment required response");
692
+ }
693
+ /**
694
+ * Extracts payment settlement response from HTTP headers.
695
+ *
696
+ * @param getHeader - Function to retrieve header value by name (case-insensitive)
697
+ * @returns The settlement response object
698
+ */
699
+ getPaymentSettleResponse(getHeader) {
700
+ const paymentResponse = getHeader("PAYMENT-RESPONSE");
701
+ if (paymentResponse) {
702
+ return decodePaymentResponseHeader(paymentResponse);
703
+ }
704
+ const xPaymentResponse = getHeader("X-PAYMENT-RESPONSE");
705
+ if (xPaymentResponse) {
706
+ return decodePaymentResponseHeader(xPaymentResponse);
707
+ }
708
+ throw new Error("Payment response header not found");
709
+ }
710
+ /**
711
+ * Creates a payment payload for the given payment requirements.
712
+ * Delegates to the underlying t402Client.
713
+ *
714
+ * @param paymentRequired - The payment required response from the server
715
+ * @returns Promise resolving to the payment payload
716
+ */
717
+ async createPaymentPayload(paymentRequired) {
718
+ return this.client.createPaymentPayload(paymentRequired);
719
+ }
720
+ };
721
+
722
+ // src/http/index.ts
723
+ function encodePaymentSignatureHeader(paymentPayload) {
724
+ return safeBase64Encode(JSON.stringify(paymentPayload));
725
+ }
726
+ function decodePaymentSignatureHeader(paymentSignatureHeader) {
727
+ if (!Base64EncodedRegex.test(paymentSignatureHeader)) {
728
+ throw new Error("Invalid payment signature header");
729
+ }
730
+ return JSON.parse(safeBase64Decode(paymentSignatureHeader));
731
+ }
732
+ function encodePaymentRequiredHeader(paymentRequired) {
733
+ return safeBase64Encode(JSON.stringify(paymentRequired));
734
+ }
735
+ function decodePaymentRequiredHeader(paymentRequiredHeader) {
736
+ if (!Base64EncodedRegex.test(paymentRequiredHeader)) {
737
+ throw new Error("Invalid payment required header");
738
+ }
739
+ return JSON.parse(safeBase64Decode(paymentRequiredHeader));
740
+ }
741
+ function encodePaymentResponseHeader(paymentResponse) {
742
+ return safeBase64Encode(JSON.stringify(paymentResponse));
743
+ }
744
+ function decodePaymentResponseHeader(paymentResponseHeader) {
745
+ if (!Base64EncodedRegex.test(paymentResponseHeader)) {
746
+ throw new Error("Invalid payment response header");
747
+ }
748
+ return JSON.parse(safeBase64Decode(paymentResponseHeader));
749
+ }
750
+ // Annotate the CommonJS export names for ESM import in node:
751
+ 0 && (module.exports = {
752
+ HTTPFacilitatorClient,
753
+ RouteConfigurationError,
754
+ decodePaymentRequiredHeader,
755
+ decodePaymentResponseHeader,
756
+ decodePaymentSignatureHeader,
757
+ encodePaymentRequiredHeader,
758
+ encodePaymentResponseHeader,
759
+ encodePaymentSignatureHeader,
760
+ t402HTTPClient,
761
+ t402HTTPResourceServer
762
+ });
763
+ //# sourceMappingURL=index.js.map