@minia2a/x402-check 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (4) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +66 -2
  3. package/cli.js +264 -0
  4. package/package.json +30 -4
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 minia2a
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,67 @@
1
- # Temporary Holding Version
1
+ # x402-check
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Inspect a live x402 endpoint **before you pay it**.
4
+
5
+ A 402 can be structurally valid and still mislead the buyer. This tool sends one
6
+ unpaid request (two when the static-offer check runs), reads the challenge the
7
+ endpoint actually serves, and reports the defects that cost money or clients:
8
+
9
+ - the body and the `PAYMENT-REQUIRED` header carry different `accepts[]`
10
+ - an EIP-712 `exact` offer with no `extra.name` / `extra.version` (unbuildable domain)
11
+ - a float or otherwise non-integer `amount` (cannot be signed losslessly)
12
+ - a non-CAIP-2 `network`, or a `payTo` / `asset` that is not a 20-byte address
13
+ - `x402Version: 2` with `resource` as a string instead of an object
14
+ - a discoverable listing whose advertised `input.example` is empty, or violates
15
+ its own `input.schema.required`
16
+ - `output.example` advertised with no `answerBasis` (nothing says it is the
17
+ response to `input.example`)
18
+ - a price above the reference client's **$1 per-call default spend cap** that the
19
+ 402 does not disclose — that client will refuse the payment
20
+ - the same cached offer on two reads with no nonce/expiry (a document, not a quote)
21
+
22
+ It does **not** test whether the endpoint enforces payment (accepts a forged
23
+ txHash, replays a receipt, etc.). That needs a signed payment and is a different
24
+ check — black-box payment-enforcement auditing is a paid service, not something
25
+ this CLI can do safely.
26
+
27
+ Nothing is signed and nothing is paid. Only run it against endpoints you are
28
+ allowed to call.
29
+
30
+ ## Usage
31
+
32
+ ```bash
33
+ npx x402-check https://minia2a.uk/x402/x402-format-bytes
34
+ npx x402-check https://example.com/paid/api --json
35
+ npx x402-check "$URL" --max-price 0.05 --header "authorization: Bearer $TOKEN"
36
+ ```
37
+
38
+ ```
39
+ x402-check 0.1.0 https://minia2a.uk/x402/x402-format-bytes
40
+ status 402 verdict PASS (0 fail, 0 warn, 2 info)
41
+ INFO static-offer two requests 1.2s apart return an identical offer ...
42
+ INFO unpaired-examples output.example is advertised without answerBasis ...
43
+ ```
44
+
45
+ Flags:
46
+
47
+ | flag | meaning |
48
+ | --- | --- |
49
+ | `--json` | machine-readable report (`verdict`, `findings[]`) |
50
+ | `--timeout <s>` | per-request timeout, default 20 |
51
+ | `--max-price <usd>` | FAIL when the cheapest offer is above this, default 1.00 |
52
+ | `--header "k: v"` | extra request header, repeatable |
53
+ | `--no-static` | skip the second read |
54
+
55
+ Exit codes: `0` no failures, `1` at least one FAIL, `2` usage or network error.
56
+
57
+ ## Scope
58
+
59
+ - Reads `PAYMENT-REQUIRED` (base64 JSON) and, when present, the 402 body. A body
60
+ document is accepted when the header is absent, but a *discoverable* listing
61
+ without the header is flagged: at least one indexer reads only the header.
62
+ - USD conversion assumes 6-decimal USDC on `eip155:*`. Anything else is reported
63
+ as unmeasured rather than converted.
64
+ - Discovery checks read the `bazaar` extension shape; other extensions are
65
+ reported only when they break the base challenge.
66
+
67
+ MIT.
package/cli.js ADDED
@@ -0,0 +1,264 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * x402-check — inspect a live x402 endpoint before you pay it.
4
+ *
5
+ * Why: a 402 can be structurally valid and still mislead a buyer — the body can
6
+ * disagree with PAYMENT-REQUIRED, an offer can be an EIP-712 domain that cannot
7
+ * sign, the advertised example can be from a different call than the output
8
+ * example, and an over-$1 price can silently trip the reference client's default
9
+ * spend cap. This tool measures the response, it does not guess.
10
+ *
11
+ * It sends ONE unpaid request (two with --static-check). Nothing is signed and
12
+ * nothing is paid. Only run it against endpoints you are allowed to call.
13
+ *
14
+ * usage: x402-check <url> [--json] [--timeout 20] [--max-price 1.00]
15
+ * [--header "k: v"]... [--no-static]
16
+ *
17
+ * exit: 0 no failures (warnings may exist) · 1 at least one FAIL · 2 usage/network
18
+ */
19
+ 'use strict';
20
+
21
+ const VERSION = require('./package.json').version;
22
+
23
+ const V2_NETWORK_RE = /^[a-z0-9-]+:[A-Za-z0-9-]+$/;
24
+ const HEX40_RE = /^0x[0-9a-fA-F]{40}$/;
25
+
26
+ function parseArgs(argv) {
27
+ const out = { url: null, json: false, timeout: 20, maxPrice: 1, headers: [], staticCheck: true };
28
+ for (let i = 0; i < argv.length; i++) {
29
+ const a = argv[i];
30
+ if (a === '--json') out.json = true;
31
+ else if (a === '--timeout') out.timeout = Number(argv[++i]);
32
+ else if (a === '--max-price') out.maxPrice = Number(argv[++i]);
33
+ else if (a === '--header') out.headers.push(argv[++i]);
34
+ else if (a === '--no-static') out.staticCheck = false;
35
+ else if (a === '-h' || a === '--help') out.help = true;
36
+ else if (a === '-v' || a === '--version') out.version = true;
37
+ else if (!a.startsWith('-')) out.url = a;
38
+ else throw new Error(`unknown flag ${a}`);
39
+ }
40
+ return out;
41
+ }
42
+
43
+ function decodePaymentRequired(res) {
44
+ const h = res.headers.get('payment-required') || res.headers.get('x-payment-required');
45
+ let fromHeader = null, headerError = null;
46
+ if (h) {
47
+ try { fromHeader = JSON.parse(Buffer.from(h.trim(), 'base64').toString('utf8')); }
48
+ catch (e) { headerError = e.message; }
49
+ }
50
+ return { raw: h, fromHeader, headerError };
51
+ }
52
+
53
+ async function fetchOne(url, headers, timeoutMs) {
54
+ const ctrl = new AbortController();
55
+ const t = setTimeout(() => ctrl.abort(), timeoutMs);
56
+ try {
57
+ const res = await fetch(url, { signal: ctrl.signal, redirect: 'manual', headers });
58
+ const text = await res.text();
59
+ return { res, text };
60
+ } finally { clearTimeout(t); }
61
+ }
62
+
63
+ // USD conversion is honest only for a 6-decimal stablecoin we can name. An
64
+ // arbitrary eip155 token may have 18 decimals, so converting it by network alone
65
+ // would inflate the price by 1e12 — report unmeasured instead.
66
+ const SIX_DEC_USD = {
67
+ 'eip155:8453|0x833589fcd6edb6e08f4c7c32d4f71b54bda02913': true, // USDC on Base
68
+ 'eip155:84532|0x036cbd53842c5426634e7929541ec2318f3dcf7e': true, // USDC on Base Sepolia
69
+ 'eip155:1|0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48': true, // USDC on Ethereum
70
+ 'eip155:137|0x3c499c542cef5e3811e1192ce70d8cc03d5c3359': true, // USDC on Polygon
71
+ 'eip155:42161|0xaf88d065e77c8cc2239327c5edb3a432268e5831': true, // USDC on Arbitrum
72
+ };
73
+ function offerAmountToUsd(amount, network, asset) {
74
+ if (!/^\d+$/.test(String(amount))) return null;
75
+ const key = `${String(network || '').toLowerCase()}|${String(asset || '').toLowerCase()}`;
76
+ if (!SIX_DEC_USD[key]) return null;
77
+ return Number(amount) / 1e6;
78
+ }
79
+
80
+ function checkChallenge(doc, headerInfo, bodyDoc) {
81
+ const findings = [];
82
+ const add = (level, code, msg) => findings.push({ level, code, msg });
83
+
84
+ if (!doc || typeof doc !== 'object') { add('FAIL', 'no-challenge', 'no JSON 402 challenge could be built'); return findings; }
85
+ const ver = doc.x402Version;
86
+ if (ver !== 1 && ver !== 2) add('FAIL', 'version', `x402Version is ${JSON.stringify(ver)}; expected 1 or 2`);
87
+ if (!Array.isArray(doc.accepts) || doc.accepts.length === 0) {
88
+ add('FAIL', 'accepts', 'accepts[] is missing or empty: the 402 names no way to pay');
89
+ return findings;
90
+ }
91
+
92
+ const seen = new Set();
93
+ doc.accepts.forEach((o, i) => {
94
+ const at = `accepts[${i}]`;
95
+ if (!o || typeof o !== 'object') { add('FAIL', 'offer-shape', `${at} is not an object`); return; }
96
+ for (const k of ['scheme', 'network', 'asset', 'amount', 'payTo', 'maxTimeoutSeconds']) {
97
+ if (o[k] === undefined || o[k] === null || o[k] === '') add('FAIL', 'offer-field', `${at}.${k} is missing`);
98
+ }
99
+ if (o.network && !V2_NETWORK_RE.test(String(o.network))) add('FAIL', 'network', `${at}.network ${JSON.stringify(o.network)} is not CAIP-2`);
100
+ if (o.payTo && String(o.network || '').startsWith('eip155:') && !HEX40_RE.test(String(o.payTo))) add('FAIL', 'payTo', `${at}.payTo ${JSON.stringify(o.payTo)} is not a 20-byte hex address`);
101
+ if (o.asset && String(o.network || '').startsWith('eip155:') && !HEX40_RE.test(String(o.asset))) add('FAIL', 'asset', `${at}.asset ${JSON.stringify(o.asset)} is not a 20-byte hex address`);
102
+ if (o.amount !== undefined && !/^\d+$/.test(String(o.amount))) add('FAIL', 'amount', `${at}.amount ${JSON.stringify(o.amount)} is not an integer string (floats cannot be signed losslessly)`);
103
+ if (String(o.network || '').startsWith('eip155:') && o.scheme === 'exact') {
104
+ const ex = o.extra || {};
105
+ if (!ex.name || !ex.version) add('FAIL', 'eip712-domain', `${at} is EIP-712 exact but extra.name/extra.version are missing: a client cannot build the signing domain`);
106
+ }
107
+ if (o.maxTimeoutSeconds !== undefined && !(Number(o.maxTimeoutSeconds) > 0)) add('FAIL', 'timeout', `${at}.maxTimeoutSeconds must be > 0`);
108
+ const key = `${o.scheme}|${o.network}|${o.asset}|${o.amount}|${o.payTo}`;
109
+ if (seen.has(key)) add('WARN', 'duplicate-offer', `${at} duplicates ${key}`);
110
+ seen.add(key);
111
+ });
112
+
113
+ if (ver === 2 && doc.resource !== undefined && (doc.resource === null || typeof doc.resource !== 'object' || Array.isArray(doc.resource))) {
114
+ add('FAIL', 'resource-shape', 'x402Version 2 resource must be an object with at least {url}');
115
+ }
116
+ if (ver === 2 && doc.resource && typeof doc.resource === 'object' && !doc.resource.url) {
117
+ add('WARN', 'resource-url', 'x402Version 2 resource has no url');
118
+ }
119
+
120
+ // body/header parity: if both doors carry a document, they must say the same thing.
121
+ if (headerInfo.fromHeader && bodyDoc) {
122
+ const a = JSON.stringify(headerInfo.fromHeader.accepts || null);
123
+ const b = JSON.stringify(bodyDoc.accepts || null);
124
+ if (a !== b && bodyDoc.accepts !== undefined) add('FAIL', 'door-disagreement', 'the body challenge and the PAYMENT-REQUIRED header disagree on accepts[]');
125
+ }
126
+ return findings;
127
+ }
128
+
129
+ function checkDiscovery(doc) {
130
+ const findings = [];
131
+ const add = (level, code, msg) => findings.push({ level, code, msg });
132
+ const bz = doc && doc.extensions && doc.extensions.bazaar;
133
+ if (!bz) return findings; // discovery is optional
134
+ if (bz.discoverable !== true) { add('INFO', 'not-discoverable', 'bazaar extension present but discoverable !== true'); return findings; }
135
+
136
+ const info = bz.info || {};
137
+ const input = info.input || null;
138
+ const output = info.output || null;
139
+ if (!input) add('WARN', 'no-input-example', 'discoverable listing has no info.input: an indexer cannot build a call from it');
140
+ else {
141
+ if (!input.method) add('WARN', 'no-method', 'info.input.method is missing');
142
+ const params = input.queryParams || input.body;
143
+ if (!params || (typeof params === 'object' && Object.keys(params).length === 0)) {
144
+ add('WARN', 'empty-input-example', 'info.input carries no example params: the advertised call is not runnable as written');
145
+ }
146
+ if (input.schema && Array.isArray(input.schema.required) && params && typeof params === 'object') {
147
+ const missing = input.schema.required.filter(k => !(k in params));
148
+ if (missing.length) add('FAIL', 'example-violates-schema', `info.input.example is missing required key(s) ${missing.join(', ')} from its own schema`);
149
+ }
150
+ }
151
+ if (output) {
152
+ if (output.example === undefined && !output.schema) add('WARN', 'no-output-example', 'info.output has neither example nor schema');
153
+ if (output.example !== undefined && !output.answerBasis) {
154
+ add('INFO', 'unpaired-examples', 'output.example is advertised without answerBasis: nothing states it is the response to input.example');
155
+ }
156
+ }
157
+ return findings;
158
+ }
159
+
160
+ function checkClientCap(doc, maxPrice) {
161
+ const findings = [];
162
+ const offers = (doc && doc.accepts) || [];
163
+ const prices = offers.map(o => offerAmountToUsd(o.amount, o.network, o.asset)).filter(v => v !== null);
164
+ if (!prices.length) {
165
+ if (offers.length) findings.push({ level: 'INFO', code: 'price-unmeasured', msg: 'no offer names a 6-decimal USD stablecoin I can convert; the price was not measured (not "0")' });
166
+ return findings;
167
+ }
168
+ const cheapest = Math.min(...prices);
169
+ if (cheapest > maxPrice) {
170
+ findings.push({ level: 'FAIL', code: 'over-max-price', msg: `cheapest offer is $${cheapest} > --max-price $${maxPrice}` });
171
+ }
172
+ // The reference x402 client defaults to a $1 per-call spend cap. A listing
173
+ // above it that does not disclose the cap will be refused by that client.
174
+ if (cheapest > 1) {
175
+ // Disclosures in the wild name the cap in different ways: the SDK field is
176
+ // maxAmountPerPayment, some sellers say "spend cap", some "spendControls".
177
+ const blob = JSON.stringify(doc);
178
+ const discloses = /spend\s*cap|spendcontrols|maxamountperpayment|max\s*value|cap\s*of\s*\$?1|>\s*\$?1/i.test(blob);
179
+ if (!discloses) {
180
+ findings.push({ level: 'WARN', code: 'client-cap-undisclosed', msg: `cheapest offer $${cheapest} exceeds the reference client's $1 default cap and the 402 does not disclose it` });
181
+ }
182
+ }
183
+ return findings;
184
+ }
185
+
186
+ async function run(argv) {
187
+ const args = parseArgs(argv);
188
+ if (args.help) { console.log(require('fs').readFileSync(__dirname + '/README.md', 'utf8').split('\n').slice(0, 40).join('\n')); return 0; }
189
+ if (args.version) { console.log(VERSION); return 0; }
190
+ if (!args.url) { console.error('usage: x402-check <url> [--json] [--timeout 20] [--max-price 1.00] [--header "k: v"]... [--no-static]'); return 2; }
191
+ if (!/^https?:\/\//i.test(args.url)) { console.error('x402-check: url must be http(s)'); return 2; }
192
+
193
+ const headers = { 'user-agent': `x402-check/${VERSION}` };
194
+ for (const h of args.headers) {
195
+ const i = h.indexOf(':');
196
+ if (i > 0) headers[h.slice(0, i).trim().toLowerCase()] = h.slice(i + 1).trim();
197
+ }
198
+
199
+ const findings = [];
200
+ let doc = null, headerRaw = null, status = null, bodyText = '';
201
+ try {
202
+ const { res, text } = await fetchOne(args.url, headers, args.timeout * 1000);
203
+ status = res.status;
204
+ bodyText = text;
205
+ if (status === 200) findings.push({ level: 'FAIL', code: 'not-paid', msg: 'endpoint answered 200 without a payment header: it is not (or no longer) paywalled' });
206
+ else if (status !== 402) findings.push({ level: 'FAIL', code: 'status', msg: `unpaid request answered HTTP ${status}, not 402` });
207
+
208
+ if (status === 402) {
209
+ const headerInfo = decodePaymentRequired(res);
210
+ headerRaw = headerInfo.fromHeader;
211
+ if (headerInfo.headerError) findings.push({ level: 'FAIL', code: 'header-base64', msg: `PAYMENT-REQUIRED is not base64 JSON: ${headerInfo.headerError}` });
212
+ let fromBody = null;
213
+ try { fromBody = JSON.parse(bodyText); } catch { /* body may be empty or non-JSON */ }
214
+ if (fromBody && fromBody.accepts === undefined && fromBody.x402Version === undefined) fromBody = null;
215
+ const headerUsable = headerInfo.fromHeader && Array.isArray(headerInfo.fromHeader.accepts) && headerInfo.fromHeader.accepts.length;
216
+ doc = headerUsable ? headerInfo.fromHeader : (fromBody || headerInfo.fromHeader);
217
+ if (!doc && fromBody) doc = fromBody;
218
+ if (!headerInfo.raw) findings.push({ level: 'WARN', code: 'no-header', msg: 'no PAYMENT-REQUIRED header; only the body carries the challenge' });
219
+ findings.push(...checkChallenge(doc, headerInfo, fromBody));
220
+ findings.push(...checkDiscovery(doc));
221
+ findings.push(...checkClientCap(doc, args.maxPrice));
222
+ if (doc && doc.extensions && doc.extensions.bazaar && doc.extensions.bazaar.discoverable === true && !headerInfo.raw) {
223
+ findings.push({ level: 'WARN', code: 'indexer-blind', msg: 'discoverable listing with no PAYMENT-REQUIRED header: at least one indexer reads only the header' });
224
+ }
225
+ }
226
+ } catch (e) {
227
+ console.error(`x402-check: request failed: ${e.message}`);
228
+ return 2;
229
+ }
230
+
231
+ if (args.staticCheck && status === 402) {
232
+ try {
233
+ const h2 = { ...headers };
234
+ await new Promise(r => setTimeout(r, 1200));
235
+ const { res: r2 } = await fetchOne(args.url, h2, args.timeout * 1000);
236
+ const second = decodePaymentRequired(r2).fromHeader;
237
+ if (second && headerRaw) {
238
+ const same = JSON.stringify(second.accepts) === JSON.stringify(headerRaw.accepts);
239
+ const hasNonce = /nonce|expiresAt|expires_at/i.test(JSON.stringify(headerRaw));
240
+ if (same && !hasNonce) findings.push({ level: 'INFO', code: 'static-offer', msg: 'two requests 1.2s apart return an identical offer with no nonce/expiry: this 402 is a cached document, not a per-request quote' });
241
+ }
242
+ } catch { /* second read is best-effort */ }
243
+ }
244
+
245
+ const fails = findings.filter(f => f.level === 'FAIL');
246
+ const warns = findings.filter(f => f.level === 'WARN');
247
+ const infos = findings.filter(f => f.level === 'INFO');
248
+
249
+ if (args.json) {
250
+ console.log(JSON.stringify({ url: args.url, version: VERSION, status, verdict: fails.length ? 'FAIL' : 'PASS', findings }, null, 2));
251
+ } else {
252
+ console.log(`x402-check ${VERSION} ${args.url}`);
253
+ console.log(`status ${status} verdict ${fails.length ? 'FAIL' : 'PASS'} (${fails.length} fail, ${warns.length} warn, ${infos.length} info)`);
254
+ if (!findings.length) console.log(' no structural problem found in the unpaid 402 challenge');
255
+ for (const f of [...fails, ...warns, ...infos]) console.log(` ${f.level.padEnd(4)} ${f.code.padEnd(24)} ${f.msg}`);
256
+ }
257
+ return fails.length ? 1 : 0;
258
+ }
259
+
260
+ if (require.main === module) {
261
+ run(process.argv.slice(2)).then(code => process.exit(code)).catch(e => { console.error('x402-check:', e.message); process.exit(2); });
262
+ }
263
+
264
+ module.exports = { checkChallenge, checkDiscovery, checkClientCap, decodePaymentRequired, parseArgs };
package/package.json CHANGED
@@ -1,6 +1,32 @@
1
1
  {
2
2
  "name": "@minia2a/x402-check",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.1",
4
+ "description": "Inspect a live x402 endpoint before you pay it: challenge shape, door parity, EIP-712 domain, discovery examples, and the $1 client-cap trap.",
5
+ "bin": {
6
+ "x402-check": "cli.js"
7
+ },
8
+ "files": [
9
+ "cli.js",
10
+ "README.md",
11
+ "LICENSE"
12
+ ],
13
+ "engines": {
14
+ "node": ">=18"
15
+ },
16
+ "keywords": [
17
+ "x402",
18
+ "http-402",
19
+ "usdc",
20
+ "payments",
21
+ "agents",
22
+ "cli",
23
+ "audit"
24
+ ],
25
+ "license": "MIT",
26
+ "author": "minia2a <hello@minia2a.uk> (https://minia2a.uk)",
27
+ "homepage": "https://minia2a.uk",
28
+ "repository": {
29
+ "type": "git",
30
+ "url": "https://github.com/minia2auk/x402-check.git"
31
+ }
32
+ }