@middy/http-x402 7.5.0 → 7.6.8

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 +50 -0
  2. package/index.d.ts +2 -0
  3. package/index.js +128 -11
  4. package/package.json +7 -6
package/README.md ADDED
@@ -0,0 +1,50 @@
1
+ <div align="center">
2
+ <h1>Middy `http-x402` middleware</h1>
3
+ <img alt="Middy logo" src="https://raw.githubusercontent.com/middyjs/middy/main/docs/img/middy-logo.svg"/>
4
+ <p><strong>x402 payment middleware for the middy framework, the stylish Node.js middleware engine for AWS Lambda</strong></p>
5
+ <p>
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
+ <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>
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
+ <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
+ <br/>
12
+ <a href="https://www.npmjs.com/package/@middy/http-x402"><img alt="npm version" src="https://img.shields.io/npm/v/@middy/http-x402.svg"></a>
13
+ <a href="https://packagephobia.com/result?p=@middy/http-x402"><img src="https://packagephobia.com/badge?p=@middy/http-x402" alt="npm install size"></a>
14
+ <a href="https://www.npmjs.com/package/@middy/http-x402">
15
+ <img alt="npm weekly downloads" src="https://img.shields.io/npm/dw/@middy/http-x402.svg"></a>
16
+ <a href="https://www.npmjs.com/package/@middy/http-x402#provenance">
17
+ <img alt="npm provenance" src="https://img.shields.io/badge/provenance-Yes-brightgreen"></a>
18
+ <br/>
19
+ <a href="https://scorecard.dev/viewer/?uri=github.com/middyjs/middy"><img src="https://api.scorecard.dev/projects/github.com/middyjs/middy/badge" alt="Open Source Security Foundation (OpenSSF) Scorecard"></a>
20
+ <a href="https://slsa.dev"><img src="https://slsa.dev/images/gh-badge-level3.svg" alt="SLSA 3"></a>
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
+ <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
+ <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">
25
+ <img alt="code coverage" src="https://img.shields.io/badge/code%20coverage-100%25-brightgreen"></a>
26
+ <br/>
27
+ </p>
28
+ <p>You can read the documentation at: <a href="https://middy.js.org/docs/middlewares/http-x402">https://middy.js.org/docs/middlewares/http-x402</a></p>
29
+ </div>
30
+
31
+ ## Install
32
+
33
+ ```bash
34
+ npm install --save @middy/http-x402
35
+ ```
36
+
37
+
38
+ ## Documentation and examples
39
+
40
+ For documentation and examples, refer to the main [Middy monorepo on GitHub](https://github.com/middyjs/middy) or [Middy official website](https://middy.js.org/docs/middlewares/http-x402).
41
+
42
+
43
+ ## Contributing
44
+
45
+ Everyone is very welcome to contribute to this repository. Feel free to [raise issues](https://github.com/middyjs/middy/issues) or to [submit Pull Requests](https://github.com/middyjs/middy/pulls).
46
+
47
+
48
+ ## License
49
+
50
+ Licensed under [MIT License](https://github.com/middyjs/middy/blob/main/LICENSE). Copyright (c) 2017-2026 [will Farrell](https://github.com/willfarrell), [Luciano Mammino](https://github.com/lmammino), and [Middy contributors](https://github.com/middyjs/middy/graphs/contributors).
package/index.d.ts CHANGED
@@ -1,3 +1,5 @@
1
+ // Copyright 2017 - 2026 will Farrell, Luciano Mammino, and Middy contributors.
2
+ // SPDX-License-Identifier: MIT
1
3
  import type middy from "@middy/core";
2
4
 
3
5
  export interface Options {
package/index.js CHANGED
@@ -10,6 +10,7 @@ const defaults = {
10
10
  FacilitatorClient: HTTPFacilitatorClient,
11
11
  facilitatorUrl: "https://x402.org/facilitator",
12
12
  price: undefined,
13
+ amount: undefined,
13
14
  decimals: 6,
14
15
  network: "eip155:8453",
15
16
  payTo: undefined,
@@ -24,16 +25,19 @@ const optionSchema = {
24
25
  properties: {
25
26
  FacilitatorClient: { instanceof: "Function" },
26
27
  facilitatorUrl: { type: "string" },
27
- price: { type: "number", exclusiveMinimum: 0 },
28
+ price: {
29
+ oneOf: [{ type: "number", exclusiveMinimum: 0 }, { type: "string" }],
30
+ },
31
+ amount: { type: "string" },
28
32
  decimals: { type: "integer" },
29
33
  network: { type: "string" },
30
34
  payTo: { type: "string" },
31
35
  asset: { type: "string" },
32
36
  description: { type: "string" },
33
37
  mimeType: { type: "string" },
34
- human: (v) => typeof v === "function",
38
+ human: { instanceof: "Function" },
35
39
  },
36
- required: ["price", "payTo", "asset"],
40
+ required: ["payTo", "asset"],
37
41
  additionalProperties: false,
38
42
  };
39
43
 
@@ -46,6 +50,7 @@ const httpX402Middleware = (opts = {}) => {
46
50
  FacilitatorClient,
47
51
  facilitatorUrl,
48
52
  price,
53
+ amount: amountOverride,
49
54
  decimals,
50
55
  network,
51
56
  payTo,
@@ -55,7 +60,7 @@ const httpX402Middleware = (opts = {}) => {
55
60
  human,
56
61
  } = options;
57
62
 
58
- const amount = String(Math.round(price * 10 ** decimals));
63
+ const amount = toAtomicAmount(price, decimals, amountOverride);
59
64
  const requirements = {
60
65
  scheme: "exact",
61
66
  network,
@@ -72,7 +77,8 @@ const httpX402Middleware = (opts = {}) => {
72
77
  if (human?.(request)) return;
73
78
 
74
79
  const headers = request.event.headers ?? {};
75
- const paymentHeader = headers["payment-signature"];
80
+ const paymentHeader =
81
+ headers["payment-signature"] ?? headers["Payment-Signature"];
76
82
 
77
83
  const resource = buildResource(request.event);
78
84
  const fullRequirements = { ...requirements, resource };
@@ -106,7 +112,33 @@ const httpX402Middleware = (opts = {}) => {
106
112
  return request.response;
107
113
  }
108
114
 
109
- const verifyResult = await facilitator.verify(payload, fullRequirements);
115
+ if (
116
+ payload.scheme !== requirements.scheme ||
117
+ payload.network !== requirements.network
118
+ ) {
119
+ normalizeHttpResponse(request);
120
+ request.response.statusCode = 402;
121
+ request.response.headers["Content-Type"] = "application/json";
122
+ request.response.body = JSON.stringify({
123
+ x402Version: 2,
124
+ error: "invalid_payment",
125
+ });
126
+ return request.response;
127
+ }
128
+
129
+ let verifyResult;
130
+ try {
131
+ verifyResult = await facilitator.verify(payload, fullRequirements);
132
+ } catch {
133
+ normalizeHttpResponse(request);
134
+ request.response.statusCode = 402;
135
+ request.response.headers["Content-Type"] = "application/json";
136
+ request.response.body = JSON.stringify({
137
+ x402Version: 2,
138
+ error: "invalid_payment",
139
+ });
140
+ return request.response;
141
+ }
110
142
  if (!verifyResult.isValid) {
111
143
  normalizeHttpResponse(request);
112
144
  request.response.statusCode = 402;
@@ -129,7 +161,18 @@ const httpX402Middleware = (opts = {}) => {
129
161
  if (request.response.statusCode >= 400) return;
130
162
 
131
163
  const { payload, requirements: fullRequirements } = stored;
132
- const settleResult = await facilitator.settle(payload, fullRequirements);
164
+ let settleResult;
165
+ try {
166
+ settleResult = await facilitator.settle(payload, fullRequirements);
167
+ } catch {
168
+ request.response.statusCode = 402;
169
+ request.response.headers["Content-Type"] = "application/json";
170
+ request.response.body = JSON.stringify({
171
+ x402Version: 2,
172
+ error: "settle_error",
173
+ });
174
+ return;
175
+ }
133
176
 
134
177
  if (!settleResult.success) {
135
178
  request.response.statusCode = 402;
@@ -156,18 +199,92 @@ const httpX402Middleware = (opts = {}) => {
156
199
  };
157
200
  };
158
201
 
202
+ const integerPattern = /^[0-9]+$/;
203
+
204
+ // Render a finite number as a plain decimal string. `String(n)` uses exponential
205
+ // notation for magnitudes below 1e-6 or at/above 1e21 (e.g. "1e-7"), which the
206
+ // decimal parser below would reject even though the value is a valid price.
207
+ const expandExponential = (value) => {
208
+ const s = String(value);
209
+ const eIdx = s.indexOf("e");
210
+ if (eIdx === -1) return s;
211
+ const exp = Number(s.slice(eIdx + 1));
212
+ const [intPart, fracPart = ""] = s.slice(0, eIdx).split(".");
213
+ const digits = intPart + fracPart;
214
+ const point = intPart.length + exp;
215
+ // JS only uses exponential notation for magnitudes < 1e-6 (point <= 0, a pure
216
+ // fraction) or >= 1e21 (point >= digits.length, a trailing-zero integer), so
217
+ // the decimal point never lands inside `digits`.
218
+ // Stryker disable next-line EqualityOperator: point===0 is unreachable. JS only emits exponential notation for magnitudes < 1e-6, so the smallest exponent is -7 with intPart.length >= 1, giving point <= -6; the <= vs < boundary at 0 can never be exercised.
219
+ return point <= 0
220
+ ? `0.${"0".repeat(-point)}${digits}`
221
+ : `${digits}${"0".repeat(point - digits.length)}`;
222
+ };
223
+
224
+ const toAtomicAmount = (price, decimals, amountOverride) => {
225
+ if (amountOverride !== undefined) {
226
+ if (!integerPattern.test(amountOverride)) {
227
+ throw new Error(`${pkg} amount must be a non-negative integer string`, {
228
+ cause: { package: pkg },
229
+ });
230
+ }
231
+ return amountOverride;
232
+ }
233
+
234
+ const priceString =
235
+ typeof price === "number" ? expandExponential(price) : String(price);
236
+ const match = /^([0-9]*)(?:\.([0-9]+))?$/.exec(priceString);
237
+ if (!match || (match[1] === "" && match[2] === undefined)) {
238
+ throw new Error(
239
+ `${pkg} price must be a non-negative decimal string or number`,
240
+ { cause: { package: pkg } },
241
+ );
242
+ }
243
+
244
+ const whole = match[1];
245
+ const fraction = match[2] ?? "";
246
+ if (fraction.length > decimals) {
247
+ throw new Error(
248
+ `${pkg} price has more fractional digits than decimals (${decimals})`,
249
+ { cause: { package: pkg } },
250
+ );
251
+ }
252
+
253
+ const padded = fraction.padEnd(decimals, "0");
254
+ // `whole` and `padded` are digit-only (regex above) and never both empty
255
+ // (the empty-string price is rejected earlier), so BigInt and its String()
256
+ // form are always a non-negative integer string matching integerPattern:
257
+ // no exponential notation, no precision loss.
258
+ return String(BigInt(`${whole}${padded}`));
259
+ };
260
+
159
261
  const buildResource = (event) => {
160
262
  if (event.version === "2.0") {
161
263
  return `https://${event.requestContext.domainName}${event.requestContext.http.path}`;
162
264
  }
163
- const host = event.headers?.Host ?? event.headers?.host ?? "localhost";
164
- return `https://${host}${event.path ?? "/"}`;
265
+ const host = event.requestContext?.domainName ?? "localhost";
266
+ const path = event.requestContext?.path ?? "/";
267
+ return `https://${host}${path}`;
165
268
  };
166
269
 
167
270
  const encodeHeader = (obj) =>
168
271
  Buffer.from(JSON.stringify(obj)).toString("base64");
169
272
 
170
- const decodeHeader = (header) =>
171
- JSON.parse(Buffer.from(header, "base64").toString());
273
+ const decodeHeader = (header) => {
274
+ const payload = JSON.parse(Buffer.from(header, "base64").toString());
275
+ if (
276
+ payload === null ||
277
+ // 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.
278
+ typeof payload !== "object" ||
279
+ Array.isArray(payload)
280
+ ) {
281
+ // 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.
282
+ throw new Error(`${pkg} payment payload must be an object`, {
283
+ // Stryker disable next-line ObjectLiteral: see above; cause is unobservable because the thrown error is swallowed.
284
+ cause: { package: pkg },
285
+ });
286
+ }
287
+ return payload;
288
+ };
172
289
 
173
290
  export default httpX402Middleware;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@middy/http-x402",
3
- "version": "7.5.0",
3
+ "version": "7.6.8",
4
4
  "description": "x402 payment middleware for the middy framework",
5
5
  "type": "module",
6
6
  "engines": {
@@ -29,7 +29,8 @@
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:perf": "node --test index.perf.js",
33
+ "test:mutation": "cd ../.. && MUTATE_PACKAGE=\"$(basename \"$OLDPWD\")\" stryker run"
33
34
  },
34
35
  "license": "MIT",
35
36
  "keywords": [
@@ -66,11 +67,11 @@
66
67
  "@x402/core": "^2.0.0"
67
68
  },
68
69
  "dependencies": {
69
- "@middy/util": "7.3.4"
70
+ "@middy/util": "7.6.8"
70
71
  },
71
72
  "devDependencies": {
72
- "@middy/core": "7.3.4",
73
- "@x402/core": "^2.0.0",
74
- "@types/node": "^22.0.0"
73
+ "@middy/core": "7.6.8",
74
+ "@types/node": "^22.0.0",
75
+ "@x402/core": "^2.0.0"
75
76
  }
76
77
  }