@middy/http-x402 8.0.0-alpha.1 → 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 (4) hide show
  1. package/README.md +2 -2
  2. package/index.d.ts +36 -7
  3. package/index.js +350 -77
  4. package/package.json +17 -6
package/README.md CHANGED
@@ -5,7 +5,7 @@
5
5
  <p>
6
6
  <a href="https://github.com/middyjs/middy/actions/workflows/test-unit.yml"><img src="https://github.com/middyjs/middy/actions/workflows/test-unit.yml/badge.svg" alt="GitHub Actions unit test status"></a>
7
7
  <a href="https://github.com/middyjs/middy/actions/workflows/test-dast.yml"><img src="https://github.com/middyjs/middy/actions/workflows/test-dast.yml/badge.svg" alt="GitHub Actions dast test status"></a>
8
- <a href="https://github.com/middyjs/middy/actions/workflows/test-perf.yml"><img src="https://github.com/middyjs/middy/actions/workflows/test-perf.yml/badge.svg" alt="GitHub Actions perf test status"></a>
8
+ <a href="https://github.com/middyjs/middy/actions/workflows/test-bench.yml"><img src="https://github.com/middyjs/middy/actions/workflows/test-bench.yml/badge.svg" alt="GitHub Actions bench test status"></a>
9
9
  <a href="https://github.com/middyjs/middy/actions/workflows/test-sast.yml"><img src="https://github.com/middyjs/middy/actions/workflows/test-sast.yml/badge.svg" alt="GitHub Actions SAST test status"></a>
10
10
  <a href="https://github.com/middyjs/middy/actions/workflows/test-lint.yml"><img src="https://github.com/middyjs/middy/actions/workflows/test-lint.yml/badge.svg" alt="GitHub Actions lint test status"></a>
11
11
  <br/>
@@ -21,7 +21,7 @@
21
21
  <a href="https://github.com/middyjs/middy/blob/main/docs/CODE_OF_CONDUCT.md"><img src="https://img.shields.io/badge/Contributor%20Covenant-2.1-4baaaa.svg"></a>
22
22
  <a href="https://biomejs.dev"><img alt="Checked with Biome" src="https://img.shields.io/badge/Checked_with-Biome-60a5fa?style=flat&logo=biome"></a>
23
23
  <a href="https://conventionalcommits.org"><img alt="Conventional Commits" src="https://img.shields.io/badge/Conventional%20Commits-1.0.0-%23FE5196?logo=conventionalcommits&logoColor=white"></a>
24
- <a href="https://github.com/middyjs/middy/blob/main/package.json#L32">
24
+ <a href="https://github.com/middyjs/middy/blob/main/package.json">
25
25
  <img alt="code coverage" src="https://img.shields.io/badge/code%20coverage-100%25-brightgreen"></a>
26
26
  <br/>
27
27
  </p>
package/index.d.ts CHANGED
@@ -1,18 +1,26 @@
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
+ import type {
5
+ APIGatewayEvent,
6
+ APIGatewayProxyEventV2,
7
+ Context as LambdaContext,
8
+ } from "aws-lambda";
5
9
 
6
10
  export type RequestEvent = APIGatewayEvent | APIGatewayProxyEventV2;
7
11
 
8
12
  interface BaseOptions {
9
13
  FacilitatorClient?: new (config: {
10
- url?: string;
14
+ url: string;
11
15
  }) => {
12
16
  verify(payload: unknown, requirements: unknown): Promise<unknown>;
13
17
  settle(payload: unknown, requirements: unknown): Promise<unknown>;
14
18
  };
15
- 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;
16
24
  versions?: readonly (1 | 2)[];
17
25
  price?: number | string;
18
26
  amount?: string;
@@ -23,18 +31,39 @@ interface BaseOptions {
23
31
  description?: string;
24
32
  mimeType?: string;
25
33
  extra?: Record<string, unknown>;
34
+ /**
35
+ * Return `true` to skip payment for this request. Only a literal `true`
36
+ * bypasses; returning a Promise throws a TypeError.
37
+ */
26
38
  human?: (request: middy.Request<RequestEvent>) => boolean;
27
39
  }
28
40
 
29
41
  export type Options = BaseOptions &
30
42
  ({ price: number | string } | { amount: string });
31
43
 
44
+ /**
45
+ * The verified payment the middleware writes to `request.internal.x402`. The
46
+ * settlement fields are added in `after`, once the facilitator settles.
47
+ */
48
+ export interface X402Internal {
49
+ payload: unknown;
50
+ requirements: unknown;
51
+ payer?: string;
52
+ transaction?: string;
53
+ network?: string;
54
+ }
55
+
56
+ /**
57
+ * `x402` is absent when `human` bypassed payment for the request.
58
+ */
59
+ export type Internal = { x402?: X402Internal };
60
+
32
61
  declare function httpX402<EventType extends RequestEvent = RequestEvent>(
33
62
  options: Options,
34
- ): middy.MiddlewareObj<EventType, unknown, Error>;
63
+ ): middy.MiddlewareObj<EventType, unknown, Error, LambdaContext, Internal>;
35
64
 
36
- export declare function httpX402ValidateOptions(
37
- options?: Record<string, unknown>,
38
- ): void;
65
+ export declare function httpX402ValidateOptions<TOptions extends Options>(
66
+ options?: TOptions,
67
+ ): TOptions;
39
68
 
40
69
  export default httpX402;
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) {
@@ -150,7 +263,7 @@ const httpX402Middleware = (opts = {}) => {
150
263
  request.response.headers["PAYMENT-REQUIRED"] =
151
264
  encodeHeader(paymentRequired);
152
265
  request.response.body = JSON.stringify(paymentRequired);
153
- return request.response;
266
+ return albMultiValueResponse(request);
154
267
  };
155
268
 
156
269
  // x402 v1 PaymentRequirements: every field is required by the v1 schema,
@@ -184,7 +297,18 @@ const httpX402Middleware = (opts = {}) => {
184
297
  request.response.body = JSON.stringify(
185
298
  buildPaymentRequiredV1(request.event, error),
186
299
  );
187
- return request.response;
300
+ return albMultiValueResponse(request);
301
+ };
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
+ }
188
312
  };
189
313
 
190
314
  const httpX402V2Before = async (request, 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
  }
@@ -254,22 +368,32 @@ const httpX402Middleware = (opts = {}) => {
254
368
  };
255
369
 
256
370
  const httpX402MiddlewareBefore = (request) => {
257
- if (human?.(request)) return;
371
+ // Only a literal `true` bypasses payment. An async callback returns a
372
+ // Promise, which is always truthy, so it would skip payment for every
373
+ // request; reject it loudly instead of failing open.
374
+ const isHuman = human?.(request);
375
+ if (typeof isHuman?.then === "function") {
376
+ throw new TypeError(`${pkg} human must return a boolean, not a Promise`, {
377
+ cause: { package: pkg },
378
+ });
379
+ }
380
+ if (isHuman === true) return;
258
381
 
259
382
  // A disabled version's payment header is not a payment header for this
260
383
  // server; the client falls through and is re-challenged with the
261
384
  // enabled formats only.
262
- const headers = request.event.headers ?? {};
385
+ // ALB with multi-value headers enabled sends only `multiValueHeaders`.
386
+ // https://docs.aws.amazon.com/elasticloadbalancing/latest/application/lambda-functions.html#multi-value-headers
387
+ const headers =
388
+ request.event.headers ?? request.event.multiValueHeaders ?? {};
263
389
  const v2PaymentHeader = v2Enabled
264
- ? (headers["payment-signature"] ??
265
- headers["Payment-Signature"] ??
266
- headers["PAYMENT-SIGNATURE"])
390
+ ? readHeader(headers, "payment-signature")
267
391
  : undefined;
268
392
  if (v2PaymentHeader) {
269
393
  return httpX402V2Before(request, v2PaymentHeader);
270
394
  }
271
395
  const v1PaymentHeader = v1Enabled
272
- ? (headers["x-payment"] ?? headers["X-Payment"] ?? headers["X-PAYMENT"])
396
+ ? readHeader(headers, "x-payment")
273
397
  : undefined;
274
398
  if (v1PaymentHeader) {
275
399
  return httpX402V1Before(request, v1PaymentHeader);
@@ -296,7 +420,7 @@ const httpX402Middleware = (opts = {}) => {
296
420
  )
297
421
  : paymentRequired,
298
422
  );
299
- return request.response;
423
+ return albMultiValueResponse(request);
300
424
  }
301
425
  return respondPaymentRequiredV1(request, "X-PAYMENT header is required");
302
426
  };
@@ -309,46 +433,50 @@ const httpX402Middleware = (opts = {}) => {
309
433
  if (request.response.statusCode >= 400) return;
310
434
 
311
435
  const { payload, requirements: storedRequirements } = stored;
436
+ // Decided by the event, not the handler's response: API Gateway REST
437
+ // accepts `headers` and `multiValueHeaders` side by side, ALB does not.
438
+ const multiValue = isAlbMultiValue(request.event);
312
439
  // v1 settlements are reported in X-PAYMENT-RESPONSE, v2 in
313
440
  // PAYMENT-RESPONSE.
314
441
  const responseHeader =
315
442
  payload.x402Version === 1 ? "X-PAYMENT-RESPONSE" : "PAYMENT-RESPONSE";
316
- let settleResult;
317
- try {
318
- settleResult = await facilitator.settle(payload, storedRequirements);
319
- } catch (error) {
320
- const settleResponse = {
321
- success: false,
322
- errorReason: settleReason(error),
323
- // settlement_pending MUST carry the broadcast hash so the client
324
- // can reconcile on chain; forward it when the thrown error has one.
325
- transaction:
326
- typeof error?.transaction === "string" ? error.transaction : "",
327
- network: storedRequirements.network,
328
- };
329
- request.response.statusCode = 402;
330
- request.response.headers["Content-Type"] = "application/json";
331
- request.response.headers[responseHeader] = encodeHeader(settleResponse);
332
- request.response.body = JSON.stringify({
333
- x402Version: payload.x402Version,
334
- error: settleResponse.errorReason,
335
- });
336
- // The handler's response is replaced in place; a stale
337
- // isBase64Encoded from a binary body would make API Gateway
338
- // base64-decode this JSON.
339
- request.response.isBase64Encoded = false;
340
- 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();
341
470
  }
342
471
 
343
472
  if (!settleResult.success) {
344
- request.response.statusCode = 402;
345
- request.response.headers["Content-Type"] = "application/json";
346
- request.response.headers[responseHeader] = encodeHeader(settleResult);
347
- request.response.body = JSON.stringify({
348
- x402Version: payload.x402Version,
349
- error: settleResult.errorReason,
350
- });
351
- request.response.isBase64Encoded = false;
473
+ request.response = settlementRefused(
474
+ payload,
475
+ responseHeader,
476
+ settleResult,
477
+ request.response,
478
+ multiValue,
479
+ );
352
480
  return;
353
481
  }
354
482
 
@@ -358,7 +486,14 @@ const httpX402Middleware = (opts = {}) => {
358
486
  transaction: settleResult.transaction,
359
487
  network: settleResult.network,
360
488
  };
361
- request.response.headers[responseHeader] = encodeHeader(settleResult);
489
+ if (multiValue) {
490
+ request.response.multiValueHeaders ??= {};
491
+ request.response.multiValueHeaders[responseHeader] = [
492
+ encodeHeader(settleResult),
493
+ ];
494
+ } else {
495
+ request.response.headers[responseHeader] = encodeHeader(settleResult);
496
+ }
362
497
  };
363
498
 
364
499
  return {
@@ -367,6 +502,111 @@ const httpX402Middleware = (opts = {}) => {
367
502
  };
368
503
  };
369
504
 
505
+ // Field names are case-insensitive (RFC 9110 §5.1) and API Gateway REST passes
506
+ // the client's casing through. ALB multi-value and VPC Lattice V2 deliver
507
+ // arrays; the first value is the one used.
508
+ const readHeader = (headers, lowerName) => {
509
+ for (const key of Object.keys(headers)) {
510
+ if (key.toLowerCase() === lowerName) {
511
+ const value = headers[key];
512
+ return Array.isArray(value) ? value[0] : value;
513
+ }
514
+ }
515
+ return undefined;
516
+ };
517
+
518
+ // Response-policy headers, not content: CORS (so a browser can read the 402 at
519
+ // all), `Vary`, and what http-security-headers sets. When those middlewares are
520
+ // .use()d after this one, their after hooks have already run on the handler's
521
+ // response, so they are carried over to the 402.
522
+ const policyHeaderNames = new Set([
523
+ "vary",
524
+ "strict-transport-security",
525
+ "x-content-type-options",
526
+ "x-frame-options",
527
+ "x-dns-prefetch-control",
528
+ "x-download-options",
529
+ "x-permitted-cross-domain-policies",
530
+ "x-xss-protection",
531
+ "referrer-policy",
532
+ "permissions-policy",
533
+ "origin-agent-cluster",
534
+ "reporting-endpoints",
535
+ "report-to",
536
+ "content-security-policy",
537
+ "content-security-policy-report-only",
538
+ ]);
539
+ const isPolicyHeader = (name) => {
540
+ const lower = name.toLowerCase();
541
+ return (
542
+ policyHeaderNames.has(lower) ||
543
+ lower.startsWith("access-control-") ||
544
+ lower.startsWith("cross-origin-")
545
+ );
546
+ };
547
+
548
+ // Payment was not taken, so nothing the handler produced for the paid resource
549
+ // may reach the client: not its body, and not its content headers, multi-value
550
+ // headers or v2 cookies (Location, Set-Cookie). The handler's response is
551
+ // replaced whole rather than patched; only policy headers are kept.
552
+ const settlementRefused = (
553
+ payload,
554
+ responseHeader,
555
+ settlement,
556
+ replaced,
557
+ multiValue,
558
+ ) => {
559
+ const headers = {};
560
+ for (const map of [replaced.headers, replaced.multiValueHeaders]) {
561
+ if (!map) continue;
562
+ for (const name of Object.keys(map)) {
563
+ if (!isPolicyHeader(name)) continue;
564
+ // Single-value `headers` cannot carry a `multiValueHeaders` array.
565
+ const value = map[name];
566
+ headers[name] =
567
+ !multiValue && Array.isArray(value) ? value.join(", ") : value;
568
+ }
569
+ }
570
+ headers["Content-Type"] = "application/json";
571
+ headers[responseHeader] = encodeHeader(settlement);
572
+ const response = {
573
+ statusCode: 402,
574
+ headers,
575
+ body: JSON.stringify({
576
+ x402Version: payload.x402Version,
577
+ error: settlement.errorReason,
578
+ }),
579
+ isBase64Encoded: false,
580
+ };
581
+ return multiValue ? toMultiValueHeaders(response) : response;
582
+ };
583
+
584
+ // An ALB target group with multi-value headers enabled sends
585
+ // `multiValueHeaders` and only reads them back: "You must use
586
+ // multiValueHeaders if you have enabled multi-value headers and headers
587
+ // otherwise." Its events are the only ones that carry `requestContext.elb`
588
+ // together with `multiValueHeaders`.
589
+ // https://docs.aws.amazon.com/elasticloadbalancing/latest/application/lambda-functions.html#multi-value-headers
590
+ const isAlbMultiValue = (event) =>
591
+ event.requestContext?.elb !== undefined &&
592
+ event.multiValueHeaders !== undefined;
593
+
594
+ const toMultiValueHeaders = ({ headers, ...response }) => {
595
+ const multiValueHeaders = {};
596
+ for (const name of Object.keys(headers)) {
597
+ const value = headers[name];
598
+ multiValueHeaders[name] = Array.isArray(value) ? value : [value];
599
+ }
600
+ return { ...response, multiValueHeaders };
601
+ };
602
+
603
+ const albMultiValueResponse = (request) => {
604
+ if (isAlbMultiValue(request.event)) {
605
+ request.response = toMultiValueHeaders(request.response);
606
+ }
607
+ return request.response;
608
+ };
609
+
370
610
  // Facilitator clients throw errors carrying `invalidReason` / `errorReason`
371
611
  // when the facilitator rejected the request; forward that reason without
372
612
  // leaking the error message.
@@ -380,6 +620,25 @@ const settleReason = (error) =>
380
620
  ? error.errorReason
381
621
  : "unexpected_settle_error";
382
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
+
383
642
  const integerPattern = /^[0-9]+$/;
384
643
 
385
644
  // Render a finite number as a plain decimal string. `String(n)` uses exponential
@@ -439,13 +698,27 @@ const toAtomicAmount = (price, decimals, amountOverride) => {
439
698
  return String(BigInt(`${whole}${padded}`));
440
699
  };
441
700
 
701
+ // The host comes only from API Gateway's `requestContext.domainName`; the Host
702
+ // header is client-controlled and never used. ALB and VPC Lattice carry no
703
+ // trusted domain, so they get `localhost`, with the request path from the
704
+ // event: `path` (ALB, Lattice V2) or `raw_path` (Lattice V1). Lattice includes
705
+ // the query string in both, which is not part of the resource. Lattice V2 also
706
+ // sends `version: "2.0"`, so the payload is told apart by
707
+ // `requestContext.http`, which only API Gateway HTTP API v2 and function URL
708
+ // events carry.
709
+ // https://docs.aws.amazon.com/elasticloadbalancing/latest/application/lambda-functions.html
710
+ // https://docs.aws.amazon.com/vpc-lattice/latest/ug/lambda-functions.html
442
711
  const buildResource = (event) => {
443
- if (event.version === "2.0") {
444
- return `https://${event.requestContext.domainName}${event.requestContext.http.path}`;
712
+ const requestContext = event.requestContext;
713
+ if (requestContext?.http) {
714
+ return `https://${requestContext.domainName}${requestContext.http.path}`;
715
+ }
716
+ if (requestContext?.domainName) {
717
+ return `https://${requestContext.domainName}${requestContext.path ?? "/"}`;
445
718
  }
446
- const host = event.requestContext?.domainName ?? "localhost";
447
- const path = event.requestContext?.path ?? "/";
448
- return `https://${host}${path}`;
719
+ const rawPath = requestContext?.path ?? event.path ?? event.raw_path;
720
+ const path = typeof rawPath === "string" ? rawPath.split("?", 1)[0] : "";
721
+ return `https://localhost${path || "/"}`;
449
722
  };
450
723
 
451
724
  const encodeHeader = (obj) =>
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@middy/http-x402",
3
- "version": "8.0.0-alpha.1",
3
+ "version": "8.0.0-rc.0",
4
4
  "description": "x402 payment middleware for the middy framework",
5
5
  "type": "module",
6
6
  "engines": {
@@ -29,7 +29,7 @@
29
29
  "test": "npm run test:unit && npm run test:fuzz",
30
30
  "test:unit": "node --test",
31
31
  "test:fuzz": "node --test index.fuzz.js",
32
- "test:perf": "node --test index.perf.js",
32
+ "test:bench": "node --experimental-bench --bench 'index.bench.js'",
33
33
  "test:mutation": "cd ../.. && MUTATE_PACKAGE=\"$(basename \"$OLDPWD\")\" stryker run"
34
34
  },
35
35
  "license": "MIT",
@@ -64,14 +64,25 @@
64
64
  "url": "https://github.com/sponsors/willfarrell"
65
65
  },
66
66
  "peerDependencies": {
67
- "@x402/core": "^2.0.0"
67
+ "@x402/core": "^2.28.0",
68
+ "@middy/core": "8.0.0-rc.0",
69
+ "@types/aws-lambda": "^8.0.0"
70
+ },
71
+ "peerDependenciesMeta": {
72
+ "@middy/core": {
73
+ "optional": true
74
+ },
75
+ "@types/aws-lambda": {
76
+ "optional": true
77
+ }
68
78
  },
69
79
  "dependencies": {
70
- "@middy/util": "8.0.0-alpha.1"
80
+ "@middy/util": "8.0.0-rc.0"
71
81
  },
72
82
  "devDependencies": {
73
- "@middy/core": "8.0.0-alpha.1",
83
+ "@middy/core": "8.0.0-rc.0",
84
+ "@types/aws-lambda": "^8.0.0",
74
85
  "@types/node": "^24.0.0",
75
- "@x402/core": "^2.0.0"
86
+ "@x402/core": "^2.28.0"
76
87
  }
77
88
  }