@x402-lens/express 0.2.0 → 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/README.md +21 -6
- package/dist/index.cjs +254 -60
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +18 -6
- package/dist/index.d.ts +18 -6
- package/dist/index.js +258 -61
- package/dist/index.js.map +1 -1
- package/package.json +55 -55
- package/dist/.tsbuildinfo +0 -1
package/README.md
CHANGED
|
@@ -41,14 +41,28 @@ Configuration comes from `X402_FACILITATOR_URL`, `X402_NETWORK`, and
|
|
|
41
41
|
|
|
42
42
|
`paymentLens()` returns `middleware`, the underlying `server` and `httpServer`
|
|
43
43
|
(for custom hooks or schemes on networks this package does not register),
|
|
44
|
-
`config`, `on(listener)`, and `close()`.
|
|
44
|
+
`config`, `ready`, `on(listener)`, and `close()`.
|
|
45
|
+
|
|
46
|
+
Await `lens.ready` before accepting traffic so a dead facilitator fails the
|
|
47
|
+
deploy instead of the first buyer's request:
|
|
48
|
+
|
|
49
|
+
```ts
|
|
50
|
+
const lens = paymentLens({ /* … */ });
|
|
51
|
+
await lens.ready;
|
|
52
|
+
app.use(lens.middleware);
|
|
53
|
+
```
|
|
45
54
|
|
|
46
55
|
## CORS
|
|
47
56
|
|
|
48
57
|
Off by default: an app with its own CORS layer should own it. When a browser
|
|
49
58
|
buys from a different origin, none of the three payment headers is
|
|
50
|
-
CORS-safelisted, so payments fail silently. `x402-lens inspect` detects this
|
|
51
|
-
|
|
59
|
+
CORS-safelisted, so payments fail silently. `x402-lens inspect` detects this.
|
|
60
|
+
|
|
61
|
+
Use `cors: { origin: "https://app.example.com" }` (or `"*"`) so
|
|
62
|
+
`Access-Control-Allow-Origin` is set together with the payment expose/allow
|
|
63
|
+
headers. `cors: true` only sets the payment expose/allow headers — it does
|
|
64
|
+
**not** set `Access-Control-Allow-Origin`; browser buyers still fail unless
|
|
65
|
+
your own CORS middleware supplies it.
|
|
52
66
|
|
|
53
67
|
## Several networks on one route
|
|
54
68
|
|
|
@@ -76,6 +90,7 @@ and exits the process if one is missing. Run `x402-lens doctor` in CI.
|
|
|
76
90
|
## Free access
|
|
77
91
|
|
|
78
92
|
`grant` runs before verification on each protected request. Return `true` for
|
|
79
|
-
access without payment, or a string to deny with a 403
|
|
80
|
-
|
|
81
|
-
|
|
93
|
+
access without payment, or a string to deny with a 403. The buyer always sees
|
|
94
|
+
`{ error: "access_denied" }`; the string is only on the `access.denied` event.
|
|
95
|
+
`request.config` is the matched route (price, scheme, metadata) when known.
|
|
96
|
+
Both decisions emit events, so a bypass is visible rather than silent.
|
package/dist/index.cjs
CHANGED
|
@@ -123,26 +123,50 @@ function observePaymentRequired(res, onChallenge, options = {}) {
|
|
|
123
123
|
|
|
124
124
|
// src/index.ts
|
|
125
125
|
var import_core2 = require("@x402-lens/core");
|
|
126
|
+
var FACILITATOR_UNAVAILABLE_BODY = {
|
|
127
|
+
error: "facilitator_unavailable",
|
|
128
|
+
code: "FACILITATOR_UNAVAILABLE"
|
|
129
|
+
};
|
|
126
130
|
function paymentLens(options = {}) {
|
|
127
|
-
const config = options.config
|
|
131
|
+
const config = options.config ? ((0, import_core.assertLensConfig)(options.config), normalisePassedConfig(options.config)) : (0, import_core.resolveConfig)({
|
|
128
132
|
...options,
|
|
129
133
|
routes: normaliseRouteInput(options.routes)
|
|
130
134
|
});
|
|
131
135
|
return buildLens(config, options);
|
|
132
136
|
}
|
|
133
137
|
async function paymentLensAsync(options = {}) {
|
|
134
|
-
const config = options.config
|
|
138
|
+
const config = options.config ? ((0, import_core.assertLensConfig)(options.config), normalisePassedConfig(options.config)) : await (0, import_core.loadConfig)({
|
|
135
139
|
...options,
|
|
136
140
|
routes: normaliseRouteInput(options.routes)
|
|
137
141
|
});
|
|
138
142
|
return buildLens(config, options);
|
|
139
143
|
}
|
|
144
|
+
function normalisePassedConfig(config) {
|
|
145
|
+
return {
|
|
146
|
+
...config,
|
|
147
|
+
facilitatorUrl: config.facilitatorUrl.replace(/\/+$/, "")
|
|
148
|
+
};
|
|
149
|
+
}
|
|
140
150
|
function normaliseRouteInput(routes) {
|
|
141
151
|
if (!routes) return void 0;
|
|
142
152
|
if (Array.isArray(routes)) return routes;
|
|
143
|
-
return Object.entries(routes).map(
|
|
144
|
-
(
|
|
145
|
-
|
|
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
|
+
}
|
|
146
170
|
}
|
|
147
171
|
function buildLens(config, options) {
|
|
148
172
|
const bus = new import_core.EventBus([
|
|
@@ -154,58 +178,81 @@ function buildLens(config, options) {
|
|
|
154
178
|
const server = new import_server.x402ResourceServer(facilitatorClient);
|
|
155
179
|
const schemes = schemesInUse(config);
|
|
156
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
|
+
}
|
|
157
187
|
const routes = options.routesConfig ?? (0, import_core.toRoutesConfig)(config);
|
|
158
188
|
attachHooks(server, bus, config);
|
|
159
189
|
const httpServer = new import_server.x402HTTPResourceServer(server, routes);
|
|
160
|
-
|
|
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
|
+
);
|
|
161
227
|
const corsHeaders = buildCorsHeaders(options.cors);
|
|
162
|
-
if (options.
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
const decision = await grant({
|
|
168
|
-
method,
|
|
169
|
-
path,
|
|
170
|
-
route: `${method} ${path}`,
|
|
171
|
-
header: (name) => safeCall(() => context.adapter.getHeader(name)),
|
|
172
|
-
query: safeCall(() => context.adapter.getQueryParams?.() ?? {}) ?? {},
|
|
173
|
-
config: routeConfig
|
|
174
|
-
});
|
|
175
|
-
if (decision === true) {
|
|
176
|
-
bus.emit(
|
|
177
|
-
(0, import_core.makeEvent)({
|
|
178
|
-
type: "access.granted",
|
|
179
|
-
requestId: currentRequestContext()?.requestId ?? (0, import_node_crypto.randomUUID)(),
|
|
180
|
-
route: `${method} ${path}`,
|
|
181
|
-
scheme: "exact",
|
|
182
|
-
network: config.network,
|
|
183
|
-
amount: "0",
|
|
184
|
-
asset: "",
|
|
185
|
-
payTo: config.payTo
|
|
186
|
-
})
|
|
187
|
-
);
|
|
188
|
-
return { grantAccess: true };
|
|
189
|
-
}
|
|
190
|
-
if (typeof decision === "string") {
|
|
191
|
-
bus.emit(
|
|
192
|
-
(0, import_core.makeEvent)({
|
|
193
|
-
type: "access.denied",
|
|
194
|
-
requestId: currentRequestContext()?.requestId ?? (0, import_node_crypto.randomUUID)(),
|
|
195
|
-
route: `${method} ${path}`,
|
|
196
|
-
scheme: "exact",
|
|
197
|
-
network: config.network,
|
|
198
|
-
amount: "0",
|
|
199
|
-
asset: "",
|
|
200
|
-
payTo: config.payTo,
|
|
201
|
-
reason: decision
|
|
202
|
-
})
|
|
203
|
-
);
|
|
204
|
-
return { abort: true, reason: decision };
|
|
205
|
-
}
|
|
206
|
-
return void 0;
|
|
207
|
-
});
|
|
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
|
+
);
|
|
208
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
|
+
};
|
|
209
256
|
const middleware = (req, res, next) => {
|
|
210
257
|
const context = {
|
|
211
258
|
requestId: (0, import_node_crypto.randomUUID)(),
|
|
@@ -214,6 +261,14 @@ function buildLens(config, options) {
|
|
|
214
261
|
path: req.path
|
|
215
262
|
};
|
|
216
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
|
+
}
|
|
217
272
|
const emitRequired = (paymentRequired) => {
|
|
218
273
|
const entries = paymentRequired.accepts ?? [];
|
|
219
274
|
const entry = entries[0];
|
|
@@ -234,13 +289,135 @@ function buildLens(config, options) {
|
|
|
234
289
|
);
|
|
235
290
|
};
|
|
236
291
|
observePaymentRequired(res, emitRequired, { mirrorBody: readableBody });
|
|
237
|
-
runWithRequestContext(context, () =>
|
|
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
|
+
});
|
|
238
414
|
};
|
|
239
415
|
return {
|
|
240
416
|
middleware,
|
|
241
417
|
server,
|
|
242
418
|
httpServer,
|
|
243
419
|
config,
|
|
420
|
+
ready,
|
|
244
421
|
on(listener) {
|
|
245
422
|
const sink = (0, import_core.callbackSink)(listener);
|
|
246
423
|
bus.add(sink);
|
|
@@ -253,6 +430,27 @@ function buildLens(config, options) {
|
|
|
253
430
|
}
|
|
254
431
|
};
|
|
255
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
|
+
}
|
|
256
454
|
function safeCall(read) {
|
|
257
455
|
try {
|
|
258
456
|
return read();
|
|
@@ -299,9 +497,10 @@ function buildCorsHeaders(cors) {
|
|
|
299
497
|
return headers;
|
|
300
498
|
}
|
|
301
499
|
function applyCorsHeaders(res, headers) {
|
|
500
|
+
const replaceHeaders = /* @__PURE__ */ new Set(["access-control-allow-origin", "vary"]);
|
|
302
501
|
for (const [name, value] of Object.entries(headers)) {
|
|
303
502
|
const existing = res.getHeader(name);
|
|
304
|
-
if (existing === void 0) {
|
|
503
|
+
if (existing === void 0 || replaceHeaders.has(name.toLowerCase())) {
|
|
305
504
|
res.setHeader(name, value);
|
|
306
505
|
continue;
|
|
307
506
|
}
|
|
@@ -387,7 +586,7 @@ function attachHooks(server, bus, config) {
|
|
|
387
586
|
});
|
|
388
587
|
server.onSettleFailure(async (context) => {
|
|
389
588
|
const requirements = context.requirements;
|
|
390
|
-
const settle =
|
|
589
|
+
const settle = (0, import_core.settleResponseFromError)(context.error);
|
|
391
590
|
bus.emit(
|
|
392
591
|
(0, import_core.makeEvent)({
|
|
393
592
|
...baseEvent(requirements, config, settle?.payer),
|
|
@@ -432,11 +631,6 @@ function syntheticChallenge(requirements) {
|
|
|
432
631
|
accepts: [requirements]
|
|
433
632
|
};
|
|
434
633
|
}
|
|
435
|
-
function settleFromError(error) {
|
|
436
|
-
if (!error || typeof error !== "object") return void 0;
|
|
437
|
-
const candidate = error;
|
|
438
|
-
return candidate.settleResponse ?? candidate.result ?? candidate.body;
|
|
439
|
-
}
|
|
440
634
|
// Annotate the CommonJS export names for ESM import in node:
|
|
441
635
|
0 && (module.exports = {
|
|
442
636
|
PrometheusRegistry,
|