@middy/http-x402 8.0.0-alpha.2 → 8.0.0-rc.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 (3) hide show
  1. package/index.d.ts +6 -2
  2. package/index.js +189 -50
  3. package/package.json +4 -4
package/index.d.ts CHANGED
@@ -11,12 +11,16 @@ export type RequestEvent = APIGatewayEvent | APIGatewayProxyEventV2;
11
11
 
12
12
  interface BaseOptions {
13
13
  FacilitatorClient?: new (config: {
14
- url?: string;
14
+ url: string;
15
15
  }) => {
16
16
  verify(payload: unknown, requirements: unknown): Promise<unknown>;
17
17
  settle(payload: unknown, requirements: unknown): Promise<unknown>;
18
18
  };
19
- facilitatorUrl?: string;
19
+ /**
20
+ * URL of the facilitator that verifies and settles payments. Required: the
21
+ * facilitator decides whether a payment is valid, so there is no default.
22
+ */
23
+ facilitatorUrl: string;
20
24
  versions?: readonly (1 | 2)[];
21
25
  price?: number | string;
22
26
  amount?: string;
package/index.js CHANGED
@@ -1,14 +1,18 @@
1
1
  // Copyright 2017 - 2026 will Farrell, Luciano Mammino, and Middy contributors.
2
2
  // SPDX-License-Identifier: MIT
3
- import { normalizeHttpResponse, validateOptions } from "@middy/util";
4
- import { HTTPFacilitatorClient } from "@x402/core/http";
3
+ import { HttpError, normalizeHttpResponse, validateOptions } from "@middy/util";
4
+ import {
5
+ FacilitatorResponseError,
6
+ FacilitatorTimeoutError,
7
+ HTTPFacilitatorClient,
8
+ } from "@x402/core/http";
5
9
 
6
10
  const name = "http-x402";
7
11
  const pkg = `@middy/${name}`;
8
12
 
9
13
  const defaults = {
10
14
  FacilitatorClient: HTTPFacilitatorClient,
11
- facilitatorUrl: "https://x402.org/facilitator",
15
+ facilitatorUrl: undefined,
12
16
  // v1 acceptance is opt-in (smaller attack surface, no legacy facilitator
13
17
  // path): pass `versions: [1, 2]` to also accept the X-PAYMENT v1 flow.
14
18
  versions: [2],
@@ -24,12 +28,95 @@ const defaults = {
24
28
  human: undefined,
25
29
  };
26
30
 
31
+ const textSchema = {
32
+ type: "string",
33
+ maxLength: 1024,
34
+ pattern: /^[\p{L}\p{N}\p{P}\p{S} ]*$/u,
35
+ };
36
+
37
+ const visibleSchema = {
38
+ type: "string",
39
+ maxLength: 1024,
40
+ pattern: /^[\x21-\x7E]+$/u,
41
+ };
42
+
43
+ const decimalSchema = { type: "string", maxLength: 1024, pattern: /^\d+$/u };
44
+
45
+ const httpsUrlSchema = {
46
+ type: "string",
47
+ maxLength: 1024,
48
+ pattern: /^https:\/\/[\x21-\x7E]+$/u,
49
+ };
50
+
51
+ // The `extra` keys of the `exact` scheme on each network, leaving out
52
+ // `paymentFlow` and `assetTransferMethod`, which select flows this middleware
53
+ // does not run.
54
+ // https://github.com/coinbase/x402/tree/0e6e8c55d86b4f14234fb6e49a4052074fb93e57/specs/schemes/exact
55
+ const extraSchema = {
56
+ type: "object",
57
+ properties: {
58
+ // EVM (EIP-3009) and Casper: the EIP-712 domain name and version.
59
+ name: { ...textSchema, minLength: 1 },
60
+ version: { ...textSchema, minLength: 1 },
61
+ // SVM, Algorand, Aptos, Concordium, Hedera and Starknet.
62
+ feePayer: visibleSchema,
63
+ // SVM: "A seller-defined UTF-8 string ... Maximum 256 bytes."
64
+ memo: { ...textSchema, maxLength: 256 },
65
+ recentBlockhash: visibleSchema,
66
+ // SVM: "as a decimal string".
67
+ lastValidBlockHeight: decimalSchema,
68
+ // Keeta.
69
+ external: visibleSchema,
70
+ // Stellar, TON, XRPL and Cardano.
71
+ areFeesSponsored: { type: "boolean" },
72
+ // Sui: the gas station URL.
73
+ gasStation: httpsUrlSchema,
74
+ // TON: an address, a base64-encoded cell and an amount of nanotons.
75
+ responseDestination: visibleSchema,
76
+ forwardPayload: {
77
+ type: "string",
78
+ maxLength: 1024,
79
+ pattern: /^[\w+/=-]+$/u,
80
+ },
81
+ forwardTonAmount: decimalSchema,
82
+ // XRPL: DestinationTag is a UInt32.
83
+ // https://xrpl.org/docs/references/protocol/transactions/types/payment
84
+ invoiceId: { ...textSchema, minLength: 1 },
85
+ destinationTag: { type: "integer", minimum: 0, maximum: 4294967295 },
86
+ issuer: visibleSchema,
87
+ // Cardano: "`confirmationPolicy.l1Confirmations` is an integer from `-1`
88
+ // through `20`".
89
+ confirmationPolicy: {
90
+ type: "object",
91
+ properties: {
92
+ l1Confirmations: { type: "integer", minimum: -1, maximum: 20 },
93
+ },
94
+ required: [],
95
+ additionalProperties: false,
96
+ unevaluatedProperties: false,
97
+ },
98
+ },
99
+ required: [],
100
+ additionalProperties: false,
101
+ unevaluatedProperties: false,
102
+ };
103
+
27
104
  const optionSchema = {
105
+ $schema: "https://json-schema.org/draft/2020-12/schema",
106
+ $id: "urn:middy:http-x402:options",
107
+ $defs: { Function: false },
28
108
  type: "object",
29
109
  properties: {
30
- FacilitatorClient: { instanceof: "Function" },
31
- facilitatorUrl: { type: "string" },
32
- versions: { type: "array", items: { enum: [1, 2] } },
110
+ FacilitatorClient: { $ref: "#/$defs/Function" },
111
+ facilitatorUrl: httpsUrlSchema,
112
+ versions: {
113
+ type: "array",
114
+ items: { type: "integer", enum: [1, 2] },
115
+ minItems: 1,
116
+ maxItems: 2,
117
+ uniqueItems: true,
118
+ unevaluatedItems: false,
119
+ },
33
120
  price: {
34
121
  oneOf: [
35
122
  {
@@ -37,21 +124,39 @@ const optionSchema = {
37
124
  exclusiveMinimum: 0,
38
125
  maximum: Number.MAX_SAFE_INTEGER,
39
126
  },
40
- { type: "string" },
127
+ {
128
+ type: "string",
129
+ maxLength: 1024,
130
+ pattern: /^(\d+(\.\d+)?|\.\d+)$/u,
131
+ },
41
132
  ],
42
133
  },
43
- amount: { type: "string" },
44
- decimals: { type: "integer" },
45
- network: { type: "string" },
46
- payTo: { type: "string" },
47
- asset: { type: "string" },
48
- description: { type: "string" },
49
- mimeType: { type: "string" },
50
- extra: { type: "object" },
51
- human: { instanceof: "Function" },
134
+ amount: decimalSchema,
135
+ // EIP-20: `function decimals() public view returns (uint8)`.
136
+ // https://eips.ethereum.org/EIPS/eip-20
137
+ decimals: { type: "integer", minimum: 0, maximum: 255 },
138
+ // CAIP-2: `[-a-z0-9]{3,8}` namespace, `:`, `[-_a-zA-Z0-9]{1,32}` reference.
139
+ // https://github.com/ChainAgnostic/CAIPs/blob/main/CAIPs/caip-2.md
140
+ network: {
141
+ type: "string",
142
+ maxLength: 41,
143
+ pattern: /^[-a-z0-9]{3,8}:[-_a-zA-Z0-9]{1,32}$/u,
144
+ },
145
+ payTo: visibleSchema,
146
+ asset: visibleSchema,
147
+ description: textSchema,
148
+ // RFC 6838 section 4.2: type and subtype names are at most 127 characters.
149
+ mimeType: {
150
+ type: "string",
151
+ maxLength: 255,
152
+ pattern: /^[\w.+-]{1,127}\/[\w.+-]{1,127}$/u,
153
+ },
154
+ extra: extraSchema,
155
+ human: { $ref: "#/$defs/Function" },
52
156
  },
53
- required: ["payTo", "asset"],
157
+ required: ["payTo", "asset", "facilitatorUrl"],
54
158
  additionalProperties: false,
159
+ unevaluatedProperties: false,
55
160
  };
56
161
 
57
162
  export const httpX402ValidateOptions = (options) =>
@@ -75,6 +180,14 @@ const httpX402Middleware = (opts = {}) => {
75
180
  human,
76
181
  } = options;
77
182
 
183
+ // @x402/core's HTTPFacilitatorClient falls back to its default facilitator,
184
+ // https://x402.org/facilitator, when `url` is empty (@x402/core 2.29.0).
185
+ if (typeof facilitatorUrl !== "string" || facilitatorUrl === "") {
186
+ throw new Error(`${pkg} facilitatorUrl is required`, {
187
+ cause: { package: pkg },
188
+ });
189
+ }
190
+
78
191
  const v1Enabled = versions.includes(1);
79
192
  const v2Enabled = versions.includes(2);
80
193
  if (!v1Enabled && !v2Enabled) {
@@ -187,6 +300,17 @@ const httpX402Middleware = (opts = {}) => {
187
300
  return albMultiValueResponse(request);
188
301
  };
189
302
 
303
+ const verifyPayment = async (payload, paymentRequirements) => {
304
+ try {
305
+ return await facilitator.verify(payload, paymentRequirements);
306
+ } catch (error) {
307
+ if (error instanceof FacilitatorResponseError) {
308
+ throw exposedFacilitatorGatewayError("verify", error);
309
+ }
310
+ return { isValid: false, invalidReason: verifyReason(error) };
311
+ }
312
+ };
313
+
190
314
  const httpX402V2Before = async (request, paymentHeader) => {
191
315
  // An undecodable header is treated the same as no payment at all.
192
316
  const payload = decodeHeader(paymentHeader);
@@ -204,12 +328,7 @@ const httpX402Middleware = (opts = {}) => {
204
328
  );
205
329
  }
206
330
 
207
- let verifyResult;
208
- try {
209
- verifyResult = await facilitator.verify(payload, requirements);
210
- } catch (error) {
211
- return respondPaymentRequired(request, verifyReason(error));
212
- }
331
+ const verifyResult = await verifyPayment(payload, requirements);
213
332
  if (!verifyResult.isValid) {
214
333
  return respondPaymentRequired(request, verifyResult.invalidReason);
215
334
  }
@@ -240,12 +359,7 @@ const httpX402Middleware = (opts = {}) => {
240
359
  }
241
360
 
242
361
  const requirementsV1 = buildRequirementsV1(request.event);
243
- let verifyResult;
244
- try {
245
- verifyResult = await facilitator.verify(payload, requirementsV1);
246
- } catch (error) {
247
- return respondPaymentRequiredV1(request, verifyReason(error));
248
- }
362
+ const verifyResult = await verifyPayment(payload, requirementsV1);
249
363
  if (!verifyResult.isValid) {
250
364
  return respondPaymentRequiredV1(request, verifyResult.invalidReason);
251
365
  }
@@ -326,27 +440,33 @@ const httpX402Middleware = (opts = {}) => {
326
440
  // PAYMENT-RESPONSE.
327
441
  const responseHeader =
328
442
  payload.x402Version === 1 ? "X-PAYMENT-RESPONSE" : "PAYMENT-RESPONSE";
329
- let settleResult;
330
- try {
331
- settleResult = await facilitator.settle(payload, storedRequirements);
332
- } catch (error) {
333
- const settleResponse = {
334
- success: false,
335
- errorReason: settleReason(error),
336
- // settlement_pending MUST carry the broadcast hash so the client
337
- // can reconcile on chain; forward it when the thrown error has one.
338
- transaction:
339
- typeof error?.transaction === "string" ? error.transaction : "",
340
- network: storedRequirements.network,
341
- };
342
- request.response = settlementRefused(
343
- payload,
344
- responseHeader,
345
- settleResponse,
346
- request.response,
347
- multiValue,
348
- );
349
- return;
443
+ const settlePayment = async () => {
444
+ try {
445
+ return await facilitator.settle(payload, storedRequirements);
446
+ } catch (error) {
447
+ if (error instanceof FacilitatorResponseError) {
448
+ throw exposedFacilitatorGatewayError("settle", error);
449
+ }
450
+ return {
451
+ success: false,
452
+ errorReason: settleReason(error),
453
+ // settlement_pending MUST carry the broadcast hash so the client
454
+ // can reconcile on chain; forward it when the thrown error has one.
455
+ transaction:
456
+ typeof error?.transaction === "string" ? error.transaction : "",
457
+ network: storedRequirements.network,
458
+ };
459
+ }
460
+ };
461
+
462
+ let settleResult = await settlePayment();
463
+ // A `settlement_pending` failure with a transaction hash was broadcast but
464
+ // not confirmed. Settling the same payload again lets the facilitator
465
+ // reconcile against that transaction instead of broadcasting another.
466
+ // @x402/core's x402ResourceServer retries exactly once
467
+ // (`settleWithPendingRetry`, @x402/core 2.29.0).
468
+ if (isSettlementPending(settleResult)) {
469
+ settleResult = await settlePayment();
350
470
  }
351
471
 
352
472
  if (!settleResult.success) {
@@ -500,6 +620,25 @@ const settleReason = (error) =>
500
620
  ? error.errorReason
501
621
  : "unexpected_settle_error";
502
622
 
623
+ // @x402/core raises `FacilitatorResponseError` when the facilitator's answer
624
+ // cannot be read, and its subclass `FacilitatorTimeoutError` when the answer
625
+ // did not come in time. The reference server rethrows both instead of
626
+ // answering 402 (@x402/core 2.29.0, src/http/x402HTTPResourceServer.ts,
627
+ // `processHTTPRequest` and `processSettlement`).
628
+ const exposedFacilitatorGatewayError = (operation, error) =>
629
+ new HttpError(error instanceof FacilitatorTimeoutError ? 504 : 502, {
630
+ expose: true,
631
+ cause: {
632
+ package: pkg,
633
+ data: { reason: `Facilitator ${operation} failed: ${error.message}` },
634
+ },
635
+ });
636
+
637
+ const isSettlementPending = (settleResult) =>
638
+ !settleResult.success &&
639
+ settleResult.errorReason === "settlement_pending" &&
640
+ Boolean(settleResult.transaction);
641
+
503
642
  const integerPattern = /^[0-9]+$/;
504
643
 
505
644
  // Render a finite number as a plain decimal string. `String(n)` uses exponential
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@middy/http-x402",
3
- "version": "8.0.0-alpha.2",
3
+ "version": "8.0.0-rc.0",
4
4
  "description": "x402 payment middleware for the middy framework",
5
5
  "type": "module",
6
6
  "engines": {
@@ -65,7 +65,7 @@
65
65
  },
66
66
  "peerDependencies": {
67
67
  "@x402/core": "^2.28.0",
68
- "@middy/core": "8.0.0-alpha.2",
68
+ "@middy/core": "8.0.0-rc.0",
69
69
  "@types/aws-lambda": "^8.0.0"
70
70
  },
71
71
  "peerDependenciesMeta": {
@@ -77,10 +77,10 @@
77
77
  }
78
78
  },
79
79
  "dependencies": {
80
- "@middy/util": "8.0.0-alpha.2"
80
+ "@middy/util": "8.0.0-rc.0"
81
81
  },
82
82
  "devDependencies": {
83
- "@middy/core": "8.0.0-alpha.2",
83
+ "@middy/core": "8.0.0-rc.0",
84
84
  "@types/aws-lambda": "^8.0.0",
85
85
  "@types/node": "^24.0.0",
86
86
  "@x402/core": "^2.28.0"