@middy/http-x402 7.7.4 → 7.9.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 (3) hide show
  1. package/index.d.ts +15 -4
  2. package/index.js +243 -46
  3. package/package.json +3 -3
package/index.d.ts CHANGED
@@ -1,8 +1,11 @@
1
1
  // Copyright 2017 - 2026 will Farrell, Luciano Mammino, and Middy contributors.
2
2
  // SPDX-License-Identifier: MIT
3
3
  import type middy from "@middy/core";
4
+ import type { APIGatewayEvent, APIGatewayProxyEventV2 } from "aws-lambda";
4
5
 
5
- export interface Options {
6
+ export type RequestEvent = APIGatewayEvent | APIGatewayProxyEventV2;
7
+
8
+ interface BaseOptions {
6
9
  FacilitatorClient?: new (config: {
7
10
  url?: string;
8
11
  }) => {
@@ -10,17 +13,25 @@ export interface Options {
10
13
  settle(payload: unknown, requirements: unknown): Promise<unknown>;
11
14
  };
12
15
  facilitatorUrl?: string;
13
- price: number;
16
+ versions?: readonly (1 | 2)[];
17
+ price?: number | string;
18
+ amount?: string;
14
19
  decimals?: number;
15
20
  network?: string;
16
21
  payTo: string;
17
22
  asset: string;
18
23
  description?: string;
19
24
  mimeType?: string;
20
- human?: (request: middy.Request) => boolean;
25
+ extra?: Record<string, unknown>;
26
+ human?: (request: middy.Request<RequestEvent>) => boolean;
21
27
  }
22
28
 
23
- declare function httpX402(options: Options): middy.MiddlewareObj;
29
+ export type Options = BaseOptions &
30
+ ({ price: number | string } | { amount: string });
31
+
32
+ declare function httpX402<EventType extends RequestEvent = RequestEvent>(
33
+ options: Options,
34
+ ): middy.MiddlewareObj<EventType, unknown, Error>;
24
35
 
25
36
  export declare function httpX402ValidateOptions(
26
37
  options?: Record<string, unknown>,
package/index.js CHANGED
@@ -9,6 +9,9 @@ const pkg = `@middy/${name}`;
9
9
  const defaults = {
10
10
  FacilitatorClient: HTTPFacilitatorClient,
11
11
  facilitatorUrl: "https://x402.org/facilitator",
12
+ // TODO remove in v8: drop 1 from the default versions so v1 acceptance
13
+ // becomes opt-in (smaller attack surface, no legacy facilitator path).
14
+ versions: [1, 2],
12
15
  price: undefined,
13
16
  amount: undefined,
14
17
  decimals: 6,
@@ -17,6 +20,7 @@ const defaults = {
17
20
  asset: undefined,
18
21
  description: "",
19
22
  mimeType: "application/json",
23
+ extra: undefined,
20
24
  human: undefined,
21
25
  };
22
26
 
@@ -25,6 +29,7 @@ const optionSchema = {
25
29
  properties: {
26
30
  FacilitatorClient: { instanceof: "Function" },
27
31
  facilitatorUrl: { type: "string" },
32
+ versions: { type: "array", items: { enum: [1, 2] } },
28
33
  price: {
29
34
  oneOf: [{ type: "number", exclusiveMinimum: 0 }, { type: "string" }],
30
35
  },
@@ -35,6 +40,7 @@ const optionSchema = {
35
40
  asset: { type: "string" },
36
41
  description: { type: "string" },
37
42
  mimeType: { type: "string" },
43
+ extra: { type: "object" },
38
44
  human: { instanceof: "Function" },
39
45
  },
40
46
  required: ["payTo", "asset"],
@@ -49,6 +55,7 @@ const httpX402Middleware = (opts = {}) => {
49
55
  const {
50
56
  FacilitatorClient,
51
57
  facilitatorUrl,
58
+ versions,
52
59
  price,
53
60
  amount: amountOverride,
54
61
  decimals,
@@ -57,72 +64,238 @@ const httpX402Middleware = (opts = {}) => {
57
64
  asset,
58
65
  description,
59
66
  mimeType,
67
+ extra,
60
68
  human,
61
69
  } = options;
62
70
 
71
+ const v1Enabled = versions.includes(1);
72
+ const v2Enabled = versions.includes(2);
73
+ if (!v1Enabled && !v2Enabled) {
74
+ throw new Error(`${pkg} versions must enable protocol version 1 or 2`, {
75
+ cause: { package: pkg },
76
+ });
77
+ }
78
+
79
+ // `extra.paymentFlow` / `extra.assetTransferMethod` select x402 payment
80
+ // flows (upfront, escrow) this middleware does not implement; it only runs
81
+ // the default authorization flow (verify before the handler, settle after).
82
+ if (
83
+ extra?.paymentFlow !== undefined ||
84
+ extra?.assetTransferMethod !== undefined
85
+ ) {
86
+ throw new Error(
87
+ `${pkg} extra.paymentFlow and extra.assetTransferMethod are not supported`,
88
+ { cause: { package: pkg } },
89
+ );
90
+ }
91
+
63
92
  const amount = toAtomicAmount(price, decimals, amountOverride);
64
- const requirements = {
93
+ // PaymentRequirements (x402 v2): advertised as an `accepts` entry in
94
+ // PAYMENT-REQUIRED responses and passed verbatim to the facilitator.
95
+ // Frozen because the one object is shared by every request of a warm
96
+ // container (challenges, facilitator calls, request.internal.x402); a
97
+ // downstream mutation would silently poison all later requests.
98
+ const requirements = Object.freeze({
65
99
  scheme: "exact",
66
100
  network,
67
101
  amount,
68
102
  asset,
69
103
  payTo,
70
104
  maxTimeoutSeconds: 60,
105
+ ...(extra !== undefined && { extra }),
106
+ });
107
+ const facilitator = new FacilitatorClient({ url: facilitatorUrl });
108
+
109
+ // x402 v2 clients echo the accepts entry they chose as `accepted`; a payment
110
+ // signed for different terms must be rejected up front.
111
+ // ponytail: `extra` is not compared here; the facilitator re-verifies the
112
+ // signature against our canonical requirements (including extra) anyway.
113
+ const matchesAccepted = (accepted) =>
114
+ typeof accepted === "object" &&
115
+ accepted !== null &&
116
+ accepted.scheme === requirements.scheme &&
117
+ accepted.network === requirements.network &&
118
+ accepted.amount === requirements.amount &&
119
+ accepted.asset === requirements.asset &&
120
+ accepted.payTo === requirements.payTo &&
121
+ accepted.maxTimeoutSeconds === requirements.maxTimeoutSeconds;
122
+
123
+ const buildPaymentRequired = (event, error) => ({
124
+ x402Version: 2,
125
+ error,
126
+ resource: {
127
+ url: buildResource(event),
128
+ description,
129
+ mimeType,
130
+ },
131
+ accepts: [requirements],
132
+ });
133
+
134
+ // Every v2 pre-handler rejection is a 402 carrying the PaymentRequired
135
+ // object in the PAYMENT-REQUIRED header (and mirrored in the body) so
136
+ // header-only clients can read the error and retry against fresh
137
+ // requirements.
138
+ const respondPaymentRequired = (request, error) => {
139
+ normalizeHttpResponse(request);
140
+ const paymentRequired = buildPaymentRequired(request.event, error);
141
+ request.response.statusCode = 402;
142
+ request.response.headers["Content-Type"] = "application/json";
143
+ request.response.headers["PAYMENT-REQUIRED"] =
144
+ encodeHeader(paymentRequired);
145
+ request.response.body = JSON.stringify(paymentRequired);
146
+ return request.response;
147
+ };
148
+
149
+ // x402 v1 PaymentRequirements: every field is required by the v1 schema,
150
+ // resource is a per-request URL string, and the amount field is named
151
+ // maxAmountRequired.
152
+ const buildRequirementsV1 = (event) => ({
153
+ scheme: "exact",
154
+ network,
155
+ maxAmountRequired: amount,
156
+ resource: buildResource(event),
71
157
  description,
72
158
  mimeType,
73
- };
74
- const facilitator = new FacilitatorClient({ url: facilitatorUrl });
159
+ outputSchema: {},
160
+ payTo,
161
+ maxTimeoutSeconds: 60,
162
+ asset,
163
+ extra: extra ?? {},
164
+ });
75
165
 
76
- const httpX402MiddlewareBefore = async (request) => {
77
- if (human?.(request)) return;
166
+ const buildPaymentRequiredV1 = (event, error) => ({
167
+ x402Version: 1,
168
+ error,
169
+ accepts: [buildRequirementsV1(event)],
170
+ });
78
171
 
79
- const headers = request.event.headers ?? {};
80
- const paymentHeader =
81
- headers["payment-signature"] ?? headers["Payment-Signature"];
172
+ // v1 clients read the challenge from the 402 response body, not a header.
173
+ const respondPaymentRequiredV1 = (request, error) => {
174
+ normalizeHttpResponse(request);
175
+ request.response.statusCode = 402;
176
+ request.response.headers["Content-Type"] = "application/json";
177
+ request.response.body = JSON.stringify(
178
+ buildPaymentRequiredV1(request.event, error),
179
+ );
180
+ return request.response;
181
+ };
82
182
 
83
- const resource = buildResource(request.event);
84
- const fullRequirements = { ...requirements, resource };
183
+ const httpX402V2Before = async (request, paymentHeader) => {
184
+ let payload;
185
+ try {
186
+ payload = decodeHeader(paymentHeader);
187
+ } catch {
188
+ // An undecodable header is treated the same as no payment at all.
189
+ return respondPaymentRequired(request, "Payment required");
190
+ }
85
191
 
86
- if (!paymentHeader) {
87
- normalizeHttpResponse(request);
88
- const paymentRequired = {
89
- x402Version: 2,
90
- error: "Payment required",
91
- accepts: [fullRequirements],
92
- };
93
- request.response.statusCode = 402;
94
- request.response.headers["Content-Type"] = "application/json";
95
- request.response.headers["PAYMENT-REQUIRED"] =
96
- encodeHeader(paymentRequired);
97
- request.response.body = JSON.stringify(paymentRequired);
98
- return request.response;
192
+ if (payload.x402Version !== 2) {
193
+ return respondPaymentRequired(request, "invalid_x402_version");
194
+ }
195
+ if (!matchesAccepted(payload.accepted)) {
196
+ return respondPaymentRequired(
197
+ request,
198
+ "No matching payment requirements",
199
+ );
99
200
  }
100
201
 
202
+ let verifyResult;
203
+ try {
204
+ verifyResult = await facilitator.verify(payload, requirements);
205
+ } catch (error) {
206
+ return respondPaymentRequired(request, verifyReason(error));
207
+ }
208
+ if (!verifyResult.isValid) {
209
+ return respondPaymentRequired(request, verifyResult.invalidReason);
210
+ }
211
+
212
+ request.internal.x402 = { payload, requirements };
213
+ };
214
+
215
+ const httpX402V1Before = async (request, paymentHeader) => {
101
216
  let payload;
102
217
  try {
103
218
  payload = decodeHeader(paymentHeader);
104
219
  } catch {
105
- return respond402(request, "invalid_payment");
220
+ return respondPaymentRequiredV1(request, "Payment required");
106
221
  }
107
222
 
223
+ if (payload.x402Version !== 1) {
224
+ return respondPaymentRequiredV1(request, "invalid_x402_version");
225
+ }
226
+ // v1 payloads carry scheme/network at the top level and echo nothing
227
+ // else; the facilitator verifies the signed value against
228
+ // maxAmountRequired.
108
229
  if (
109
230
  payload.scheme !== requirements.scheme ||
110
231
  payload.network !== requirements.network
111
232
  ) {
112
- return respond402(request, "invalid_payment");
233
+ return respondPaymentRequiredV1(
234
+ request,
235
+ "No matching payment requirements",
236
+ );
113
237
  }
114
238
 
239
+ const requirementsV1 = buildRequirementsV1(request.event);
115
240
  let verifyResult;
116
241
  try {
117
- verifyResult = await facilitator.verify(payload, fullRequirements);
118
- } catch {
119
- return respond402(request, "invalid_payment");
242
+ verifyResult = await facilitator.verify(payload, requirementsV1);
243
+ } catch (error) {
244
+ return respondPaymentRequiredV1(request, verifyReason(error));
120
245
  }
121
246
  if (!verifyResult.isValid) {
122
- return respond402(request, verifyResult.invalidReason);
247
+ return respondPaymentRequiredV1(request, verifyResult.invalidReason);
123
248
  }
124
249
 
125
- request.internal.x402 = { payload, requirements: fullRequirements };
250
+ request.internal.x402 = { payload, requirements: requirementsV1 };
251
+ };
252
+
253
+ const httpX402MiddlewareBefore = async (request) => {
254
+ if (human?.(request)) return;
255
+
256
+ // A disabled version's payment header is not a payment header for this
257
+ // server; the client falls through and is re-challenged with the
258
+ // enabled formats only.
259
+ const headers = request.event.headers ?? {};
260
+ const v2PaymentHeader = v2Enabled
261
+ ? (headers["payment-signature"] ??
262
+ headers["Payment-Signature"] ??
263
+ headers["PAYMENT-SIGNATURE"])
264
+ : undefined;
265
+ if (v2PaymentHeader) {
266
+ return httpX402V2Before(request, v2PaymentHeader);
267
+ }
268
+ const v1PaymentHeader = v1Enabled
269
+ ? (headers["x-payment"] ?? headers["X-Payment"] ?? headers["X-PAYMENT"])
270
+ : undefined;
271
+ if (v1PaymentHeader) {
272
+ return httpX402V1Before(request, v1PaymentHeader);
273
+ }
274
+
275
+ // Unknown client generation: challenge with every enabled format at
276
+ // once - v2 clients read the PAYMENT-REQUIRED header, v1 clients read
277
+ // the body, so the formats never conflict.
278
+ if (v2Enabled) {
279
+ normalizeHttpResponse(request);
280
+ const paymentRequired = buildPaymentRequired(
281
+ request.event,
282
+ "PAYMENT-SIGNATURE header is required",
283
+ );
284
+ request.response.statusCode = 402;
285
+ request.response.headers["Content-Type"] = "application/json";
286
+ request.response.headers["PAYMENT-REQUIRED"] =
287
+ encodeHeader(paymentRequired);
288
+ request.response.body = JSON.stringify(
289
+ v1Enabled
290
+ ? buildPaymentRequiredV1(
291
+ request.event,
292
+ "X-PAYMENT header is required",
293
+ )
294
+ : paymentRequired,
295
+ );
296
+ return request.response;
297
+ }
298
+ return respondPaymentRequiredV1(request, "X-PAYMENT header is required");
126
299
  };
127
300
 
128
301
  const httpX402MiddlewareAfter = async (request) => {
@@ -132,27 +305,47 @@ const httpX402Middleware = (opts = {}) => {
132
305
  normalizeHttpResponse(request);
133
306
  if (request.response.statusCode >= 400) return;
134
307
 
135
- const { payload, requirements: fullRequirements } = stored;
308
+ const { payload, requirements: storedRequirements } = stored;
309
+ // v1 settlements are reported in X-PAYMENT-RESPONSE, v2 in
310
+ // PAYMENT-RESPONSE.
311
+ const responseHeader =
312
+ payload.x402Version === 1 ? "X-PAYMENT-RESPONSE" : "PAYMENT-RESPONSE";
136
313
  let settleResult;
137
314
  try {
138
- settleResult = await facilitator.settle(payload, fullRequirements);
139
- } catch {
315
+ settleResult = await facilitator.settle(payload, storedRequirements);
316
+ } catch (error) {
317
+ const settleResponse = {
318
+ success: false,
319
+ errorReason: settleReason(error),
320
+ // settlement_pending MUST carry the broadcast hash so the client
321
+ // can reconcile on chain; forward it when the thrown error has one.
322
+ transaction:
323
+ typeof error?.transaction === "string" ? error.transaction : "",
324
+ network: storedRequirements.network,
325
+ };
140
326
  request.response.statusCode = 402;
141
327
  request.response.headers["Content-Type"] = "application/json";
328
+ request.response.headers[responseHeader] = encodeHeader(settleResponse);
142
329
  request.response.body = JSON.stringify({
143
- x402Version: 2,
144
- error: "settle_error",
330
+ x402Version: payload.x402Version,
331
+ error: settleResponse.errorReason,
145
332
  });
333
+ // The handler's response is replaced in place; a stale
334
+ // isBase64Encoded from a binary body would make API Gateway
335
+ // base64-decode this JSON.
336
+ request.response.isBase64Encoded = false;
146
337
  return;
147
338
  }
148
339
 
149
340
  if (!settleResult.success) {
150
341
  request.response.statusCode = 402;
151
342
  request.response.headers["Content-Type"] = "application/json";
343
+ request.response.headers[responseHeader] = encodeHeader(settleResult);
152
344
  request.response.body = JSON.stringify({
153
- x402Version: 2,
345
+ x402Version: payload.x402Version,
154
346
  error: settleResult.errorReason,
155
347
  });
348
+ request.response.isBase64Encoded = false;
156
349
  return;
157
350
  }
158
351
 
@@ -162,7 +355,7 @@ const httpX402Middleware = (opts = {}) => {
162
355
  transaction: settleResult.transaction,
163
356
  network: settleResult.network,
164
357
  };
165
- request.response.headers["PAYMENT-RESPONSE"] = encodeHeader(settleResult);
358
+ request.response.headers[responseHeader] = encodeHeader(settleResult);
166
359
  };
167
360
 
168
361
  return {
@@ -171,13 +364,18 @@ const httpX402Middleware = (opts = {}) => {
171
364
  };
172
365
  };
173
366
 
174
- const respond402 = (request, error) => {
175
- normalizeHttpResponse(request);
176
- request.response.statusCode = 402;
177
- request.response.headers["Content-Type"] = "application/json";
178
- request.response.body = JSON.stringify({ x402Version: 2, error });
179
- return request.response;
180
- };
367
+ // Facilitator clients throw errors carrying `invalidReason` / `errorReason`
368
+ // when the facilitator rejected the request; forward that reason without
369
+ // leaking the error message.
370
+ const verifyReason = (error) =>
371
+ typeof error?.invalidReason === "string"
372
+ ? error.invalidReason
373
+ : "unexpected_verify_error";
374
+
375
+ const settleReason = (error) =>
376
+ typeof error?.errorReason === "string"
377
+ ? error.errorReason
378
+ : "unexpected_settle_error";
181
379
 
182
380
  const integerPattern = /^[0-9]+$/;
183
381
 
@@ -254,11 +452,10 @@ const decodeHeader = (header) => {
254
452
  const payload = JSON.parse(Buffer.from(header, "base64").toString());
255
453
  if (
256
454
  payload === null ||
257
- // Stryker disable next-line ConditionalExpression: a non-null, non-array primitive that slips past this check has no matching scheme, so the scheme/network guard returns the same invalid_payment 402; forcing this operand false is therefore unobservable.
258
455
  typeof payload !== "object" ||
259
456
  Array.isArray(payload)
260
457
  ) {
261
- // Stryker disable next-line StringLiteral,ObjectLiteral: the before-hook catch block discards this error entirely (only a generic invalid_payment 402 is returned), so the message and cause are never observable.
458
+ // Stryker disable next-line StringLiteral,ObjectLiteral: the before-hook catch block discards this error entirely (only a generic "Payment required" 402 is returned), so the message and cause are never observable.
262
459
  throw new Error(`${pkg} payment payload must be an object`, {
263
460
  // Stryker disable next-line ObjectLiteral: see above; cause is unobservable because the thrown error is swallowed.
264
461
  cause: { package: pkg },
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@middy/http-x402",
3
- "version": "7.7.4",
3
+ "version": "7.9.2",
4
4
  "description": "x402 payment middleware for the middy framework",
5
5
  "type": "module",
6
6
  "engines": {
@@ -67,10 +67,10 @@
67
67
  "@x402/core": "^2.0.0"
68
68
  },
69
69
  "dependencies": {
70
- "@middy/util": "7.7.4"
70
+ "@middy/util": "7.9.2"
71
71
  },
72
72
  "devDependencies": {
73
- "@middy/core": "7.7.4",
73
+ "@middy/core": "7.9.2",
74
74
  "@types/node": "^22.0.0",
75
75
  "@x402/core": "^2.0.0"
76
76
  }