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