x402-express-mantle 1.0.0 → 1.0.2

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 (125) hide show
  1. package/README.md +19 -1
  2. package/lib/cjs/index.d.ts +119 -81
  3. package/lib/cjs/index.js +3 -3
  4. package/lib/esm/index.d.mts +5 -5
  5. package/lib/esm/index.mjs +3 -3
  6. package/package.json +4 -3
  7. package/lib/cjs/client/index.d.ts +0 -243
  8. package/lib/cjs/client/index.js +0 -413
  9. package/lib/cjs/client/index.js.map +0 -1
  10. package/lib/cjs/exact/client/index.d.ts +0 -37
  11. package/lib/cjs/exact/client/index.js +0 -281
  12. package/lib/cjs/exact/client/index.js.map +0 -1
  13. package/lib/cjs/exact/facilitator/index.d.ts +0 -110
  14. package/lib/cjs/exact/facilitator/index.js +0 -714
  15. package/lib/cjs/exact/facilitator/index.js.map +0 -1
  16. package/lib/cjs/exact/server/index.d.ts +0 -87
  17. package/lib/cjs/exact/server/index.js +0 -209
  18. package/lib/cjs/exact/server/index.js.map +0 -1
  19. package/lib/cjs/exact/v1/client/index.d.ts +0 -33
  20. package/lib/cjs/exact/v1/client/index.js +0 -169
  21. package/lib/cjs/exact/v1/client/index.js.map +0 -1
  22. package/lib/cjs/exact/v1/facilitator/index.d.ts +0 -71
  23. package/lib/cjs/exact/v1/facilitator/index.js +0 -384
  24. package/lib/cjs/exact/v1/facilitator/index.js.map +0 -1
  25. package/lib/cjs/facilitator/index.d.ts +0 -192
  26. package/lib/cjs/facilitator/index.js +0 -398
  27. package/lib/cjs/facilitator/index.js.map +0 -1
  28. package/lib/cjs/http/index.d.ts +0 -52
  29. package/lib/cjs/http/index.js +0 -827
  30. package/lib/cjs/http/index.js.map +0 -1
  31. package/lib/cjs/mechanisms-CzuGzYsS.d.ts +0 -270
  32. package/lib/cjs/scheme-MoBRXFM8.d.ts +0 -29
  33. package/lib/cjs/server/index.d.ts +0 -2
  34. package/lib/cjs/server/index.js +0 -1305
  35. package/lib/cjs/server/index.js.map +0 -1
  36. package/lib/cjs/signer-5OVDxViv.d.ts +0 -79
  37. package/lib/cjs/signer-BMkbhFYE.d.ts +0 -123
  38. package/lib/cjs/types/index.d.ts +0 -1
  39. package/lib/cjs/types/index.js +0 -66
  40. package/lib/cjs/types/index.js.map +0 -1
  41. package/lib/cjs/types/v1/index.d.ts +0 -1
  42. package/lib/cjs/types/v1/index.js +0 -19
  43. package/lib/cjs/types/v1/index.js.map +0 -1
  44. package/lib/cjs/utils/index.d.ts +0 -48
  45. package/lib/cjs/utils/index.js +0 -116
  46. package/lib/cjs/utils/index.js.map +0 -1
  47. package/lib/cjs/v1/index.d.ts +0 -12
  48. package/lib/cjs/v1/index.js +0 -180
  49. package/lib/cjs/v1/index.js.map +0 -1
  50. package/lib/cjs/x402HTTPResourceServer-D1YtlH_r.d.ts +0 -719
  51. package/lib/esm/chunk-3CEIVWNN.mjs +0 -339
  52. package/lib/esm/chunk-3CEIVWNN.mjs.map +0 -1
  53. package/lib/esm/chunk-BJTO5JO5.mjs +0 -11
  54. package/lib/esm/chunk-BJTO5JO5.mjs.map +0 -1
  55. package/lib/esm/chunk-EEA7DKZI.mjs +0 -111
  56. package/lib/esm/chunk-EEA7DKZI.mjs.map +0 -1
  57. package/lib/esm/chunk-FOUXRQAV.mjs +0 -88
  58. package/lib/esm/chunk-FOUXRQAV.mjs.map +0 -1
  59. package/lib/esm/chunk-IKSTWKEM.mjs +0 -157
  60. package/lib/esm/chunk-IKSTWKEM.mjs.map +0 -1
  61. package/lib/esm/chunk-JYZWCLMP.mjs +0 -305
  62. package/lib/esm/chunk-JYZWCLMP.mjs.map +0 -1
  63. package/lib/esm/chunk-PNSAJQCF.mjs +0 -108
  64. package/lib/esm/chunk-PNSAJQCF.mjs.map +0 -1
  65. package/lib/esm/chunk-PSA4YVU2.mjs +0 -92
  66. package/lib/esm/chunk-PSA4YVU2.mjs.map +0 -1
  67. package/lib/esm/chunk-QLXM7BIB.mjs +0 -23
  68. package/lib/esm/chunk-QLXM7BIB.mjs.map +0 -1
  69. package/lib/esm/chunk-TDLQZ6MP.mjs +0 -86
  70. package/lib/esm/chunk-TDLQZ6MP.mjs.map +0 -1
  71. package/lib/esm/chunk-VE37GDG2.mjs +0 -7
  72. package/lib/esm/chunk-VE37GDG2.mjs.map +0 -1
  73. package/lib/esm/chunk-WWACQNRQ.mjs +0 -7
  74. package/lib/esm/chunk-WWACQNRQ.mjs.map +0 -1
  75. package/lib/esm/chunk-X4W4S5RB.mjs +0 -39
  76. package/lib/esm/chunk-X4W4S5RB.mjs.map +0 -1
  77. package/lib/esm/chunk-Z4QX3O5V.mjs +0 -748
  78. package/lib/esm/chunk-Z4QX3O5V.mjs.map +0 -1
  79. package/lib/esm/chunk-ZYXTTU74.mjs +0 -88
  80. package/lib/esm/chunk-ZYXTTU74.mjs.map +0 -1
  81. package/lib/esm/client/index.d.mts +0 -243
  82. package/lib/esm/client/index.mjs +0 -260
  83. package/lib/esm/client/index.mjs.map +0 -1
  84. package/lib/esm/exact/client/index.d.mts +0 -37
  85. package/lib/esm/exact/client/index.mjs +0 -36
  86. package/lib/esm/exact/client/index.mjs.map +0 -1
  87. package/lib/esm/exact/facilitator/index.d.mts +0 -110
  88. package/lib/esm/exact/facilitator/index.mjs +0 -350
  89. package/lib/esm/exact/facilitator/index.mjs.map +0 -1
  90. package/lib/esm/exact/server/index.d.mts +0 -87
  91. package/lib/esm/exact/server/index.mjs +0 -129
  92. package/lib/esm/exact/server/index.mjs.map +0 -1
  93. package/lib/esm/exact/v1/client/index.d.mts +0 -33
  94. package/lib/esm/exact/v1/client/index.mjs +0 -8
  95. package/lib/esm/exact/v1/client/index.mjs.map +0 -1
  96. package/lib/esm/exact/v1/facilitator/index.d.mts +0 -71
  97. package/lib/esm/exact/v1/facilitator/index.mjs +0 -8
  98. package/lib/esm/exact/v1/facilitator/index.mjs.map +0 -1
  99. package/lib/esm/facilitator/index.d.mts +0 -192
  100. package/lib/esm/facilitator/index.mjs +0 -373
  101. package/lib/esm/facilitator/index.mjs.map +0 -1
  102. package/lib/esm/http/index.d.mts +0 -52
  103. package/lib/esm/http/index.mjs +0 -29
  104. package/lib/esm/http/index.mjs.map +0 -1
  105. package/lib/esm/mechanisms-CzuGzYsS.d.mts +0 -270
  106. package/lib/esm/scheme-fjF-9LhT.d.mts +0 -29
  107. package/lib/esm/server/index.d.mts +0 -2
  108. package/lib/esm/server/index.mjs +0 -563
  109. package/lib/esm/server/index.mjs.map +0 -1
  110. package/lib/esm/signer-5OVDxViv.d.mts +0 -79
  111. package/lib/esm/signer-BMkbhFYE.d.mts +0 -123
  112. package/lib/esm/types/index.d.mts +0 -1
  113. package/lib/esm/types/index.mjs +0 -10
  114. package/lib/esm/types/index.mjs.map +0 -1
  115. package/lib/esm/types/v1/index.d.mts +0 -1
  116. package/lib/esm/types/v1/index.mjs +0 -1
  117. package/lib/esm/types/v1/index.mjs.map +0 -1
  118. package/lib/esm/utils/index.d.mts +0 -48
  119. package/lib/esm/utils/index.mjs +0 -20
  120. package/lib/esm/utils/index.mjs.map +0 -1
  121. package/lib/esm/v1/index.d.mts +0 -12
  122. package/lib/esm/v1/index.mjs +0 -13
  123. package/lib/esm/v1/index.mjs.map +0 -1
  124. package/lib/esm/x402HTTPResourceServer-BIfIK5HS.d.mts +0 -719
  125. package/src/index.js +0 -4
@@ -1,563 +0,0 @@
1
- import {
2
- HTTPFacilitatorClient,
3
- RouteConfigurationError,
4
- x402HTTPResourceServer
5
- } from "../chunk-Z4QX3O5V.mjs";
6
- import {
7
- x402Version
8
- } from "../chunk-VE37GDG2.mjs";
9
- import "../chunk-X4W4S5RB.mjs";
10
- import {
11
- deepEqual,
12
- findByNetworkAndScheme
13
- } from "../chunk-TDLQZ6MP.mjs";
14
- import "../chunk-BJTO5JO5.mjs";
15
-
16
- // src/server/x402ResourceServer.ts
17
- var x402ResourceServer = class {
18
- /**
19
- * Creates a new x402ResourceServer instance.
20
- *
21
- * @param facilitatorClients - Optional facilitator client(s) for payment processing
22
- */
23
- constructor(facilitatorClients) {
24
- this.registeredServerSchemes = /* @__PURE__ */ new Map();
25
- this.supportedResponsesMap = /* @__PURE__ */ new Map();
26
- this.facilitatorClientsMap = /* @__PURE__ */ new Map();
27
- this.registeredExtensions = /* @__PURE__ */ new Map();
28
- this.beforeVerifyHooks = [];
29
- this.afterVerifyHooks = [];
30
- this.onVerifyFailureHooks = [];
31
- this.beforeSettleHooks = [];
32
- this.afterSettleHooks = [];
33
- this.onSettleFailureHooks = [];
34
- if (!facilitatorClients) {
35
- this.facilitatorClients = [new HTTPFacilitatorClient()];
36
- } else if (Array.isArray(facilitatorClients)) {
37
- this.facilitatorClients = facilitatorClients.length > 0 ? facilitatorClients : [new HTTPFacilitatorClient()];
38
- } else {
39
- this.facilitatorClients = [facilitatorClients];
40
- }
41
- }
42
- /**
43
- * Register a scheme/network server implementation.
44
- *
45
- * @param network - The network identifier
46
- * @param server - The scheme/network server implementation
47
- * @returns The x402ResourceServer instance for chaining
48
- */
49
- register(network, server) {
50
- if (!this.registeredServerSchemes.has(network)) {
51
- this.registeredServerSchemes.set(network, /* @__PURE__ */ new Map());
52
- }
53
- const serverByScheme = this.registeredServerSchemes.get(network);
54
- if (!serverByScheme.has(server.scheme)) {
55
- serverByScheme.set(server.scheme, server);
56
- }
57
- return this;
58
- }
59
- /**
60
- * Check if a scheme is registered for a given network.
61
- *
62
- * @param network - The network identifier
63
- * @param scheme - The payment scheme name
64
- * @returns True if the scheme is registered for the network, false otherwise
65
- */
66
- hasRegisteredScheme(network, scheme) {
67
- return !!findByNetworkAndScheme(this.registeredServerSchemes, scheme, network);
68
- }
69
- /**
70
- * Registers a resource service extension that can enrich extension declarations.
71
- *
72
- * @param extension - The extension to register
73
- * @returns The x402ResourceServer instance for chaining
74
- */
75
- registerExtension(extension) {
76
- this.registeredExtensions.set(extension.key, extension);
77
- return this;
78
- }
79
- /**
80
- * Enriches declared extensions using registered extension hooks.
81
- *
82
- * @param declaredExtensions - Extensions declared on the route
83
- * @param transportContext - Transport-specific context (HTTP, A2A, MCP, etc.)
84
- * @returns Enriched extensions map
85
- */
86
- enrichExtensions(declaredExtensions, transportContext) {
87
- const enriched = {};
88
- for (const [key, declaration] of Object.entries(declaredExtensions)) {
89
- const extension = this.registeredExtensions.get(key);
90
- if (extension?.enrichDeclaration) {
91
- enriched[key] = extension.enrichDeclaration(declaration, transportContext);
92
- } else {
93
- enriched[key] = declaration;
94
- }
95
- }
96
- return enriched;
97
- }
98
- /**
99
- * Register a hook to execute before payment verification.
100
- * Can abort verification by returning { abort: true, reason: string }
101
- *
102
- * @param hook - The hook function to register
103
- * @returns The x402ResourceServer instance for chaining
104
- */
105
- onBeforeVerify(hook) {
106
- this.beforeVerifyHooks.push(hook);
107
- return this;
108
- }
109
- /**
110
- * Register a hook to execute after successful payment verification.
111
- *
112
- * @param hook - The hook function to register
113
- * @returns The x402ResourceServer instance for chaining
114
- */
115
- onAfterVerify(hook) {
116
- this.afterVerifyHooks.push(hook);
117
- return this;
118
- }
119
- /**
120
- * Register a hook to execute when payment verification fails.
121
- * Can recover from failure by returning { recovered: true, result: VerifyResponse }
122
- *
123
- * @param hook - The hook function to register
124
- * @returns The x402ResourceServer instance for chaining
125
- */
126
- onVerifyFailure(hook) {
127
- this.onVerifyFailureHooks.push(hook);
128
- return this;
129
- }
130
- /**
131
- * Register a hook to execute before payment settlement.
132
- * Can abort settlement by returning { abort: true, reason: string }
133
- *
134
- * @param hook - The hook function to register
135
- * @returns The x402ResourceServer instance for chaining
136
- */
137
- onBeforeSettle(hook) {
138
- this.beforeSettleHooks.push(hook);
139
- return this;
140
- }
141
- /**
142
- * Register a hook to execute after successful payment settlement.
143
- *
144
- * @param hook - The hook function to register
145
- * @returns The x402ResourceServer instance for chaining
146
- */
147
- onAfterSettle(hook) {
148
- this.afterSettleHooks.push(hook);
149
- return this;
150
- }
151
- /**
152
- * Register a hook to execute when payment settlement fails.
153
- * Can recover from failure by returning { recovered: true, result: SettleResponse }
154
- *
155
- * @param hook - The hook function to register
156
- * @returns The x402ResourceServer instance for chaining
157
- */
158
- onSettleFailure(hook) {
159
- this.onSettleFailureHooks.push(hook);
160
- return this;
161
- }
162
- /**
163
- * Initialize by fetching supported kinds from all facilitators
164
- * Creates mappings for supported responses and facilitator clients
165
- * Earlier facilitators in the array get precedence
166
- */
167
- async initialize() {
168
- this.supportedResponsesMap.clear();
169
- this.facilitatorClientsMap.clear();
170
- for (const facilitatorClient of this.facilitatorClients) {
171
- try {
172
- const supported = await facilitatorClient.getSupported();
173
- for (const kind of supported.kinds) {
174
- const x402Version2 = kind.x402Version;
175
- if (!this.supportedResponsesMap.has(x402Version2)) {
176
- this.supportedResponsesMap.set(x402Version2, /* @__PURE__ */ new Map());
177
- }
178
- const responseVersionMap = this.supportedResponsesMap.get(x402Version2);
179
- if (!this.facilitatorClientsMap.has(x402Version2)) {
180
- this.facilitatorClientsMap.set(x402Version2, /* @__PURE__ */ new Map());
181
- }
182
- const clientVersionMap = this.facilitatorClientsMap.get(x402Version2);
183
- if (!responseVersionMap.has(kind.network)) {
184
- responseVersionMap.set(kind.network, /* @__PURE__ */ new Map());
185
- }
186
- const responseNetworkMap = responseVersionMap.get(kind.network);
187
- if (!clientVersionMap.has(kind.network)) {
188
- clientVersionMap.set(kind.network, /* @__PURE__ */ new Map());
189
- }
190
- const clientNetworkMap = clientVersionMap.get(kind.network);
191
- if (!responseNetworkMap.has(kind.scheme)) {
192
- responseNetworkMap.set(kind.scheme, supported);
193
- clientNetworkMap.set(kind.scheme, facilitatorClient);
194
- }
195
- }
196
- } catch (error) {
197
- console.warn(`Failed to fetch supported kinds from facilitator: ${error}`);
198
- }
199
- }
200
- }
201
- /**
202
- * Get supported kind for a specific version, network, and scheme
203
- *
204
- * @param x402Version - The x402 version
205
- * @param network - The network identifier
206
- * @param scheme - The payment scheme
207
- * @returns The supported kind or undefined if not found
208
- */
209
- getSupportedKind(x402Version2, network, scheme) {
210
- const versionMap = this.supportedResponsesMap.get(x402Version2);
211
- if (!versionMap) return void 0;
212
- const supportedResponse = findByNetworkAndScheme(versionMap, scheme, network);
213
- if (!supportedResponse) return void 0;
214
- return supportedResponse.kinds.find(
215
- (kind) => kind.x402Version === x402Version2 && kind.network === network && kind.scheme === scheme
216
- );
217
- }
218
- /**
219
- * Get facilitator extensions for a specific version, network, and scheme
220
- *
221
- * @param x402Version - The x402 version
222
- * @param network - The network identifier
223
- * @param scheme - The payment scheme
224
- * @returns The facilitator extensions or empty array if not found
225
- */
226
- getFacilitatorExtensions(x402Version2, network, scheme) {
227
- const versionMap = this.supportedResponsesMap.get(x402Version2);
228
- if (!versionMap) return [];
229
- const supportedResponse = findByNetworkAndScheme(versionMap, scheme, network);
230
- return supportedResponse?.extensions || [];
231
- }
232
- /**
233
- * Build payment requirements for a protected resource
234
- *
235
- * @param resourceConfig - Configuration for the protected resource
236
- * @returns Array of payment requirements
237
- */
238
- async buildPaymentRequirements(resourceConfig) {
239
- const requirements = [];
240
- const scheme = resourceConfig.scheme;
241
- const SchemeNetworkServer = findByNetworkAndScheme(
242
- this.registeredServerSchemes,
243
- scheme,
244
- resourceConfig.network
245
- );
246
- if (!SchemeNetworkServer) {
247
- console.warn(
248
- `No server implementation registered for scheme: ${scheme}, network: ${resourceConfig.network}`
249
- );
250
- return requirements;
251
- }
252
- const supportedKind = this.getSupportedKind(
253
- x402Version,
254
- resourceConfig.network,
255
- SchemeNetworkServer.scheme
256
- );
257
- if (!supportedKind) {
258
- throw new Error(
259
- `Facilitator does not support ${SchemeNetworkServer.scheme} on ${resourceConfig.network}. Make sure to call initialize() to fetch supported kinds from facilitators.`
260
- );
261
- }
262
- const facilitatorExtensions = this.getFacilitatorExtensions(
263
- x402Version,
264
- resourceConfig.network,
265
- SchemeNetworkServer.scheme
266
- );
267
- const parsedPrice = await SchemeNetworkServer.parsePrice(
268
- resourceConfig.price,
269
- resourceConfig.network
270
- );
271
- const baseRequirements = {
272
- scheme: SchemeNetworkServer.scheme,
273
- network: resourceConfig.network,
274
- amount: parsedPrice.amount,
275
- asset: parsedPrice.asset,
276
- payTo: resourceConfig.payTo,
277
- maxTimeoutSeconds: resourceConfig.maxTimeoutSeconds || 300,
278
- // Default 5 minutes
279
- extra: {
280
- ...parsedPrice.extra
281
- }
282
- };
283
- const requirement = await SchemeNetworkServer.enhancePaymentRequirements(
284
- baseRequirements,
285
- {
286
- ...supportedKind,
287
- x402Version
288
- },
289
- facilitatorExtensions
290
- );
291
- requirements.push(requirement);
292
- return requirements;
293
- }
294
- /**
295
- * Build payment requirements from multiple payment options
296
- * This method handles resolving dynamic payTo/price functions and builds requirements for each option
297
- *
298
- * @param paymentOptions - Array of payment options to convert
299
- * @param context - HTTP request context for resolving dynamic functions
300
- * @returns Array of payment requirements (one per option)
301
- */
302
- async buildPaymentRequirementsFromOptions(paymentOptions, context) {
303
- const allRequirements = [];
304
- for (const option of paymentOptions) {
305
- const resolvedPayTo = typeof option.payTo === "function" ? await option.payTo(context) : option.payTo;
306
- const resolvedPrice = typeof option.price === "function" ? await option.price(context) : option.price;
307
- const resourceConfig = {
308
- scheme: option.scheme,
309
- payTo: resolvedPayTo,
310
- price: resolvedPrice,
311
- network: option.network,
312
- maxTimeoutSeconds: option.maxTimeoutSeconds
313
- };
314
- const requirements = await this.buildPaymentRequirements(resourceConfig);
315
- allRequirements.push(...requirements);
316
- }
317
- return allRequirements;
318
- }
319
- /**
320
- * Create a payment required response
321
- *
322
- * @param requirements - Payment requirements
323
- * @param resourceInfo - Resource information
324
- * @param error - Error message
325
- * @param extensions - Optional extensions
326
- * @returns Payment required response object
327
- */
328
- createPaymentRequiredResponse(requirements, resourceInfo, error, extensions) {
329
- const response = {
330
- x402Version: 2,
331
- error,
332
- resource: resourceInfo,
333
- accepts: requirements
334
- };
335
- if (extensions && Object.keys(extensions).length > 0) {
336
- response.extensions = extensions;
337
- }
338
- return response;
339
- }
340
- /**
341
- * Verify a payment against requirements
342
- *
343
- * @param paymentPayload - The payment payload to verify
344
- * @param requirements - The payment requirements
345
- * @returns Verification response
346
- */
347
- async verifyPayment(paymentPayload, requirements) {
348
- const context = {
349
- paymentPayload,
350
- requirements
351
- };
352
- for (const hook of this.beforeVerifyHooks) {
353
- const result = await hook(context);
354
- if (result && "abort" in result && result.abort) {
355
- return {
356
- isValid: false,
357
- invalidReason: result.reason
358
- };
359
- }
360
- }
361
- try {
362
- const facilitatorClient = this.getFacilitatorClient(
363
- paymentPayload.x402Version,
364
- requirements.network,
365
- requirements.scheme
366
- );
367
- let verifyResult;
368
- if (!facilitatorClient) {
369
- let lastError;
370
- for (const client of this.facilitatorClients) {
371
- try {
372
- verifyResult = await client.verify(paymentPayload, requirements);
373
- break;
374
- } catch (error) {
375
- lastError = error;
376
- }
377
- }
378
- if (!verifyResult) {
379
- throw lastError || new Error(
380
- `No facilitator supports ${requirements.scheme} on ${requirements.network} for v${paymentPayload.x402Version}`
381
- );
382
- }
383
- } else {
384
- verifyResult = await facilitatorClient.verify(paymentPayload, requirements);
385
- }
386
- const resultContext = {
387
- ...context,
388
- result: verifyResult
389
- };
390
- for (const hook of this.afterVerifyHooks) {
391
- await hook(resultContext);
392
- }
393
- return verifyResult;
394
- } catch (error) {
395
- const failureContext = {
396
- ...context,
397
- error
398
- };
399
- for (const hook of this.onVerifyFailureHooks) {
400
- const result = await hook(failureContext);
401
- if (result && "recovered" in result && result.recovered) {
402
- return result.result;
403
- }
404
- }
405
- throw error;
406
- }
407
- }
408
- /**
409
- * Settle a verified payment
410
- *
411
- * @param paymentPayload - The payment payload to settle
412
- * @param requirements - The payment requirements
413
- * @returns Settlement response
414
- */
415
- async settlePayment(paymentPayload, requirements) {
416
- const context = {
417
- paymentPayload,
418
- requirements
419
- };
420
- for (const hook of this.beforeSettleHooks) {
421
- const result = await hook(context);
422
- if (result && "abort" in result && result.abort) {
423
- throw new Error(`Settlement aborted: ${result.reason}`);
424
- }
425
- }
426
- try {
427
- const facilitatorClient = this.getFacilitatorClient(
428
- paymentPayload.x402Version,
429
- requirements.network,
430
- requirements.scheme
431
- );
432
- let settleResult;
433
- if (!facilitatorClient) {
434
- let lastError;
435
- for (const client of this.facilitatorClients) {
436
- try {
437
- settleResult = await client.settle(paymentPayload, requirements);
438
- break;
439
- } catch (error) {
440
- lastError = error;
441
- }
442
- }
443
- if (!settleResult) {
444
- throw lastError || new Error(
445
- `No facilitator supports ${requirements.scheme} on ${requirements.network} for v${paymentPayload.x402Version}`
446
- );
447
- }
448
- } else {
449
- settleResult = await facilitatorClient.settle(paymentPayload, requirements);
450
- }
451
- const resultContext = {
452
- ...context,
453
- result: settleResult
454
- };
455
- for (const hook of this.afterSettleHooks) {
456
- await hook(resultContext);
457
- }
458
- return settleResult;
459
- } catch (error) {
460
- const failureContext = {
461
- ...context,
462
- error
463
- };
464
- for (const hook of this.onSettleFailureHooks) {
465
- const result = await hook(failureContext);
466
- if (result && "recovered" in result && result.recovered) {
467
- return result.result;
468
- }
469
- }
470
- throw error;
471
- }
472
- }
473
- /**
474
- * Find matching payment requirements for a payment
475
- *
476
- * @param availableRequirements - Array of available payment requirements
477
- * @param paymentPayload - The payment payload
478
- * @returns Matching payment requirements or undefined
479
- */
480
- findMatchingRequirements(availableRequirements, paymentPayload) {
481
- switch (paymentPayload.x402Version) {
482
- case 2:
483
- return availableRequirements.find(
484
- (paymentRequirements) => deepEqual(paymentRequirements, paymentPayload.accepted)
485
- );
486
- case 1:
487
- return availableRequirements.find(
488
- (req) => req.scheme === paymentPayload.accepted.scheme && req.network === paymentPayload.accepted.network
489
- );
490
- default:
491
- throw new Error(
492
- `Unsupported x402 version: ${paymentPayload.x402Version}`
493
- );
494
- }
495
- }
496
- /**
497
- * Process a payment request
498
- *
499
- * @param paymentPayload - Optional payment payload if provided
500
- * @param resourceConfig - Configuration for the protected resource
501
- * @param resourceInfo - Information about the resource being accessed
502
- * @param extensions - Optional extensions to include in the response
503
- * @returns Processing result
504
- */
505
- async processPaymentRequest(paymentPayload, resourceConfig, resourceInfo, extensions) {
506
- const requirements = await this.buildPaymentRequirements(resourceConfig);
507
- if (!paymentPayload) {
508
- return {
509
- success: false,
510
- requiresPayment: this.createPaymentRequiredResponse(
511
- requirements,
512
- resourceInfo,
513
- "Payment required",
514
- extensions
515
- )
516
- };
517
- }
518
- const matchingRequirements = this.findMatchingRequirements(requirements, paymentPayload);
519
- if (!matchingRequirements) {
520
- return {
521
- success: false,
522
- requiresPayment: this.createPaymentRequiredResponse(
523
- requirements,
524
- resourceInfo,
525
- "No matching payment requirements found",
526
- extensions
527
- )
528
- };
529
- }
530
- const verificationResult = await this.verifyPayment(paymentPayload, matchingRequirements);
531
- if (!verificationResult.isValid) {
532
- return {
533
- success: false,
534
- error: verificationResult.invalidReason,
535
- verificationResult
536
- };
537
- }
538
- return {
539
- success: true,
540
- verificationResult
541
- };
542
- }
543
- /**
544
- * Get facilitator client for a specific version, network, and scheme
545
- *
546
- * @param x402Version - The x402 version
547
- * @param network - The network identifier
548
- * @param scheme - The payment scheme
549
- * @returns The facilitator client or undefined if not found
550
- */
551
- getFacilitatorClient(x402Version2, network, scheme) {
552
- const versionMap = this.facilitatorClientsMap.get(x402Version2);
553
- if (!versionMap) return void 0;
554
- return findByNetworkAndScheme(versionMap, scheme, network);
555
- }
556
- };
557
- export {
558
- HTTPFacilitatorClient,
559
- RouteConfigurationError,
560
- x402HTTPResourceServer,
561
- x402ResourceServer
562
- };
563
- //# sourceMappingURL=index.mjs.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../../../src/server/x402ResourceServer.ts"],"sourcesContent":["import {\n SettleResponse,\n VerifyResponse,\n SupportedResponse,\n SupportedKind,\n} from \"../types/facilitator\";\nimport { PaymentPayload, PaymentRequirements, PaymentRequired } from \"../types/payments\";\nimport { SchemeNetworkServer } from \"../types/mechanisms\";\nimport { Price, Network, ResourceServerExtension } from \"../types\";\nimport { deepEqual, findByNetworkAndScheme } from \"../utils\";\nimport { FacilitatorClient, HTTPFacilitatorClient } from \"../http/httpFacilitatorClient\";\nimport { x402Version } from \"..\";\n\n/**\n * Configuration for a protected resource\n * Only contains payment-specific configuration, not resource metadata\n */\nexport interface ResourceConfig {\n scheme: string;\n payTo: string; // Payment recipient address\n price: Price;\n network: Network;\n maxTimeoutSeconds?: number;\n}\n\n/**\n * Resource information for PaymentRequired response\n */\nexport interface ResourceInfo {\n url: string;\n description: string;\n mimeType: string;\n}\n\n/**\n * Lifecycle Hook Context Interfaces\n */\n\nexport interface VerifyContext {\n paymentPayload: PaymentPayload;\n requirements: PaymentRequirements;\n}\n\nexport interface VerifyResultContext extends VerifyContext {\n result: VerifyResponse;\n}\n\nexport interface VerifyFailureContext extends VerifyContext {\n error: Error;\n}\n\nexport interface SettleContext {\n paymentPayload: PaymentPayload;\n requirements: PaymentRequirements;\n}\n\nexport interface SettleResultContext extends SettleContext {\n result: SettleResponse;\n}\n\nexport interface SettleFailureContext extends SettleContext {\n error: Error;\n}\n\n/**\n * Lifecycle Hook Type Definitions\n */\n\nexport type BeforeVerifyHook = (\n context: VerifyContext,\n) => Promise<void | { abort: true; reason: string }>;\n\nexport type AfterVerifyHook = (context: VerifyResultContext) => Promise<void>;\n\nexport type OnVerifyFailureHook = (\n context: VerifyFailureContext,\n) => Promise<void | { recovered: true; result: VerifyResponse }>;\n\nexport type BeforeSettleHook = (\n context: SettleContext,\n) => Promise<void | { abort: true; reason: string }>;\n\nexport type AfterSettleHook = (context: SettleResultContext) => Promise<void>;\n\nexport type OnSettleFailureHook = (\n context: SettleFailureContext,\n) => Promise<void | { recovered: true; result: SettleResponse }>;\n\n/**\n * Core x402 protocol server for resource protection\n * Transport-agnostic implementation of the x402 payment protocol\n */\nexport class x402ResourceServer {\n private facilitatorClients: FacilitatorClient[];\n private registeredServerSchemes: Map<string, Map<string, SchemeNetworkServer>> = new Map();\n private supportedResponsesMap: Map<number, Map<string, Map<string, SupportedResponse>>> =\n new Map();\n private facilitatorClientsMap: Map<number, Map<string, Map<string, FacilitatorClient>>> =\n new Map();\n private registeredExtensions: Map<string, ResourceServerExtension> = new Map();\n\n private beforeVerifyHooks: BeforeVerifyHook[] = [];\n private afterVerifyHooks: AfterVerifyHook[] = [];\n private onVerifyFailureHooks: OnVerifyFailureHook[] = [];\n private beforeSettleHooks: BeforeSettleHook[] = [];\n private afterSettleHooks: AfterSettleHook[] = [];\n private onSettleFailureHooks: OnSettleFailureHook[] = [];\n\n /**\n * Creates a new x402ResourceServer instance.\n *\n * @param facilitatorClients - Optional facilitator client(s) for payment processing\n */\n constructor(facilitatorClients?: FacilitatorClient | FacilitatorClient[]) {\n // Normalize facilitator clients to array\n if (!facilitatorClients) {\n // No clients provided, create a default HTTP client\n this.facilitatorClients = [new HTTPFacilitatorClient()];\n } else if (Array.isArray(facilitatorClients)) {\n // Array of clients provided\n this.facilitatorClients =\n facilitatorClients.length > 0 ? facilitatorClients : [new HTTPFacilitatorClient()];\n } else {\n // Single client provided\n this.facilitatorClients = [facilitatorClients];\n }\n }\n\n /**\n * Register a scheme/network server implementation.\n *\n * @param network - The network identifier\n * @param server - The scheme/network server implementation\n * @returns The x402ResourceServer instance for chaining\n */\n register(network: Network, server: SchemeNetworkServer): x402ResourceServer {\n if (!this.registeredServerSchemes.has(network)) {\n this.registeredServerSchemes.set(network, new Map());\n }\n\n const serverByScheme = this.registeredServerSchemes.get(network)!;\n if (!serverByScheme.has(server.scheme)) {\n serverByScheme.set(server.scheme, server);\n }\n\n return this;\n }\n\n /**\n * Check if a scheme is registered for a given network.\n *\n * @param network - The network identifier\n * @param scheme - The payment scheme name\n * @returns True if the scheme is registered for the network, false otherwise\n */\n hasRegisteredScheme(network: Network, scheme: string): boolean {\n return !!findByNetworkAndScheme(this.registeredServerSchemes, scheme, network);\n }\n\n /**\n * Registers a resource service extension that can enrich extension declarations.\n *\n * @param extension - The extension to register\n * @returns The x402ResourceServer instance for chaining\n */\n registerExtension(extension: ResourceServerExtension): this {\n this.registeredExtensions.set(extension.key, extension);\n return this;\n }\n\n /**\n * Enriches declared extensions using registered extension hooks.\n *\n * @param declaredExtensions - Extensions declared on the route\n * @param transportContext - Transport-specific context (HTTP, A2A, MCP, etc.)\n * @returns Enriched extensions map\n */\n enrichExtensions(\n declaredExtensions: Record<string, unknown>,\n transportContext: unknown,\n ): Record<string, unknown> {\n const enriched: Record<string, unknown> = {};\n\n for (const [key, declaration] of Object.entries(declaredExtensions)) {\n const extension = this.registeredExtensions.get(key);\n\n if (extension?.enrichDeclaration) {\n enriched[key] = extension.enrichDeclaration(declaration, transportContext);\n } else {\n enriched[key] = declaration;\n }\n }\n\n return enriched;\n }\n\n /**\n * Register a hook to execute before payment verification.\n * Can abort verification by returning { abort: true, reason: string }\n *\n * @param hook - The hook function to register\n * @returns The x402ResourceServer instance for chaining\n */\n onBeforeVerify(hook: BeforeVerifyHook): x402ResourceServer {\n this.beforeVerifyHooks.push(hook);\n return this;\n }\n\n /**\n * Register a hook to execute after successful payment verification.\n *\n * @param hook - The hook function to register\n * @returns The x402ResourceServer instance for chaining\n */\n onAfterVerify(hook: AfterVerifyHook): x402ResourceServer {\n this.afterVerifyHooks.push(hook);\n return this;\n }\n\n /**\n * Register a hook to execute when payment verification fails.\n * Can recover from failure by returning { recovered: true, result: VerifyResponse }\n *\n * @param hook - The hook function to register\n * @returns The x402ResourceServer instance for chaining\n */\n onVerifyFailure(hook: OnVerifyFailureHook): x402ResourceServer {\n this.onVerifyFailureHooks.push(hook);\n return this;\n }\n\n /**\n * Register a hook to execute before payment settlement.\n * Can abort settlement by returning { abort: true, reason: string }\n *\n * @param hook - The hook function to register\n * @returns The x402ResourceServer instance for chaining\n */\n onBeforeSettle(hook: BeforeSettleHook): x402ResourceServer {\n this.beforeSettleHooks.push(hook);\n return this;\n }\n\n /**\n * Register a hook to execute after successful payment settlement.\n *\n * @param hook - The hook function to register\n * @returns The x402ResourceServer instance for chaining\n */\n onAfterSettle(hook: AfterSettleHook): x402ResourceServer {\n this.afterSettleHooks.push(hook);\n return this;\n }\n\n /**\n * Register a hook to execute when payment settlement fails.\n * Can recover from failure by returning { recovered: true, result: SettleResponse }\n *\n * @param hook - The hook function to register\n * @returns The x402ResourceServer instance for chaining\n */\n onSettleFailure(hook: OnSettleFailureHook): x402ResourceServer {\n this.onSettleFailureHooks.push(hook);\n return this;\n }\n\n /**\n * Initialize by fetching supported kinds from all facilitators\n * Creates mappings for supported responses and facilitator clients\n * Earlier facilitators in the array get precedence\n */\n async initialize(): Promise<void> {\n // Clear existing mappings\n this.supportedResponsesMap.clear();\n this.facilitatorClientsMap.clear();\n\n // Fetch supported kinds from all facilitator clients\n // Process in order to give precedence to earlier facilitators\n for (const facilitatorClient of this.facilitatorClients) {\n try {\n const supported = await facilitatorClient.getSupported();\n\n // Process each supported kind (now flat array with version in each element)\n for (const kind of supported.kinds) {\n const x402Version = kind.x402Version;\n\n // Get or create version map for supported responses\n if (!this.supportedResponsesMap.has(x402Version)) {\n this.supportedResponsesMap.set(x402Version, new Map());\n }\n const responseVersionMap = this.supportedResponsesMap.get(x402Version)!;\n\n // Get or create version map for facilitator clients\n if (!this.facilitatorClientsMap.has(x402Version)) {\n this.facilitatorClientsMap.set(x402Version, new Map());\n }\n const clientVersionMap = this.facilitatorClientsMap.get(x402Version)!;\n\n // Get or create network map for responses\n if (!responseVersionMap.has(kind.network)) {\n responseVersionMap.set(kind.network, new Map());\n }\n const responseNetworkMap = responseVersionMap.get(kind.network)!;\n\n // Get or create network map for clients\n if (!clientVersionMap.has(kind.network)) {\n clientVersionMap.set(kind.network, new Map());\n }\n const clientNetworkMap = clientVersionMap.get(kind.network)!;\n\n // Only store if not already present (gives precedence to earlier facilitators)\n if (!responseNetworkMap.has(kind.scheme)) {\n responseNetworkMap.set(kind.scheme, supported);\n clientNetworkMap.set(kind.scheme, facilitatorClient);\n }\n }\n } catch (error) {\n // Log error but continue with other facilitators\n console.warn(`Failed to fetch supported kinds from facilitator: ${error}`);\n }\n }\n }\n\n /**\n * Get supported kind for a specific version, network, and scheme\n *\n * @param x402Version - The x402 version\n * @param network - The network identifier\n * @param scheme - The payment scheme\n * @returns The supported kind or undefined if not found\n */\n getSupportedKind(\n x402Version: number,\n network: Network,\n scheme: string,\n ): SupportedKind | undefined {\n const versionMap = this.supportedResponsesMap.get(x402Version);\n if (!versionMap) return undefined;\n\n const supportedResponse = findByNetworkAndScheme(versionMap, scheme, network);\n if (!supportedResponse) return undefined;\n\n // Find the specific kind from the response (kinds are flat array with version in each element)\n return supportedResponse.kinds.find(\n kind =>\n kind.x402Version === x402Version && kind.network === network && kind.scheme === scheme,\n );\n }\n\n /**\n * Get facilitator extensions for a specific version, network, and scheme\n *\n * @param x402Version - The x402 version\n * @param network - The network identifier\n * @param scheme - The payment scheme\n * @returns The facilitator extensions or empty array if not found\n */\n getFacilitatorExtensions(x402Version: number, network: Network, scheme: string): string[] {\n const versionMap = this.supportedResponsesMap.get(x402Version);\n if (!versionMap) return [];\n\n const supportedResponse = findByNetworkAndScheme(versionMap, scheme, network);\n return supportedResponse?.extensions || [];\n }\n\n /**\n * Build payment requirements for a protected resource\n *\n * @param resourceConfig - Configuration for the protected resource\n * @returns Array of payment requirements\n */\n async buildPaymentRequirements(resourceConfig: ResourceConfig): Promise<PaymentRequirements[]> {\n const requirements: PaymentRequirements[] = [];\n\n // Find the matching server implementation\n const scheme = resourceConfig.scheme;\n const SchemeNetworkServer = findByNetworkAndScheme(\n this.registeredServerSchemes,\n scheme,\n resourceConfig.network,\n );\n\n if (!SchemeNetworkServer) {\n // Fallback to placeholder implementation if no server registered\n // TODO: Remove this fallback once implementations are registered\n console.warn(\n `No server implementation registered for scheme: ${scheme}, network: ${resourceConfig.network}`,\n );\n return requirements;\n }\n\n // Find the matching supported kind from facilitator\n const supportedKind = this.getSupportedKind(\n x402Version,\n resourceConfig.network,\n SchemeNetworkServer.scheme,\n );\n\n if (!supportedKind) {\n throw new Error(\n `Facilitator does not support ${SchemeNetworkServer.scheme} on ${resourceConfig.network}. ` +\n `Make sure to call initialize() to fetch supported kinds from facilitators.`,\n );\n }\n\n // Get facilitator extensions for this combination\n const facilitatorExtensions = this.getFacilitatorExtensions(\n x402Version,\n resourceConfig.network,\n SchemeNetworkServer.scheme,\n );\n\n // Parse the price using the scheme's price parser\n const parsedPrice = await SchemeNetworkServer.parsePrice(\n resourceConfig.price,\n resourceConfig.network,\n );\n\n // Build base payment requirements from resource config\n const baseRequirements: PaymentRequirements = {\n scheme: SchemeNetworkServer.scheme,\n network: resourceConfig.network,\n amount: parsedPrice.amount,\n asset: parsedPrice.asset,\n payTo: resourceConfig.payTo,\n maxTimeoutSeconds: resourceConfig.maxTimeoutSeconds || 300, // Default 5 minutes\n extra: {\n ...parsedPrice.extra,\n },\n };\n\n // Delegate to the implementation for scheme-specific enhancements\n // Note: enhancePaymentRequirements expects x402Version in the kind, so we add it back\n const requirement = await SchemeNetworkServer.enhancePaymentRequirements(\n baseRequirements,\n {\n ...supportedKind,\n x402Version,\n },\n facilitatorExtensions,\n );\n\n requirements.push(requirement);\n return requirements;\n }\n\n /**\n * Build payment requirements from multiple payment options\n * This method handles resolving dynamic payTo/price functions and builds requirements for each option\n *\n * @param paymentOptions - Array of payment options to convert\n * @param context - HTTP request context for resolving dynamic functions\n * @returns Array of payment requirements (one per option)\n */\n async buildPaymentRequirementsFromOptions<TContext = unknown>(\n paymentOptions: Array<{\n scheme: string;\n payTo: string | ((context: TContext) => string | Promise<string>);\n price: Price | ((context: TContext) => Price | Promise<Price>);\n network: Network;\n maxTimeoutSeconds?: number;\n }>,\n context: TContext,\n ): Promise<PaymentRequirements[]> {\n const allRequirements: PaymentRequirements[] = [];\n\n for (const option of paymentOptions) {\n // Resolve dynamic payTo and price if they are functions\n const resolvedPayTo =\n typeof option.payTo === \"function\" ? await option.payTo(context) : option.payTo;\n const resolvedPrice =\n typeof option.price === \"function\" ? await option.price(context) : option.price;\n\n const resourceConfig: ResourceConfig = {\n scheme: option.scheme,\n payTo: resolvedPayTo,\n price: resolvedPrice,\n network: option.network,\n maxTimeoutSeconds: option.maxTimeoutSeconds,\n };\n\n // Use existing buildPaymentRequirements for each option\n const requirements = await this.buildPaymentRequirements(resourceConfig);\n allRequirements.push(...requirements);\n }\n\n return allRequirements;\n }\n\n /**\n * Create a payment required response\n *\n * @param requirements - Payment requirements\n * @param resourceInfo - Resource information\n * @param error - Error message\n * @param extensions - Optional extensions\n * @returns Payment required response object\n */\n createPaymentRequiredResponse(\n requirements: PaymentRequirements[],\n resourceInfo: ResourceInfo,\n error?: string,\n extensions?: Record<string, unknown>,\n ): PaymentRequired {\n // V2 response with resource at top level\n const response: PaymentRequired = {\n x402Version: 2,\n error,\n resource: resourceInfo,\n accepts: requirements as PaymentRequirements[],\n };\n\n // Add extensions if provided\n if (extensions && Object.keys(extensions).length > 0) {\n response.extensions = extensions;\n }\n\n return response;\n }\n\n /**\n * Verify a payment against requirements\n *\n * @param paymentPayload - The payment payload to verify\n * @param requirements - The payment requirements\n * @returns Verification response\n */\n async verifyPayment(\n paymentPayload: PaymentPayload,\n requirements: PaymentRequirements,\n ): Promise<VerifyResponse> {\n const context: VerifyContext = {\n paymentPayload,\n requirements,\n };\n\n // Execute beforeVerify hooks\n for (const hook of this.beforeVerifyHooks) {\n const result = await hook(context);\n if (result && \"abort\" in result && result.abort) {\n return {\n isValid: false,\n invalidReason: result.reason,\n };\n }\n }\n\n try {\n // Find the facilitator that supports this payment type\n const facilitatorClient = this.getFacilitatorClient(\n paymentPayload.x402Version,\n requirements.network,\n requirements.scheme,\n );\n\n let verifyResult: VerifyResponse;\n\n if (!facilitatorClient) {\n // Fallback: try all facilitators if no specific support found\n let lastError: Error | undefined;\n\n for (const client of this.facilitatorClients) {\n try {\n verifyResult = await client.verify(paymentPayload, requirements);\n break;\n } catch (error) {\n lastError = error as Error;\n }\n }\n\n if (!verifyResult!) {\n throw (\n lastError ||\n new Error(\n `No facilitator supports ${requirements.scheme} on ${requirements.network} for v${paymentPayload.x402Version}`,\n )\n );\n }\n } else {\n // Use the specific facilitator that supports this payment\n verifyResult = await facilitatorClient.verify(paymentPayload, requirements);\n }\n\n // Execute afterVerify hooks\n const resultContext: VerifyResultContext = {\n ...context,\n result: verifyResult,\n };\n\n for (const hook of this.afterVerifyHooks) {\n await hook(resultContext);\n }\n\n return verifyResult;\n } catch (error) {\n const failureContext: VerifyFailureContext = {\n ...context,\n error: error as Error,\n };\n\n // Execute onVerifyFailure hooks\n for (const hook of this.onVerifyFailureHooks) {\n const result = await hook(failureContext);\n if (result && \"recovered\" in result && result.recovered) {\n return result.result;\n }\n }\n\n throw error;\n }\n }\n\n /**\n * Settle a verified payment\n *\n * @param paymentPayload - The payment payload to settle\n * @param requirements - The payment requirements\n * @returns Settlement response\n */\n async settlePayment(\n paymentPayload: PaymentPayload,\n requirements: PaymentRequirements,\n ): Promise<SettleResponse> {\n const context: SettleContext = {\n paymentPayload,\n requirements,\n };\n\n // Execute beforeSettle hooks\n for (const hook of this.beforeSettleHooks) {\n const result = await hook(context);\n if (result && \"abort\" in result && result.abort) {\n throw new Error(`Settlement aborted: ${result.reason}`);\n }\n }\n\n try {\n // Find the facilitator that supports this payment type\n const facilitatorClient = this.getFacilitatorClient(\n paymentPayload.x402Version,\n requirements.network,\n requirements.scheme,\n );\n\n let settleResult: SettleResponse;\n\n if (!facilitatorClient) {\n // Fallback: try all facilitators if no specific support found\n let lastError: Error | undefined;\n\n for (const client of this.facilitatorClients) {\n try {\n settleResult = await client.settle(paymentPayload, requirements);\n break;\n } catch (error) {\n lastError = error as Error;\n }\n }\n\n if (!settleResult!) {\n throw (\n lastError ||\n new Error(\n `No facilitator supports ${requirements.scheme} on ${requirements.network} for v${paymentPayload.x402Version}`,\n )\n );\n }\n } else {\n // Use the specific facilitator that supports this payment\n settleResult = await facilitatorClient.settle(paymentPayload, requirements);\n }\n\n // Execute afterSettle hooks\n const resultContext: SettleResultContext = {\n ...context,\n result: settleResult,\n };\n\n for (const hook of this.afterSettleHooks) {\n await hook(resultContext);\n }\n\n return settleResult;\n } catch (error) {\n const failureContext: SettleFailureContext = {\n ...context,\n error: error as Error,\n };\n\n // Execute onSettleFailure hooks\n for (const hook of this.onSettleFailureHooks) {\n const result = await hook(failureContext);\n if (result && \"recovered\" in result && result.recovered) {\n return result.result;\n }\n }\n\n throw error;\n }\n }\n\n /**\n * Find matching payment requirements for a payment\n *\n * @param availableRequirements - Array of available payment requirements\n * @param paymentPayload - The payment payload\n * @returns Matching payment requirements or undefined\n */\n findMatchingRequirements(\n availableRequirements: PaymentRequirements[],\n paymentPayload: PaymentPayload,\n ): PaymentRequirements | undefined {\n switch (paymentPayload.x402Version) {\n case 2:\n // For v2, match by accepted requirements\n return availableRequirements.find(paymentRequirements =>\n deepEqual(paymentRequirements, paymentPayload.accepted),\n );\n case 1:\n // For v1, match by scheme and network\n return availableRequirements.find(\n req =>\n req.scheme === paymentPayload.accepted.scheme &&\n req.network === paymentPayload.accepted.network,\n );\n default:\n throw new Error(\n `Unsupported x402 version: ${(paymentPayload as PaymentPayload).x402Version}`,\n );\n }\n }\n\n /**\n * Process a payment request\n *\n * @param paymentPayload - Optional payment payload if provided\n * @param resourceConfig - Configuration for the protected resource\n * @param resourceInfo - Information about the resource being accessed\n * @param extensions - Optional extensions to include in the response\n * @returns Processing result\n */\n async processPaymentRequest(\n paymentPayload: PaymentPayload | null,\n resourceConfig: ResourceConfig,\n resourceInfo: ResourceInfo,\n extensions?: Record<string, unknown>,\n ): Promise<{\n success: boolean;\n requiresPayment?: PaymentRequired;\n verificationResult?: VerifyResponse;\n settlementResult?: SettleResponse;\n error?: string;\n }> {\n const requirements = await this.buildPaymentRequirements(resourceConfig);\n\n if (!paymentPayload) {\n return {\n success: false,\n requiresPayment: this.createPaymentRequiredResponse(\n requirements,\n resourceInfo,\n \"Payment required\",\n extensions,\n ),\n };\n }\n\n // Find matching requirements\n const matchingRequirements = this.findMatchingRequirements(requirements, paymentPayload);\n if (!matchingRequirements) {\n return {\n success: false,\n requiresPayment: this.createPaymentRequiredResponse(\n requirements,\n resourceInfo,\n \"No matching payment requirements found\",\n extensions,\n ),\n };\n }\n\n // Verify payment\n const verificationResult = await this.verifyPayment(paymentPayload, matchingRequirements);\n if (!verificationResult.isValid) {\n return {\n success: false,\n error: verificationResult.invalidReason,\n verificationResult,\n };\n }\n\n // Payment verified, ready for settlement\n return {\n success: true,\n verificationResult,\n };\n }\n\n /**\n * Get facilitator client for a specific version, network, and scheme\n *\n * @param x402Version - The x402 version\n * @param network - The network identifier\n * @param scheme - The payment scheme\n * @returns The facilitator client or undefined if not found\n */\n private getFacilitatorClient(\n x402Version: number,\n network: Network,\n scheme: string,\n ): FacilitatorClient | undefined {\n const versionMap = this.facilitatorClientsMap.get(x402Version);\n if (!versionMap) return undefined;\n\n // Use findByNetworkAndScheme for pattern matching\n return findByNetworkAndScheme(versionMap, scheme, network);\n }\n}\n\nexport default x402ResourceServer;\n"],"mappings":";;;;;;;;;;;;;;;;AA4FO,IAAM,qBAAN,MAAyB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAqB9B,YAAY,oBAA8D;AAnB1E,SAAQ,0BAAyE,oBAAI,IAAI;AACzF,SAAQ,wBACN,oBAAI,IAAI;AACV,SAAQ,wBACN,oBAAI,IAAI;AACV,SAAQ,uBAA6D,oBAAI,IAAI;AAE7E,SAAQ,oBAAwC,CAAC;AACjD,SAAQ,mBAAsC,CAAC;AAC/C,SAAQ,uBAA8C,CAAC;AACvD,SAAQ,oBAAwC,CAAC;AACjD,SAAQ,mBAAsC,CAAC;AAC/C,SAAQ,uBAA8C,CAAC;AASrD,QAAI,CAAC,oBAAoB;AAEvB,WAAK,qBAAqB,CAAC,IAAI,sBAAsB,CAAC;AAAA,IACxD,WAAW,MAAM,QAAQ,kBAAkB,GAAG;AAE5C,WAAK,qBACH,mBAAmB,SAAS,IAAI,qBAAqB,CAAC,IAAI,sBAAsB,CAAC;AAAA,IACrF,OAAO;AAEL,WAAK,qBAAqB,CAAC,kBAAkB;AAAA,IAC/C;AAAA,EACF;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EASA,SAAS,SAAkB,QAAiD;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