@middy/http-x402 7.5.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 +27 -0
  2. package/index.js +173 -0
  3. package/package.json +76 -0
package/index.d.ts ADDED
@@ -0,0 +1,27 @@
1
+ import type middy from "@middy/core";
2
+
3
+ export interface Options {
4
+ FacilitatorClient?: new (config: {
5
+ url?: string;
6
+ }) => {
7
+ verify(payload: unknown, requirements: unknown): Promise<unknown>;
8
+ settle(payload: unknown, requirements: unknown): Promise<unknown>;
9
+ };
10
+ facilitatorUrl?: string;
11
+ price: number;
12
+ decimals?: number;
13
+ network?: string;
14
+ payTo: string;
15
+ asset: string;
16
+ description?: string;
17
+ mimeType?: string;
18
+ human?: (request: middy.Request) => boolean;
19
+ }
20
+
21
+ declare function httpX402(options: Options): middy.MiddlewareObj;
22
+
23
+ export declare function httpX402ValidateOptions(
24
+ options?: Record<string, unknown>,
25
+ ): void;
26
+
27
+ export default httpX402;
package/index.js ADDED
@@ -0,0 +1,173 @@
1
+ // Copyright 2017 - 2026 will Farrell, Luciano Mammino, and Middy contributors.
2
+ // SPDX-License-Identifier: MIT
3
+ import { normalizeHttpResponse, validateOptions } from "@middy/util";
4
+ import { HTTPFacilitatorClient } from "@x402/core/http";
5
+
6
+ const name = "http-x402";
7
+ const pkg = `@middy/${name}`;
8
+
9
+ const defaults = {
10
+ FacilitatorClient: HTTPFacilitatorClient,
11
+ facilitatorUrl: "https://x402.org/facilitator",
12
+ price: undefined,
13
+ decimals: 6,
14
+ network: "eip155:8453",
15
+ payTo: undefined,
16
+ asset: undefined,
17
+ description: "",
18
+ mimeType: "application/json",
19
+ human: undefined,
20
+ };
21
+
22
+ const optionSchema = {
23
+ type: "object",
24
+ properties: {
25
+ FacilitatorClient: { instanceof: "Function" },
26
+ facilitatorUrl: { type: "string" },
27
+ price: { type: "number", exclusiveMinimum: 0 },
28
+ decimals: { type: "integer" },
29
+ network: { type: "string" },
30
+ payTo: { type: "string" },
31
+ asset: { type: "string" },
32
+ description: { type: "string" },
33
+ mimeType: { type: "string" },
34
+ human: (v) => typeof v === "function",
35
+ },
36
+ required: ["price", "payTo", "asset"],
37
+ additionalProperties: false,
38
+ };
39
+
40
+ export const httpX402ValidateOptions = (options) =>
41
+ validateOptions(pkg, optionSchema, options);
42
+
43
+ const httpX402Middleware = (opts = {}) => {
44
+ const options = { ...defaults, ...opts };
45
+ const {
46
+ FacilitatorClient,
47
+ facilitatorUrl,
48
+ price,
49
+ decimals,
50
+ network,
51
+ payTo,
52
+ asset,
53
+ description,
54
+ mimeType,
55
+ human,
56
+ } = options;
57
+
58
+ const amount = String(Math.round(price * 10 ** decimals));
59
+ const requirements = {
60
+ scheme: "exact",
61
+ network,
62
+ amount,
63
+ asset,
64
+ payTo,
65
+ maxTimeoutSeconds: 60,
66
+ description,
67
+ mimeType,
68
+ };
69
+ const facilitator = new FacilitatorClient({ url: facilitatorUrl });
70
+
71
+ const httpX402MiddlewareBefore = async (request) => {
72
+ if (human?.(request)) return;
73
+
74
+ const headers = request.event.headers ?? {};
75
+ const paymentHeader = headers["payment-signature"];
76
+
77
+ const resource = buildResource(request.event);
78
+ const fullRequirements = { ...requirements, resource };
79
+
80
+ if (!paymentHeader) {
81
+ normalizeHttpResponse(request);
82
+ const paymentRequired = {
83
+ x402Version: 2,
84
+ error: "Payment required",
85
+ accepts: [fullRequirements],
86
+ };
87
+ request.response.statusCode = 402;
88
+ request.response.headers["Content-Type"] = "application/json";
89
+ request.response.headers["PAYMENT-REQUIRED"] =
90
+ encodeHeader(paymentRequired);
91
+ request.response.body = JSON.stringify(paymentRequired);
92
+ return request.response;
93
+ }
94
+
95
+ let payload;
96
+ try {
97
+ payload = decodeHeader(paymentHeader);
98
+ } catch {
99
+ normalizeHttpResponse(request);
100
+ request.response.statusCode = 402;
101
+ request.response.headers["Content-Type"] = "application/json";
102
+ request.response.body = JSON.stringify({
103
+ x402Version: 2,
104
+ error: "invalid_payment",
105
+ });
106
+ return request.response;
107
+ }
108
+
109
+ const verifyResult = await facilitator.verify(payload, fullRequirements);
110
+ if (!verifyResult.isValid) {
111
+ normalizeHttpResponse(request);
112
+ request.response.statusCode = 402;
113
+ request.response.headers["Content-Type"] = "application/json";
114
+ request.response.body = JSON.stringify({
115
+ x402Version: 2,
116
+ error: verifyResult.invalidReason,
117
+ });
118
+ return request.response;
119
+ }
120
+
121
+ request.internal.x402 = { payload, requirements: fullRequirements };
122
+ };
123
+
124
+ const httpX402MiddlewareAfter = async (request) => {
125
+ const stored = request.internal.x402;
126
+ if (!stored) return;
127
+
128
+ normalizeHttpResponse(request);
129
+ if (request.response.statusCode >= 400) return;
130
+
131
+ const { payload, requirements: fullRequirements } = stored;
132
+ const settleResult = await facilitator.settle(payload, fullRequirements);
133
+
134
+ if (!settleResult.success) {
135
+ request.response.statusCode = 402;
136
+ request.response.headers["Content-Type"] = "application/json";
137
+ request.response.body = JSON.stringify({
138
+ x402Version: 2,
139
+ error: settleResult.errorReason,
140
+ });
141
+ return;
142
+ }
143
+
144
+ request.internal.x402 = {
145
+ ...stored,
146
+ payer: settleResult.payer,
147
+ transaction: settleResult.transaction,
148
+ network: settleResult.network,
149
+ };
150
+ request.response.headers["PAYMENT-RESPONSE"] = encodeHeader(settleResult);
151
+ };
152
+
153
+ return {
154
+ before: httpX402MiddlewareBefore,
155
+ after: httpX402MiddlewareAfter,
156
+ };
157
+ };
158
+
159
+ const buildResource = (event) => {
160
+ if (event.version === "2.0") {
161
+ return `https://${event.requestContext.domainName}${event.requestContext.http.path}`;
162
+ }
163
+ const host = event.headers?.Host ?? event.headers?.host ?? "localhost";
164
+ return `https://${host}${event.path ?? "/"}`;
165
+ };
166
+
167
+ const encodeHeader = (obj) =>
168
+ Buffer.from(JSON.stringify(obj)).toString("base64");
169
+
170
+ const decodeHeader = (header) =>
171
+ JSON.parse(Buffer.from(header, "base64").toString());
172
+
173
+ export default httpX402Middleware;
package/package.json ADDED
@@ -0,0 +1,76 @@
1
+ {
2
+ "name": "@middy/http-x402",
3
+ "version": "7.5.0",
4
+ "description": "x402 payment middleware for the middy framework",
5
+ "type": "module",
6
+ "engines": {
7
+ "node": ">=22"
8
+ },
9
+ "engineStrict": true,
10
+ "publishConfig": {
11
+ "access": "public"
12
+ },
13
+ "module": "./index.js",
14
+ "sideEffects": false,
15
+ "exports": {
16
+ ".": {
17
+ "import": {
18
+ "types": "./index.d.ts",
19
+ "default": "./index.js"
20
+ }
21
+ }
22
+ },
23
+ "types": "index.d.ts",
24
+ "files": [
25
+ "index.js",
26
+ "index.d.ts"
27
+ ],
28
+ "scripts": {
29
+ "test": "npm run test:unit && npm run test:fuzz",
30
+ "test:unit": "node --test",
31
+ "test:fuzz": "node --test index.fuzz.js",
32
+ "test:perf": "node --test index.perf.js"
33
+ },
34
+ "license": "MIT",
35
+ "keywords": [
36
+ "Lambda",
37
+ "Middleware",
38
+ "Serverless",
39
+ "Framework",
40
+ "AWS",
41
+ "AWS Lambda",
42
+ "Middy",
43
+ "HTTP",
44
+ "x402",
45
+ "Payments",
46
+ "Web3"
47
+ ],
48
+ "author": {
49
+ "name": "Middy contributors",
50
+ "url": "https://github.com/middyjs/middy/graphs/contributors"
51
+ },
52
+ "repository": {
53
+ "type": "git",
54
+ "url": "git+https://github.com/middyjs/middy.git",
55
+ "directory": "packages/http-x402"
56
+ },
57
+ "bugs": {
58
+ "url": "https://github.com/middyjs/middy/issues"
59
+ },
60
+ "homepage": "https://middy.js.org",
61
+ "funding": {
62
+ "type": "github",
63
+ "url": "https://github.com/sponsors/willfarrell"
64
+ },
65
+ "peerDependencies": {
66
+ "@x402/core": "^2.0.0"
67
+ },
68
+ "dependencies": {
69
+ "@middy/util": "7.3.4"
70
+ },
71
+ "devDependencies": {
72
+ "@middy/core": "7.3.4",
73
+ "@x402/core": "^2.0.0",
74
+ "@types/node": "^22.0.0"
75
+ }
76
+ }