@x402-lens/express 0.0.0-stage → 0.2.4
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.
- package/LICENSE +21 -0
- package/README.md +96 -3
- package/dist/index.cjs +641 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +172 -0
- package/dist/index.d.ts +172 -0
- package/dist/index.js +636 -0
- package/dist/index.js.map +1 -0
- package/package.json +55 -6
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,641 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
+
var __export = (target, all) => {
|
|
7
|
+
for (var name in all)
|
|
8
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
9
|
+
};
|
|
10
|
+
var __copyProps = (to, from, except, desc) => {
|
|
11
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
12
|
+
for (let key of __getOwnPropNames(from))
|
|
13
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
14
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
15
|
+
}
|
|
16
|
+
return to;
|
|
17
|
+
};
|
|
18
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
19
|
+
|
|
20
|
+
// src/index.ts
|
|
21
|
+
var index_exports = {};
|
|
22
|
+
__export(index_exports, {
|
|
23
|
+
PrometheusRegistry: () => import_core2.PrometheusRegistry,
|
|
24
|
+
paymentLens: () => paymentLens,
|
|
25
|
+
paymentLensAsync: () => paymentLensAsync,
|
|
26
|
+
prometheusHandler: () => import_core2.prometheusHandler
|
|
27
|
+
});
|
|
28
|
+
module.exports = __toCommonJS(index_exports);
|
|
29
|
+
var import_node_crypto = require("crypto");
|
|
30
|
+
var import_core = require("@x402-lens/core");
|
|
31
|
+
var import_server = require("@x402/core/server");
|
|
32
|
+
var import_express = require("@x402/express");
|
|
33
|
+
var import_server2 = require("@x402/evm/exact/server");
|
|
34
|
+
var import_server3 = require("@x402/evm/upto/server");
|
|
35
|
+
var import_server4 = require("@x402/svm/exact/server");
|
|
36
|
+
var import_server5 = require("@x402/svm/upto/server");
|
|
37
|
+
|
|
38
|
+
// src/context.ts
|
|
39
|
+
var import_node_async_hooks = require("async_hooks");
|
|
40
|
+
var storage = new import_node_async_hooks.AsyncLocalStorage();
|
|
41
|
+
function runWithRequestContext(context, fn) {
|
|
42
|
+
return storage.run(context, fn);
|
|
43
|
+
}
|
|
44
|
+
function currentRequestContext() {
|
|
45
|
+
return storage.getStore();
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
// src/observe.ts
|
|
49
|
+
var import_http = require("@x402/core/http");
|
|
50
|
+
function bodyFieldsFromChallenge(paymentRequired) {
|
|
51
|
+
return {
|
|
52
|
+
x402Version: paymentRequired.x402Version,
|
|
53
|
+
...paymentRequired.error ? { error: paymentRequired.error } : {},
|
|
54
|
+
...paymentRequired.resource ? { resource: paymentRequired.resource } : {},
|
|
55
|
+
...paymentRequired.accepts ? { accepts: paymentRequired.accepts } : {}
|
|
56
|
+
};
|
|
57
|
+
}
|
|
58
|
+
function observePaymentRequired(res, onChallenge, options = {}) {
|
|
59
|
+
const mirrorBody = options.mirrorBody ?? true;
|
|
60
|
+
const target = res;
|
|
61
|
+
const originalSetHeader = target.setHeader;
|
|
62
|
+
const originalWriteHead = target.writeHead;
|
|
63
|
+
const originalJson = target.json;
|
|
64
|
+
let captured;
|
|
65
|
+
let capturedRaw;
|
|
66
|
+
let emitted = false;
|
|
67
|
+
let restored = false;
|
|
68
|
+
const capture = (value) => {
|
|
69
|
+
if (typeof value !== "string" || value.length === 0) return;
|
|
70
|
+
if (value === capturedRaw) return;
|
|
71
|
+
try {
|
|
72
|
+
captured = (0, import_http.decodePaymentRequiredHeader)(value);
|
|
73
|
+
capturedRaw = value;
|
|
74
|
+
} catch {
|
|
75
|
+
}
|
|
76
|
+
};
|
|
77
|
+
const emitIfChallenge = () => {
|
|
78
|
+
if (emitted || !captured) return;
|
|
79
|
+
emitted = true;
|
|
80
|
+
onChallenge(captured);
|
|
81
|
+
};
|
|
82
|
+
target.setHeader = function patchedSetHeader(name, value) {
|
|
83
|
+
if (typeof name === "string" && name.toLowerCase() === "payment-required") {
|
|
84
|
+
capture(value);
|
|
85
|
+
}
|
|
86
|
+
return originalSetHeader.call(this, name, value);
|
|
87
|
+
};
|
|
88
|
+
target.writeHead = function patchedWriteHead(statusCode, ...rest) {
|
|
89
|
+
if (statusCode === 402) {
|
|
90
|
+
for (const candidate of rest) {
|
|
91
|
+
if (candidate && typeof candidate === "object") {
|
|
92
|
+
for (const [key, value] of Object.entries(candidate)) {
|
|
93
|
+
if (key.toLowerCase() === "payment-required") capture(value);
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
emitIfChallenge();
|
|
98
|
+
}
|
|
99
|
+
return originalWriteHead.call(this, statusCode, ...rest);
|
|
100
|
+
};
|
|
101
|
+
target.json = function patchedJson(body, ...rest) {
|
|
102
|
+
if (res.statusCode === 402 && captured) {
|
|
103
|
+
emitIfChallenge();
|
|
104
|
+
if (!mirrorBody) return originalJson.call(this, body, ...rest);
|
|
105
|
+
const base = body && typeof body === "object" && !Array.isArray(body) ? body : {};
|
|
106
|
+
return originalJson.call(this, { ...base, ...bodyFieldsFromChallenge(captured) }, ...rest);
|
|
107
|
+
}
|
|
108
|
+
return originalJson.call(this, body, ...rest);
|
|
109
|
+
};
|
|
110
|
+
const restore = () => {
|
|
111
|
+
if (restored) return;
|
|
112
|
+
restored = true;
|
|
113
|
+
target.setHeader = originalSetHeader;
|
|
114
|
+
target.writeHead = originalWriteHead;
|
|
115
|
+
target.json = originalJson;
|
|
116
|
+
res.off("finish", restore);
|
|
117
|
+
res.off("close", restore);
|
|
118
|
+
};
|
|
119
|
+
res.on("finish", restore);
|
|
120
|
+
res.on("close", restore);
|
|
121
|
+
return restore;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
// src/index.ts
|
|
125
|
+
var import_core2 = require("@x402-lens/core");
|
|
126
|
+
var FACILITATOR_UNAVAILABLE_BODY = {
|
|
127
|
+
error: "facilitator_unavailable",
|
|
128
|
+
code: "FACILITATOR_UNAVAILABLE"
|
|
129
|
+
};
|
|
130
|
+
function paymentLens(options = {}) {
|
|
131
|
+
const config = options.config ? ((0, import_core.assertLensConfig)(options.config), normalisePassedConfig(options.config)) : (0, import_core.resolveConfig)({
|
|
132
|
+
...options,
|
|
133
|
+
routes: normaliseRouteInput(options.routes)
|
|
134
|
+
});
|
|
135
|
+
return buildLens(config, options);
|
|
136
|
+
}
|
|
137
|
+
async function paymentLensAsync(options = {}) {
|
|
138
|
+
const config = options.config ? ((0, import_core.assertLensConfig)(options.config), normalisePassedConfig(options.config)) : await (0, import_core.loadConfig)({
|
|
139
|
+
...options,
|
|
140
|
+
routes: normaliseRouteInput(options.routes)
|
|
141
|
+
});
|
|
142
|
+
return buildLens(config, options);
|
|
143
|
+
}
|
|
144
|
+
function normalisePassedConfig(config) {
|
|
145
|
+
return {
|
|
146
|
+
...config,
|
|
147
|
+
facilitatorUrl: config.facilitatorUrl.replace(/\/+$/, "")
|
|
148
|
+
};
|
|
149
|
+
}
|
|
150
|
+
function normaliseRouteInput(routes) {
|
|
151
|
+
if (!routes) return void 0;
|
|
152
|
+
if (Array.isArray(routes)) return routes;
|
|
153
|
+
return Object.entries(routes).map(([route, value]) => {
|
|
154
|
+
if (typeof value === "string") return { route, price: value };
|
|
155
|
+
if (value && typeof value === "object" && !Array.isArray(value)) {
|
|
156
|
+
return { route, ...value };
|
|
157
|
+
}
|
|
158
|
+
throw new import_core.ConfigError(
|
|
159
|
+
"routes",
|
|
160
|
+
`routes["${route}"] must be a price string or an options object, got ${JSON.stringify(value)}.`
|
|
161
|
+
);
|
|
162
|
+
});
|
|
163
|
+
}
|
|
164
|
+
function decodedRoutePath(path) {
|
|
165
|
+
try {
|
|
166
|
+
return decodeURIComponent(path);
|
|
167
|
+
} catch {
|
|
168
|
+
return path;
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
function buildLens(config, options) {
|
|
172
|
+
const bus = new import_core.EventBus([
|
|
173
|
+
...buildSinks(options.sinks),
|
|
174
|
+
...options.extraSinks ?? []
|
|
175
|
+
]);
|
|
176
|
+
const readableBody = options.readableBody ?? true;
|
|
177
|
+
const facilitatorClient = options.facilitatorClient ?? buildFacilitatorClient(config);
|
|
178
|
+
const server = new import_server.x402ResourceServer(facilitatorClient);
|
|
179
|
+
const schemes = schemesInUse(config);
|
|
180
|
+
for (const network of config.networks) registerScheme(server, network, schemes);
|
|
181
|
+
if (options.routesConfig && Object.keys(options.routesConfig).length === 0) {
|
|
182
|
+
throw new import_core.ConfigError(
|
|
183
|
+
"routesConfig",
|
|
184
|
+
"routesConfig is empty. Omit it to use config.routes, or pass at least one protected route \u2014 an empty map silently disables payment protection."
|
|
185
|
+
);
|
|
186
|
+
}
|
|
187
|
+
const routes = options.routesConfig ?? (0, import_core.toRoutesConfig)(config);
|
|
188
|
+
attachHooks(server, bus, config);
|
|
189
|
+
const httpServer = new import_server.x402HTTPResourceServer(server, routes);
|
|
190
|
+
let initFailure;
|
|
191
|
+
let initFailureEmitted = false;
|
|
192
|
+
const emitInitFailure = (error) => {
|
|
193
|
+
if (initFailureEmitted) return;
|
|
194
|
+
initFailureEmitted = true;
|
|
195
|
+
bus.emit(
|
|
196
|
+
(0, import_core.makeEvent)({
|
|
197
|
+
type: "facilitator.error",
|
|
198
|
+
ts: (/* @__PURE__ */ new Date()).toISOString(),
|
|
199
|
+
requestId: (0, import_node_crypto.randomUUID)(),
|
|
200
|
+
route: "INIT /supported",
|
|
201
|
+
scheme: "exact",
|
|
202
|
+
network: config.network,
|
|
203
|
+
amount: "0",
|
|
204
|
+
asset: "",
|
|
205
|
+
payTo: config.payTo,
|
|
206
|
+
message: error.message
|
|
207
|
+
})
|
|
208
|
+
);
|
|
209
|
+
};
|
|
210
|
+
const ready = httpServer.initialize().then(
|
|
211
|
+
() => void 0,
|
|
212
|
+
(error) => {
|
|
213
|
+
const asError = error instanceof Error ? error : new Error(String(error));
|
|
214
|
+
initFailure = asError;
|
|
215
|
+
emitInitFailure(asError);
|
|
216
|
+
throw asError;
|
|
217
|
+
}
|
|
218
|
+
);
|
|
219
|
+
void ready.catch(() => {
|
|
220
|
+
});
|
|
221
|
+
const inner = (0, import_express.paymentMiddlewareFromHTTPServer)(
|
|
222
|
+
httpServer,
|
|
223
|
+
void 0,
|
|
224
|
+
void 0,
|
|
225
|
+
false
|
|
226
|
+
);
|
|
227
|
+
const corsHeaders = buildCorsHeaders(options.cors);
|
|
228
|
+
if (options.cors === true) {
|
|
229
|
+
process.emitWarning(
|
|
230
|
+
'[x402-lens] cors: true does not set Access-Control-Allow-Origin. Pass cors: { origin: "\u2026" } for browser buyers.',
|
|
231
|
+
"X402LensCors"
|
|
232
|
+
);
|
|
233
|
+
}
|
|
234
|
+
const grant = options.grant;
|
|
235
|
+
const respondFacilitatorUnavailable = (res, requestId, route, error) => {
|
|
236
|
+
bus.emit(
|
|
237
|
+
(0, import_core.makeEvent)({
|
|
238
|
+
type: "facilitator.error",
|
|
239
|
+
ts: (/* @__PURE__ */ new Date()).toISOString(),
|
|
240
|
+
requestId,
|
|
241
|
+
route,
|
|
242
|
+
scheme: "exact",
|
|
243
|
+
network: config.network,
|
|
244
|
+
amount: "0",
|
|
245
|
+
asset: "",
|
|
246
|
+
payTo: config.payTo,
|
|
247
|
+
message: error.message
|
|
248
|
+
})
|
|
249
|
+
);
|
|
250
|
+
if (!res.headersSent) {
|
|
251
|
+
res.status(502).json(FACILITATOR_UNAVAILABLE_BODY);
|
|
252
|
+
} else if (!res.writableEnded) {
|
|
253
|
+
res.end();
|
|
254
|
+
}
|
|
255
|
+
};
|
|
256
|
+
const middleware = (req, res, next) => {
|
|
257
|
+
const context = {
|
|
258
|
+
requestId: (0, import_node_crypto.randomUUID)(),
|
|
259
|
+
startedAt: Date.now(),
|
|
260
|
+
method: req.method,
|
|
261
|
+
path: req.path
|
|
262
|
+
};
|
|
263
|
+
if (corsHeaders) applyCorsHeaders(res, corsHeaders);
|
|
264
|
+
if (req.method === "OPTIONS") {
|
|
265
|
+
if (corsHeaders) {
|
|
266
|
+
if (!res.headersSent) res.sendStatus(204);
|
|
267
|
+
return;
|
|
268
|
+
}
|
|
269
|
+
next();
|
|
270
|
+
return;
|
|
271
|
+
}
|
|
272
|
+
const emitRequired = (paymentRequired) => {
|
|
273
|
+
const entries = paymentRequired.accepts ?? [];
|
|
274
|
+
const entry = entries[0];
|
|
275
|
+
bus.emit(
|
|
276
|
+
(0, import_core.makeEvent)({
|
|
277
|
+
type: "payment.required",
|
|
278
|
+
requestId: context.requestId,
|
|
279
|
+
route: `${context.method} ${context.path}`,
|
|
280
|
+
scheme: entry?.scheme ?? "exact",
|
|
281
|
+
network: entry?.network ?? config.network,
|
|
282
|
+
amount: entry?.amount ?? "0",
|
|
283
|
+
asset: entry?.asset ?? "",
|
|
284
|
+
payTo: entry?.payTo ?? config.payTo,
|
|
285
|
+
offers: entries.length,
|
|
286
|
+
durationMs: Date.now() - context.startedAt,
|
|
287
|
+
findings: (0, import_core.diagnose)({ paymentRequired, now: context.startedAt })
|
|
288
|
+
})
|
|
289
|
+
);
|
|
290
|
+
};
|
|
291
|
+
observePaymentRequired(res, emitRequired, { mirrorBody: readableBody });
|
|
292
|
+
runWithRequestContext(context, () => {
|
|
293
|
+
void (async () => {
|
|
294
|
+
const adapter = new import_express.ExpressAdapter(req);
|
|
295
|
+
const httpContext = {
|
|
296
|
+
adapter,
|
|
297
|
+
path: req.path,
|
|
298
|
+
decodedPath: decodedRoutePath(req.path),
|
|
299
|
+
method: req.method,
|
|
300
|
+
paymentHeader: adapter.getHeader("payment-signature") || adapter.getHeader("x-payment")
|
|
301
|
+
};
|
|
302
|
+
if (!httpServer.requiresPayment(httpContext)) {
|
|
303
|
+
next();
|
|
304
|
+
return;
|
|
305
|
+
}
|
|
306
|
+
if (grant) {
|
|
307
|
+
try {
|
|
308
|
+
const decision = await grant({
|
|
309
|
+
method: context.method,
|
|
310
|
+
path: context.path,
|
|
311
|
+
route: `${context.method} ${context.path}`,
|
|
312
|
+
header: (name) => safeCall(() => adapter.getHeader(name)),
|
|
313
|
+
query: safeCall(() => adapter.getQueryParams?.() ?? {}) ?? {},
|
|
314
|
+
config: matchRouteConfig(config, context.method, context.path)
|
|
315
|
+
});
|
|
316
|
+
if (decision === true) {
|
|
317
|
+
bus.emit(
|
|
318
|
+
(0, import_core.makeEvent)({
|
|
319
|
+
type: "access.granted",
|
|
320
|
+
requestId: context.requestId,
|
|
321
|
+
route: `${context.method} ${context.path}`,
|
|
322
|
+
scheme: "exact",
|
|
323
|
+
network: config.network,
|
|
324
|
+
amount: "0",
|
|
325
|
+
asset: "",
|
|
326
|
+
payTo: config.payTo
|
|
327
|
+
})
|
|
328
|
+
);
|
|
329
|
+
next();
|
|
330
|
+
return;
|
|
331
|
+
}
|
|
332
|
+
if (typeof decision === "string") {
|
|
333
|
+
bus.emit(
|
|
334
|
+
(0, import_core.makeEvent)({
|
|
335
|
+
type: "access.denied",
|
|
336
|
+
requestId: context.requestId,
|
|
337
|
+
route: `${context.method} ${context.path}`,
|
|
338
|
+
scheme: "exact",
|
|
339
|
+
network: config.network,
|
|
340
|
+
amount: "0",
|
|
341
|
+
asset: "",
|
|
342
|
+
payTo: config.payTo,
|
|
343
|
+
reason: decision
|
|
344
|
+
})
|
|
345
|
+
);
|
|
346
|
+
if (!res.headersSent) res.status(403).json({ error: "access_denied" });
|
|
347
|
+
return;
|
|
348
|
+
}
|
|
349
|
+
} catch (error) {
|
|
350
|
+
const reason = error instanceof Error ? error.message.slice(0, 200) : "grant_error";
|
|
351
|
+
bus.emit(
|
|
352
|
+
(0, import_core.makeEvent)({
|
|
353
|
+
type: "access.denied",
|
|
354
|
+
requestId: context.requestId,
|
|
355
|
+
route: `${context.method} ${context.path}`,
|
|
356
|
+
scheme: "exact",
|
|
357
|
+
network: config.network,
|
|
358
|
+
amount: "0",
|
|
359
|
+
asset: "",
|
|
360
|
+
payTo: config.payTo,
|
|
361
|
+
reason
|
|
362
|
+
})
|
|
363
|
+
);
|
|
364
|
+
if (!res.headersSent) {
|
|
365
|
+
res.status(403).json({ error: "access_denied" });
|
|
366
|
+
}
|
|
367
|
+
return;
|
|
368
|
+
}
|
|
369
|
+
}
|
|
370
|
+
try {
|
|
371
|
+
await ready;
|
|
372
|
+
} catch (error) {
|
|
373
|
+
const asError = initFailure ?? (error instanceof Error ? error : new Error(String(error)));
|
|
374
|
+
emitInitFailure(asError);
|
|
375
|
+
if (!res.headersSent) {
|
|
376
|
+
res.status(502).json(FACILITATOR_UNAVAILABLE_BODY);
|
|
377
|
+
} else if (!res.writableEnded) {
|
|
378
|
+
res.end();
|
|
379
|
+
}
|
|
380
|
+
return;
|
|
381
|
+
}
|
|
382
|
+
void Promise.resolve(inner(req, res, next)).catch((error) => {
|
|
383
|
+
const asError = error instanceof Error ? error : new Error(String(error));
|
|
384
|
+
respondFacilitatorUnavailable(
|
|
385
|
+
res,
|
|
386
|
+
context.requestId,
|
|
387
|
+
`${context.method} ${context.path}`,
|
|
388
|
+
asError
|
|
389
|
+
);
|
|
390
|
+
});
|
|
391
|
+
})().catch((error) => {
|
|
392
|
+
const asError = error instanceof Error ? error : new Error(String(error));
|
|
393
|
+
bus.emit(
|
|
394
|
+
(0, import_core.makeEvent)({
|
|
395
|
+
type: "facilitator.error",
|
|
396
|
+
ts: (/* @__PURE__ */ new Date()).toISOString(),
|
|
397
|
+
requestId: context.requestId,
|
|
398
|
+
route: `${context.method} ${context.path}`,
|
|
399
|
+
scheme: "exact",
|
|
400
|
+
network: config.network,
|
|
401
|
+
amount: "0",
|
|
402
|
+
asset: "",
|
|
403
|
+
payTo: config.payTo,
|
|
404
|
+
message: `middleware: ${asError.message}`
|
|
405
|
+
})
|
|
406
|
+
);
|
|
407
|
+
if (!res.headersSent) {
|
|
408
|
+
res.status(500).json({ error: "internal_error", code: "MIDDLEWARE_ERROR" });
|
|
409
|
+
} else if (!res.writableEnded) {
|
|
410
|
+
res.end();
|
|
411
|
+
}
|
|
412
|
+
});
|
|
413
|
+
});
|
|
414
|
+
};
|
|
415
|
+
return {
|
|
416
|
+
middleware,
|
|
417
|
+
server,
|
|
418
|
+
httpServer,
|
|
419
|
+
config,
|
|
420
|
+
ready,
|
|
421
|
+
on(listener) {
|
|
422
|
+
const sink = (0, import_core.callbackSink)(listener);
|
|
423
|
+
bus.add(sink);
|
|
424
|
+
return () => {
|
|
425
|
+
bus.remove(sink);
|
|
426
|
+
};
|
|
427
|
+
},
|
|
428
|
+
close() {
|
|
429
|
+
return bus.close();
|
|
430
|
+
}
|
|
431
|
+
};
|
|
432
|
+
}
|
|
433
|
+
function matchRouteConfig(config, method, path) {
|
|
434
|
+
const candidates = config.routes.filter(
|
|
435
|
+
(route) => route.method === method || route.method === "*"
|
|
436
|
+
);
|
|
437
|
+
const exact = candidates.find((route) => route.path === path);
|
|
438
|
+
if (exact) return exact;
|
|
439
|
+
return candidates.find((route) => pathMatchesPattern(route.path, path));
|
|
440
|
+
}
|
|
441
|
+
function pathMatchesPattern(pattern, path) {
|
|
442
|
+
if (pattern === path) return true;
|
|
443
|
+
const patternParts = pattern.split("/");
|
|
444
|
+
const pathParts = path.split("/");
|
|
445
|
+
if (patternParts.length !== pathParts.length) return false;
|
|
446
|
+
for (let index = 0; index < patternParts.length; index += 1) {
|
|
447
|
+
const expected = patternParts[index] ?? "";
|
|
448
|
+
const actual = pathParts[index] ?? "";
|
|
449
|
+
if (expected.startsWith(":") || expected === "*") continue;
|
|
450
|
+
if (expected !== actual) return false;
|
|
451
|
+
}
|
|
452
|
+
return true;
|
|
453
|
+
}
|
|
454
|
+
function safeCall(read) {
|
|
455
|
+
try {
|
|
456
|
+
return read();
|
|
457
|
+
} catch {
|
|
458
|
+
return void 0;
|
|
459
|
+
}
|
|
460
|
+
}
|
|
461
|
+
function buildFacilitatorClient(config) {
|
|
462
|
+
const authHeaders = config.facilitatorHeaders;
|
|
463
|
+
const timeoutMs = config.facilitatorTimeoutMs;
|
|
464
|
+
return new import_server.HTTPFacilitatorClient({
|
|
465
|
+
url: config.facilitatorUrl,
|
|
466
|
+
...timeoutMs !== void 0 ? { timeoutMs } : {},
|
|
467
|
+
...authHeaders ? { createAuthHeaders: async () => authHeaders } : {}
|
|
468
|
+
});
|
|
469
|
+
}
|
|
470
|
+
function buildSinks(sinkOptions) {
|
|
471
|
+
const sinks = [];
|
|
472
|
+
if (sinkOptions?.console ?? true) sinks.push((0, import_core.consoleSink)());
|
|
473
|
+
if (sinkOptions?.jsonlPath) sinks.push((0, import_core.jsonlFileSink)(sinkOptions.jsonlPath));
|
|
474
|
+
if (sinkOptions?.onEvent) sinks.push((0, import_core.callbackSink)(sinkOptions.onEvent));
|
|
475
|
+
if (sinkOptions?.prometheus) {
|
|
476
|
+
sinks.push(
|
|
477
|
+
(0, import_core.prometheusSink)(
|
|
478
|
+
sinkOptions.prometheus === true ? void 0 : sinkOptions.prometheus
|
|
479
|
+
)
|
|
480
|
+
);
|
|
481
|
+
}
|
|
482
|
+
if (sinkOptions?.otel) sinks.push((0, import_core.openTelemetrySink)(sinkOptions.otel));
|
|
483
|
+
if (sinkOptions?.sentry) sinks.push((0, import_core.sentryBreadcrumbSink)(sinkOptions.sentry));
|
|
484
|
+
return sinks;
|
|
485
|
+
}
|
|
486
|
+
function buildCorsHeaders(cors) {
|
|
487
|
+
if (!cors) return void 0;
|
|
488
|
+
const headers = {
|
|
489
|
+
"Access-Control-Expose-Headers": "PAYMENT-REQUIRED, PAYMENT-RESPONSE",
|
|
490
|
+
"Access-Control-Allow-Headers": "Content-Type, PAYMENT-SIGNATURE",
|
|
491
|
+
"Access-Control-Allow-Methods": "GET, POST, PUT, PATCH, DELETE, OPTIONS"
|
|
492
|
+
};
|
|
493
|
+
if (typeof cors === "object" && cors.origin) {
|
|
494
|
+
headers["Access-Control-Allow-Origin"] = cors.origin;
|
|
495
|
+
if (cors.origin !== "*") headers.Vary = "Origin";
|
|
496
|
+
}
|
|
497
|
+
return headers;
|
|
498
|
+
}
|
|
499
|
+
function applyCorsHeaders(res, headers) {
|
|
500
|
+
const replaceHeaders = /* @__PURE__ */ new Set(["access-control-allow-origin", "vary"]);
|
|
501
|
+
for (const [name, value] of Object.entries(headers)) {
|
|
502
|
+
const existing = res.getHeader(name);
|
|
503
|
+
if (existing === void 0 || replaceHeaders.has(name.toLowerCase())) {
|
|
504
|
+
res.setHeader(name, value);
|
|
505
|
+
continue;
|
|
506
|
+
}
|
|
507
|
+
const merged = new Set(
|
|
508
|
+
String(existing).split(",").map((part) => part.trim()).filter(Boolean)
|
|
509
|
+
);
|
|
510
|
+
for (const item of value.split(",").map((part) => part.trim())) merged.add(item);
|
|
511
|
+
res.setHeader(name, Array.from(merged).join(", "));
|
|
512
|
+
}
|
|
513
|
+
}
|
|
514
|
+
function registerScheme(server, network, schemes) {
|
|
515
|
+
const separator = network.indexOf(":");
|
|
516
|
+
const namespace = separator === -1 ? network : network.slice(0, separator);
|
|
517
|
+
const caip2 = network;
|
|
518
|
+
switch (namespace) {
|
|
519
|
+
case "eip155": {
|
|
520
|
+
server.register(caip2, new import_server2.ExactEvmScheme());
|
|
521
|
+
if (schemes.has("upto")) server.register(caip2, new import_server3.UptoEvmScheme());
|
|
522
|
+
return;
|
|
523
|
+
}
|
|
524
|
+
case "solana": {
|
|
525
|
+
server.register(caip2, new import_server4.ExactSvmScheme());
|
|
526
|
+
if (schemes.has("upto")) server.register(caip2, new import_server5.UptoSvmScheme({}));
|
|
527
|
+
return;
|
|
528
|
+
}
|
|
529
|
+
default:
|
|
530
|
+
throw new Error(
|
|
531
|
+
`[x402-lens] No scheme for namespace "${namespace}". This package registers exact (and upto) schemes for eip155 and solana. For any other network, keep the returned server instance and call server.register(network, scheme) yourself.`
|
|
532
|
+
);
|
|
533
|
+
}
|
|
534
|
+
}
|
|
535
|
+
function schemesInUse(config) {
|
|
536
|
+
const used = /* @__PURE__ */ new Set();
|
|
537
|
+
for (const route of config.routes) used.add(route.scheme ?? "exact");
|
|
538
|
+
return used;
|
|
539
|
+
}
|
|
540
|
+
function attachHooks(server, bus, config) {
|
|
541
|
+
server.onAfterVerify(async (context) => {
|
|
542
|
+
const requirements = context.requirements;
|
|
543
|
+
const result = context.result;
|
|
544
|
+
const payload = context.paymentPayload;
|
|
545
|
+
const base = baseEvent(requirements, config, result.isValid ? result.payer : void 0);
|
|
546
|
+
const findings = (0, import_core.diagnose)({
|
|
547
|
+
verifyResponse: result,
|
|
548
|
+
paymentPayload: payload,
|
|
549
|
+
paymentRequired: syntheticChallenge(requirements)
|
|
550
|
+
});
|
|
551
|
+
if (!result.isValid) {
|
|
552
|
+
bus.emit(
|
|
553
|
+
(0, import_core.makeEvent)({
|
|
554
|
+
...base,
|
|
555
|
+
type: "payment.failed",
|
|
556
|
+
reason: result.invalidReason ?? "unknown",
|
|
557
|
+
findings
|
|
558
|
+
})
|
|
559
|
+
);
|
|
560
|
+
return;
|
|
561
|
+
}
|
|
562
|
+
bus.emit((0, import_core.makeEvent)({ ...base, type: "payment.verified" }));
|
|
563
|
+
});
|
|
564
|
+
server.onVerifyFailure(async (context) => {
|
|
565
|
+
const requirements = context.requirements;
|
|
566
|
+
bus.emit(
|
|
567
|
+
(0, import_core.makeEvent)({
|
|
568
|
+
...baseEvent(requirements, config),
|
|
569
|
+
type: "facilitator.error",
|
|
570
|
+
message: context.error.message
|
|
571
|
+
})
|
|
572
|
+
);
|
|
573
|
+
});
|
|
574
|
+
server.onAfterSettle(async (context) => {
|
|
575
|
+
const requirements = context.requirements;
|
|
576
|
+
const result = context.result;
|
|
577
|
+
bus.emit(
|
|
578
|
+
(0, import_core.makeEvent)({
|
|
579
|
+
...baseEvent(requirements, config, result.payer),
|
|
580
|
+
type: "payment.settled",
|
|
581
|
+
txHash: result.transaction ?? "",
|
|
582
|
+
phase: context.phase,
|
|
583
|
+
findings: (0, import_core.diagnose)({ settleResponse: result })
|
|
584
|
+
})
|
|
585
|
+
);
|
|
586
|
+
});
|
|
587
|
+
server.onSettleFailure(async (context) => {
|
|
588
|
+
const requirements = context.requirements;
|
|
589
|
+
const settle = (0, import_core.settleResponseFromError)(context.error);
|
|
590
|
+
bus.emit(
|
|
591
|
+
(0, import_core.makeEvent)({
|
|
592
|
+
...baseEvent(requirements, config, settle?.payer),
|
|
593
|
+
type: "payment.settle_failed",
|
|
594
|
+
reason: settle?.errorReason ?? context.error.message,
|
|
595
|
+
...settle?.transaction ? { txHash: settle.transaction } : {},
|
|
596
|
+
phase: context.phase,
|
|
597
|
+
findings: (0, import_core.diagnose)({ settleResponse: settle })
|
|
598
|
+
})
|
|
599
|
+
);
|
|
600
|
+
});
|
|
601
|
+
server.onVerifiedPaymentCanceled(async (context) => {
|
|
602
|
+
const requirements = context.requirements;
|
|
603
|
+
bus.emit(
|
|
604
|
+
(0, import_core.makeEvent)({
|
|
605
|
+
...baseEvent(requirements, config),
|
|
606
|
+
type: "payment.canceled",
|
|
607
|
+
cancelReason: context.reason,
|
|
608
|
+
phase: context.phase
|
|
609
|
+
})
|
|
610
|
+
);
|
|
611
|
+
});
|
|
612
|
+
}
|
|
613
|
+
function baseEvent(requirements, config, buyer) {
|
|
614
|
+
const context = currentRequestContext();
|
|
615
|
+
return {
|
|
616
|
+
ts: (/* @__PURE__ */ new Date()).toISOString(),
|
|
617
|
+
requestId: context?.requestId ?? (0, import_node_crypto.randomUUID)(),
|
|
618
|
+
route: `${context?.method ?? "GET"} ${context?.path ?? "/"}`,
|
|
619
|
+
scheme: requirements.scheme ?? "exact",
|
|
620
|
+
network: requirements.network ?? config.network,
|
|
621
|
+
amount: requirements.amount ?? "0",
|
|
622
|
+
asset: requirements.asset ?? "",
|
|
623
|
+
payTo: requirements.payTo ?? config.payTo,
|
|
624
|
+
...buyer ? { buyer } : {},
|
|
625
|
+
...context ? { durationMs: Date.now() - context.startedAt } : {}
|
|
626
|
+
};
|
|
627
|
+
}
|
|
628
|
+
function syntheticChallenge(requirements) {
|
|
629
|
+
return {
|
|
630
|
+
x402Version: 2,
|
|
631
|
+
accepts: [requirements]
|
|
632
|
+
};
|
|
633
|
+
}
|
|
634
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
635
|
+
0 && (module.exports = {
|
|
636
|
+
PrometheusRegistry,
|
|
637
|
+
paymentLens,
|
|
638
|
+
paymentLensAsync,
|
|
639
|
+
prometheusHandler
|
|
640
|
+
});
|
|
641
|
+
//# sourceMappingURL=index.cjs.map
|