@x402-lens/cli 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/dist/index.js +182 -34
- package/dist/index.js.map +1 -1
- package/package.json +41 -41
package/dist/index.js
CHANGED
|
@@ -13,7 +13,8 @@ var IMPORT_LINE = 'import { paymentLens } from "@x402-lens/express";';
|
|
|
13
13
|
var LENS_DECLARATION = "const lens = paymentLens();";
|
|
14
14
|
var MOUNT_LINE = "app.use(lens.middleware);";
|
|
15
15
|
async function addProtection(options) {
|
|
16
|
-
const { file, route
|
|
16
|
+
const { file, route } = options;
|
|
17
|
+
const price = assertAddPrice(options.price);
|
|
17
18
|
if (basename(file).match(/\.(ts|js|mjs|cjs)$/) === null) {
|
|
18
19
|
throw new AddError(
|
|
19
20
|
`${file} is not a JavaScript or TypeScript file. This command edits source files, not compiled output.`
|
|
@@ -40,9 +41,9 @@ async function addProtection(options) {
|
|
|
40
41
|
const routePattern = findRouteDeclaration(original, parsed);
|
|
41
42
|
if (!routePattern) {
|
|
42
43
|
throw new AddError(
|
|
43
|
-
`Could not find a route declaration for
|
|
44
|
+
`Could not find a route declaration for ${tsStringLiteral(`${parsed.method} ${parsed.path}`)} in ${file}. The add command recognises app.get("/path", ...) and router.post("/path", ...) forms written on one line. Add the middleware manually:
|
|
44
45
|
|
|
45
|
-
const lens = paymentLens({ routes: {
|
|
46
|
+
const lens = paymentLens({ routes: { ${routeMapEntry(parsed, price)} } });
|
|
46
47
|
app.use(lens.middleware);
|
|
47
48
|
`
|
|
48
49
|
);
|
|
@@ -89,6 +90,19 @@ function parseRoute(route) {
|
|
|
89
90
|
function routeKey(route) {
|
|
90
91
|
return `${route.method} ${route.path}`;
|
|
91
92
|
}
|
|
93
|
+
function tsStringLiteral(value) {
|
|
94
|
+
return JSON.stringify(value);
|
|
95
|
+
}
|
|
96
|
+
function routeMapEntry(route, price) {
|
|
97
|
+
return `${tsStringLiteral(routeKey(route))}: ${tsStringLiteral(price)}`;
|
|
98
|
+
}
|
|
99
|
+
function assertAddPrice(price) {
|
|
100
|
+
const trimmed = price.trim();
|
|
101
|
+
if (trimmed.length === 0) {
|
|
102
|
+
throw new AddError('price is empty. Use a decimal such as "0.001".');
|
|
103
|
+
}
|
|
104
|
+
return trimmed;
|
|
105
|
+
}
|
|
92
106
|
function matchBrace(source, open) {
|
|
93
107
|
let depth = 0;
|
|
94
108
|
for (let index = open; index < source.length; index += 1) {
|
|
@@ -194,7 +208,7 @@ function withRouteEntry(source, file, route, price) {
|
|
|
194
208
|
throw new AddError(
|
|
195
209
|
`${file} passes routes as an array, which x402-lens add does not rewrite. Add the entry by hand:
|
|
196
210
|
|
|
197
|
-
{ route:
|
|
211
|
+
{ route: ${tsStringLiteral(routeKey(route))}, price: ${tsStringLiteral(price)} }
|
|
198
212
|
`
|
|
199
213
|
);
|
|
200
214
|
}
|
|
@@ -203,11 +217,11 @@ function withRouteEntry(source, file, route, price) {
|
|
|
203
217
|
throw new AddError(
|
|
204
218
|
`paymentLens is already called, but its routes map could not be found, so x402-lens add will not guess where to put ${routeKey(route)}. Add it by hand:
|
|
205
219
|
|
|
206
|
-
routes: {
|
|
220
|
+
routes: { ${routeMapEntry(route, price)} }
|
|
207
221
|
`
|
|
208
222
|
);
|
|
209
223
|
}
|
|
210
|
-
const entry =
|
|
224
|
+
const entry = routeMapEntry(route, price);
|
|
211
225
|
const inner = source.slice(routes.open + 1, routes.close);
|
|
212
226
|
const trailing = inner.match(/\s*$/)?.[0] ?? "";
|
|
213
227
|
const insertAt = routes.close - trailing.length;
|
|
@@ -252,7 +266,7 @@ function applyEdits(source, route, price, routeMatch) {
|
|
|
252
266
|
`;
|
|
253
267
|
const body = `${LENS_DECLARATION.replace(
|
|
254
268
|
"paymentLens()",
|
|
255
|
-
`paymentLens({ routes: {
|
|
269
|
+
`paymentLens({ routes: { ${routeMapEntry(route, price)} } })`
|
|
256
270
|
)}
|
|
257
271
|
${MOUNT_LINE}
|
|
258
272
|
|
|
@@ -445,7 +459,8 @@ async function explainPayment(input) {
|
|
|
445
459
|
" --settle <json|@file> facilitator /settle response"
|
|
446
460
|
].join("\n"),
|
|
447
461
|
exitCode: 2,
|
|
448
|
-
findingCount: 0
|
|
462
|
+
findingCount: 0,
|
|
463
|
+
findings: []
|
|
449
464
|
};
|
|
450
465
|
}
|
|
451
466
|
const findings = diagnose({
|
|
@@ -467,12 +482,14 @@ async function explainPayment(input) {
|
|
|
467
482
|
|
|
468
483
|
${formatFindings(findings)}`,
|
|
469
484
|
exitCode: hasError ? 1 : 0,
|
|
470
|
-
findingCount: findings.length
|
|
485
|
+
findingCount: findings.length,
|
|
486
|
+
findings
|
|
471
487
|
};
|
|
472
488
|
}
|
|
473
489
|
|
|
474
490
|
// src/commands/doctor.ts
|
|
475
491
|
import {
|
|
492
|
+
ConfigError,
|
|
476
493
|
WELL_KNOWN_NETWORKS,
|
|
477
494
|
describeNetwork,
|
|
478
495
|
isCaip2,
|
|
@@ -484,14 +501,26 @@ async function runDoctor(options = {}) {
|
|
|
484
501
|
let config;
|
|
485
502
|
let configError;
|
|
486
503
|
try {
|
|
487
|
-
config = options.config ?? await loadConfig({
|
|
504
|
+
config = options.config ?? await loadConfig({
|
|
505
|
+
readConfigFile: true,
|
|
506
|
+
...options.cwd !== void 0 ? { cwd: options.cwd } : {}
|
|
507
|
+
});
|
|
488
508
|
checks.push({
|
|
489
509
|
name: "config",
|
|
490
510
|
ok: true,
|
|
491
511
|
detail: `facilitator ${config.facilitatorUrl}, network ${config.networks.length > 1 ? config.networks.map(describeNetwork).join(", ") : describeNetwork(config.network)}, ${config.routes.length} route(s)`
|
|
492
512
|
});
|
|
513
|
+
checks.push(checkFacilitatorHeadersOk(config));
|
|
493
514
|
} catch (error) {
|
|
494
515
|
configError = error;
|
|
516
|
+
if (isFacilitatorHeadersConfigError(configError)) {
|
|
517
|
+
checks.push({
|
|
518
|
+
name: "facilitatorHeaders",
|
|
519
|
+
ok: false,
|
|
520
|
+
detail: configError.message
|
|
521
|
+
});
|
|
522
|
+
return finish(checks);
|
|
523
|
+
}
|
|
495
524
|
}
|
|
496
525
|
const facilitatorUrl = (options.facilitatorUrl ?? config?.facilitatorUrl ?? "").replace(/\/+$/, "");
|
|
497
526
|
const networks = options.networks ?? (options.network ? [options.network] : config?.networks ?? []);
|
|
@@ -526,12 +555,20 @@ async function runDoctor(options = {}) {
|
|
|
526
555
|
detail: describeNetwork(network)
|
|
527
556
|
});
|
|
528
557
|
if (config) {
|
|
529
|
-
|
|
558
|
+
for (const net of networks.length > 0 ? networks : config.networks) {
|
|
559
|
+
const address = config.payToByNetwork[net] ?? config.payTo;
|
|
560
|
+
checks.push(checkPayToShape(address, net));
|
|
561
|
+
}
|
|
530
562
|
}
|
|
531
563
|
let supported;
|
|
532
564
|
try {
|
|
565
|
+
const authHeaders = config?.facilitatorHeaders?.supported ?? {};
|
|
533
566
|
const response = await fetch(`${facilitatorUrl}/supported`, {
|
|
534
|
-
headers: {
|
|
567
|
+
headers: {
|
|
568
|
+
Accept: "application/json",
|
|
569
|
+
"User-Agent": "x402-lens/0.2",
|
|
570
|
+
...authHeaders
|
|
571
|
+
},
|
|
535
572
|
signal: AbortSignal.timeout(options.timeoutMs ?? 15e3)
|
|
536
573
|
});
|
|
537
574
|
if (!response.ok) {
|
|
@@ -595,12 +632,26 @@ async function runDoctor(options = {}) {
|
|
|
595
632
|
}
|
|
596
633
|
);
|
|
597
634
|
}
|
|
598
|
-
const
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
|
|
635
|
+
const requiredSchemes = Array.from(
|
|
636
|
+
new Set(
|
|
637
|
+
(config?.routes ?? []).map((route) => route.scheme ?? "exact")
|
|
638
|
+
)
|
|
639
|
+
);
|
|
640
|
+
const schemesToCheck = requiredSchemes.length > 0 ? requiredSchemes : ["exact"];
|
|
641
|
+
const networksForSchemes = networks.length > 0 ? networks : [network];
|
|
642
|
+
for (const scheme of schemesToCheck) {
|
|
643
|
+
const missingSchemeNetworks = networksForSchemes.filter(
|
|
644
|
+
(candidate) => !kinds.some(
|
|
645
|
+
(kind) => kind.network === candidate && kind.x402Version === 2 && kind.scheme === scheme
|
|
646
|
+
)
|
|
647
|
+
);
|
|
648
|
+
const schemeOk = missingSchemeNetworks.length === 0;
|
|
649
|
+
checks.push({
|
|
650
|
+
name: `${scheme} scheme`,
|
|
651
|
+
ok: schemeOk,
|
|
652
|
+
detail: schemeOk ? networksForSchemes.length > 1 ? `The facilitator supports the ${scheme} scheme on all configured networks.` : `The facilitator supports the ${scheme} scheme on this network.` : `Configured routes use the ${scheme} scheme, which is not listed for: ${missingSchemeNetworks.join(", ")}.`
|
|
653
|
+
});
|
|
654
|
+
}
|
|
604
655
|
if (WELL_KNOWN_NETWORKS[network]) {
|
|
605
656
|
checks.push({
|
|
606
657
|
name: "known network",
|
|
@@ -616,6 +667,23 @@ async function runDoctor(options = {}) {
|
|
|
616
667
|
}
|
|
617
668
|
return finish(checks);
|
|
618
669
|
}
|
|
670
|
+
function isFacilitatorHeadersConfigError(error) {
|
|
671
|
+
return error instanceof ConfigError && error.field === "facilitatorHeaders";
|
|
672
|
+
}
|
|
673
|
+
function checkFacilitatorHeadersOk(config) {
|
|
674
|
+
if (!config.facilitatorHeaders) {
|
|
675
|
+
return {
|
|
676
|
+
name: "facilitatorHeaders",
|
|
677
|
+
ok: true,
|
|
678
|
+
detail: "No facilitatorHeaders set (public facilitator or X402_FACILITATOR_TOKEN unset)."
|
|
679
|
+
};
|
|
680
|
+
}
|
|
681
|
+
return {
|
|
682
|
+
name: "facilitatorHeaders",
|
|
683
|
+
ok: true,
|
|
684
|
+
detail: "facilitatorHeaders use the per-path shape (verify/settle/supported), not a flat object."
|
|
685
|
+
};
|
|
686
|
+
}
|
|
619
687
|
function checkPayToShape(payTo, network) {
|
|
620
688
|
const namespace = network.slice(0, network.indexOf(":"));
|
|
621
689
|
if (namespace === "eip155") {
|
|
@@ -667,11 +735,12 @@ async function inspectEndpoint(options) {
|
|
|
667
735
|
method,
|
|
668
736
|
headers: {
|
|
669
737
|
Accept: "application/json",
|
|
670
|
-
"User-Agent": "x402-lens/0.
|
|
738
|
+
"User-Agent": "x402-lens/0.2",
|
|
671
739
|
...options.headers
|
|
672
740
|
},
|
|
673
741
|
signal: AbortSignal.timeout(options.timeoutMs ?? 15e3),
|
|
674
|
-
|
|
742
|
+
// Do not follow redirects away from a 402 paywall.
|
|
743
|
+
redirect: "manual"
|
|
675
744
|
});
|
|
676
745
|
const headerValue = response.headers.get("payment-required");
|
|
677
746
|
let paymentRequired;
|
|
@@ -703,12 +772,22 @@ async function inspectEndpoint(options) {
|
|
|
703
772
|
lines.push(`${method} ${options.url} \u2192 HTTP ${response.status}`);
|
|
704
773
|
if (!paymentRequired) {
|
|
705
774
|
lines.push("");
|
|
706
|
-
|
|
707
|
-
|
|
708
|
-
|
|
709
|
-
|
|
710
|
-
|
|
711
|
-
|
|
775
|
+
if (response.status >= 300 && response.status < 400) {
|
|
776
|
+
const location = response.headers.get("location") ?? "(no Location header)";
|
|
777
|
+
lines.push(
|
|
778
|
+
`Redirected (HTTP ${response.status}) to ${location}. inspect does not follow redirects, so a reverse proxy can hide a 402 paywall behind a 3xx.`
|
|
779
|
+
);
|
|
780
|
+
lines.push(
|
|
781
|
+
"Point inspect at the final paywall URL, or stop the redirect for this path."
|
|
782
|
+
);
|
|
783
|
+
} else {
|
|
784
|
+
lines.push(
|
|
785
|
+
"No x402 challenge found. Expected a PAYMENT-REQUIRED header (base64 PaymentRequired) on a 402 response."
|
|
786
|
+
);
|
|
787
|
+
lines.push(
|
|
788
|
+
"If this route is unprotected, you will see its normal response instead. If it is protected, check that paymentMiddleware is mounted before the route."
|
|
789
|
+
);
|
|
790
|
+
}
|
|
712
791
|
} else {
|
|
713
792
|
lines.push(
|
|
714
793
|
headerPresent ? "Challenge: PAYMENT-REQUIRED header" : "Challenge: response body (no PAYMENT-REQUIRED header)"
|
|
@@ -1037,19 +1116,19 @@ function flagEnabled(args, name) {
|
|
|
1037
1116
|
var USAGE = `x402-lens \u2014 explain and verify x402 v2 payments
|
|
1038
1117
|
|
|
1039
1118
|
Usage:
|
|
1040
|
-
x402-lens inspect <url> [--method GET] [--header "K: V"] [--timeout 15000]
|
|
1119
|
+
x402-lens inspect <url> [--method GET] [--header "K: V"] [--timeout 15000] [--json]
|
|
1041
1120
|
Fetch an endpoint unpaid, decode PAYMENT-REQUIRED, and report schema
|
|
1042
1121
|
conformance and CORS readiness for browser buyers.
|
|
1043
1122
|
|
|
1044
1123
|
x402-lens explain [--challenge <b64|json|@file>] [--payment <...>]
|
|
1045
|
-
[--verify <...>] [--settle <...>]
|
|
1124
|
+
[--verify <...>] [--settle <...>] [--json]
|
|
1046
1125
|
Diagnose a failed exchange: what is wrong, and what to change.
|
|
1047
1126
|
|
|
1048
|
-
x402-lens doctor [--facilitator <url>] [--network <caip2>] [--networks <a,b>]
|
|
1127
|
+
x402-lens doctor [--facilitator <url>] [--network <caip2>] [--networks <a,b>] [--json]
|
|
1049
1128
|
Verify that configuration can actually accept payments, including that
|
|
1050
1129
|
the facilitator supports every configured network with x402Version 2.
|
|
1051
1130
|
|
|
1052
|
-
x402-lens reconcile --tx <hash> [--network <caip2>] [--rpc <url>]
|
|
1131
|
+
x402-lens reconcile --tx <hash> [--network <caip2>] [--rpc <url>] [--json]
|
|
1053
1132
|
Check whether a settlement transaction confirmed on chain. Use this
|
|
1054
1133
|
after settlement_pending \u2014 never retry a payment until you know.
|
|
1055
1134
|
|
|
@@ -1058,6 +1137,7 @@ Usage:
|
|
|
1058
1137
|
--write is passed.
|
|
1059
1138
|
|
|
1060
1139
|
Options:
|
|
1140
|
+
--json Machine-readable JSON on stdout (inspect / explain / doctor / reconcile)
|
|
1061
1141
|
--help, -h Show this help.
|
|
1062
1142
|
|
|
1063
1143
|
Exit codes:
|
|
@@ -1067,6 +1147,7 @@ Exit codes:
|
|
|
1067
1147
|
`;
|
|
1068
1148
|
async function main(argv) {
|
|
1069
1149
|
const args = parseArgs(argv);
|
|
1150
|
+
const asJson = flagEnabled(args, "json");
|
|
1070
1151
|
if (flagEnabled(args, "help") || flagEnabled(args, "h") || args.command === void 0) {
|
|
1071
1152
|
process.stdout.write(USAGE);
|
|
1072
1153
|
return args.command === void 0 && !flagEnabled(args, "help") && !flagEnabled(args, "h") ? 2 : 0;
|
|
@@ -1085,8 +1166,27 @@ async function main(argv) {
|
|
|
1085
1166
|
...flagValue(args, "header") ? { headers: parseHeaderFlags(argv) } : {},
|
|
1086
1167
|
...flagValue(args, "timeout") ? { timeoutMs: Number.parseInt(flagValue(args, "timeout"), 10) } : {}
|
|
1087
1168
|
});
|
|
1088
|
-
|
|
1169
|
+
if (asJson) {
|
|
1170
|
+
process.stdout.write(
|
|
1171
|
+
`${JSON.stringify(
|
|
1172
|
+
{
|
|
1173
|
+
status: result.status,
|
|
1174
|
+
headerPresent: result.headerPresent,
|
|
1175
|
+
decodedFromBody: result.decodedFromBody,
|
|
1176
|
+
paymentRequired: result.paymentRequired ?? null,
|
|
1177
|
+
conformance: result.conformance,
|
|
1178
|
+
cors: result.cors,
|
|
1179
|
+
exitCode: result.exitCode
|
|
1180
|
+
},
|
|
1181
|
+
null,
|
|
1182
|
+
2
|
|
1183
|
+
)}
|
|
1184
|
+
`
|
|
1185
|
+
);
|
|
1186
|
+
} else {
|
|
1187
|
+
process.stdout.write(`${result.findings}
|
|
1089
1188
|
`);
|
|
1189
|
+
}
|
|
1090
1190
|
return result.exitCode;
|
|
1091
1191
|
}
|
|
1092
1192
|
case "explain": {
|
|
@@ -1096,8 +1196,23 @@ async function main(argv) {
|
|
|
1096
1196
|
...flagValue(args, "verify") ? { verify: flagValue(args, "verify") } : {},
|
|
1097
1197
|
...flagValue(args, "settle") ? { settle: flagValue(args, "settle") } : {}
|
|
1098
1198
|
});
|
|
1099
|
-
|
|
1199
|
+
if (asJson) {
|
|
1200
|
+
process.stdout.write(
|
|
1201
|
+
`${JSON.stringify(
|
|
1202
|
+
{
|
|
1203
|
+
findings: result.findings,
|
|
1204
|
+
findingCount: result.findingCount,
|
|
1205
|
+
exitCode: result.exitCode
|
|
1206
|
+
},
|
|
1207
|
+
null,
|
|
1208
|
+
2
|
|
1209
|
+
)}
|
|
1210
|
+
`
|
|
1211
|
+
);
|
|
1212
|
+
} else {
|
|
1213
|
+
process.stdout.write(`${result.text}
|
|
1100
1214
|
`);
|
|
1215
|
+
}
|
|
1101
1216
|
return result.exitCode;
|
|
1102
1217
|
}
|
|
1103
1218
|
case "doctor": {
|
|
@@ -1109,8 +1224,22 @@ async function main(argv) {
|
|
|
1109
1224
|
networks: networksFlag.split(",").map((part) => part.trim()).filter(Boolean)
|
|
1110
1225
|
} : {}
|
|
1111
1226
|
});
|
|
1112
|
-
|
|
1227
|
+
if (asJson) {
|
|
1228
|
+
process.stdout.write(
|
|
1229
|
+
`${JSON.stringify(
|
|
1230
|
+
{
|
|
1231
|
+
checks: result.checks,
|
|
1232
|
+
exitCode: result.exitCode
|
|
1233
|
+
},
|
|
1234
|
+
null,
|
|
1235
|
+
2
|
|
1236
|
+
)}
|
|
1237
|
+
`
|
|
1238
|
+
);
|
|
1239
|
+
} else {
|
|
1240
|
+
process.stdout.write(`${result.text}
|
|
1113
1241
|
`);
|
|
1242
|
+
}
|
|
1114
1243
|
return result.exitCode;
|
|
1115
1244
|
}
|
|
1116
1245
|
case "add": {
|
|
@@ -1147,8 +1276,27 @@ async function main(argv) {
|
|
|
1147
1276
|
...flagValue(args, "rpc") ? { rpcUrl: flagValue(args, "rpc") } : {},
|
|
1148
1277
|
...flagValue(args, "timeout") ? { timeoutMs: Number.parseInt(flagValue(args, "timeout"), 10) } : {}
|
|
1149
1278
|
});
|
|
1150
|
-
|
|
1279
|
+
if (asJson) {
|
|
1280
|
+
process.stdout.write(
|
|
1281
|
+
`${JSON.stringify(
|
|
1282
|
+
{
|
|
1283
|
+
status: result.status,
|
|
1284
|
+
network: result.network,
|
|
1285
|
+
tx: result.tx,
|
|
1286
|
+
rpcUrl: result.rpcUrl,
|
|
1287
|
+
block: result.block ?? null,
|
|
1288
|
+
detail: result.detail,
|
|
1289
|
+
exitCode: result.exitCode
|
|
1290
|
+
},
|
|
1291
|
+
null,
|
|
1292
|
+
2
|
|
1293
|
+
)}
|
|
1294
|
+
`
|
|
1295
|
+
);
|
|
1296
|
+
} else {
|
|
1297
|
+
process.stdout.write(`${result.text}
|
|
1151
1298
|
`);
|
|
1299
|
+
}
|
|
1152
1300
|
return result.exitCode;
|
|
1153
1301
|
}
|
|
1154
1302
|
default:
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/commands/add.ts","../src/commands/explain.ts","../src/input.ts","../src/commands/doctor.ts","../src/commands/inspect.ts","../src/commands/reconcile.ts","../src/args.ts","../src/index.ts"],"sourcesContent":["/**\r\n * `x402-lens add` — put x402 protection on an existing Express route.\r\n *\r\n * Scaffolders create new projects; this edits the file you already have. The\r\n * approach is deliberately conservative: it only recognises the two route forms\r\n * it can rewrite safely, refuses anything else with a clear explanation, and\r\n * never writes without `--write`. A bad regex edit on someone's server file is\r\n * far worse than a refusal.\r\n */\r\n\r\nimport { readFile, writeFile } from \"node:fs/promises\";\r\nimport { basename } from \"node:path\";\r\n\r\nexport class AddError extends Error {\r\n constructor(message: string) {\r\n super(message);\r\n this.name = \"AddError\";\r\n }\r\n}\r\n\r\nexport interface AddOptions {\r\n file: string;\r\n /** Route as written by the user, e.g. `\"GET /weather\"`. */\r\n route: string;\r\n price: string;\r\n /** Apply the change. When false, only the diff is produced. */\r\n write?: boolean;\r\n}\r\n\r\nexport interface AddResult {\r\n changed: boolean;\r\n diff: string;\r\n text: string;\r\n exitCode: number;\r\n}\r\n\r\nconst IMPORT_LINE = 'import { paymentLens } from \"@x402-lens/express\";';\r\nconst LENS_DECLARATION = \"const lens = paymentLens();\";\r\nconst MOUNT_LINE = \"app.use(lens.middleware);\";\r\n\r\n/**\r\n * Insert payment protection into an existing Express server file.\r\n *\r\n * Idempotent: running it twice leaves the file unchanged the second time.\r\n *\r\n * @param options - Target file, route, and price\r\n * @returns Diff, report, and exit code\r\n * @throws {AddError} When the file is not a supported Express setup\r\n */\r\nexport async function addProtection(options: AddOptions): Promise<AddResult> {\r\n const { file, route, price } = options;\r\n\r\n if (basename(file).match(/\\.(ts|js|mjs|cjs)$/) === null) {\r\n throw new AddError(\r\n `${file} is not a JavaScript or TypeScript file. This command edits source files, not compiled output.`,\r\n );\r\n }\r\n\r\n const original = await readFile(file, \"utf8\");\r\n const parsed = parseRoute(route);\r\n\r\n const hasLens = original.includes(\"paymentLens(\");\r\n const hasRouteEntry = hasRouteEntryFor(original, parsed);\r\n\r\n if (hasLens && hasRouteEntry) {\r\n return {\r\n changed: false,\r\n diff: \"\",\r\n text: `${file} already charges for ${parsed.method} ${parsed.path}. Nothing to do.`,\r\n exitCode: 0,\r\n };\r\n }\r\n\r\n const framework = detectFramework(original);\r\n if (framework !== \"express\") {\r\n throw new AddError(\r\n `${file} does not look like an Express app (${framework}). The add command only supports Express; use paymentLens() from @x402-lens/express manually for anything else.`,\r\n );\r\n }\r\n\r\n const routePattern = findRouteDeclaration(original, parsed);\r\n if (!routePattern) {\r\n throw new AddError(\r\n `Could not find a route declaration for \"${parsed.method} ${parsed.path}\" in ${file}. The add command recognises app.get(\"/path\", ...) and router.post(\"/path\", ...) forms written on one line. Add the middleware manually:\\n\\n const lens = paymentLens({ routes: { \"${parsed.method} ${parsed.path}\": \"${price}\" } });\\n app.use(lens.middleware);\\n`,\r\n );\r\n }\r\n\r\n const updated = hasLens\r\n ? withRouteEntry(original, file, parsed, price)\r\n : applyEdits(original, parsed, price, routePattern);\r\n const diff = unifiedDiff(file, original, updated);\r\n\r\n if (!options.write) {\r\n return {\r\n changed: true,\r\n diff,\r\n text: [\r\n `Dry run — ${file} would change as follows.`,\r\n \"\",\r\n diff,\r\n \"\",\r\n \"Re-run with --write to apply. Set X402_FACILITATOR_URL, X402_NETWORK, and X402_PAY_TO first; paymentLens() refuses to guess them.\",\r\n ].join(\"\\n\"),\r\n exitCode: 0,\r\n };\r\n }\r\n\r\n await writeFile(file, updated, \"utf8\");\r\n return {\r\n changed: true,\r\n diff,\r\n text: `Updated ${file}.\\n\\n${diff}\\n\\nNext: set X402_FACILITATOR_URL, X402_NETWORK, and X402_PAY_TO, then restart. Run \\`x402-lens doctor\\` to verify the configuration.`,\r\n exitCode: 0,\r\n };\r\n}\r\n\r\ninterface ParsedRoute {\r\n method: string;\r\n path: string;\r\n}\r\n\r\nfunction parseRoute(route: string): ParsedRoute {\r\n const trimmed = route.trim();\r\n const spaceIndex = trimmed.indexOf(\" \");\r\n if (spaceIndex === -1) {\r\n return { method: \"GET\", path: trimmed };\r\n }\r\n return {\r\n method: trimmed.slice(0, spaceIndex).toUpperCase(),\r\n path: trimmed.slice(spaceIndex + 1).trim(),\r\n };\r\n}\r\n\r\n/** `\"GET /weather\"`, the key format the lens route map uses. */\r\nfunction routeKey(route: ParsedRoute): string {\r\n return `${route.method} ${route.path}`;\r\n}\r\n\r\n/**\r\n * Index of the `}` that closes the `{` at `open`, skipping strings and comments.\r\n *\r\n * A brace counter alone would trip over a route path containing `}` or a\r\n * comment mentioning `{`, so the scan respects quoting and both comment styles.\r\n *\r\n * @returns Index of the closing brace, or -1 when the source is unbalanced\r\n */\r\nfunction matchBrace(source: string, open: number): number {\r\n let depth = 0;\r\n for (let index = open; index < source.length; index += 1) {\r\n const char = source[index];\r\n const next = source[index + 1];\r\n\r\n if (char === \"/\" && next === \"/\") {\r\n const newline = source.indexOf(\"\\n\", index);\r\n if (newline === -1) return -1;\r\n index = newline;\r\n continue;\r\n }\r\n if (char === \"/\" && next === \"*\") {\r\n const end = source.indexOf(\"*/\", index + 2);\r\n if (end === -1) return -1;\r\n index = end + 1;\r\n continue;\r\n }\r\n if (char === '\"' || char === \"'\" || char === \"`\") {\r\n index = skipString(source, index);\r\n if (index === -1) return -1;\r\n continue;\r\n }\r\n if (char === \"{\") depth += 1;\r\n else if (char === \"}\") {\r\n depth -= 1;\r\n if (depth === 0) return index;\r\n }\r\n }\r\n return -1;\r\n}\r\n\r\n/** Index just past the closing quote, or -1 when the literal never closes. */\r\nfunction skipString(source: string, open: number): number {\r\n const quote = source[open];\r\n for (let index = open + 1; index < source.length; index += 1) {\r\n const char = source[index];\r\n if (char === \"\\\\\") {\r\n index += 1;\r\n continue;\r\n }\r\n if (char === quote) return index;\r\n }\r\n return -1;\r\n}\r\n\r\n/** The span of the `paymentLens(...)` argument list, when the file has one. */\r\nfunction findLensCall(source: string): { open: number; close: number } | undefined {\r\n const pattern = /\\bpaymentLens(?:Async)?\\s*\\(/;\r\n const match = pattern.exec(source);\r\n if (!match) return undefined;\r\n const open = source.indexOf(\"(\", match.index);\r\n const close = matchParen(source, open);\r\n if (close === -1) return undefined;\r\n return { open, close };\r\n}\r\n\r\n/** Index of the `)` closing the `(` at `open`, skipping strings and comments. */\r\nfunction matchParen(source: string, open: number): number {\r\n let depth = 0;\r\n for (let index = open; index < source.length; index += 1) {\r\n const char = source[index];\r\n const next = source[index + 1];\r\n\r\n if (char === \"/\" && next === \"/\") {\r\n const newline = source.indexOf(\"\\n\", index);\r\n if (newline === -1) return -1;\r\n index = newline;\r\n continue;\r\n }\r\n if (char === \"/\" && next === \"*\") {\r\n const end = source.indexOf(\"*/\", index + 2);\r\n if (end === -1) return -1;\r\n index = end + 1;\r\n continue;\r\n }\r\n if (char === '\"' || char === \"'\" || char === \"`\") {\r\n index = skipString(source, index);\r\n if (index === -1) return -1;\r\n continue;\r\n }\r\n if (char === \"(\") depth += 1;\r\n else if (char === \")\") {\r\n depth -= 1;\r\n if (depth === 0) return index;\r\n }\r\n }\r\n return -1;\r\n}\r\n\r\n/** Locate the `routes: { ... }` object literal inside a `paymentLens` call. */\r\nfunction findRoutesObject(source: string): { open: number; close: number } | undefined {\r\n const call = findLensCall(source);\r\n const scope = call ?? { open: 0, close: source.length - 1 };\r\n const inner = source.slice(scope.open, scope.close + 1);\r\n const pattern = /\\broutes\\s*:\\s*\\{/;\r\n const match = pattern.exec(inner);\r\n if (!match) return undefined;\r\n const open = scope.open + match.index + match[0].length - 1;\r\n const close = matchBrace(source, open);\r\n if (close === -1) return undefined;\r\n return { open, close };\r\n}\r\n\r\n/** True when the lens route map already charges for this route. */\r\nfunction hasRouteEntryFor(source: string, route: ParsedRoute): boolean {\r\n const key = escapeRegExp(routeKey(route));\r\n const quotedKey = new RegExp(`[\"'\\`]${key}[\"'\\`]\\\\s*:`);\r\n const routes = findRoutesObject(source);\r\n if (routes) return quotedKey.test(source.slice(routes.open, routes.close + 1));\r\n // No routes map in code: the prices come from env or x402.config.json, so a\r\n // mention of the path elsewhere says nothing about whether it is priced.\r\n return false;\r\n}\r\n\r\n/**\r\n * Add one entry to the lens route map, preserving the file's own formatting.\r\n *\r\n * Refuses the forms it cannot rewrite safely — an array-form `routes`, or a\r\n * `paymentLens()` call carrying options the command does not understand — with\r\n * instructions instead of a guess.\r\n */\r\nfunction withRouteEntry(\r\n source: string,\r\n file: string,\r\n route: ParsedRoute,\r\n price: string,\r\n): string {\r\n if (/\\broutes\\s*:\\s*\\[/.test(source)) {\r\n throw new AddError(\r\n `${file} passes routes as an array, which x402-lens add does not rewrite. Add the entry by hand:\\n\\n { route: \"${routeKey(route)}\", price: \"${price}\" }\\n`,\r\n );\r\n }\r\n\r\n const routes = findRoutesObject(source);\r\n if (!routes) {\r\n throw new AddError(\r\n `paymentLens is already called, but its routes map could not be found, so x402-lens add will not guess where to put ${routeKey(route)}. Add it by hand:\\n\\n routes: { \"${routeKey(route)}\": \"${price}\" }\\n`,\r\n );\r\n }\r\n\r\n const entry = `\"${routeKey(route)}\": \"${price}\"`;\r\n const inner = source.slice(routes.open + 1, routes.close);\r\n\r\n // Insert after the last entry, keeping the closing brace on its own line when\r\n // the object already spans several.\r\n const trailing = inner.match(/\\s*$/)?.[0] ?? \"\";\r\n const insertAt = routes.close - trailing.length;\r\n const lastEntry = source.slice(routes.open + 1, insertAt);\r\n\r\n if (lastEntry.trim().length === 0) {\r\n return `${source.slice(0, routes.open + 1)} ${entry} ${source.slice(routes.close)}`;\r\n }\r\n\r\n // Indentation comes from the line the last entry starts on, never from the\r\n // insertion point — which sits just before the closing brace's newline.\r\n const entryEnd = routes.open + 1 + lastEntry.length;\r\n const lineStart = source.lastIndexOf(\"\\n\", entryEnd - 1) + 1;\r\n const indent = source.slice(lineStart, entryEnd).match(/^[ \\t]*/)?.[0] ?? \"\";\r\n const spacer = trailing.includes(\"\\n\") ? \"\\n\" : \" \";\r\n // Follow whatever comma style the file already uses: a trailing comma on the\r\n // last entry means the author wants one on every entry.\r\n const trailingComma = lastEntry.trimEnd().endsWith(\",\");\r\n const inserted = trailingComma ? `${entry},` : entry;\r\n const separator = trailingComma ? \"\" : \",\";\r\n\r\n return `${source.slice(0, insertAt)}${separator}${spacer}${indent}${inserted}${source.slice(insertAt)}`;\r\n}\r\n\r\ntype Framework = \"express\" | \"fastify\" | \"hono\" | \"fastapi\" | \"unknown\";\r\n\r\nfunction detectFramework(source: string): Framework {\r\n if (/from\\s+[\"']express[\"']|require\\(\\s*[\"']express[\"']\\s*\\)/.test(source)) return \"express\";\r\n if (/from\\s+[\"']fastify[\"']|require\\(\\s*[\"']fastify[\"']\\s*\\)/.test(source)) return \"fastify\";\r\n if (/from\\s+[\"']hono[\"']/.test(source)) return \"hono\";\r\n if (/from\\s+fastapi\\s+import|import\\s+fastapi/.test(source)) return \"fastapi\";\r\n return \"unknown\";\r\n}\r\n\r\ninterface RouteMatch {\r\n /** Index of the route declaration's start. */\r\n routeStart: number;\r\n /** The matched declaration text, for reporting. */\r\n matched: string;\r\n}\r\n\r\n/**\r\n * Find the route and where to insert the guard.\r\n *\r\n * Matches `app.get(\"/path\",` and `router.get(\"/path\",` — including single- or\r\n * double-quoted paths. Refuses multi-line and computed-path variants by simply\r\n * not matching them.\r\n */\r\nfunction findRouteDeclaration(source: string, route: ParsedRoute): RouteMatch | undefined {\r\n const method = route.method.toLowerCase();\r\n const escapedPath = escapeRegExp(route.path);\r\n const pattern = new RegExp(\r\n `\\\\b(?:app|router|server)\\\\.${method}\\\\(\\\\s*([\"'\\`])${escapedPath}\\\\1\\\\s*,`,\r\n );\r\n const match = pattern.exec(source);\r\n if (!match) return undefined;\r\n return {\r\n routeStart: match.index,\r\n matched: match[0],\r\n };\r\n}\r\n\r\nfunction applyEdits(\r\n source: string,\r\n route: ParsedRoute,\r\n price: string,\r\n routeMatch: RouteMatch,\r\n): string {\r\n let updated = source;\r\n\r\n // The lens is mounted globally and its route map decides what is protected,\r\n // so no per-route guard is needed. Adding one as well would duplicate the\r\n // check on the same request.\r\n if (!updated.includes(\"paymentLens(\")) {\r\n // Normalise spacing rather than guess at it: exactly one blank line before\r\n // the declaration and one after the mount, whatever the file had. `\\r?` so\r\n // a CRLF file is treated the same as an LF one.\r\n const before = `${updated\r\n .slice(0, routeMatch.routeStart)\r\n .replace(/(?:[ \\t]*\\r?\\n)+$/, \"\")}\\n\\n`;\r\n const body = `${LENS_DECLARATION.replace(\r\n \"paymentLens()\",\r\n `paymentLens({ routes: { \"${route.method} ${route.path}\": \"${price}\" } })`,\r\n )}\\n${MOUNT_LINE}\\n\\n`;\r\n updated = `${before}${body}${updated.slice(routeMatch.routeStart)}`;\r\n }\r\n\r\n // Add the import after the last top-level import.\r\n if (!updated.includes(\"@x402-lens/express\")) {\r\n const lastImport = findLastImportEnd(updated);\r\n if (lastImport === -1) {\r\n updated = `${IMPORT_LINE}\\n${updated}`;\r\n } else {\r\n updated = `${updated.slice(0, lastImport)}\\n${IMPORT_LINE}${updated.slice(lastImport)}`;\r\n }\r\n }\r\n\r\n return updated;\r\n}\r\n\r\nfunction findLastImportEnd(source: string): number {\r\n const lines = source.split(\"\\n\");\r\n let offset = 0;\r\n let lastEnd = -1;\r\n\r\n for (const line of lines) {\r\n const trimmed = line.trim();\r\n const isImportStart = trimmed.startsWith(\"import \");\r\n const isImportContinuation = lastEnd !== -1 && trimmed.length > 0 && !trimmed.startsWith(\"//\");\r\n\r\n if (isImportStart) {\r\n // A one-liner import ends on its own line.\r\n if (/from\\s+[\"'][^\"']+[\"'];?$/.test(trimmed) || /^import\\s+[\"'][^\"']+[\"'];?$/.test(trimmed)) {\r\n lastEnd = offset + line.length;\r\n } else {\r\n // Multi-line import: remember the start and wait for the close.\r\n lastEnd = -2;\r\n }\r\n } else if (lastEnd === -2 && isImportContinuation && trimmed.endsWith(\";\")) {\r\n lastEnd = offset + line.length;\r\n }\r\n offset += line.length + 1;\r\n }\r\n\r\n return lastEnd > 0 ? lastEnd : -1;\r\n}\r\n\r\nfunction escapeRegExp(value: string): string {\r\n return value.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\r\n}\r\n\r\n/**\r\n * Produce a unified diff with three lines of context.\r\n *\r\n * Only used for display, so it favours readability over exactness: it diffs by\r\n * line and emits a single hunk per changed region.\r\n *\r\n * @param file - Path shown in the diff header\r\n * @param before - Original contents\r\n * @param after - Updated contents\r\n * @returns Unified diff text\r\n */\r\nexport function unifiedDiff(file: string, before: string, after: string): string {\r\n const beforeLines = before.split(\"\\n\");\r\n const afterLines = after.split(\"\\n\");\r\n const operations = diffLines(beforeLines, afterLines);\r\n\r\n const changedIndices = operations\r\n .map((op, index) => (op.type === \"equal\" ? -1 : index))\r\n .filter(index => index !== -1);\r\n\r\n if (changedIndices.length === 0) return \"\";\r\n\r\n const firstChanged = Math.max(0, (changedIndices[0] ?? 0) - 3);\r\n const lastChanged = Math.min(operations.length - 1, (changedIndices.at(-1) ?? 0) + 3);\r\n\r\n const header = [`--- a/${file}`, `+++ b/${file}`];\r\n let beforeCount = 0;\r\n let afterCount = 0;\r\n for (let index = firstChanged; index <= lastChanged; index += 1) {\r\n const op = operations[index];\r\n if (!op) continue;\r\n if (op.type !== \"insert\") beforeCount += 1;\r\n if (op.type !== \"delete\") afterCount += 1;\r\n }\r\n\r\n const body: string[] = [`@@ -${firstChanged + 1},${beforeCount} +${firstChanged + 1},${afterCount} @@`];\r\n for (let index = firstChanged; index <= lastChanged; index += 1) {\r\n const op = operations[index];\r\n if (!op) continue;\r\n if (op.type === \"equal\") body.push(` ${op.line}`);\r\n else if (op.type === \"delete\") body.push(`-${op.line}`);\r\n else body.push(`+${op.line}`);\r\n }\r\n\r\n return [...header, ...body].join(\"\\n\");\r\n}\r\n\r\ntype LineOp =\r\n | { type: \"equal\"; line: string }\r\n | { type: \"delete\"; line: string }\r\n | { type: \"insert\"; line: string };\r\n\r\n/**\r\n * Line diff via longest-common-subsequence. Quadratic, which is fine for source\r\n * files of a few thousand lines and keeps the command dependency-free.\r\n */\r\nfunction diffLines(before: string[], after: string[]): LineOp[] {\r\n const rows = before.length + 1;\r\n const cols = after.length + 1;\r\n const table: number[][] = Array.from({ length: rows }, () => new Array<number>(cols).fill(0));\r\n\r\n for (let i = before.length - 1; i >= 0; i -= 1) {\r\n for (let j = after.length - 1; j >= 0; j -= 1) {\r\n const row = table[i];\r\n const nextRow = table[i + 1];\r\n if (!row || !nextRow) continue;\r\n row[j] =\r\n before[i] === after[j]\r\n ? (nextRow[j + 1] ?? 0) + 1\r\n : Math.max(nextRow[j] ?? 0, row[j + 1] ?? 0);\r\n }\r\n }\r\n\r\n const operations: LineOp[] = [];\r\n let i = 0;\r\n let j = 0;\r\n while (i < before.length && j < after.length) {\r\n if (before[i] === after[j]) {\r\n operations.push({ type: \"equal\", line: before[i] as string });\r\n i += 1;\r\n j += 1;\r\n continue;\r\n }\r\n const nextRow = table[i + 1];\r\n const row = table[i];\r\n if (!nextRow || !row) break;\r\n if ((nextRow[j] ?? 0) >= (row[j + 1] ?? 0)) {\r\n operations.push({ type: \"delete\", line: before[i] as string });\r\n i += 1;\r\n } else {\r\n operations.push({ type: \"insert\", line: after[j] as string });\r\n j += 1;\r\n }\r\n }\r\n while (i < before.length) {\r\n operations.push({ type: \"delete\", line: before[i] as string });\r\n i += 1;\r\n }\r\n while (j < after.length) {\r\n operations.push({ type: \"insert\", line: after[j] as string });\r\n j += 1;\r\n }\r\n\r\n return operations;\r\n}\r\n","/**\r\n * `x402-lens explain` — why did this payment fail.\r\n *\r\n * Feed it any subset of the exchange: the challenge, the payment the client\r\n * sent, and the facilitator's verify or settle response. It runs the findings\r\n * engine and prints the result with fixes.\r\n */\r\n\r\nimport {\r\n diagnose,\r\n formatFindings,\r\n type WirePaymentPayload,\r\n type WirePaymentRequired,\r\n type WireSettleResponse,\r\n type WireVerifyResponse,\r\n} from \"@x402-lens/core\";\r\nimport { readJsonArgument } from \"../input.js\";\r\n\r\nexport interface ExplainInput {\r\n challenge?: string;\r\n payment?: string;\r\n verify?: string;\r\n settle?: string;\r\n}\r\n\r\nexport interface ExplainResult {\r\n text: string;\r\n exitCode: number;\r\n findingCount: number;\r\n}\r\n\r\n/**\r\n * Diagnose a captured exchange.\r\n *\r\n * @param input - Raw arguments, each JSON / base64 / `@file`\r\n * @returns Rendered report and an exit code (1 when anything is an error)\r\n */\r\nexport async function explainPayment(input: ExplainInput): Promise<ExplainResult> {\r\n const paymentRequired = input.challenge\r\n ? ((await readJsonArgument(input.challenge, \"--challenge\")) as WirePaymentRequired)\r\n : undefined;\r\n const paymentPayload = input.payment\r\n ? ((await readJsonArgument(input.payment, \"--payment\")) as WirePaymentPayload)\r\n : undefined;\r\n const verifyResponse = input.verify\r\n ? ((await readJsonArgument(input.verify, \"--verify\")) as WireVerifyResponse)\r\n : undefined;\r\n const settleResponse = input.settle\r\n ? ((await readJsonArgument(input.settle, \"--settle\")) as WireSettleResponse)\r\n : undefined;\r\n\r\n if (!paymentRequired && !paymentPayload && !verifyResponse && !settleResponse) {\r\n return {\r\n text: [\r\n \"Nothing to explain.\",\r\n \"\",\r\n \"Pass at least one of:\",\r\n \" --challenge <PAYMENT-REQUIRED|@file> the 402 terms\",\r\n \" --payment <PAYMENT-SIGNATURE|@file> what the client sent\",\r\n \" --verify <json|@file> facilitator /verify response\",\r\n \" --settle <json|@file> facilitator /settle response\",\r\n ].join(\"\\n\"),\r\n exitCode: 2,\r\n findingCount: 0,\r\n };\r\n }\r\n\r\n const findings = diagnose({\r\n ...(paymentRequired ? { paymentRequired } : {}),\r\n ...(paymentPayload ? { paymentPayload } : {}),\r\n ...(verifyResponse ? { verifyResponse } : {}),\r\n ...(settleResponse ? { settleResponse } : {}),\r\n });\r\n\r\n const header = [\r\n \"x402-lens explain\",\r\n ` challenge: ${paymentRequired ? \"yes\" : \"no\"}`,\r\n ` payment: ${paymentPayload ? \"yes\" : \"no\"}`,\r\n ` verify: ${verifyResponse ? (verifyResponse.isValid ? \"valid\" : \"invalid\") : \"no\"}`,\r\n ` settle: ${settleResponse ? (settleResponse.success ? \"settled\" : \"failed\") : \"no\"}`,\r\n ].join(\"\\n\");\r\n\r\n const hasError = findings.some(finding => finding.severity === \"error\");\r\n\r\n return {\r\n text: `${header}\\n\\n${formatFindings(findings)}`,\r\n exitCode: hasError ? 1 : 0,\r\n findingCount: findings.length,\r\n };\r\n}\r\n","/**\r\n * Reading x402 wire objects from arguments.\r\n *\r\n * Everything a developer pastes into a debugging session arrives in one of\r\n * three shapes: raw base64, base64 in an `@file`, or already-decoded JSON. All\r\n * three are supported so nobody has to transform a header by hand.\r\n */\r\n\r\nimport { readFile } from \"node:fs/promises\";\r\n\r\n/** Raised when an argument cannot be decoded. */\r\nexport class InputError extends Error {\r\n constructor(message: string) {\r\n super(message);\r\n this.name = \"InputError\";\r\n }\r\n}\r\n\r\n/**\r\n * Decode an argument into a JSON value.\r\n *\r\n * Accepts `@path` (read the file), raw JSON, or base64-encoded JSON. The order\r\n * matters: JSON is tried first because a base64 string is never valid JSON, so\r\n * a JSON-looking value never falls through to the base64 branch.\r\n *\r\n * @param raw - The argument value\r\n * @param label - Argument name, used in error messages\r\n * @returns The parsed value\r\n * @throws {InputError} When nothing can be parsed\r\n */\r\nexport async function readJsonArgument(raw: string, label: string): Promise<unknown> {\r\n const source = raw.startsWith(\"@\") ? await readFile(raw.slice(1), \"utf8\") : raw;\r\n return parseJsonOrBase64(source, label);\r\n}\r\n\r\n/**\r\n * Parse a string that is either JSON or base64-encoded JSON.\r\n *\r\n * @param source - Raw string\r\n * @param label - Name used in error messages\r\n * @returns The parsed value\r\n * @throws {InputError} When neither form parses\r\n */\r\nexport function parseJsonOrBase64(source: string, label: string): unknown {\r\n const trimmed = source.trim();\r\n if (trimmed.length === 0) {\r\n throw new InputError(`${label} is empty.`);\r\n }\r\n\r\n const asJson = tryParseJson(trimmed);\r\n if (asJson !== undefined) return asJson;\r\n\r\n const decoded = tryDecodeBase64(trimmed);\r\n if (decoded !== undefined) {\r\n const fromBase64 = tryParseJson(decoded);\r\n if (fromBase64 !== undefined) return fromBase64;\r\n throw new InputError(\r\n `${label} decodes from base64 but the result is not JSON. Got: ${decoded.slice(0, 120)}`,\r\n );\r\n }\r\n\r\n throw new InputError(\r\n `${label} is neither JSON nor base64-encoded JSON. Pass the header value verbatim, or JSON, or @file.`,\r\n );\r\n}\r\n\r\nfunction tryParseJson(value: string): unknown | undefined {\r\n const first = value[0];\r\n if (first !== \"{\" && first !== \"[\" && first !== '\"') return undefined;\r\n try {\r\n return JSON.parse(value) as unknown;\r\n } catch {\r\n return undefined;\r\n }\r\n}\r\n\r\nfunction tryDecodeBase64(value: string): string | undefined {\r\n const normalised = value.replace(/-/g, \"+\").replace(/_/g, \"/\");\r\n const padded = normalised.padEnd(\r\n normalised.length + ((4 - (normalised.length % 4)) % 4),\r\n \"=\",\r\n );\r\n if (!/^[A-Za-z0-9+/]+={0,2}$/.test(padded)) return undefined;\r\n try {\r\n const decoded = Buffer.from(padded, \"base64\").toString(\"utf8\");\r\n // Base64 of binary decodes to replacement characters; reject that.\r\n return decoded.includes(\"\\uFFFD\") ? undefined : decoded;\r\n } catch {\r\n return undefined;\r\n }\r\n}\r\n","/**\r\n * `x402-lens doctor` — check that a configuration can actually accept payments.\r\n *\r\n * Three things break a deployment before a single buyer arrives: a network the\r\n * facilitator does not support, a missing or wrong-shaped receiving address, and\r\n * a facilitator that is simply unreachable. All three are checkable up front.\r\n */\r\n\r\nimport {\r\n WELL_KNOWN_NETWORKS,\r\n describeNetwork,\r\n isCaip2,\r\n loadConfig,\r\n suggestCaip2,\r\n type LensConfig,\r\n} from \"@x402-lens/core\";\r\n\r\nexport interface DoctorOptions {\r\n /** Config to check. When absent, it is loaded from env and `x402.config.json`. */\r\n config?: LensConfig;\r\n /** Override the facilitator to probe. */\r\n facilitatorUrl?: string;\r\n /** Override the network to verify against `/supported`. */\r\n network?: string;\r\n /** Override the full network list. Wins over `network` when present. */\r\n networks?: string[];\r\n /** Fetch timeout, milliseconds. */\r\n timeoutMs?: number;\r\n}\r\n\r\nexport interface DoctorCheck {\r\n name: string;\r\n ok: boolean;\r\n detail: string;\r\n}\r\n\r\nexport interface DoctorResult {\r\n checks: DoctorCheck[];\r\n exitCode: number;\r\n text: string;\r\n}\r\n\r\ninterface SupportedResponse {\r\n kinds?: Array<{ x402Version?: number; scheme?: string; network?: string }>;\r\n extensions?: string[];\r\n signers?: Record<string, string[]>;\r\n}\r\n\r\n/**\r\n * Run every configuration check that does not require a buyer.\r\n *\r\n * @param options - Config and probe overrides\r\n * @returns Individual checks, a rendered report, and an exit code\r\n */\r\nexport async function runDoctor(options: DoctorOptions = {}): Promise<DoctorResult> {\r\n const checks: DoctorCheck[] = [];\r\n\r\n let config: LensConfig | undefined;\r\n let configError: Error | undefined;\r\n try {\r\n config = options.config ?? (await loadConfig({ readConfigFile: true }));\r\n checks.push({\r\n name: \"config\",\r\n ok: true,\r\n detail: `facilitator ${config.facilitatorUrl}, network ${\r\n config.networks.length > 1\r\n ? config.networks.map(describeNetwork).join(\", \")\r\n : describeNetwork(config.network)\r\n }, ${config.routes.length} route(s)`,\r\n });\r\n } catch (error) {\r\n configError = error as Error;\r\n }\r\n\r\n const facilitatorUrl = (\r\n options.facilitatorUrl ??\r\n config?.facilitatorUrl ??\r\n \"\"\r\n ).replace(/\\/+$/, \"\");\r\n // An explicit network override replaces the list rather than adding to it:\r\n // `--network` asks a question about one chain, not about the deployment.\r\n const networks =\r\n options.networks ??\r\n (options.network ? [options.network] : (config?.networks ?? []));\r\n const network = networks[0] ?? \"\";\r\n\r\n if (!config) {\r\n if (!facilitatorUrl || !network) {\r\n checks.push({\r\n name: \"config\",\r\n ok: false,\r\n detail: configError?.message ?? \"Configuration could not be loaded.\",\r\n });\r\n return finish(checks);\r\n }\r\n // Overrides supplied enough to probe the facilitator; the rest is reported.\r\n checks.push({\r\n name: \"config\",\r\n ok: true,\r\n detail:\r\n \"Probing with facilitator and network overrides. Full configuration (payTo, routes) was not loaded, so it was not checked.\",\r\n });\r\n }\r\n\r\n if (!isCaip2(network)) {\r\n const suggestion = suggestCaip2(network);\r\n checks.push({\r\n name: \"network format\",\r\n ok: false,\r\n detail: `\"${network}\" is not CAIP-2.${suggestion ? ` Use \"${suggestion}\".` : \"\"}`,\r\n });\r\n return finish(checks);\r\n }\r\n checks.push({\r\n name: \"network format\",\r\n ok: true,\r\n detail: describeNetwork(network),\r\n });\r\n\r\n if (config) {\r\n checks.push(checkPayToShape(config.payTo, network));\r\n }\r\n\r\n let supported: SupportedResponse | undefined;\r\n try {\r\n const response = await fetch(`${facilitatorUrl}/supported`, {\r\n headers: { Accept: \"application/json\", \"User-Agent\": \"x402-lens/0.1\" },\r\n signal: AbortSignal.timeout(options.timeoutMs ?? 15_000),\r\n });\r\n if (!response.ok) {\r\n checks.push({\r\n name: \"facilitator reachable\",\r\n ok: false,\r\n detail: `GET ${facilitatorUrl}/supported returned HTTP ${response.status}.`,\r\n });\r\n return finish(checks);\r\n }\r\n supported = (await response.json()) as SupportedResponse;\r\n checks.push({\r\n name: \"facilitator reachable\",\r\n ok: true,\r\n detail: `${facilitatorUrl}/supported responded with ${String(supported.kinds?.length ?? 0)} kind(s).`,\r\n });\r\n } catch (error) {\r\n checks.push({\r\n name: \"facilitator reachable\",\r\n ok: false,\r\n detail: `Could not reach ${facilitatorUrl}/supported: ${(error as Error).message}. Check the URL, the network path, and any proxy in between.`,\r\n });\r\n return finish(checks);\r\n }\r\n\r\n const kinds = supported.kinds ?? [];\r\n const matching = kinds.filter(\r\n kind => kind.network === network && kind.x402Version === 2,\r\n );\r\n\r\n if (matching.length === 0) {\r\n const v1Only = kinds.some(kind => kind.network === network && kind.x402Version === 1);\r\n const available = Array.from(\r\n new Set(kinds.filter(kind => kind.x402Version === 2).map(kind => kind.network ?? \"\")),\r\n ).filter(Boolean);\r\n checks.push({\r\n name: \"network supported\",\r\n ok: false,\r\n detail: v1Only\r\n ? `The facilitator lists ${network} for x402Version 1 only. This middleware speaks v2, so payments will be rejected.`\r\n : `The facilitator does not list ${network} with x402Version 2. It supports: ${available.join(\", \") || \"nothing\"}.`,\r\n });\r\n } else {\r\n checks.push({\r\n name: \"network supported\",\r\n ok: true,\r\n detail: `${network} is available for scheme(s): ${matching.map(kind => kind.scheme ?? \"?\").join(\", \")}.`,\r\n });\r\n }\r\n\r\n // Every configured network is validated by the SDK at startup, and a missing\r\n // one is fatal: `@x402/core` calls process.exit(1) from its background init,\r\n // which kills the server rather than returning a 402. Checking all of them\r\n // here is the only place that failure can be caught before a deploy.\r\n const missing = networks.filter(\r\n candidate =>\r\n !kinds.some(kind => kind.network === candidate && kind.x402Version === 2),\r\n );\r\n if (networks.length > 1) {\r\n checks.push(\r\n missing.length === 0\r\n ? {\r\n name: \"all networks supported\",\r\n ok: true,\r\n detail: `All ${networks.length} configured networks are listed for x402Version 2: ${networks.join(\", \")}.`,\r\n }\r\n : {\r\n name: \"all networks supported\",\r\n ok: false,\r\n detail: `These configured networks are not listed for x402Version 2: ${missing.join(\r\n \", \",\r\n )}. The SDK treats this as a fatal startup error and exits the process, so the server will not start. Remove them from networks, or use a facilitator that supports them.`,\r\n },\r\n );\r\n }\r\n\r\n const exactSupported = matching.some(kind => kind.scheme === \"exact\");\r\n checks.push({\r\n name: \"exact scheme\",\r\n ok: exactSupported,\r\n detail: exactSupported\r\n ? \"The facilitator supports the exact scheme on this network.\"\r\n : `Routes use the exact scheme, which is not listed for ${network}.`,\r\n });\r\n\r\n if (WELL_KNOWN_NETWORKS[network as keyof typeof WELL_KNOWN_NETWORKS]) {\r\n checks.push({\r\n name: \"known network\",\r\n ok: true,\r\n detail: `${describeNetwork(network)} — widely deployed, safe for production.`,\r\n });\r\n } else {\r\n checks.push({\r\n name: \"known network\",\r\n ok: true,\r\n detail: `${network} is not in the built-in list. That is fine if you intended it; verify token and facilitator support yourself.`,\r\n });\r\n }\r\n\r\n return finish(checks);\r\n}\r\n\r\n/** Cheap shape check: EVM addresses are 0x + 40 hex, SVM are base58. */\r\nfunction checkPayToShape(payTo: string, network: string): DoctorCheck {\r\n const namespace = network.slice(0, network.indexOf(\":\"));\r\n\r\n if (namespace === \"eip155\") {\r\n const ok = /^0x[0-9a-fA-F]{40}$/.test(payTo);\r\n return {\r\n name: \"payTo address\",\r\n ok,\r\n detail: ok\r\n ? `${payTo} looks like an EVM address.`\r\n : `\"${payTo}\" is not a 0x-prefixed 20-byte address, which ${describeNetwork(network)} requires.`,\r\n };\r\n }\r\n\r\n if (namespace === \"solana\") {\r\n const ok = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/.test(payTo);\r\n return {\r\n name: \"payTo address\",\r\n ok,\r\n detail: ok\r\n ? `${payTo} looks like a base58 Solana address.`\r\n : `\"${payTo}\" is not a base58 public key, which ${describeNetwork(network)} requires.`,\r\n };\r\n }\r\n\r\n return {\r\n name: \"payTo address\",\r\n ok: payTo.length > 0,\r\n detail: `No format check available for namespace \"${namespace}\". Confirm the address format with the network's tooling.`,\r\n };\r\n}\r\n\r\nfunction finish(checks: DoctorCheck[]): DoctorResult {\r\n const failed = checks.filter(check => !check.ok);\r\n const lines = checks.map(check => `${check.ok ? \"ok \" : \"FAIL\"} ${check.name}: ${check.detail}`);\r\n const summary =\r\n failed.length === 0\r\n ? \"\\nAll checks passed.\"\r\n : `\\n${failed.length} check(s) failed. Fix the FAIL lines above; every one of them prevents real payments.`;\r\n\r\n return {\r\n checks,\r\n exitCode: failed.length === 0 ? 0 : 1,\r\n text: [...lines, summary].join(\"\\n\"),\r\n };\r\n}\r\n","/**\r\n * `x402-lens inspect` — look at a live endpoint from the outside.\r\n *\r\n * Sends an unpaid request, decodes the challenge, and reports both schema\r\n * conformance and CORS readiness. That is the whole \"is my paywall correct\"\r\n * question, answerable without reading the server's source.\r\n */\r\n\r\nimport {\r\n checkCors,\r\n describeNetwork,\r\n diagnose,\r\n formatFindings,\r\n validatePaymentRequired,\r\n type WirePaymentRequired,\r\n} from \"@x402-lens/core\";\r\nimport { decodePaymentRequiredHeader } from \"@x402/core/http\";\r\n\r\nexport interface InspectOptions {\r\n url: string;\r\n method?: string;\r\n headers?: Record<string, string>;\r\n timeoutMs?: number;\r\n}\r\n\r\nexport interface InspectResult {\r\n status: number;\r\n paymentRequired?: WirePaymentRequired;\r\n headerPresent: boolean;\r\n decodedFromBody: boolean;\r\n conformance: ReturnType<typeof validatePaymentRequired>;\r\n cors: ReturnType<typeof checkCors>;\r\n findings: string;\r\n /** Non-zero when the endpoint is not a working x402 v2 paywall. */\r\n exitCode: number;\r\n}\r\n\r\n/**\r\n * Inspect one endpoint.\r\n *\r\n * @param options - Target URL and request tweaks\r\n * @returns Everything observed, plus an exit code for CI use\r\n */\r\nexport async function inspectEndpoint(options: InspectOptions): Promise<InspectResult> {\r\n const method = options.method ?? \"GET\";\r\n const response = await fetch(options.url, {\r\n method,\r\n headers: {\r\n Accept: \"application/json\",\r\n \"User-Agent\": \"x402-lens/0.1\",\r\n ...options.headers,\r\n },\r\n signal: AbortSignal.timeout(options.timeoutMs ?? 15_000),\r\n redirect: \"follow\",\r\n });\r\n\r\n const headerValue = response.headers.get(\"payment-required\");\r\n let paymentRequired: WirePaymentRequired | undefined;\r\n let decodedFromBody = false;\r\n let headerPresent = false;\r\n\r\n if (headerValue) {\r\n headerPresent = true;\r\n try {\r\n paymentRequired = decodePaymentRequiredHeader(headerValue) as unknown as WirePaymentRequired;\r\n } catch {\r\n // Fall through to the body, which we mirror there on purpose.\r\n }\r\n }\r\n\r\n if (!paymentRequired) {\r\n // Our middleware mirrors the challenge into the body; other servers may too.\r\n const text = await response.text().catch(() => \"\");\r\n const fromBody = extractChallengeFromBody(text);\r\n if (fromBody) {\r\n paymentRequired = fromBody;\r\n decodedFromBody = true;\r\n }\r\n }\r\n\r\n const headerRecord: Record<string, string | undefined> = {};\r\n response.headers.forEach((value, key) => {\r\n headerRecord[key.toLowerCase()] = value;\r\n });\r\n const cors = checkCors(headerRecord);\r\n\r\n const conformance = paymentRequired ? validatePaymentRequired(paymentRequired) : [];\r\n const findingsList = paymentRequired\r\n ? diagnose({ paymentRequired })\r\n : [];\r\n\r\n const lines: string[] = [];\r\n lines.push(`${method} ${options.url} → HTTP ${response.status}`);\r\n if (!paymentRequired) {\r\n lines.push(\"\");\r\n lines.push(\r\n \"No x402 challenge found. Expected a PAYMENT-REQUIRED header (base64 PaymentRequired) on a 402 response.\",\r\n );\r\n lines.push(\r\n \"If this route is unprotected, you will see its normal response instead. If it is protected, check that paymentMiddleware is mounted before the route.\",\r\n );\r\n } else {\r\n lines.push(\r\n headerPresent\r\n ? \"Challenge: PAYMENT-REQUIRED header\"\r\n : \"Challenge: response body (no PAYMENT-REQUIRED header)\",\r\n );\r\n lines.push(describeChallenge(paymentRequired));\r\n }\r\n\r\n if (conformance.length > 0) {\r\n lines.push(\"\");\r\n lines.push(\"Schema conformance:\");\r\n for (const issue of conformance) {\r\n lines.push(` [error] ${issue.field}: ${issue.problem}`);\r\n }\r\n }\r\n\r\n if (cors.issues.length > 0) {\r\n lines.push(\"\");\r\n lines.push(\"Browser (CORS):\");\r\n for (const issue of cors.issues) {\r\n lines.push(` [error] ${issue.field}: ${issue.problem}`);\r\n }\r\n } else if (paymentRequired) {\r\n lines.push(\"\");\r\n lines.push(\"Browser (CORS): PAYMENT-REQUIRED, PAYMENT-RESPONSE exposed; PAYMENT-SIGNATURE allowed.\");\r\n }\r\n\r\n if (findingsList.length > 0) {\r\n lines.push(\"\");\r\n lines.push(formatFindings(findingsList));\r\n }\r\n\r\n const failed =\r\n !paymentRequired || conformance.length > 0 || cors.issues.length > 0;\r\n\r\n return {\r\n status: response.status,\r\n ...(paymentRequired ? { paymentRequired } : {}),\r\n headerPresent,\r\n decodedFromBody,\r\n conformance,\r\n cors,\r\n findings: lines.join(\"\\n\"),\r\n exitCode: failed ? 1 : 0,\r\n };\r\n}\r\n\r\nfunction describeChallenge(paymentRequired: WirePaymentRequired): string {\r\n const lines = [`x402Version: ${String(paymentRequired.x402Version)}`];\r\n if (paymentRequired.resource?.url) {\r\n lines.push(`resource: ${paymentRequired.resource.url}`);\r\n }\r\n if (paymentRequired.error) {\r\n lines.push(`error: ${paymentRequired.error}`);\r\n }\r\n const accepts = paymentRequired.accepts ?? [];\r\n lines.push(`accepts: ${accepts.length}`);\r\n accepts.forEach((entry, index) => {\r\n lines.push(\r\n ` [${index}] ${entry.scheme} on ${describeNetwork(entry.network)}`,\r\n ` amount: ${entry.amount} (atomic units)`,\r\n ` asset: ${entry.asset}`,\r\n ` payTo: ${entry.payTo}`,\r\n ` timeout: ${String(entry.maxTimeoutSeconds)}s`,\r\n );\r\n });\r\n if (accepts.length > 1) {\r\n // Two entries can be the same price and still differ in what the buyer\r\n // owes, because each chain has its own token decimals. Saying so prevents\r\n // the natural but wrong assumption that the amounts should match.\r\n const amounts = new Set(accepts.map(entry => entry.amount));\r\n const assets = new Set(accepts.map(entry => entry.asset));\r\n lines.push(\r\n ` note: ${accepts.length} payment options — one per network. ${\r\n amounts.size === 1\r\n ? \"Amounts match across networks.\"\r\n : `Amounts differ by token decimals (${Array.from(amounts).join(\", \")}).`\r\n }`,\r\n );\r\n if (assets.size === 1) {\r\n lines.push(\r\n ` note: Every option uses the same asset, which is only valid if that token exists on all of them.`,\r\n );\r\n }\r\n }\r\n return lines.join(\"\\n\");\r\n}\r\n\r\n/** Pull a mirrored challenge out of a JSON body or paywall-free error body. */\r\nfunction extractChallengeFromBody(text: string): WirePaymentRequired | undefined {\r\n if (!text) return undefined;\r\n try {\r\n const parsed = JSON.parse(text) as unknown;\r\n if (\r\n parsed &&\r\n typeof parsed === \"object\" &&\r\n (parsed as { x402Version?: unknown }).x402Version === 2 &&\r\n Array.isArray((parsed as { accepts?: unknown }).accepts)\r\n ) {\r\n return parsed as WirePaymentRequired;\r\n }\r\n } catch {\r\n return undefined;\r\n }\r\n return undefined;\r\n}\r\n","/**\r\n * `x402-lens reconcile` — check whether a settlement transaction actually\r\n * landed on chain.\r\n *\r\n * `settlement_pending` is non-terminal: the facilitator broadcast a tx but\r\n * could not confirm it. Retrying opens a second payment. This command answers\r\n * the only safe next question — \"is the hash confirmed yet?\" — against a public\r\n * RPC, without needing the SDK or a wallet.\r\n */\r\n\r\nimport { describeNetwork, isCaip2, suggestCaip2 } from \"@x402-lens/core\";\r\n\r\nexport interface ReconcileOptions {\r\n /** Transaction hash (`0x…` for EVM, base58 signature for Solana). */\r\n tx: string;\r\n /** CAIP-2 network. Defaults to `eip155:84532` (Base Sepolia). */\r\n network?: string;\r\n /** Override the RPC URL. When absent, a public endpoint for the network is used. */\r\n rpcUrl?: string;\r\n /** Fetch timeout, milliseconds. */\r\n timeoutMs?: number;\r\n /** Injected fetch, for tests. */\r\n fetchImpl?: typeof fetch;\r\n}\r\n\r\nexport type ReconcileStatus = \"confirmed\" | \"failed\" | \"pending\" | \"not_found\" | \"unknown\";\r\n\r\nexport interface ReconcileResult {\r\n status: ReconcileStatus;\r\n network: string;\r\n tx: string;\r\n rpcUrl: string;\r\n /** Block number / slot when known. */\r\n block?: string;\r\n /** Raw RPC detail for operators who need more than the status. */\r\n detail: string;\r\n exitCode: number;\r\n text: string;\r\n}\r\n\r\nconst DEFAULT_RPC: Record<string, string> = {\r\n \"eip155:1\": \"https://ethereum.publicnode.com\",\r\n \"eip155:8453\": \"https://mainnet.base.org\",\r\n \"eip155:84532\": \"https://sepolia.base.org\",\r\n \"eip155:11155111\": \"https://ethereum-sepolia.publicnode.com\",\r\n \"solana:5eykt4Usfv8P8NJdTREpY1vzqKqZKvdp\": \"https://api.mainnet-beta.solana.com\",\r\n \"solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1\": \"https://api.devnet.solana.com\",\r\n};\r\n\r\n/**\r\n * Ask the chain whether a settlement transaction is confirmed.\r\n *\r\n * @param options - Hash, network, and optional RPC override\r\n * @returns Status, a rendered report, and an exit code (0 = confirmed)\r\n */\r\nexport async function reconcileTransaction(\r\n options: ReconcileOptions,\r\n): Promise<ReconcileResult> {\r\n const tx = options.tx.trim();\r\n if (!tx) {\r\n return report({\r\n status: \"unknown\",\r\n network: options.network ?? \"\",\r\n tx: \"\",\r\n rpcUrl: \"\",\r\n detail: \"No transaction hash was provided.\",\r\n exitCode: 2,\r\n });\r\n }\r\n\r\n const network = options.network ?? \"eip155:84532\";\r\n if (!isCaip2(network)) {\r\n const suggestion = suggestCaip2(network);\r\n return report({\r\n status: \"unknown\",\r\n network,\r\n tx,\r\n rpcUrl: \"\",\r\n detail: suggestion\r\n ? `\"${network}\" is not CAIP-2. Use \"${suggestion}\".`\r\n : `\"${network}\" is not a CAIP-2 network id.`,\r\n exitCode: 2,\r\n });\r\n }\r\n\r\n const rpcUrl = options.rpcUrl ?? DEFAULT_RPC[network];\r\n if (!rpcUrl) {\r\n return report({\r\n status: \"unknown\",\r\n network,\r\n tx,\r\n rpcUrl: \"\",\r\n detail: `No default RPC for ${describeNetwork(network)}. Pass --rpc <url>.`,\r\n exitCode: 2,\r\n });\r\n }\r\n\r\n const fetchImpl = options.fetchImpl ?? fetch;\r\n const timeoutMs = options.timeoutMs ?? 15_000;\r\n const namespace = network.slice(0, network.indexOf(\":\"));\r\n\r\n try {\r\n if (namespace === \"eip155\") {\r\n return await reconcileEvm({ tx, network, rpcUrl, fetchImpl, timeoutMs });\r\n }\r\n if (namespace === \"solana\") {\r\n return await reconcileSolana({ tx, network, rpcUrl, fetchImpl, timeoutMs });\r\n }\r\n return report({\r\n status: \"unknown\",\r\n network,\r\n tx,\r\n rpcUrl,\r\n detail: `Namespace \"${namespace}\" is not supported by reconcile. Use eip155:* or solana:*.`,\r\n exitCode: 2,\r\n });\r\n } catch (error) {\r\n return report({\r\n status: \"unknown\",\r\n network,\r\n tx,\r\n rpcUrl,\r\n detail: `RPC call failed: ${(error as Error).message}`,\r\n exitCode: 1,\r\n });\r\n }\r\n}\r\n\r\nasync function reconcileEvm(input: {\r\n tx: string;\r\n network: string;\r\n rpcUrl: string;\r\n fetchImpl: typeof fetch;\r\n timeoutMs: number;\r\n}): Promise<ReconcileResult> {\r\n const receipt = (await rpc(input, \"eth_getTransactionReceipt\", [input.tx])) as\r\n | { status?: string; blockNumber?: string }\r\n | null;\r\n\r\n if (receipt === null) {\r\n const pending = (await rpc(input, \"eth_getTransactionByHash\", [input.tx])) as\r\n | { hash?: string }\r\n | null;\r\n if (pending && pending.hash) {\r\n return report({\r\n status: \"pending\",\r\n network: input.network,\r\n tx: input.tx,\r\n rpcUrl: input.rpcUrl,\r\n detail: \"Transaction is in the mempool or not yet mined. Do not retry the payment.\",\r\n exitCode: 1,\r\n });\r\n }\r\n return report({\r\n status: \"not_found\",\r\n network: input.network,\r\n tx: input.tx,\r\n rpcUrl: input.rpcUrl,\r\n detail: \"No transaction with this hash on this network. The settle may never have broadcast.\",\r\n exitCode: 1,\r\n });\r\n }\r\n\r\n const statusHex = receipt.status ?? \"0x0\";\r\n const confirmed = statusHex === \"0x1\" || statusHex === \"1\";\r\n const block = receipt.blockNumber\r\n ? String(Number.parseInt(receipt.blockNumber, 16))\r\n : undefined;\r\n\r\n if (confirmed) {\r\n return report({\r\n status: \"confirmed\",\r\n network: input.network,\r\n tx: input.tx,\r\n rpcUrl: input.rpcUrl,\r\n ...(block ? { block } : {}),\r\n detail: `Receipt status success${block ? ` in block ${block}` : \"\"}. Settlement landed; do not charge the buyer again.`,\r\n exitCode: 0,\r\n });\r\n }\r\n\r\n return report({\r\n status: \"failed\",\r\n network: input.network,\r\n tx: input.tx,\r\n rpcUrl: input.rpcUrl,\r\n ...(block ? { block } : {}),\r\n detail: `Receipt status failed${block ? ` in block ${block}` : \"\"}. Funds did not move; a fresh payment is safe after investigation.`,\r\n exitCode: 1,\r\n });\r\n}\r\n\r\nasync function reconcileSolana(input: {\r\n tx: string;\r\n network: string;\r\n rpcUrl: string;\r\n fetchImpl: typeof fetch;\r\n timeoutMs: number;\r\n}): Promise<ReconcileResult> {\r\n const value = (await rpc(input, \"getTransaction\", [\r\n input.tx,\r\n { encoding: \"json\", maxSupportedTransactionVersion: 0 },\r\n ])) as { meta?: { err?: unknown }; slot?: number } | null;\r\n\r\n if (value === null) {\r\n return report({\r\n status: \"not_found\",\r\n network: input.network,\r\n tx: input.tx,\r\n rpcUrl: input.rpcUrl,\r\n detail: \"Signature not found on this cluster. It may still be propagating, or it never landed.\",\r\n exitCode: 1,\r\n });\r\n }\r\n\r\n const err = value.meta?.err;\r\n const slot = value.slot !== undefined ? String(value.slot) : undefined;\r\n if (err == null) {\r\n return report({\r\n status: \"confirmed\",\r\n network: input.network,\r\n tx: input.tx,\r\n rpcUrl: input.rpcUrl,\r\n ...(slot ? { block: slot } : {}),\r\n detail: `Transaction confirmed${slot ? ` at slot ${slot}` : \"\"}. Settlement landed; do not charge the buyer again.`,\r\n exitCode: 0,\r\n });\r\n }\r\n\r\n return report({\r\n status: \"failed\",\r\n network: input.network,\r\n tx: input.tx,\r\n rpcUrl: input.rpcUrl,\r\n ...(slot ? { block: slot } : {}),\r\n detail: `Transaction failed on chain${slot ? ` at slot ${slot}` : \"\"}: ${JSON.stringify(err)}.`,\r\n exitCode: 1,\r\n });\r\n}\r\n\r\nasync function rpc(\r\n input: { rpcUrl: string; fetchImpl: typeof fetch; timeoutMs: number },\r\n method: string,\r\n params: unknown[],\r\n): Promise<unknown> {\r\n const controller = new AbortController();\r\n const timer = setTimeout(() => controller.abort(), input.timeoutMs);\r\n try {\r\n const response = await input.fetchImpl(input.rpcUrl, {\r\n method: \"POST\",\r\n headers: { \"content-type\": \"application/json\" },\r\n body: JSON.stringify({ jsonrpc: \"2.0\", id: 1, method, params }),\r\n signal: controller.signal,\r\n });\r\n if (!response.ok) {\r\n throw new Error(`HTTP ${response.status}`);\r\n }\r\n const body = (await response.json()) as { result?: unknown; error?: { message?: string } };\r\n if (body.error) {\r\n throw new Error(body.error.message ?? \"RPC error\");\r\n }\r\n return body.result;\r\n } finally {\r\n clearTimeout(timer);\r\n }\r\n}\r\n\r\nfunction report(\r\n result: Omit<ReconcileResult, \"text\"> & { text?: string },\r\n): ReconcileResult {\r\n const lines = [\r\n `tx: ${result.tx || \"(none)\"}`,\r\n `network: ${result.network ? describeNetwork(result.network) : \"(none)\"}`,\r\n `rpc: ${result.rpcUrl || \"(none)\"}`,\r\n `status: ${result.status}`,\r\n ...(result.block ? [`block: ${result.block}`] : []),\r\n \"\",\r\n result.detail,\r\n ];\r\n return { ...result, text: lines.join(\"\\n\") };\r\n}\r\n","/**\r\n * Minimal argv parsing.\r\n *\r\n * The CLI has five commands and a handful of flags; a dependency would be more\r\n * code to audit than the parser itself.\r\n */\r\n\r\nexport interface ParsedArgs {\r\n command: string | undefined;\r\n positionals: string[];\r\n flags: Record<string, string | true>;\r\n}\r\n\r\n/**\r\n * Split argv into a command, positionals, and flags.\r\n *\r\n * Supports `--key value`, `--key=value`, and boolean `--flag`. A `--flag` that\r\n * is followed by another flag or by nothing is treated as boolean.\r\n *\r\n * @param argv - Arguments after the executable and script path\r\n * @returns Parsed structure\r\n */\r\nexport function parseArgs(argv: string[]): ParsedArgs {\r\n const flags: Record<string, string | true> = {};\r\n const positionals: string[] = [];\r\n let command: string | undefined;\r\n\r\n for (let index = 0; index < argv.length; index += 1) {\r\n const token = argv[index];\r\n if (token === undefined) continue;\r\n\r\n if (token.startsWith(\"--\")) {\r\n const withoutDashes = token.slice(2);\r\n if (withoutDashes.length === 0) continue;\r\n\r\n const equalsIndex = withoutDashes.indexOf(\"=\");\r\n if (equalsIndex !== -1) {\r\n flags[withoutDashes.slice(0, equalsIndex)] = withoutDashes.slice(equalsIndex + 1);\r\n continue;\r\n }\r\n\r\n const next = argv[index + 1];\r\n if (next !== undefined && !next.startsWith(\"--\")) {\r\n flags[withoutDashes] = next;\r\n index += 1;\r\n } else {\r\n flags[withoutDashes] = true;\r\n }\r\n continue;\r\n }\r\n\r\n if (token.startsWith(\"-\") && token.length > 1) {\r\n // Short aliases: -h, -v.\r\n flags[token.slice(1)] = true;\r\n continue;\r\n }\r\n\r\n if (command === undefined) {\r\n command = token;\r\n continue;\r\n }\r\n positionals.push(token);\r\n }\r\n\r\n return { command, positionals, flags };\r\n}\r\n\r\n/** Read a flag as a string, or `undefined` when absent or boolean. */\r\nexport function flagValue(args: ParsedArgs, name: string): string | undefined {\r\n const value = args.flags[name];\r\n return typeof value === \"string\" ? value : undefined;\r\n}\r\n\r\n/** Read a flag as a boolean. Any presence counts, including `--flag=false`. */\r\nexport function flagEnabled(args: ParsedArgs, name: string): boolean {\r\n return args.flags[name] !== undefined;\r\n}\r\n","/**\r\n * `x402-lens` command line entry point.\r\n *\r\n * Every command exits non-zero when something is wrong, so CI can gate on it.\r\n */\r\n\r\nimport { AddError, addProtection } from \"./commands/add.js\";\r\nimport { explainPayment } from \"./commands/explain.js\";\r\nimport { runDoctor } from \"./commands/doctor.js\";\r\nimport { inspectEndpoint } from \"./commands/inspect.js\";\r\nimport { reconcileTransaction } from \"./commands/reconcile.js\";\r\nimport { flagEnabled, flagValue, parseArgs } from \"./args.js\";\r\nimport { InputError } from \"./input.js\";\r\n\r\nconst USAGE = `x402-lens — explain and verify x402 v2 payments\r\n\r\nUsage:\r\n x402-lens inspect <url> [--method GET] [--header \"K: V\"] [--timeout 15000]\r\n Fetch an endpoint unpaid, decode PAYMENT-REQUIRED, and report schema\r\n conformance and CORS readiness for browser buyers.\r\n\r\n x402-lens explain [--challenge <b64|json|@file>] [--payment <...>]\r\n [--verify <...>] [--settle <...>]\r\n Diagnose a failed exchange: what is wrong, and what to change.\r\n\r\n x402-lens doctor [--facilitator <url>] [--network <caip2>] [--networks <a,b>]\r\n Verify that configuration can actually accept payments, including that\r\n the facilitator supports every configured network with x402Version 2.\r\n\r\n x402-lens reconcile --tx <hash> [--network <caip2>] [--rpc <url>]\r\n Check whether a settlement transaction confirmed on chain. Use this\r\n after settlement_pending — never retry a payment until you know.\r\n\r\n x402-lens add \"<METHOD> <path>\" --file <path> --price <amount> [--write]\r\n Add x402 protection to an existing Express route. Prints a diff unless\r\n --write is passed.\r\n\r\nOptions:\r\n --help, -h Show this help.\r\n\r\nExit codes:\r\n 0 success\r\n 1 a check failed or a finding is an error\r\n 2 bad usage\r\n`;\r\n\r\n/**\r\n * Run the CLI.\r\n *\r\n * @param argv - Arguments after the script path\r\n * @returns Process exit code\r\n */\r\nexport async function main(argv: string[]): Promise<number> {\r\n const args = parseArgs(argv);\r\n\r\n if (flagEnabled(args, \"help\") || flagEnabled(args, \"h\") || args.command === undefined) {\r\n process.stdout.write(USAGE);\r\n return args.command === undefined && !flagEnabled(args, \"help\") && !flagEnabled(args, \"h\")\r\n ? 2\r\n : 0;\r\n }\r\n\r\n try {\r\n switch (args.command) {\r\n case \"inspect\": {\r\n const url = args.positionals[0];\r\n if (!url) {\r\n process.stderr.write(\"inspect requires a URL.\\n\\n\" + USAGE);\r\n return 2;\r\n }\r\n const result = await inspectEndpoint({\r\n url,\r\n ...(flagValue(args, \"method\") ? { method: flagValue(args, \"method\") as string } : {}),\r\n ...(flagValue(args, \"header\")\r\n ? { headers: parseHeaderFlags(argv) }\r\n : {}),\r\n ...(flagValue(args, \"timeout\")\r\n ? { timeoutMs: Number.parseInt(flagValue(args, \"timeout\") as string, 10) }\r\n : {}),\r\n });\r\n process.stdout.write(`${result.findings}\\n`);\r\n return result.exitCode;\r\n }\r\n\r\n case \"explain\": {\r\n const result = await explainPayment({\r\n ...(flagValue(args, \"challenge\") ? { challenge: flagValue(args, \"challenge\") as string } : {}),\r\n ...(flagValue(args, \"payment\") ? { payment: flagValue(args, \"payment\") as string } : {}),\r\n ...(flagValue(args, \"verify\") ? { verify: flagValue(args, \"verify\") as string } : {}),\r\n ...(flagValue(args, \"settle\") ? { settle: flagValue(args, \"settle\") as string } : {}),\r\n });\r\n process.stdout.write(`${result.text}\\n`);\r\n return result.exitCode;\r\n }\r\n\r\n case \"doctor\": {\r\n const networksFlag = flagValue(args, \"networks\");\r\n const result = await runDoctor({\r\n ...(flagValue(args, \"facilitator\")\r\n ? { facilitatorUrl: flagValue(args, \"facilitator\") as string }\r\n : {}),\r\n ...(flagValue(args, \"network\") ? { network: flagValue(args, \"network\") as string } : {}),\r\n ...(networksFlag\r\n ? {\r\n networks: networksFlag\r\n .split(\",\")\r\n .map(part => part.trim())\r\n .filter(Boolean),\r\n }\r\n : {}),\r\n });\r\n process.stdout.write(`${result.text}\\n`);\r\n return result.exitCode;\r\n }\r\n\r\n case \"add\": {\r\n const route = args.positionals[0];\r\n const file = flagValue(args, \"file\");\r\n const price = flagValue(args, \"price\");\r\n if (!route || !file || !price) {\r\n process.stderr.write(\r\n 'add requires a route, --file, and --price. Example:\\n x402-lens add \"GET /weather\" --file src/server.ts --price 0.001\\n',\r\n );\r\n return 2;\r\n }\r\n const result = await addProtection({\r\n file,\r\n route,\r\n price,\r\n write: flagEnabled(args, \"write\"),\r\n });\r\n process.stdout.write(`${result.text}\\n`);\r\n return result.exitCode;\r\n }\r\n\r\n case \"reconcile\": {\r\n const tx = flagValue(args, \"tx\") ?? args.positionals[0];\r\n if (!tx) {\r\n process.stderr.write(\r\n \"reconcile requires --tx <hash>. Example:\\n x402-lens reconcile --tx 0xabc… --network eip155:84532\\n\",\r\n );\r\n return 2;\r\n }\r\n const result = await reconcileTransaction({\r\n tx,\r\n ...(flagValue(args, \"network\")\r\n ? { network: flagValue(args, \"network\") as string }\r\n : {}),\r\n ...(flagValue(args, \"rpc\") ? { rpcUrl: flagValue(args, \"rpc\") as string } : {}),\r\n ...(flagValue(args, \"timeout\")\r\n ? { timeoutMs: Number.parseInt(flagValue(args, \"timeout\") as string, 10) }\r\n : {}),\r\n });\r\n process.stdout.write(`${result.text}\\n`);\r\n return result.exitCode;\r\n }\r\n\r\n default:\r\n process.stderr.write(`Unknown command \"${args.command}\".\\n\\n${USAGE}`);\r\n return 2;\r\n }\r\n } catch (error) {\r\n if (error instanceof InputError || error instanceof AddError) {\r\n process.stderr.write(`${error.message}\\n`);\r\n return 2;\r\n }\r\n process.stderr.write(`${(error as Error).message}\\n`);\r\n return 1;\r\n }\r\n}\r\n\r\n/**\r\n * `--header` may repeat; `parseArgs` only keeps the last. Re-scan argv for all\r\n * occurrences so `inspect` can send several headers.\r\n */\r\nfunction parseHeaderFlags(argv: string[]): Record<string, string> {\r\n const headers: Record<string, string> = {};\r\n for (let index = 0; index < argv.length; index += 1) {\r\n if (argv[index] !== \"--header\") continue;\r\n const value = argv[index + 1];\r\n if (!value) continue;\r\n const separator = value.indexOf(\":\");\r\n if (separator === -1) continue;\r\n headers[value.slice(0, separator).trim()] = value.slice(separator + 1).trim();\r\n index += 1;\r\n }\r\n return headers;\r\n}\r\n\r\nconst isDirectRun =\r\n process.argv[1] !== undefined &&\r\n (process.argv[1].endsWith(\"x402-lens\") || process.argv[1].endsWith(\"index.js\"));\r\n\r\nif (isDirectRun) {\r\n main(process.argv.slice(2))\r\n .then(code => {\r\n process.exitCode = code;\r\n })\r\n .catch(error => {\r\n process.stderr.write(`Unexpected error: ${(error as Error).message}\\n`);\r\n process.exitCode = 1;\r\n });\r\n}\r\n"],"mappings":";;;AAUA,SAAS,UAAU,iBAAiB;AACpC,SAAS,gBAAgB;AAElB,IAAM,WAAN,cAAuB,MAAM;AAAA,EAClC,YAAY,SAAiB;AAC3B,UAAM,OAAO;AACb,SAAK,OAAO;AAAA,EACd;AACF;AAkBA,IAAM,cAAc;AACpB,IAAM,mBAAmB;AACzB,IAAM,aAAa;AAWnB,eAAsB,cAAc,SAAyC;AAC3E,QAAM,EAAE,MAAM,OAAO,MAA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Z,YAAQ,WAAW;AAAA,EACrB,CAAC,EACA,MAAM,WAAS;AACd,YAAQ,OAAO,MAAM,qBAAsB,MAAgB,OAAO;AAAA,CAAI;AACtE,YAAQ,WAAW;AAAA,EACrB,CAAC;AACL;","names":["i","j","readFile","describeNetwork","diagnose","formatFindings","describeNetwork","isCaip2","suggestCaip2"]}
|
|
1
|
+
{"version":3,"sources":["../src/commands/add.ts","../src/commands/explain.ts","../src/input.ts","../src/commands/doctor.ts","../src/commands/inspect.ts","../src/commands/reconcile.ts","../src/args.ts","../src/index.ts"],"sourcesContent":["/**\r\n * `x402-lens add` — put x402 protection on an existing Express route.\r\n *\r\n * Scaffolders create new projects; this edits the file you already have. The\r\n * approach is deliberately conservative: it only recognises the two route forms\r\n * it can rewrite safely, refuses anything else with a clear explanation, and\r\n * never writes without `--write`. A bad regex edit on someone's server file is\r\n * far worse than a refusal.\r\n */\r\n\r\nimport { readFile, writeFile } from \"node:fs/promises\";\r\nimport { basename } from \"node:path\";\r\n\r\nexport class AddError extends Error {\r\n constructor(message: string) {\r\n super(message);\r\n this.name = \"AddError\";\r\n }\r\n}\r\n\r\nexport interface AddOptions {\r\n file: string;\r\n /** Route as written by the user, e.g. `\"GET /weather\"`. */\r\n route: string;\r\n price: string;\r\n /** Apply the change. When false, only the diff is produced. */\r\n write?: boolean;\r\n}\r\n\r\nexport interface AddResult {\r\n changed: boolean;\r\n diff: string;\r\n text: string;\r\n exitCode: number;\r\n}\r\n\r\nconst IMPORT_LINE = 'import { paymentLens } from \"@x402-lens/express\";';\r\nconst LENS_DECLARATION = \"const lens = paymentLens();\";\r\nconst MOUNT_LINE = \"app.use(lens.middleware);\";\r\n\r\n/**\r\n * Insert payment protection into an existing Express server file.\r\n *\r\n * Idempotent: running it twice leaves the file unchanged the second time.\r\n *\r\n * @param options - Target file, route, and price\r\n * @returns Diff, report, and exit code\r\n * @throws {AddError} When the file is not a supported Express setup\r\n */\r\nexport async function addProtection(options: AddOptions): Promise<AddResult> {\r\n const { file, route } = options;\r\n const price = assertAddPrice(options.price);\r\n\r\n if (basename(file).match(/\\.(ts|js|mjs|cjs)$/) === null) {\r\n throw new AddError(\r\n `${file} is not a JavaScript or TypeScript file. This command edits source files, not compiled output.`,\r\n );\r\n }\r\n\r\n const original = await readFile(file, \"utf8\");\r\n const parsed = parseRoute(route);\r\n\r\n const hasLens = original.includes(\"paymentLens(\");\r\n const hasRouteEntry = hasRouteEntryFor(original, parsed);\r\n\r\n if (hasLens && hasRouteEntry) {\r\n return {\r\n changed: false,\r\n diff: \"\",\r\n text: `${file} already charges for ${parsed.method} ${parsed.path}. Nothing to do.`,\r\n exitCode: 0,\r\n };\r\n }\r\n\r\n const framework = detectFramework(original);\r\n if (framework !== \"express\") {\r\n throw new AddError(\r\n `${file} does not look like an Express app (${framework}). The add command only supports Express; use paymentLens() from @x402-lens/express manually for anything else.`,\r\n );\r\n }\r\n\r\n const routePattern = findRouteDeclaration(original, parsed);\r\n if (!routePattern) {\r\n throw new AddError(\r\n `Could not find a route declaration for ${tsStringLiteral(`${parsed.method} ${parsed.path}`)} in ${file}. The add command recognises app.get(\"/path\", ...) and router.post(\"/path\", ...) forms written on one line. Add the middleware manually:\\n\\n const lens = paymentLens({ routes: { ${routeMapEntry(parsed, price)} } });\\n app.use(lens.middleware);\\n`,\r\n );\r\n }\r\n\r\n const updated = hasLens\r\n ? withRouteEntry(original, file, parsed, price)\r\n : applyEdits(original, parsed, price, routePattern);\r\n const diff = unifiedDiff(file, original, updated);\r\n\r\n if (!options.write) {\r\n return {\r\n changed: true,\r\n diff,\r\n text: [\r\n `Dry run — ${file} would change as follows.`,\r\n \"\",\r\n diff,\r\n \"\",\r\n \"Re-run with --write to apply. Set X402_FACILITATOR_URL, X402_NETWORK, and X402_PAY_TO first; paymentLens() refuses to guess them.\",\r\n ].join(\"\\n\"),\r\n exitCode: 0,\r\n };\r\n }\r\n\r\n await writeFile(file, updated, \"utf8\");\r\n return {\r\n changed: true,\r\n diff,\r\n text: `Updated ${file}.\\n\\n${diff}\\n\\nNext: set X402_FACILITATOR_URL, X402_NETWORK, and X402_PAY_TO, then restart. Run \\`x402-lens doctor\\` to verify the configuration.`,\r\n exitCode: 0,\r\n };\r\n}\r\n\r\ninterface ParsedRoute {\r\n method: string;\r\n path: string;\r\n}\r\n\r\nfunction parseRoute(route: string): ParsedRoute {\r\n const trimmed = route.trim();\r\n const spaceIndex = trimmed.indexOf(\" \");\r\n if (spaceIndex === -1) {\r\n return { method: \"GET\", path: trimmed };\r\n }\r\n return {\r\n method: trimmed.slice(0, spaceIndex).toUpperCase(),\r\n path: trimmed.slice(spaceIndex + 1).trim(),\r\n };\r\n}\r\n\r\n/** `\"GET /weather\"`, the key format the lens route map uses. */\r\nfunction routeKey(route: ParsedRoute): string {\r\n return `${route.method} ${route.path}`;\r\n}\r\n\r\n/**\r\n * A double-quoted TypeScript/JavaScript string literal, safe for source insert.\r\n *\r\n * Quotes, backslashes, and newlines are escaped so a crafted `--price` cannot\r\n * break out of the literal or inject object keys.\r\n */\r\nfunction tsStringLiteral(value: string): string {\r\n return JSON.stringify(value);\r\n}\r\n\r\n/** One routes-map entry: `\"GET /path\": \"0.001\"`. */\r\nfunction routeMapEntry(route: ParsedRoute, price: string): string {\r\n return `${tsStringLiteral(routeKey(route))}: ${tsStringLiteral(price)}`;\r\n}\r\n\r\n/**\r\n * Same rule as config string prices: non-empty after trim. Object asset prices\r\n * are not a CLI flag form.\r\n */\r\nfunction assertAddPrice(price: string): string {\r\n const trimmed = price.trim();\r\n if (trimmed.length === 0) {\r\n throw new AddError('price is empty. Use a decimal such as \"0.001\".');\r\n }\r\n return trimmed;\r\n}\r\n\r\n/**\r\n * Index of the `}` that closes the `{` at `open`, skipping strings and comments.\r\n *\r\n * A brace counter alone would trip over a route path containing `}` or a\r\n * comment mentioning `{`, so the scan respects quoting and both comment styles.\r\n *\r\n * @returns Index of the closing brace, or -1 when the source is unbalanced\r\n */\r\nfunction matchBrace(source: string, open: number): number {\r\n let depth = 0;\r\n for (let index = open; index < source.length; index += 1) {\r\n const char = source[index];\r\n const next = source[index + 1];\r\n\r\n if (char === \"/\" && next === \"/\") {\r\n const newline = source.indexOf(\"\\n\", index);\r\n if (newline === -1) return -1;\r\n index = newline;\r\n continue;\r\n }\r\n if (char === \"/\" && next === \"*\") {\r\n const end = source.indexOf(\"*/\", index + 2);\r\n if (end === -1) return -1;\r\n index = end + 1;\r\n continue;\r\n }\r\n if (char === '\"' || char === \"'\" || char === \"`\") {\r\n index = skipString(source, index);\r\n if (index === -1) return -1;\r\n continue;\r\n }\r\n if (char === \"{\") depth += 1;\r\n else if (char === \"}\") {\r\n depth -= 1;\r\n if (depth === 0) return index;\r\n }\r\n }\r\n return -1;\r\n}\r\n\r\n/** Index just past the closing quote, or -1 when the literal never closes. */\r\nfunction skipString(source: string, open: number): number {\r\n const quote = source[open];\r\n for (let index = open + 1; index < source.length; index += 1) {\r\n const char = source[index];\r\n if (char === \"\\\\\") {\r\n index += 1;\r\n continue;\r\n }\r\n if (char === quote) return index;\r\n }\r\n return -1;\r\n}\r\n\r\n/** The span of the `paymentLens(...)` argument list, when the file has one. */\r\nfunction findLensCall(source: string): { open: number; close: number } | undefined {\r\n const pattern = /\\bpaymentLens(?:Async)?\\s*\\(/;\r\n const match = pattern.exec(source);\r\n if (!match) return undefined;\r\n const open = source.indexOf(\"(\", match.index);\r\n const close = matchParen(source, open);\r\n if (close === -1) return undefined;\r\n return { open, close };\r\n}\r\n\r\n/** Index of the `)` closing the `(` at `open`, skipping strings and comments. */\r\nfunction matchParen(source: string, open: number): number {\r\n let depth = 0;\r\n for (let index = open; index < source.length; index += 1) {\r\n const char = source[index];\r\n const next = source[index + 1];\r\n\r\n if (char === \"/\" && next === \"/\") {\r\n const newline = source.indexOf(\"\\n\", index);\r\n if (newline === -1) return -1;\r\n index = newline;\r\n continue;\r\n }\r\n if (char === \"/\" && next === \"*\") {\r\n const end = source.indexOf(\"*/\", index + 2);\r\n if (end === -1) return -1;\r\n index = end + 1;\r\n continue;\r\n }\r\n if (char === '\"' || char === \"'\" || char === \"`\") {\r\n index = skipString(source, index);\r\n if (index === -1) return -1;\r\n continue;\r\n }\r\n if (char === \"(\") depth += 1;\r\n else if (char === \")\") {\r\n depth -= 1;\r\n if (depth === 0) return index;\r\n }\r\n }\r\n return -1;\r\n}\r\n\r\n/** Locate the `routes: { ... }` object literal inside a `paymentLens` call. */\r\nfunction findRoutesObject(source: string): { open: number; close: number } | undefined {\r\n const call = findLensCall(source);\r\n const scope = call ?? { open: 0, close: source.length - 1 };\r\n const inner = source.slice(scope.open, scope.close + 1);\r\n const pattern = /\\broutes\\s*:\\s*\\{/;\r\n const match = pattern.exec(inner);\r\n if (!match) return undefined;\r\n const open = scope.open + match.index + match[0].length - 1;\r\n const close = matchBrace(source, open);\r\n if (close === -1) return undefined;\r\n return { open, close };\r\n}\r\n\r\n/** True when the lens route map already charges for this route. */\r\nfunction hasRouteEntryFor(source: string, route: ParsedRoute): boolean {\r\n const key = escapeRegExp(routeKey(route));\r\n const quotedKey = new RegExp(`[\"'\\`]${key}[\"'\\`]\\\\s*:`);\r\n const routes = findRoutesObject(source);\r\n if (routes) return quotedKey.test(source.slice(routes.open, routes.close + 1));\r\n // No routes map in code: the prices come from env or x402.config.json, so a\r\n // mention of the path elsewhere says nothing about whether it is priced.\r\n return false;\r\n}\r\n\r\n/**\r\n * Add one entry to the lens route map, preserving the file's own formatting.\r\n *\r\n * Refuses the forms it cannot rewrite safely — an array-form `routes`, or a\r\n * `paymentLens()` call carrying options the command does not understand — with\r\n * instructions instead of a guess.\r\n */\r\nfunction withRouteEntry(\r\n source: string,\r\n file: string,\r\n route: ParsedRoute,\r\n price: string,\r\n): string {\r\n if (/\\broutes\\s*:\\s*\\[/.test(source)) {\r\n throw new AddError(\r\n `${file} passes routes as an array, which x402-lens add does not rewrite. Add the entry by hand:\\n\\n { route: ${tsStringLiteral(routeKey(route))}, price: ${tsStringLiteral(price)} }\\n`,\r\n );\r\n }\r\n\r\n const routes = findRoutesObject(source);\r\n if (!routes) {\r\n throw new AddError(\r\n `paymentLens is already called, but its routes map could not be found, so x402-lens add will not guess where to put ${routeKey(route)}. Add it by hand:\\n\\n routes: { ${routeMapEntry(route, price)} }\\n`,\r\n );\r\n }\r\n\r\n const entry = routeMapEntry(route, price);\r\n const inner = source.slice(routes.open + 1, routes.close);\r\n\r\n // Insert after the last entry, keeping the closing brace on its own line when\r\n // the object already spans several.\r\n const trailing = inner.match(/\\s*$/)?.[0] ?? \"\";\r\n const insertAt = routes.close - trailing.length;\r\n const lastEntry = source.slice(routes.open + 1, insertAt);\r\n\r\n if (lastEntry.trim().length === 0) {\r\n return `${source.slice(0, routes.open + 1)} ${entry} ${source.slice(routes.close)}`;\r\n }\r\n\r\n // Indentation comes from the line the last entry starts on, never from the\r\n // insertion point — which sits just before the closing brace's newline.\r\n const entryEnd = routes.open + 1 + lastEntry.length;\r\n const lineStart = source.lastIndexOf(\"\\n\", entryEnd - 1) + 1;\r\n const indent = source.slice(lineStart, entryEnd).match(/^[ \\t]*/)?.[0] ?? \"\";\r\n const spacer = trailing.includes(\"\\n\") ? \"\\n\" : \" \";\r\n // Follow whatever comma style the file already uses: a trailing comma on the\r\n // last entry means the author wants one on every entry.\r\n const trailingComma = lastEntry.trimEnd().endsWith(\",\");\r\n const inserted = trailingComma ? `${entry},` : entry;\r\n const separator = trailingComma ? \"\" : \",\";\r\n\r\n return `${source.slice(0, insertAt)}${separator}${spacer}${indent}${inserted}${source.slice(insertAt)}`;\r\n}\r\n\r\ntype Framework = \"express\" | \"fastify\" | \"hono\" | \"fastapi\" | \"unknown\";\r\n\r\nfunction detectFramework(source: string): Framework {\r\n if (/from\\s+[\"']express[\"']|require\\(\\s*[\"']express[\"']\\s*\\)/.test(source)) return \"express\";\r\n if (/from\\s+[\"']fastify[\"']|require\\(\\s*[\"']fastify[\"']\\s*\\)/.test(source)) return \"fastify\";\r\n if (/from\\s+[\"']hono[\"']/.test(source)) return \"hono\";\r\n if (/from\\s+fastapi\\s+import|import\\s+fastapi/.test(source)) return \"fastapi\";\r\n return \"unknown\";\r\n}\r\n\r\ninterface RouteMatch {\r\n /** Index of the route declaration's start. */\r\n routeStart: number;\r\n /** The matched declaration text, for reporting. */\r\n matched: string;\r\n}\r\n\r\n/**\r\n * Find the route and where to insert the guard.\r\n *\r\n * Matches `app.get(\"/path\",` and `router.get(\"/path\",` — including single- or\r\n * double-quoted paths. Refuses multi-line and computed-path variants by simply\r\n * not matching them.\r\n */\r\nfunction findRouteDeclaration(source: string, route: ParsedRoute): RouteMatch | undefined {\r\n const method = route.method.toLowerCase();\r\n const escapedPath = escapeRegExp(route.path);\r\n const pattern = new RegExp(\r\n `\\\\b(?:app|router|server)\\\\.${method}\\\\(\\\\s*([\"'\\`])${escapedPath}\\\\1\\\\s*,`,\r\n );\r\n const match = pattern.exec(source);\r\n if (!match) return undefined;\r\n return {\r\n routeStart: match.index,\r\n matched: match[0],\r\n };\r\n}\r\n\r\nfunction applyEdits(\r\n source: string,\r\n route: ParsedRoute,\r\n price: string,\r\n routeMatch: RouteMatch,\r\n): string {\r\n let updated = source;\r\n\r\n // The lens is mounted globally and its route map decides what is protected,\r\n // so no per-route guard is needed. Adding one as well would duplicate the\r\n // check on the same request.\r\n if (!updated.includes(\"paymentLens(\")) {\r\n // Normalise spacing rather than guess at it: exactly one blank line before\r\n // the declaration and one after the mount, whatever the file had. `\\r?` so\r\n // a CRLF file is treated the same as an LF one.\r\n const before = `${updated\r\n .slice(0, routeMatch.routeStart)\r\n .replace(/(?:[ \\t]*\\r?\\n)+$/, \"\")}\\n\\n`;\r\n const body = `${LENS_DECLARATION.replace(\r\n \"paymentLens()\",\r\n `paymentLens({ routes: { ${routeMapEntry(route, price)} } })`,\r\n )}\\n${MOUNT_LINE}\\n\\n`;\r\n updated = `${before}${body}${updated.slice(routeMatch.routeStart)}`;\r\n }\r\n\r\n // Add the import after the last top-level import.\r\n if (!updated.includes(\"@x402-lens/express\")) {\r\n const lastImport = findLastImportEnd(updated);\r\n if (lastImport === -1) {\r\n updated = `${IMPORT_LINE}\\n${updated}`;\r\n } else {\r\n updated = `${updated.slice(0, lastImport)}\\n${IMPORT_LINE}${updated.slice(lastImport)}`;\r\n }\r\n }\r\n\r\n return updated;\r\n}\r\n\r\nfunction findLastImportEnd(source: string): number {\r\n const lines = source.split(\"\\n\");\r\n let offset = 0;\r\n let lastEnd = -1;\r\n\r\n for (const line of lines) {\r\n const trimmed = line.trim();\r\n const isImportStart = trimmed.startsWith(\"import \");\r\n const isImportContinuation = lastEnd !== -1 && trimmed.length > 0 && !trimmed.startsWith(\"//\");\r\n\r\n if (isImportStart) {\r\n // A one-liner import ends on its own line.\r\n if (/from\\s+[\"'][^\"']+[\"'];?$/.test(trimmed) || /^import\\s+[\"'][^\"']+[\"'];?$/.test(trimmed)) {\r\n lastEnd = offset + line.length;\r\n } else {\r\n // Multi-line import: remember the start and wait for the close.\r\n lastEnd = -2;\r\n }\r\n } else if (lastEnd === -2 && isImportContinuation && trimmed.endsWith(\";\")) {\r\n lastEnd = offset + line.length;\r\n }\r\n offset += line.length + 1;\r\n }\r\n\r\n return lastEnd > 0 ? lastEnd : -1;\r\n}\r\n\r\nfunction escapeRegExp(value: string): string {\r\n return value.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\r\n}\r\n\r\n/**\r\n * Produce a unified diff with three lines of context.\r\n *\r\n * Only used for display, so it favours readability over exactness: it diffs by\r\n * line and emits a single hunk per changed region.\r\n *\r\n * @param file - Path shown in the diff header\r\n * @param before - Original contents\r\n * @param after - Updated contents\r\n * @returns Unified diff text\r\n */\r\nexport function unifiedDiff(file: string, before: string, after: string): string {\r\n const beforeLines = before.split(\"\\n\");\r\n const afterLines = after.split(\"\\n\");\r\n const operations = diffLines(beforeLines, afterLines);\r\n\r\n const changedIndices = operations\r\n .map((op, index) => (op.type === \"equal\" ? -1 : index))\r\n .filter(index => index !== -1);\r\n\r\n if (changedIndices.length === 0) return \"\";\r\n\r\n const firstChanged = Math.max(0, (changedIndices[0] ?? 0) - 3);\r\n const lastChanged = Math.min(operations.length - 1, (changedIndices.at(-1) ?? 0) + 3);\r\n\r\n const header = [`--- a/${file}`, `+++ b/${file}`];\r\n let beforeCount = 0;\r\n let afterCount = 0;\r\n for (let index = firstChanged; index <= lastChanged; index += 1) {\r\n const op = operations[index];\r\n if (!op) continue;\r\n if (op.type !== \"insert\") beforeCount += 1;\r\n if (op.type !== \"delete\") afterCount += 1;\r\n }\r\n\r\n const body: string[] = [`@@ -${firstChanged + 1},${beforeCount} +${firstChanged + 1},${afterCount} @@`];\r\n for (let index = firstChanged; index <= lastChanged; index += 1) {\r\n const op = operations[index];\r\n if (!op) continue;\r\n if (op.type === \"equal\") body.push(` ${op.line}`);\r\n else if (op.type === \"delete\") body.push(`-${op.line}`);\r\n else body.push(`+${op.line}`);\r\n }\r\n\r\n return [...header, ...body].join(\"\\n\");\r\n}\r\n\r\ntype LineOp =\r\n | { type: \"equal\"; line: string }\r\n | { type: \"delete\"; line: string }\r\n | { type: \"insert\"; line: string };\r\n\r\n/**\r\n * Line diff via longest-common-subsequence. Quadratic, which is fine for source\r\n * files of a few thousand lines and keeps the command dependency-free.\r\n */\r\nfunction diffLines(before: string[], after: string[]): LineOp[] {\r\n const rows = before.length + 1;\r\n const cols = after.length + 1;\r\n const table: number[][] = Array.from({ length: rows }, () => new Array<number>(cols).fill(0));\r\n\r\n for (let i = before.length - 1; i >= 0; i -= 1) {\r\n for (let j = after.length - 1; j >= 0; j -= 1) {\r\n const row = table[i];\r\n const nextRow = table[i + 1];\r\n if (!row || !nextRow) continue;\r\n row[j] =\r\n before[i] === after[j]\r\n ? (nextRow[j + 1] ?? 0) + 1\r\n : Math.max(nextRow[j] ?? 0, row[j + 1] ?? 0);\r\n }\r\n }\r\n\r\n const operations: LineOp[] = [];\r\n let i = 0;\r\n let j = 0;\r\n while (i < before.length && j < after.length) {\r\n if (before[i] === after[j]) {\r\n operations.push({ type: \"equal\", line: before[i] as string });\r\n i += 1;\r\n j += 1;\r\n continue;\r\n }\r\n const nextRow = table[i + 1];\r\n const row = table[i];\r\n if (!nextRow || !row) break;\r\n if ((nextRow[j] ?? 0) >= (row[j + 1] ?? 0)) {\r\n operations.push({ type: \"delete\", line: before[i] as string });\r\n i += 1;\r\n } else {\r\n operations.push({ type: \"insert\", line: after[j] as string });\r\n j += 1;\r\n }\r\n }\r\n while (i < before.length) {\r\n operations.push({ type: \"delete\", line: before[i] as string });\r\n i += 1;\r\n }\r\n while (j < after.length) {\r\n operations.push({ type: \"insert\", line: after[j] as string });\r\n j += 1;\r\n }\r\n\r\n return operations;\r\n}\r\n","/**\r\n * `x402-lens explain` — why did this payment fail.\r\n *\r\n * Feed it any subset of the exchange: the challenge, the payment the client\r\n * sent, and the facilitator's verify or settle response. It runs the findings\r\n * engine and prints the result with fixes.\r\n */\r\n\r\nimport {\r\n diagnose,\r\n formatFindings,\r\n type Finding,\r\n type WirePaymentPayload,\r\n type WirePaymentRequired,\r\n type WireSettleResponse,\r\n type WireVerifyResponse,\r\n} from \"@x402-lens/core\";\r\nimport { readJsonArgument } from \"../input.js\";\r\n\r\nexport interface ExplainInput {\r\n challenge?: string;\r\n payment?: string;\r\n verify?: string;\r\n settle?: string;\r\n}\r\n\r\nexport interface ExplainResult {\r\n text: string;\r\n exitCode: number;\r\n findingCount: number;\r\n /** Structured findings for `--json` consumers. */\r\n findings: Finding[];\r\n}\r\n\r\n/**\r\n * Diagnose a captured exchange.\r\n *\r\n * @param input - Raw arguments, each JSON / base64 / `@file`\r\n * @returns Rendered report and an exit code (1 when anything is an error)\r\n */\r\nexport async function explainPayment(input: ExplainInput): Promise<ExplainResult> {\r\n const paymentRequired = input.challenge\r\n ? ((await readJsonArgument(input.challenge, \"--challenge\")) as WirePaymentRequired)\r\n : undefined;\r\n const paymentPayload = input.payment\r\n ? ((await readJsonArgument(input.payment, \"--payment\")) as WirePaymentPayload)\r\n : undefined;\r\n const verifyResponse = input.verify\r\n ? ((await readJsonArgument(input.verify, \"--verify\")) as WireVerifyResponse)\r\n : undefined;\r\n const settleResponse = input.settle\r\n ? ((await readJsonArgument(input.settle, \"--settle\")) as WireSettleResponse)\r\n : undefined;\r\n\r\n if (!paymentRequired && !paymentPayload && !verifyResponse && !settleResponse) {\r\n return {\r\n text: [\r\n \"Nothing to explain.\",\r\n \"\",\r\n \"Pass at least one of:\",\r\n \" --challenge <PAYMENT-REQUIRED|@file> the 402 terms\",\r\n \" --payment <PAYMENT-SIGNATURE|@file> what the client sent\",\r\n \" --verify <json|@file> facilitator /verify response\",\r\n \" --settle <json|@file> facilitator /settle response\",\r\n ].join(\"\\n\"),\r\n exitCode: 2,\r\n findingCount: 0,\r\n findings: [],\r\n };\r\n }\r\n\r\n const findings = diagnose({\r\n ...(paymentRequired ? { paymentRequired } : {}),\r\n ...(paymentPayload ? { paymentPayload } : {}),\r\n ...(verifyResponse ? { verifyResponse } : {}),\r\n ...(settleResponse ? { settleResponse } : {}),\r\n });\r\n\r\n const header = [\r\n \"x402-lens explain\",\r\n ` challenge: ${paymentRequired ? \"yes\" : \"no\"}`,\r\n ` payment: ${paymentPayload ? \"yes\" : \"no\"}`,\r\n ` verify: ${verifyResponse ? (verifyResponse.isValid ? \"valid\" : \"invalid\") : \"no\"}`,\r\n ` settle: ${settleResponse ? (settleResponse.success ? \"settled\" : \"failed\") : \"no\"}`,\r\n ].join(\"\\n\");\r\n\r\n const hasError = findings.some(finding => finding.severity === \"error\");\r\n\r\n return {\r\n text: `${header}\\n\\n${formatFindings(findings)}`,\r\n exitCode: hasError ? 1 : 0,\r\n findingCount: findings.length,\r\n findings,\r\n };\r\n}\r\n","/**\r\n * Reading x402 wire objects from arguments.\r\n *\r\n * Everything a developer pastes into a debugging session arrives in one of\r\n * three shapes: raw base64, base64 in an `@file`, or already-decoded JSON. All\r\n * three are supported so nobody has to transform a header by hand.\r\n */\r\n\r\nimport { readFile } from \"node:fs/promises\";\r\n\r\n/** Raised when an argument cannot be decoded. */\r\nexport class InputError extends Error {\r\n constructor(message: string) {\r\n super(message);\r\n this.name = \"InputError\";\r\n }\r\n}\r\n\r\n/**\r\n * Decode an argument into a JSON value.\r\n *\r\n * Accepts `@path` (read the file), raw JSON, or base64-encoded JSON. The order\r\n * matters: JSON is tried first because a base64 string is never valid JSON, so\r\n * a JSON-looking value never falls through to the base64 branch.\r\n *\r\n * @param raw - The argument value\r\n * @param label - Argument name, used in error messages\r\n * @returns The parsed value\r\n * @throws {InputError} When nothing can be parsed\r\n */\r\nexport async function readJsonArgument(raw: string, label: string): Promise<unknown> {\r\n const source = raw.startsWith(\"@\") ? await readFile(raw.slice(1), \"utf8\") : raw;\r\n return parseJsonOrBase64(source, label);\r\n}\r\n\r\n/**\r\n * Parse a string that is either JSON or base64-encoded JSON.\r\n *\r\n * @param source - Raw string\r\n * @param label - Name used in error messages\r\n * @returns The parsed value\r\n * @throws {InputError} When neither form parses\r\n */\r\nexport function parseJsonOrBase64(source: string, label: string): unknown {\r\n const trimmed = source.trim();\r\n if (trimmed.length === 0) {\r\n throw new InputError(`${label} is empty.`);\r\n }\r\n\r\n const asJson = tryParseJson(trimmed);\r\n if (asJson !== undefined) return asJson;\r\n\r\n const decoded = tryDecodeBase64(trimmed);\r\n if (decoded !== undefined) {\r\n const fromBase64 = tryParseJson(decoded);\r\n if (fromBase64 !== undefined) return fromBase64;\r\n throw new InputError(\r\n `${label} decodes from base64 but the result is not JSON. Got: ${decoded.slice(0, 120)}`,\r\n );\r\n }\r\n\r\n throw new InputError(\r\n `${label} is neither JSON nor base64-encoded JSON. Pass the header value verbatim, or JSON, or @file.`,\r\n );\r\n}\r\n\r\nfunction tryParseJson(value: string): unknown | undefined {\r\n const first = value[0];\r\n if (first !== \"{\" && first !== \"[\" && first !== '\"') return undefined;\r\n try {\r\n return JSON.parse(value) as unknown;\r\n } catch {\r\n return undefined;\r\n }\r\n}\r\n\r\nfunction tryDecodeBase64(value: string): string | undefined {\r\n const normalised = value.replace(/-/g, \"+\").replace(/_/g, \"/\");\r\n const padded = normalised.padEnd(\r\n normalised.length + ((4 - (normalised.length % 4)) % 4),\r\n \"=\",\r\n );\r\n if (!/^[A-Za-z0-9+/]+={0,2}$/.test(padded)) return undefined;\r\n try {\r\n const decoded = Buffer.from(padded, \"base64\").toString(\"utf8\");\r\n // Base64 of binary decodes to replacement characters; reject that.\r\n return decoded.includes(\"\\uFFFD\") ? undefined : decoded;\r\n } catch {\r\n return undefined;\r\n }\r\n}\r\n","/**\r\n * `x402-lens doctor` — check that a configuration can actually accept payments.\r\n *\r\n * Three things break a deployment before a single buyer arrives: a network the\r\n * facilitator does not support, a missing or wrong-shaped receiving address, and\r\n * a facilitator that is simply unreachable. All three are checkable up front.\r\n */\r\n\r\nimport {\r\n ConfigError,\r\n WELL_KNOWN_NETWORKS,\r\n describeNetwork,\r\n isCaip2,\r\n loadConfig,\r\n suggestCaip2,\r\n type LensConfig,\r\n} from \"@x402-lens/core\";\r\n\r\nexport interface DoctorOptions {\r\n /** Config to check. When absent, it is loaded from env and `x402.config.json`. */\r\n config?: LensConfig;\r\n /** Directory used to resolve `x402.config.json`. Defaults to `process.cwd()`. */\r\n cwd?: string;\r\n /** Override the facilitator to probe. */\r\n facilitatorUrl?: string;\r\n /** Override the network to verify against `/supported`. */\r\n network?: string;\r\n /** Override the full network list. Wins over `network` when present. */\r\n networks?: string[];\r\n /** Fetch timeout, milliseconds. */\r\n timeoutMs?: number;\r\n}\r\n\r\nexport interface DoctorCheck {\r\n name: string;\r\n ok: boolean;\r\n detail: string;\r\n}\r\n\r\nexport interface DoctorResult {\r\n checks: DoctorCheck[];\r\n exitCode: number;\r\n text: string;\r\n}\r\n\r\ninterface SupportedResponse {\r\n kinds?: Array<{ x402Version?: number; scheme?: string; network?: string }>;\r\n extensions?: string[];\r\n signers?: Record<string, string[]>;\r\n}\r\n\r\n/**\r\n * Run every configuration check that does not require a buyer.\r\n *\r\n * @param options - Config and probe overrides\r\n * @returns Individual checks, a rendered report, and an exit code\r\n */\r\nexport async function runDoctor(options: DoctorOptions = {}): Promise<DoctorResult> {\r\n const checks: DoctorCheck[] = [];\r\n\r\n let config: LensConfig | undefined;\r\n let configError: Error | undefined;\r\n try {\r\n config =\r\n options.config ??\r\n (await loadConfig({\r\n readConfigFile: true,\r\n ...(options.cwd !== undefined ? { cwd: options.cwd } : {}),\r\n }));\r\n checks.push({\r\n name: \"config\",\r\n ok: true,\r\n detail: `facilitator ${config.facilitatorUrl}, network ${\r\n config.networks.length > 1\r\n ? config.networks.map(describeNetwork).join(\", \")\r\n : describeNetwork(config.network)\r\n }, ${config.routes.length} route(s)`,\r\n });\r\n checks.push(checkFacilitatorHeadersOk(config));\r\n } catch (error) {\r\n configError = error as Error;\r\n if (isFacilitatorHeadersConfigError(configError)) {\r\n checks.push({\r\n name: \"facilitatorHeaders\",\r\n ok: false,\r\n detail: configError.message,\r\n });\r\n // Do not continue with facilitator overrides: a bad header shape is a\r\n // deploy blocker even when --facilitator / --network are supplied.\r\n return finish(checks);\r\n }\r\n }\r\n\r\n const facilitatorUrl = (\r\n options.facilitatorUrl ??\r\n config?.facilitatorUrl ??\r\n \"\"\r\n ).replace(/\\/+$/, \"\");\r\n // An explicit network override replaces the list rather than adding to it:\r\n // `--network` asks a question about one chain, not about the deployment.\r\n const networks =\r\n options.networks ??\r\n (options.network ? [options.network] : (config?.networks ?? []));\r\n const network = networks[0] ?? \"\";\r\n\r\n if (!config) {\r\n if (!facilitatorUrl || !network) {\r\n checks.push({\r\n name: \"config\",\r\n ok: false,\r\n detail: configError?.message ?? \"Configuration could not be loaded.\",\r\n });\r\n return finish(checks);\r\n }\r\n // Overrides supplied enough to probe the facilitator; the rest is reported.\r\n checks.push({\r\n name: \"config\",\r\n ok: true,\r\n detail:\r\n \"Probing with facilitator and network overrides. Full configuration (payTo, routes) was not loaded, so it was not checked.\",\r\n });\r\n }\r\n\r\n if (!isCaip2(network)) {\r\n const suggestion = suggestCaip2(network);\r\n checks.push({\r\n name: \"network format\",\r\n ok: false,\r\n detail: `\"${network}\" is not CAIP-2.${suggestion ? ` Use \"${suggestion}\".` : \"\"}`,\r\n });\r\n return finish(checks);\r\n }\r\n checks.push({\r\n name: \"network format\",\r\n ok: true,\r\n detail: describeNetwork(network),\r\n });\r\n\r\n if (config) {\r\n for (const net of networks.length > 0 ? networks : config.networks) {\r\n const address = config.payToByNetwork[net] ?? config.payTo;\r\n checks.push(checkPayToShape(address, net));\r\n }\r\n }\r\n\r\n let supported: SupportedResponse | undefined;\r\n try {\r\n const authHeaders = config?.facilitatorHeaders?.supported ?? {};\r\n const response = await fetch(`${facilitatorUrl}/supported`, {\r\n headers: {\r\n Accept: \"application/json\",\r\n \"User-Agent\": \"x402-lens/0.2\",\r\n ...authHeaders,\r\n },\r\n signal: AbortSignal.timeout(options.timeoutMs ?? 15_000),\r\n });\r\n if (!response.ok) {\r\n checks.push({\r\n name: \"facilitator reachable\",\r\n ok: false,\r\n detail: `GET ${facilitatorUrl}/supported returned HTTP ${response.status}.`,\r\n });\r\n return finish(checks);\r\n }\r\n supported = (await response.json()) as SupportedResponse;\r\n checks.push({\r\n name: \"facilitator reachable\",\r\n ok: true,\r\n detail: `${facilitatorUrl}/supported responded with ${String(supported.kinds?.length ?? 0)} kind(s).`,\r\n });\r\n } catch (error) {\r\n checks.push({\r\n name: \"facilitator reachable\",\r\n ok: false,\r\n detail: `Could not reach ${facilitatorUrl}/supported: ${(error as Error).message}. Check the URL, the network path, and any proxy in between.`,\r\n });\r\n return finish(checks);\r\n }\r\n\r\n const kinds = supported.kinds ?? [];\r\n const matching = kinds.filter(\r\n kind => kind.network === network && kind.x402Version === 2,\r\n );\r\n\r\n if (matching.length === 0) {\r\n const v1Only = kinds.some(kind => kind.network === network && kind.x402Version === 1);\r\n const available = Array.from(\r\n new Set(kinds.filter(kind => kind.x402Version === 2).map(kind => kind.network ?? \"\")),\r\n ).filter(Boolean);\r\n checks.push({\r\n name: \"network supported\",\r\n ok: false,\r\n detail: v1Only\r\n ? `The facilitator lists ${network} for x402Version 1 only. This middleware speaks v2, so payments will be rejected.`\r\n : `The facilitator does not list ${network} with x402Version 2. It supports: ${available.join(\", \") || \"nothing\"}.`,\r\n });\r\n } else {\r\n checks.push({\r\n name: \"network supported\",\r\n ok: true,\r\n detail: `${network} is available for scheme(s): ${matching.map(kind => kind.scheme ?? \"?\").join(\", \")}.`,\r\n });\r\n }\r\n\r\n // Every configured network is validated by the SDK at startup, and a missing\r\n // one is fatal: `@x402/core` calls process.exit(1) from its background init,\r\n // which kills the server rather than returning a 402. Checking all of them\r\n // here is the only place that failure can be caught before a deploy.\r\n const missing = networks.filter(\r\n candidate =>\r\n !kinds.some(kind => kind.network === candidate && kind.x402Version === 2),\r\n );\r\n if (networks.length > 1) {\r\n checks.push(\r\n missing.length === 0\r\n ? {\r\n name: \"all networks supported\",\r\n ok: true,\r\n detail: `All ${networks.length} configured networks are listed for x402Version 2: ${networks.join(\", \")}.`,\r\n }\r\n : {\r\n name: \"all networks supported\",\r\n ok: false,\r\n detail: `These configured networks are not listed for x402Version 2: ${missing.join(\r\n \", \",\r\n )}. The SDK treats this as a fatal startup error and exits the process, so the server will not start. Remove them from networks, or use a facilitator that supports them.`,\r\n },\r\n );\r\n }\r\n\r\n const requiredSchemes = Array.from(\r\n new Set(\r\n (config?.routes ?? []).map(route => route.scheme ?? \"exact\"),\r\n ),\r\n );\r\n // No loaded routes: keep the historical exact check so a facilitator-only\r\n // probe still answers the common default.\r\n const schemesToCheck = requiredSchemes.length > 0 ? requiredSchemes : [\"exact\"];\r\n const networksForSchemes = networks.length > 0 ? networks : [network];\r\n for (const scheme of schemesToCheck) {\r\n const missingSchemeNetworks = networksForSchemes.filter(\r\n candidate =>\r\n !kinds.some(\r\n kind =>\r\n kind.network === candidate &&\r\n kind.x402Version === 2 &&\r\n kind.scheme === scheme,\r\n ),\r\n );\r\n const schemeOk = missingSchemeNetworks.length === 0;\r\n checks.push({\r\n name: `${scheme} scheme`,\r\n ok: schemeOk,\r\n detail: schemeOk\r\n ? networksForSchemes.length > 1\r\n ? `The facilitator supports the ${scheme} scheme on all configured networks.`\r\n : `The facilitator supports the ${scheme} scheme on this network.`\r\n : `Configured routes use the ${scheme} scheme, which is not listed for: ${missingSchemeNetworks.join(\", \")}.`,\r\n });\r\n }\r\n\r\n if (WELL_KNOWN_NETWORKS[network as keyof typeof WELL_KNOWN_NETWORKS]) {\r\n checks.push({\r\n name: \"known network\",\r\n ok: true,\r\n detail: `${describeNetwork(network)} — widely deployed, safe for production.`,\r\n });\r\n } else {\r\n checks.push({\r\n name: \"known network\",\r\n ok: true,\r\n detail: `${network} is not in the built-in list. That is fine if you intended it; verify token and facilitator support yourself.`,\r\n });\r\n }\r\n\r\n return finish(checks);\r\n}\r\n\r\nfunction isFacilitatorHeadersConfigError(error: Error): error is ConfigError {\r\n return error instanceof ConfigError && error.field === \"facilitatorHeaders\";\r\n}\r\n\r\n/**\r\n * Report that auth headers are either absent or already in the per-path shape\r\n * `resolveConfig` accepts. Flat objects and file-based secrets never reach here.\r\n */\r\nfunction checkFacilitatorHeadersOk(config: LensConfig): DoctorCheck {\r\n if (!config.facilitatorHeaders) {\r\n return {\r\n name: \"facilitatorHeaders\",\r\n ok: true,\r\n detail:\r\n \"No facilitatorHeaders set (public facilitator or X402_FACILITATOR_TOKEN unset).\",\r\n };\r\n }\r\n return {\r\n name: \"facilitatorHeaders\",\r\n ok: true,\r\n detail:\r\n \"facilitatorHeaders use the per-path shape (verify/settle/supported), not a flat object.\",\r\n };\r\n}\r\n\r\n/** Cheap shape check: EVM addresses are 0x + 40 hex, SVM are base58. */\r\nfunction checkPayToShape(payTo: string, network: string): DoctorCheck {\r\n const namespace = network.slice(0, network.indexOf(\":\"));\r\n\r\n if (namespace === \"eip155\") {\r\n const ok = /^0x[0-9a-fA-F]{40}$/.test(payTo);\r\n return {\r\n name: \"payTo address\",\r\n ok,\r\n detail: ok\r\n ? `${payTo} looks like an EVM address.`\r\n : `\"${payTo}\" is not a 0x-prefixed 20-byte address, which ${describeNetwork(network)} requires.`,\r\n };\r\n }\r\n\r\n if (namespace === \"solana\") {\r\n const ok = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/.test(payTo);\r\n return {\r\n name: \"payTo address\",\r\n ok,\r\n detail: ok\r\n ? `${payTo} looks like a base58 Solana address.`\r\n : `\"${payTo}\" is not a base58 public key, which ${describeNetwork(network)} requires.`,\r\n };\r\n }\r\n\r\n return {\r\n name: \"payTo address\",\r\n ok: payTo.length > 0,\r\n detail: `No format check available for namespace \"${namespace}\". Confirm the address format with the network's tooling.`,\r\n };\r\n}\r\n\r\nfunction finish(checks: DoctorCheck[]): DoctorResult {\r\n const failed = checks.filter(check => !check.ok);\r\n const lines = checks.map(check => `${check.ok ? \"ok \" : \"FAIL\"} ${check.name}: ${check.detail}`);\r\n const summary =\r\n failed.length === 0\r\n ? \"\\nAll checks passed.\"\r\n : `\\n${failed.length} check(s) failed. Fix the FAIL lines above; every one of them prevents real payments.`;\r\n\r\n return {\r\n checks,\r\n exitCode: failed.length === 0 ? 0 : 1,\r\n text: [...lines, summary].join(\"\\n\"),\r\n };\r\n}\r\n","/**\r\n * `x402-lens inspect` — look at a live endpoint from the outside.\r\n *\r\n * Sends an unpaid request, decodes the challenge, and reports both schema\r\n * conformance and CORS readiness. That is the whole \"is my paywall correct\"\r\n * question, answerable without reading the server's source.\r\n */\r\n\r\nimport {\r\n checkCors,\r\n describeNetwork,\r\n diagnose,\r\n formatFindings,\r\n validatePaymentRequired,\r\n type WirePaymentRequired,\r\n} from \"@x402-lens/core\";\r\nimport { decodePaymentRequiredHeader } from \"@x402/core/http\";\r\n\r\nexport interface InspectOptions {\r\n url: string;\r\n method?: string;\r\n headers?: Record<string, string>;\r\n timeoutMs?: number;\r\n}\r\n\r\nexport interface InspectResult {\r\n status: number;\r\n paymentRequired?: WirePaymentRequired;\r\n headerPresent: boolean;\r\n decodedFromBody: boolean;\r\n conformance: ReturnType<typeof validatePaymentRequired>;\r\n cors: ReturnType<typeof checkCors>;\r\n findings: string;\r\n /** Non-zero when the endpoint is not a working x402 v2 paywall. */\r\n exitCode: number;\r\n}\r\n\r\n/**\r\n * Inspect one endpoint.\r\n *\r\n * @param options - Target URL and request tweaks\r\n * @returns Everything observed, plus an exit code for CI use\r\n */\r\nexport async function inspectEndpoint(options: InspectOptions): Promise<InspectResult> {\r\n const method = options.method ?? \"GET\";\r\n const response = await fetch(options.url, {\r\n method,\r\n headers: {\r\n Accept: \"application/json\",\r\n \"User-Agent\": \"x402-lens/0.2\",\r\n ...options.headers,\r\n },\r\n signal: AbortSignal.timeout(options.timeoutMs ?? 15_000),\r\n // Do not follow redirects away from a 402 paywall.\r\n redirect: \"manual\",\r\n });\r\n\r\n const headerValue = response.headers.get(\"payment-required\");\r\n let paymentRequired: WirePaymentRequired | undefined;\r\n let decodedFromBody = false;\r\n let headerPresent = false;\r\n\r\n if (headerValue) {\r\n headerPresent = true;\r\n try {\r\n paymentRequired = decodePaymentRequiredHeader(headerValue) as unknown as WirePaymentRequired;\r\n } catch {\r\n // Fall through to the body, which we mirror there on purpose.\r\n }\r\n }\r\n\r\n if (!paymentRequired) {\r\n // Our middleware mirrors the challenge into the body; other servers may too.\r\n const text = await response.text().catch(() => \"\");\r\n const fromBody = extractChallengeFromBody(text);\r\n if (fromBody) {\r\n paymentRequired = fromBody;\r\n decodedFromBody = true;\r\n }\r\n }\r\n\r\n const headerRecord: Record<string, string | undefined> = {};\r\n response.headers.forEach((value, key) => {\r\n headerRecord[key.toLowerCase()] = value;\r\n });\r\n const cors = checkCors(headerRecord);\r\n\r\n const conformance = paymentRequired ? validatePaymentRequired(paymentRequired) : [];\r\n const findingsList = paymentRequired\r\n ? diagnose({ paymentRequired })\r\n : [];\r\n\r\n const lines: string[] = [];\r\n lines.push(`${method} ${options.url} → HTTP ${response.status}`);\r\n if (!paymentRequired) {\r\n lines.push(\"\");\r\n if (response.status >= 300 && response.status < 400) {\r\n const location = response.headers.get(\"location\") ?? \"(no Location header)\";\r\n lines.push(\r\n `Redirected (HTTP ${response.status}) to ${location}. inspect does not follow redirects, so a reverse proxy can hide a 402 paywall behind a 3xx.`,\r\n );\r\n lines.push(\r\n \"Point inspect at the final paywall URL, or stop the redirect for this path.\",\r\n );\r\n } else {\r\n lines.push(\r\n \"No x402 challenge found. Expected a PAYMENT-REQUIRED header (base64 PaymentRequired) on a 402 response.\",\r\n );\r\n lines.push(\r\n \"If this route is unprotected, you will see its normal response instead. If it is protected, check that paymentMiddleware is mounted before the route.\",\r\n );\r\n }\r\n } else {\r\n lines.push(\r\n headerPresent\r\n ? \"Challenge: PAYMENT-REQUIRED header\"\r\n : \"Challenge: response body (no PAYMENT-REQUIRED header)\",\r\n );\r\n lines.push(describeChallenge(paymentRequired));\r\n }\r\n\r\n if (conformance.length > 0) {\r\n lines.push(\"\");\r\n lines.push(\"Schema conformance:\");\r\n for (const issue of conformance) {\r\n lines.push(` [error] ${issue.field}: ${issue.problem}`);\r\n }\r\n }\r\n\r\n if (cors.issues.length > 0) {\r\n lines.push(\"\");\r\n lines.push(\"Browser (CORS):\");\r\n for (const issue of cors.issues) {\r\n lines.push(` [error] ${issue.field}: ${issue.problem}`);\r\n }\r\n } else if (paymentRequired) {\r\n lines.push(\"\");\r\n lines.push(\"Browser (CORS): PAYMENT-REQUIRED, PAYMENT-RESPONSE exposed; PAYMENT-SIGNATURE allowed.\");\r\n }\r\n\r\n if (findingsList.length > 0) {\r\n lines.push(\"\");\r\n lines.push(formatFindings(findingsList));\r\n }\r\n\r\n const failed =\r\n !paymentRequired || conformance.length > 0 || cors.issues.length > 0;\r\n\r\n return {\r\n status: response.status,\r\n ...(paymentRequired ? { paymentRequired } : {}),\r\n headerPresent,\r\n decodedFromBody,\r\n conformance,\r\n cors,\r\n findings: lines.join(\"\\n\"),\r\n exitCode: failed ? 1 : 0,\r\n };\r\n}\r\n\r\nfunction describeChallenge(paymentRequired: WirePaymentRequired): string {\r\n const lines = [`x402Version: ${String(paymentRequired.x402Version)}`];\r\n if (paymentRequired.resource?.url) {\r\n lines.push(`resource: ${paymentRequired.resource.url}`);\r\n }\r\n if (paymentRequired.error) {\r\n lines.push(`error: ${paymentRequired.error}`);\r\n }\r\n const accepts = paymentRequired.accepts ?? [];\r\n lines.push(`accepts: ${accepts.length}`);\r\n accepts.forEach((entry, index) => {\r\n lines.push(\r\n ` [${index}] ${entry.scheme} on ${describeNetwork(entry.network)}`,\r\n ` amount: ${entry.amount} (atomic units)`,\r\n ` asset: ${entry.asset}`,\r\n ` payTo: ${entry.payTo}`,\r\n ` timeout: ${String(entry.maxTimeoutSeconds)}s`,\r\n );\r\n });\r\n if (accepts.length > 1) {\r\n // Two entries can be the same price and still differ in what the buyer\r\n // owes, because each chain has its own token decimals. Saying so prevents\r\n // the natural but wrong assumption that the amounts should match.\r\n const amounts = new Set(accepts.map(entry => entry.amount));\r\n const assets = new Set(accepts.map(entry => entry.asset));\r\n lines.push(\r\n ` note: ${accepts.length} payment options — one per network. ${\r\n amounts.size === 1\r\n ? \"Amounts match across networks.\"\r\n : `Amounts differ by token decimals (${Array.from(amounts).join(\", \")}).`\r\n }`,\r\n );\r\n if (assets.size === 1) {\r\n lines.push(\r\n ` note: Every option uses the same asset, which is only valid if that token exists on all of them.`,\r\n );\r\n }\r\n }\r\n return lines.join(\"\\n\");\r\n}\r\n\r\n/** Pull a mirrored challenge out of a JSON body or paywall-free error body. */\r\nfunction extractChallengeFromBody(text: string): WirePaymentRequired | undefined {\r\n if (!text) return undefined;\r\n try {\r\n const parsed = JSON.parse(text) as unknown;\r\n if (\r\n parsed &&\r\n typeof parsed === \"object\" &&\r\n (parsed as { x402Version?: unknown }).x402Version === 2 &&\r\n Array.isArray((parsed as { accepts?: unknown }).accepts)\r\n ) {\r\n return parsed as WirePaymentRequired;\r\n }\r\n } catch {\r\n return undefined;\r\n }\r\n return undefined;\r\n}\r\n","/**\r\n * `x402-lens reconcile` — check whether a settlement transaction actually\r\n * landed on chain.\r\n *\r\n * `settlement_pending` is non-terminal: the facilitator broadcast a tx but\r\n * could not confirm it. Retrying opens a second payment. This command answers\r\n * the only safe next question — \"is the hash confirmed yet?\" — against a public\r\n * RPC, without needing the SDK or a wallet.\r\n */\r\n\r\nimport { describeNetwork, isCaip2, suggestCaip2 } from \"@x402-lens/core\";\r\n\r\nexport interface ReconcileOptions {\r\n /** Transaction hash (`0x…` for EVM, base58 signature for Solana). */\r\n tx: string;\r\n /** CAIP-2 network. Defaults to `eip155:84532` (Base Sepolia). */\r\n network?: string;\r\n /** Override the RPC URL. When absent, a public endpoint for the network is used. */\r\n rpcUrl?: string;\r\n /** Fetch timeout, milliseconds. */\r\n timeoutMs?: number;\r\n /** Injected fetch, for tests. */\r\n fetchImpl?: typeof fetch;\r\n}\r\n\r\nexport type ReconcileStatus = \"confirmed\" | \"failed\" | \"pending\" | \"not_found\" | \"unknown\";\r\n\r\nexport interface ReconcileResult {\r\n status: ReconcileStatus;\r\n network: string;\r\n tx: string;\r\n rpcUrl: string;\r\n /** Block number / slot when known. */\r\n block?: string;\r\n /** Raw RPC detail for operators who need more than the status. */\r\n detail: string;\r\n exitCode: number;\r\n text: string;\r\n}\r\n\r\nconst DEFAULT_RPC: Record<string, string> = {\r\n \"eip155:1\": \"https://ethereum.publicnode.com\",\r\n \"eip155:8453\": \"https://mainnet.base.org\",\r\n \"eip155:84532\": \"https://sepolia.base.org\",\r\n \"eip155:11155111\": \"https://ethereum-sepolia.publicnode.com\",\r\n \"solana:5eykt4Usfv8P8NJdTREpY1vzqKqZKvdp\": \"https://api.mainnet-beta.solana.com\",\r\n \"solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1\": \"https://api.devnet.solana.com\",\r\n};\r\n\r\n/**\r\n * Ask the chain whether a settlement transaction is confirmed.\r\n *\r\n * @param options - Hash, network, and optional RPC override\r\n * @returns Status, a rendered report, and an exit code (0 = confirmed)\r\n */\r\nexport async function reconcileTransaction(\r\n options: ReconcileOptions,\r\n): Promise<ReconcileResult> {\r\n const tx = options.tx.trim();\r\n if (!tx) {\r\n return report({\r\n status: \"unknown\",\r\n network: options.network ?? \"\",\r\n tx: \"\",\r\n rpcUrl: \"\",\r\n detail: \"No transaction hash was provided.\",\r\n exitCode: 2,\r\n });\r\n }\r\n\r\n const network = options.network ?? \"eip155:84532\";\r\n if (!isCaip2(network)) {\r\n const suggestion = suggestCaip2(network);\r\n return report({\r\n status: \"unknown\",\r\n network,\r\n tx,\r\n rpcUrl: \"\",\r\n detail: suggestion\r\n ? `\"${network}\" is not CAIP-2. Use \"${suggestion}\".`\r\n : `\"${network}\" is not a CAIP-2 network id.`,\r\n exitCode: 2,\r\n });\r\n }\r\n\r\n const rpcUrl = options.rpcUrl ?? DEFAULT_RPC[network];\r\n if (!rpcUrl) {\r\n return report({\r\n status: \"unknown\",\r\n network,\r\n tx,\r\n rpcUrl: \"\",\r\n detail: `No default RPC for ${describeNetwork(network)}. Pass --rpc <url>.`,\r\n exitCode: 2,\r\n });\r\n }\r\n\r\n const fetchImpl = options.fetchImpl ?? fetch;\r\n const timeoutMs = options.timeoutMs ?? 15_000;\r\n const namespace = network.slice(0, network.indexOf(\":\"));\r\n\r\n try {\r\n if (namespace === \"eip155\") {\r\n return await reconcileEvm({ tx, network, rpcUrl, fetchImpl, timeoutMs });\r\n }\r\n if (namespace === \"solana\") {\r\n return await reconcileSolana({ tx, network, rpcUrl, fetchImpl, timeoutMs });\r\n }\r\n return report({\r\n status: \"unknown\",\r\n network,\r\n tx,\r\n rpcUrl,\r\n detail: `Namespace \"${namespace}\" is not supported by reconcile. Use eip155:* or solana:*.`,\r\n exitCode: 2,\r\n });\r\n } catch (error) {\r\n return report({\r\n status: \"unknown\",\r\n network,\r\n tx,\r\n rpcUrl,\r\n detail: `RPC call failed: ${(error as Error).message}`,\r\n exitCode: 1,\r\n });\r\n }\r\n}\r\n\r\nasync function reconcileEvm(input: {\r\n tx: string;\r\n network: string;\r\n rpcUrl: string;\r\n fetchImpl: typeof fetch;\r\n timeoutMs: number;\r\n}): Promise<ReconcileResult> {\r\n const receipt = (await rpc(input, \"eth_getTransactionReceipt\", [input.tx])) as\r\n | { status?: string; blockNumber?: string }\r\n | null;\r\n\r\n if (receipt === null) {\r\n const pending = (await rpc(input, \"eth_getTransactionByHash\", [input.tx])) as\r\n | { hash?: string }\r\n | null;\r\n if (pending && pending.hash) {\r\n return report({\r\n status: \"pending\",\r\n network: input.network,\r\n tx: input.tx,\r\n rpcUrl: input.rpcUrl,\r\n detail: \"Transaction is in the mempool or not yet mined. Do not retry the payment.\",\r\n exitCode: 1,\r\n });\r\n }\r\n return report({\r\n status: \"not_found\",\r\n network: input.network,\r\n tx: input.tx,\r\n rpcUrl: input.rpcUrl,\r\n detail: \"No transaction with this hash on this network. The settle may never have broadcast.\",\r\n exitCode: 1,\r\n });\r\n }\r\n\r\n const statusHex = receipt.status ?? \"0x0\";\r\n const confirmed = statusHex === \"0x1\" || statusHex === \"1\";\r\n const block = receipt.blockNumber\r\n ? String(Number.parseInt(receipt.blockNumber, 16))\r\n : undefined;\r\n\r\n if (confirmed) {\r\n return report({\r\n status: \"confirmed\",\r\n network: input.network,\r\n tx: input.tx,\r\n rpcUrl: input.rpcUrl,\r\n ...(block ? { block } : {}),\r\n detail: `Receipt status success${block ? ` in block ${block}` : \"\"}. Settlement landed; do not charge the buyer again.`,\r\n exitCode: 0,\r\n });\r\n }\r\n\r\n return report({\r\n status: \"failed\",\r\n network: input.network,\r\n tx: input.tx,\r\n rpcUrl: input.rpcUrl,\r\n ...(block ? { block } : {}),\r\n detail: `Receipt status failed${block ? ` in block ${block}` : \"\"}. Funds did not move; a fresh payment is safe after investigation.`,\r\n exitCode: 1,\r\n });\r\n}\r\n\r\nasync function reconcileSolana(input: {\r\n tx: string;\r\n network: string;\r\n rpcUrl: string;\r\n fetchImpl: typeof fetch;\r\n timeoutMs: number;\r\n}): Promise<ReconcileResult> {\r\n const value = (await rpc(input, \"getTransaction\", [\r\n input.tx,\r\n { encoding: \"json\", maxSupportedTransactionVersion: 0 },\r\n ])) as { meta?: { err?: unknown }; slot?: number } | null;\r\n\r\n if (value === null) {\r\n return report({\r\n status: \"not_found\",\r\n network: input.network,\r\n tx: input.tx,\r\n rpcUrl: input.rpcUrl,\r\n detail: \"Signature not found on this cluster. It may still be propagating, or it never landed.\",\r\n exitCode: 1,\r\n });\r\n }\r\n\r\n const err = value.meta?.err;\r\n const slot = value.slot !== undefined ? String(value.slot) : undefined;\r\n if (err == null) {\r\n return report({\r\n status: \"confirmed\",\r\n network: input.network,\r\n tx: input.tx,\r\n rpcUrl: input.rpcUrl,\r\n ...(slot ? { block: slot } : {}),\r\n detail: `Transaction confirmed${slot ? ` at slot ${slot}` : \"\"}. Settlement landed; do not charge the buyer again.`,\r\n exitCode: 0,\r\n });\r\n }\r\n\r\n return report({\r\n status: \"failed\",\r\n network: input.network,\r\n tx: input.tx,\r\n rpcUrl: input.rpcUrl,\r\n ...(slot ? { block: slot } : {}),\r\n detail: `Transaction failed on chain${slot ? ` at slot ${slot}` : \"\"}: ${JSON.stringify(err)}.`,\r\n exitCode: 1,\r\n });\r\n}\r\n\r\nasync function rpc(\r\n input: { rpcUrl: string; fetchImpl: typeof fetch; timeoutMs: number },\r\n method: string,\r\n params: unknown[],\r\n): Promise<unknown> {\r\n const controller = new AbortController();\r\n const timer = setTimeout(() => controller.abort(), input.timeoutMs);\r\n try {\r\n const response = await input.fetchImpl(input.rpcUrl, {\r\n method: \"POST\",\r\n headers: { \"content-type\": \"application/json\" },\r\n body: JSON.stringify({ jsonrpc: \"2.0\", id: 1, method, params }),\r\n signal: controller.signal,\r\n });\r\n if (!response.ok) {\r\n throw new Error(`HTTP ${response.status}`);\r\n }\r\n const body = (await response.json()) as { result?: unknown; error?: { message?: string } };\r\n if (body.error) {\r\n throw new Error(body.error.message ?? \"RPC error\");\r\n }\r\n return body.result;\r\n } finally {\r\n clearTimeout(timer);\r\n }\r\n}\r\n\r\nfunction report(\r\n result: Omit<ReconcileResult, \"text\"> & { text?: string },\r\n): ReconcileResult {\r\n const lines = [\r\n `tx: ${result.tx || \"(none)\"}`,\r\n `network: ${result.network ? describeNetwork(result.network) : \"(none)\"}`,\r\n `rpc: ${result.rpcUrl || \"(none)\"}`,\r\n `status: ${result.status}`,\r\n ...(result.block ? [`block: ${result.block}`] : []),\r\n \"\",\r\n result.detail,\r\n ];\r\n return { ...result, text: lines.join(\"\\n\") };\r\n}\r\n","/**\r\n * Minimal argv parsing.\r\n *\r\n * The CLI has five commands and a handful of flags; a dependency would be more\r\n * code to audit than the parser itself.\r\n */\r\n\r\nexport interface ParsedArgs {\r\n command: string | undefined;\r\n positionals: string[];\r\n flags: Record<string, string | true>;\r\n}\r\n\r\n/**\r\n * Split argv into a command, positionals, and flags.\r\n *\r\n * Supports `--key value`, `--key=value`, and boolean `--flag`. A `--flag` that\r\n * is followed by another flag or by nothing is treated as boolean.\r\n *\r\n * @param argv - Arguments after the executable and script path\r\n * @returns Parsed structure\r\n */\r\nexport function parseArgs(argv: string[]): ParsedArgs {\r\n const flags: Record<string, string | true> = {};\r\n const positionals: string[] = [];\r\n let command: string | undefined;\r\n\r\n for (let index = 0; index < argv.length; index += 1) {\r\n const token = argv[index];\r\n if (token === undefined) continue;\r\n\r\n if (token.startsWith(\"--\")) {\r\n const withoutDashes = token.slice(2);\r\n if (withoutDashes.length === 0) continue;\r\n\r\n const equalsIndex = withoutDashes.indexOf(\"=\");\r\n if (equalsIndex !== -1) {\r\n flags[withoutDashes.slice(0, equalsIndex)] = withoutDashes.slice(equalsIndex + 1);\r\n continue;\r\n }\r\n\r\n const next = argv[index + 1];\r\n if (next !== undefined && !next.startsWith(\"--\")) {\r\n flags[withoutDashes] = next;\r\n index += 1;\r\n } else {\r\n flags[withoutDashes] = true;\r\n }\r\n continue;\r\n }\r\n\r\n if (token.startsWith(\"-\") && token.length > 1) {\r\n // Short aliases: -h, -v.\r\n flags[token.slice(1)] = true;\r\n continue;\r\n }\r\n\r\n if (command === undefined) {\r\n command = token;\r\n continue;\r\n }\r\n positionals.push(token);\r\n }\r\n\r\n return { command, positionals, flags };\r\n}\r\n\r\n/** Read a flag as a string, or `undefined` when absent or boolean. */\r\nexport function flagValue(args: ParsedArgs, name: string): string | undefined {\r\n const value = args.flags[name];\r\n return typeof value === \"string\" ? value : undefined;\r\n}\r\n\r\n/** Read a flag as a boolean. Any presence counts, including `--flag=false`. */\r\nexport function flagEnabled(args: ParsedArgs, name: string): boolean {\r\n return args.flags[name] !== undefined;\r\n}\r\n","/**\r\n * `x402-lens` command line entry point.\r\n *\r\n * Every command exits non-zero when something is wrong, so CI can gate on it.\r\n */\r\n\r\nimport { AddError, addProtection } from \"./commands/add.js\";\r\nimport { explainPayment } from \"./commands/explain.js\";\r\nimport { runDoctor } from \"./commands/doctor.js\";\r\nimport { inspectEndpoint } from \"./commands/inspect.js\";\r\nimport { reconcileTransaction } from \"./commands/reconcile.js\";\r\nimport { flagEnabled, flagValue, parseArgs } from \"./args.js\";\r\nimport { InputError } from \"./input.js\";\r\n\r\nconst USAGE = `x402-lens — explain and verify x402 v2 payments\r\n\r\nUsage:\r\n x402-lens inspect <url> [--method GET] [--header \"K: V\"] [--timeout 15000] [--json]\r\n Fetch an endpoint unpaid, decode PAYMENT-REQUIRED, and report schema\r\n conformance and CORS readiness for browser buyers.\r\n\r\n x402-lens explain [--challenge <b64|json|@file>] [--payment <...>]\r\n [--verify <...>] [--settle <...>] [--json]\r\n Diagnose a failed exchange: what is wrong, and what to change.\r\n\r\n x402-lens doctor [--facilitator <url>] [--network <caip2>] [--networks <a,b>] [--json]\r\n Verify that configuration can actually accept payments, including that\r\n the facilitator supports every configured network with x402Version 2.\r\n\r\n x402-lens reconcile --tx <hash> [--network <caip2>] [--rpc <url>] [--json]\r\n Check whether a settlement transaction confirmed on chain. Use this\r\n after settlement_pending — never retry a payment until you know.\r\n\r\n x402-lens add \"<METHOD> <path>\" --file <path> --price <amount> [--write]\r\n Add x402 protection to an existing Express route. Prints a diff unless\r\n --write is passed.\r\n\r\nOptions:\r\n --json Machine-readable JSON on stdout (inspect / explain / doctor / reconcile)\r\n --help, -h Show this help.\r\n\r\nExit codes:\r\n 0 success\r\n 1 a check failed or a finding is an error\r\n 2 bad usage\r\n`;\r\n\r\n/**\r\n * Run the CLI.\r\n *\r\n * @param argv - Arguments after the script path\r\n * @returns Process exit code\r\n */\r\nexport async function main(argv: string[]): Promise<number> {\r\n const args = parseArgs(argv);\r\n const asJson = flagEnabled(args, \"json\");\r\n\r\n if (flagEnabled(args, \"help\") || flagEnabled(args, \"h\") || args.command === undefined) {\r\n process.stdout.write(USAGE);\r\n return args.command === undefined && !flagEnabled(args, \"help\") && !flagEnabled(args, \"h\")\r\n ? 2\r\n : 0;\r\n }\r\n\r\n try {\r\n switch (args.command) {\r\n case \"inspect\": {\r\n const url = args.positionals[0];\r\n if (!url) {\r\n process.stderr.write(\"inspect requires a URL.\\n\\n\" + USAGE);\r\n return 2;\r\n }\r\n const result = await inspectEndpoint({\r\n url,\r\n ...(flagValue(args, \"method\") ? { method: flagValue(args, \"method\") as string } : {}),\r\n ...(flagValue(args, \"header\")\r\n ? { headers: parseHeaderFlags(argv) }\r\n : {}),\r\n ...(flagValue(args, \"timeout\")\r\n ? { timeoutMs: Number.parseInt(flagValue(args, \"timeout\") as string, 10) }\r\n : {}),\r\n });\r\n if (asJson) {\r\n process.stdout.write(\r\n `${JSON.stringify(\r\n {\r\n status: result.status,\r\n headerPresent: result.headerPresent,\r\n decodedFromBody: result.decodedFromBody,\r\n paymentRequired: result.paymentRequired ?? null,\r\n conformance: result.conformance,\r\n cors: result.cors,\r\n exitCode: result.exitCode,\r\n },\r\n null,\r\n 2,\r\n )}\\n`,\r\n );\r\n } else {\r\n process.stdout.write(`${result.findings}\\n`);\r\n }\r\n return result.exitCode;\r\n }\r\n\r\n case \"explain\": {\r\n const result = await explainPayment({\r\n ...(flagValue(args, \"challenge\") ? { challenge: flagValue(args, \"challenge\") as string } : {}),\r\n ...(flagValue(args, \"payment\") ? { payment: flagValue(args, \"payment\") as string } : {}),\r\n ...(flagValue(args, \"verify\") ? { verify: flagValue(args, \"verify\") as string } : {}),\r\n ...(flagValue(args, \"settle\") ? { settle: flagValue(args, \"settle\") as string } : {}),\r\n });\r\n if (asJson) {\r\n process.stdout.write(\r\n `${JSON.stringify(\r\n {\r\n findings: result.findings,\r\n findingCount: result.findingCount,\r\n exitCode: result.exitCode,\r\n },\r\n null,\r\n 2,\r\n )}\\n`,\r\n );\r\n } else {\r\n process.stdout.write(`${result.text}\\n`);\r\n }\r\n return result.exitCode;\r\n }\r\n\r\n case \"doctor\": {\r\n const networksFlag = flagValue(args, \"networks\");\r\n const result = await runDoctor({\r\n ...(flagValue(args, \"facilitator\")\r\n ? { facilitatorUrl: flagValue(args, \"facilitator\") as string }\r\n : {}),\r\n ...(flagValue(args, \"network\") ? { network: flagValue(args, \"network\") as string } : {}),\r\n ...(networksFlag\r\n ? {\r\n networks: networksFlag\r\n .split(\",\")\r\n .map(part => part.trim())\r\n .filter(Boolean),\r\n }\r\n : {}),\r\n });\r\n if (asJson) {\r\n process.stdout.write(\r\n `${JSON.stringify(\r\n {\r\n checks: result.checks,\r\n exitCode: result.exitCode,\r\n },\r\n null,\r\n 2,\r\n )}\\n`,\r\n );\r\n } else {\r\n process.stdout.write(`${result.text}\\n`);\r\n }\r\n return result.exitCode;\r\n }\r\n\r\n case \"add\": {\r\n const route = args.positionals[0];\r\n const file = flagValue(args, \"file\");\r\n const price = flagValue(args, \"price\");\r\n if (!route || !file || !price) {\r\n process.stderr.write(\r\n 'add requires a route, --file, and --price. Example:\\n x402-lens add \"GET /weather\" --file src/server.ts --price 0.001\\n',\r\n );\r\n return 2;\r\n }\r\n const result = await addProtection({\r\n file,\r\n route,\r\n price,\r\n write: flagEnabled(args, \"write\"),\r\n });\r\n process.stdout.write(`${result.text}\\n`);\r\n return result.exitCode;\r\n }\r\n\r\n case \"reconcile\": {\r\n const tx = flagValue(args, \"tx\") ?? args.positionals[0];\r\n if (!tx) {\r\n process.stderr.write(\r\n \"reconcile requires --tx <hash>. Example:\\n x402-lens reconcile --tx 0xabc… --network eip155:84532\\n\",\r\n );\r\n return 2;\r\n }\r\n const result = await reconcileTransaction({\r\n tx,\r\n ...(flagValue(args, \"network\")\r\n ? { network: flagValue(args, \"network\") as string }\r\n : {}),\r\n ...(flagValue(args, \"rpc\") ? { rpcUrl: flagValue(args, \"rpc\") as string } : {}),\r\n ...(flagValue(args, \"timeout\")\r\n ? { timeoutMs: Number.parseInt(flagValue(args, \"timeout\") as string, 10) }\r\n : {}),\r\n });\r\n if (asJson) {\r\n process.stdout.write(\r\n `${JSON.stringify(\r\n {\r\n status: result.status,\r\n network: result.network,\r\n tx: result.tx,\r\n rpcUrl: result.rpcUrl,\r\n block: result.block ?? null,\r\n detail: result.detail,\r\n exitCode: result.exitCode,\r\n },\r\n null,\r\n 2,\r\n )}\\n`,\r\n );\r\n } else {\r\n process.stdout.write(`${result.text}\\n`);\r\n }\r\n return result.exitCode;\r\n }\r\n\r\n default:\r\n process.stderr.write(`Unknown command \"${args.command}\".\\n\\n${USAGE}`);\r\n return 2;\r\n }\r\n } catch (error) {\r\n if (error instanceof InputError || error instanceof AddError) {\r\n process.stderr.write(`${error.message}\\n`);\r\n return 2;\r\n }\r\n process.stderr.write(`${(error as Error).message}\\n`);\r\n return 1;\r\n }\r\n}\r\n\r\n/**\r\n * `--header` may repeat; `parseArgs` only keeps the last. Re-scan argv for all\r\n * occurrences so `inspect` can send several headers.\r\n */\r\nfunction parseHeaderFlags(argv: string[]): Record<string, string> {\r\n const headers: Record<string, string> = {};\r\n for (let index = 0; index < argv.length; index += 1) {\r\n if (argv[index] !== \"--header\") continue;\r\n const value = argv[index + 1];\r\n if (!value) continue;\r\n const separator = value.indexOf(\":\");\r\n if (separator === -1) continue;\r\n headers[value.slice(0, separator).trim()] = value.slice(separator + 1).trim();\r\n index += 1;\r\n }\r\n return headers;\r\n}\r\n\r\nconst isDirectRun =\r\n process.argv[1] !== undefined &&\r\n (process.argv[1].endsWith(\"x402-lens\") || process.argv[1].endsWith(\"index.js\"));\r\n\r\nif (isDirectRun) {\r\n main(process.argv.slice(2))\r\n .then(code => {\r\n process.exitCode = code;\r\n })\r\n .catch(error => {\r\n process.stderr.write(`Unexpected error: ${(error as Error).message}\\n`);\r\n process.exitCode = 1;\r\n });\r\n}\r\n"],"mappings":";;;AAUA,SAAS,UAAU,iBAAiB;AACpC,SAAS,gBAAgB;AAElB,IAAM,WAAN,cAAuB,MAAM;AAAA,EAClC,YAAY,SAAiB;AAC3B,UAAM,OAAO;AACb,SAAK,OAAO;AAAA,EACd;AACF;AAkBA,IAAM,cAAc;AACpB,IAAM,mBAAmB;AACzB,IAAM,aAAa;AAWnB,eAAsB,cAAc,SAAyC;AAC3E,QAAM,EAAE,MAAM,MAAM,IAAI;AACxB,QAAM,QAAQ,eAAe,QAAQ,KAAK;AAE1C,MAAI,SAAS,IAAI,EAAE,MAAM,oBAAoB,MAAM,MAAM;AACvD,UAAM,IAAI;AAAA,MACR,GAAG,IAAI;AAAA,IACT;AAAA,EACF;AAEA,QAAM,WAAW,MAAM,SAAS,MAAM,MAAM;AAC5C,QAAM,SAAS,WAAW,KAAK;AAE/B,QAAM,UAAU,SAAS,SAAS,cAAc;AAChD,QAAM,gBAAgB,iBAAiB,UAAU,MAAM;AAEvD,MAAI,WAAW,eAAe;AAC5B,WAAO;AAAA,MACL,SAAS;AAAA,MACT,MAAM;AAAA,MACN,MAAM,GAAG,IAAI,wBAAwB,OAAO,MAAM,IAAI,OAAO,IAAI;AAAA,MACjE,UAAU;AAAA,IACZ;AAAA,EACF;AAEA,QAAM,YAAY,gBAAgB,QAAQ;AAC1C,MAAI,cAAc,WAAW;AAC3B,UAAM,IAAI;AAAA,MACR,GAAG,IAAI,uCAAuC,SAAS;AAAA,IACzD;AAAA,EACF;AAEA,QAAM,eAAe,qBAAqB,UAAU,MAAM;AAC1D,MAAI,CAAC,cAAc;AACjB,UAAM,IAAI;AAAA,MACR,0CAA0C,gBAAgB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B,MAAgB,OAAO;AAAA,CAAI;AACtE,YAAQ,WAAW;AAAA,EACrB,CAAC;AACL;","names":["i","j","readFile","describeNetwork","diagnose","formatFindings","describeNetwork","isCaip2","suggestCaip2"]}
|
package/package.json
CHANGED
|
@@ -1,41 +1,41 @@
|
|
|
1
|
-
{
|
|
2
|
-
"name": "@x402-lens/cli",
|
|
3
|
-
"version": "0.2.
|
|
4
|
-
"description": "CLI for x402-lens: inspect x402 v2 endpoints, explain failed payments, audit facilitator config",
|
|
5
|
-
"license": "MIT",
|
|
6
|
-
"repository": {
|
|
7
|
-
"type": "git",
|
|
8
|
-
"url": "git+https://github.com/Rozenberg888/x402-lens.git",
|
|
9
|
-
"directory": "packages/cli"
|
|
10
|
-
},
|
|
11
|
-
"homepage": "https://github.com/Rozenberg888/x402-lens#readme",
|
|
12
|
-
"bugs": {
|
|
13
|
-
"url": "https://github.com/Rozenberg888/x402-lens/issues"
|
|
14
|
-
},
|
|
15
|
-
"type": "module",
|
|
16
|
-
"bin": {
|
|
17
|
-
"x402-lens": "dist/index.js"
|
|
18
|
-
},
|
|
19
|
-
"files": [
|
|
20
|
-
"dist",
|
|
21
|
-
"README.md"
|
|
22
|
-
],
|
|
23
|
-
"engines": {
|
|
24
|
-
"node": ">=20.11"
|
|
25
|
-
},
|
|
26
|
-
"scripts": {
|
|
27
|
-
"build": "tsup",
|
|
28
|
-
"typecheck": "tsc --noEmit -p tsconfig.json",
|
|
29
|
-
"prepublishOnly": "node ../../scripts/check-workspace-versions.mjs && npm --prefix ../.. run typecheck && npm run build && npm --prefix ../.. test"
|
|
30
|
-
},
|
|
31
|
-
"dependencies": {
|
|
32
|
-
"@x402-lens/core": "0.2.
|
|
33
|
-
"@x402/core": "^2.31.0"
|
|
34
|
-
},
|
|
35
|
-
"keywords": [
|
|
36
|
-
"x402",
|
|
37
|
-
"cli",
|
|
38
|
-
"debugging",
|
|
39
|
-
"payments"
|
|
40
|
-
]
|
|
41
|
-
}
|
|
1
|
+
{
|
|
2
|
+
"name": "@x402-lens/cli",
|
|
3
|
+
"version": "0.2.4",
|
|
4
|
+
"description": "CLI for x402-lens: inspect x402 v2 endpoints, explain failed payments, audit facilitator config",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"repository": {
|
|
7
|
+
"type": "git",
|
|
8
|
+
"url": "git+https://github.com/Rozenberg888/x402-lens.git",
|
|
9
|
+
"directory": "packages/cli"
|
|
10
|
+
},
|
|
11
|
+
"homepage": "https://github.com/Rozenberg888/x402-lens#readme",
|
|
12
|
+
"bugs": {
|
|
13
|
+
"url": "https://github.com/Rozenberg888/x402-lens/issues"
|
|
14
|
+
},
|
|
15
|
+
"type": "module",
|
|
16
|
+
"bin": {
|
|
17
|
+
"x402-lens": "dist/index.js"
|
|
18
|
+
},
|
|
19
|
+
"files": [
|
|
20
|
+
"dist",
|
|
21
|
+
"README.md"
|
|
22
|
+
],
|
|
23
|
+
"engines": {
|
|
24
|
+
"node": ">=20.11"
|
|
25
|
+
},
|
|
26
|
+
"scripts": {
|
|
27
|
+
"build": "tsup",
|
|
28
|
+
"typecheck": "tsc --noEmit -p tsconfig.json",
|
|
29
|
+
"prepublishOnly": "node ../../scripts/check-workspace-versions.mjs && npm --prefix ../.. run typecheck && npm run build && npm --prefix ../.. test"
|
|
30
|
+
},
|
|
31
|
+
"dependencies": {
|
|
32
|
+
"@x402-lens/core": "0.2.4",
|
|
33
|
+
"@x402/core": "^2.31.0"
|
|
34
|
+
},
|
|
35
|
+
"keywords": [
|
|
36
|
+
"x402",
|
|
37
|
+
"cli",
|
|
38
|
+
"debugging",
|
|
39
|
+
"payments"
|
|
40
|
+
]
|
|
41
|
+
}
|