verify402-mcp 1.0.8 → 1.1.0
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/.env.example +6 -0
- package/README.md +48 -4
- package/index.mjs +151 -19
- package/package.json +9 -10
- package/payment-policy.mjs +17 -17
- package/x402-client.mjs +342 -0
package/.env.example
CHANGED
|
@@ -17,6 +17,12 @@ SPEND_LEDGER_PATH= # optional override for the ledger file (default .spen
|
|
|
17
17
|
# Base Sepolia testnet: the live demo's EVM payment rail.
|
|
18
18
|
VERIFY402_NETWORKS=eip155:84532
|
|
19
19
|
VERIFY402_PAY_TO=0xAeEF086DD4e436c69d6d0F684b4c9F43392df9cb
|
|
20
|
+
|
|
21
|
+
# Anonymous usage telemetry, opt-in. When set to 1 the bridge sends one
|
|
22
|
+
# fire-and-forget line per tool call to the service: the tool name and whether
|
|
23
|
+
# it worked. Never arguments, intents, results, wallet data, or IPs. Default is
|
|
24
|
+
# off, and a failed ping never changes a tool's answer.
|
|
25
|
+
# VERIFY402_TELEMETRY=1
|
|
20
26
|
# VERIFY402_RESOURCE_PREFIX=https://verify402.onrender.com
|
|
21
27
|
# Explicit mainnet is a separate deployment, not a demo setting. Set this only
|
|
22
28
|
# after separate readiness verification, with a mainnet facilitator and host:
|
package/README.md
CHANGED
|
@@ -10,26 +10,40 @@ dedicated hot wallet funded with **Base Sepolia testnet USDC** (`eip155:84532`).
|
|
|
10
10
|
The analysis reads mainnet chain data, but the demo never settles mainnet
|
|
11
11
|
payments. The bridge never signs or sends a trade.
|
|
12
12
|
|
|
13
|
-
> **Published package note:** `verify402-mcp@1.0.
|
|
13
|
+
> **Published package note:** `verify402-mcp@1.0.9` is published to npm and
|
|
14
14
|
> defaults paid calls to Base Sepolia testnet (`eip155:84532`) for the public
|
|
15
15
|
> demo. Base mainnet (`eip155:8453`) requires an explicit `VERIFY402_NETWORKS`
|
|
16
16
|
> opt-in in a separate deployment and is not enabled by this release. The
|
|
17
|
-
> previously published `1.0.6
|
|
18
|
-
>
|
|
17
|
+
> previously published `1.0.8`, `1.0.6`, `1.0.5`, and `1.0.4` packages are
|
|
18
|
+
> immutable, and `1.0.4` used Base mainnet by default. Do not republish or
|
|
19
19
|
> overwrite any of them.
|
|
20
20
|
|
|
21
|
+
## Anonymous usage telemetry (opt-in)
|
|
22
|
+
|
|
23
|
+
The bridge can send one anonymous line per tool call to the service: the tool
|
|
24
|
+
name and whether it succeeded (`POST /usage/ping`). Never arguments, intents,
|
|
25
|
+
results, wallet data, or IPs. Off by default; set `VERIFY402_TELEMETRY=1` to
|
|
26
|
+
turn it on. A failed ping never changes the tool's answer, and only these
|
|
27
|
+
tool names are accepted: `preflight_gate`, `inspect_402`, `directory_402`,
|
|
28
|
+
`verify_arbitrage`, `check_token_safety`, `get_best_route`,
|
|
29
|
+
`verify_quote_fairness`, `get_trade_depth`.
|
|
30
|
+
|
|
21
31
|
## Tools
|
|
22
32
|
|
|
23
33
|
| tool | price | what it answers |
|
|
24
34
|
|---|---|---|
|
|
25
35
|
| `preflight_gate` | **free** | "Should I sign this payment request or transaction?" — PASS / CAUTION / BLOCK with reasons, `checked` / `notChecked`, and a short-lived receipt |
|
|
36
|
+
| `inspect_402` | **free** | "What does this 402 actually ask for?" — price, token, network, payee, bound resource, and a PASS / CAUTION / BLOCK verdict from a read-only fetch |
|
|
37
|
+
| `directory_402` | **free** | "What is the x402 ecosystem asking for right now?" — watched public endpoints with protocol and sign verdicts, plus recorded changes |
|
|
26
38
|
| `verify_arbitrage` | $0.05 | "Is this cross-venue arbitrage opportunity real, right now?" |
|
|
27
39
|
| `check_token_safety` | $0.10 | "Is this token sellable at a realistic size, and what does the round trip cost?" — TRUST / CAUTION / AVOID with evidence; not a code audit |
|
|
28
40
|
| `get_best_route` | $0.03 | "What would the chain actually pay for this swap?" — best route + every quoted venue |
|
|
29
41
|
| `verify_quote_fairness` | $0.05 | "A broker/bot offered me this number — is it honest?" fair / overpaying / too_good_to_be_true |
|
|
30
42
|
| `get_trade_depth` | $0.05 | "How big can I trade here before the round trip eats me?" — per-size impact, round-trip cost, capacity |
|
|
31
43
|
|
|
32
|
-
`preflight_gate` is the front door.
|
|
44
|
+
`preflight_gate` is the front door. `inspect_402` reads a 402 challenge
|
|
45
|
+
before an agent pays it, and `directory_402` lists the endpoints we watch.
|
|
46
|
+
Call the gate before signing any crypto
|
|
33
47
|
transaction or x402 payment request. If `sign_allowed` is false, **do not
|
|
34
48
|
sign**. If `requires_ack` is true, surface the reasons to the operator. The
|
|
35
49
|
receipt expires (default 90s); call again instead of reusing it.
|
|
@@ -225,6 +239,36 @@ Once configured, your agent automatically sees the tools in its context. You can
|
|
|
225
239
|
- Use the [reference executor](https://github.com/a32116150-ctrl/verify402/blob/master/examples/preflight-guard.mjs)
|
|
226
240
|
when you want enforcement rather than advice.
|
|
227
241
|
|
|
242
|
+
## Dependencies and `npm audit`
|
|
243
|
+
|
|
244
|
+
This package no longer depends on `@x402/axios` or `@x402/evm`. The x402 payer
|
|
245
|
+
(PAYMENT-REQUIRED / PAYMENT-SIGNATURE / PAYMENT-RESPONSE, scheme `exact`,
|
|
246
|
+
EIP-3009 authorization) is implemented here on `viem`, and the runtime
|
|
247
|
+
dependency list is: the MCP SDK, axios, dotenv, viem, zod 4.
|
|
248
|
+
|
|
249
|
+
Why: `@x402` 2.28.0 depended on `zod ^3.24.2`, which resolves into
|
|
250
|
+
[GHSA-mrhx-c7xc-m3w5](https://github.com/advisories/GHSA-mrhx-c7xc-m3w5)
|
|
251
|
+
(memory-exhaustion DoS while validating oversized arrays; the advisory covers
|
|
252
|
+
all zod < 4.6.6, and no patched 3.x exists). npm ignores `overrides` declared
|
|
253
|
+
inside a dependency, so installs of 1.0.8 and earlier showed a "high severity"
|
|
254
|
+
audit banner. The upstream request is
|
|
255
|
+
[x402-foundation/x402#3953](https://github.com/x402-foundation/x402/issues/3953).
|
|
256
|
+
|
|
257
|
+
The current package, installed from its tarball:
|
|
258
|
+
|
|
259
|
+
```console
|
|
260
|
+
$ npm i verify402-mcp
|
|
261
|
+
added 123 packages
|
|
262
|
+
$ npm audit
|
|
263
|
+
found 0 vulnerabilities
|
|
264
|
+
```
|
|
265
|
+
|
|
266
|
+
The bridge pays the same wire protocol. The only behavior change is cosmetic:
|
|
267
|
+
`npm ls @x402` shows nothing, and the install is 5 packages smaller. The
|
|
268
|
+
paid-call policy (network allowlist, configured payee, canonical USDC,
|
|
269
|
+
per-payment cap, tool-bound resource) is unchanged and still runs before any
|
|
270
|
+
signature exists, in `payment-policy.mjs`.
|
|
271
|
+
|
|
228
272
|
## Explicit mainnet configuration (not the public demo)
|
|
229
273
|
|
|
230
274
|
Mainnet settlement is a separate deployment choice, not a bridge or demo
|
package/index.mjs
CHANGED
|
@@ -14,18 +14,20 @@
|
|
|
14
14
|
// 2. paid GET/POST 4. sign payment (wallet in env)
|
|
15
15
|
// 5. retry with proof → verdict
|
|
16
16
|
//
|
|
17
|
-
// PAYMENT POLICY (load-bearing, do not remove): before a signature exists,
|
|
18
|
-
//
|
|
19
|
-
//
|
|
20
|
-
// the
|
|
21
|
-
//
|
|
22
|
-
//
|
|
17
|
+
// PAYMENT POLICY (load-bearing, do not remove): before a signature exists, the
|
|
18
|
+
// local x402 payer (x402-client.mjs) selects a requirement, payment-policy.mjs
|
|
19
|
+
// validates the whole challenge against the network allowlist, the verify402
|
|
20
|
+
// payee, canonical USDC, the per-payment USD cap, and a known paid resource on
|
|
21
|
+
// the configured server, and the tool-bound guard refuses any challenge that is
|
|
22
|
+
// not for the route the current tool owns. Redirects are refused. An MCP server
|
|
23
|
+
// that signs anything any remote 402 asks for is a blank cheque. This one is
|
|
24
|
+
// not. The payer is implemented here on viem; it carries no @x402 dependency,
|
|
25
|
+
// so installing the bridge does not pull the nested zod 3.x advisory.
|
|
23
26
|
|
|
24
27
|
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
25
28
|
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
|
|
26
29
|
import axios from "axios";
|
|
27
|
-
import { x402Client, wrapAxiosWithPayment } from "
|
|
28
|
-
import { ExactEvmScheme } from "@x402/evm/exact/client";
|
|
30
|
+
import { x402Client, wrapAxiosWithPayment, createExactEvmScheme } from "./x402-client.mjs";
|
|
29
31
|
import { privateKeyToAccount } from "viem/accounts";
|
|
30
32
|
import { config } from "dotenv";
|
|
31
33
|
import { z } from "zod";
|
|
@@ -55,9 +57,29 @@ const SERVER_URL = (process.env.VERIFY402_URL || "https://verify402.onrender.com
|
|
|
55
57
|
// two clients separate means a misconfigured 402 on a free route can never
|
|
56
58
|
// turn into a signature.
|
|
57
59
|
const freeApi = axios.create({ baseURL: SERVER_URL, timeout: 30_000, maxRedirects: 0, headers: CLIENT_HEADERS });
|
|
58
|
-
|
|
59
|
-
//
|
|
60
|
-
//
|
|
60
|
+
|
|
61
|
+
// Anonymous usage telemetry, strictly opt-in (VERIFY402_TELEMETRY=1). One
|
|
62
|
+
// fire-and-forget line per tool call: the tool name and whether it worked.
|
|
63
|
+
// No arguments, no intent, no result, no wallet. A ping failure never blocks
|
|
64
|
+
// or changes the tool's answer, and the bridge never pings when it is off.
|
|
65
|
+
const TELEMETRY_ENABLED = process.env.VERIFY402_TELEMETRY === "1";
|
|
66
|
+
|
|
67
|
+
// Fire-and-forget. Exported for tests; the tool handlers call it positionally.
|
|
68
|
+
export function pingUsage(tool, ok, deps = {}) {
|
|
69
|
+
if (!TELEMETRY_ENABLED) return false;
|
|
70
|
+
const post = deps.post ?? ((body) => freeApi.post("/usage/ping", body, { timeout: 3000 }).catch(() => {}));
|
|
71
|
+
try {
|
|
72
|
+
const result = post({ tool, ok: Boolean(ok) });
|
|
73
|
+
if (result && typeof result.then === "function") result.catch(() => {});
|
|
74
|
+
return true;
|
|
75
|
+
} catch {
|
|
76
|
+
return false;
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
// Spend guard: the payer refuses to SIGN any payment above this, before a
|
|
80
|
+
// signature exists. Enforced by the pre-signature guard in payment-policy.mjs
|
|
81
|
+
// (validatePaymentChallenge), not by request code - so it cannot be bypassed
|
|
82
|
+
// by a caller.
|
|
61
83
|
const MAX_PAYMENT_USD = Number(process.env.MAX_PAYMENT_USD || 0.25);
|
|
62
84
|
|
|
63
85
|
// Free-only mode is deliberate: an agent can install the bridge and call the
|
|
@@ -114,7 +136,7 @@ Environment:
|
|
|
114
136
|
VERIFY402_PAY_TO EVM payee the 402 must name (default the verify402 payee)
|
|
115
137
|
VERIFY402_RESOURCE_PREFIX resource origin/prefix the 402 must match (default VERIFY402_URL)
|
|
116
138
|
|
|
117
|
-
The free
|
|
139
|
+
The free tools are preflight_gate, inspect_402 and directory_402. The paid tools are verify_arbitrage,
|
|
118
140
|
check_token_safety, get_best_route, verify_quote_fairness and get_trade_depth.
|
|
119
141
|
The bridge signs x402 payments only; it never signs or sends a trade.
|
|
120
142
|
`);
|
|
@@ -141,11 +163,11 @@ export function createBridgeClientFromEnv() {
|
|
|
141
163
|
policies: [(version, requirements) => policy.filter(version, requirements)],
|
|
142
164
|
});
|
|
143
165
|
for (const network of policy.allowedNetworks) {
|
|
144
|
-
client.register(network,
|
|
166
|
+
client.register(network, createExactEvmScheme(account));
|
|
145
167
|
}
|
|
146
168
|
// Full-challenge guard (version, every EVM offer, canonical asset/domain,
|
|
147
169
|
// payee, amount cap, timeout, EIP-3009) plus the resource/route layer. It
|
|
148
|
-
// runs after the
|
|
170
|
+
// runs after the client has selected a requirement and before the signer.
|
|
149
171
|
// The expected resource is resolved per invocation from the tool handler
|
|
150
172
|
// context, never from the 402 challenge.
|
|
151
173
|
client.onBeforePaymentCreation(
|
|
@@ -221,6 +243,17 @@ const DESCRIPTIONS = {
|
|
|
221
243
|
"Optional caller-supplied checks: policy.sellerPayoutWallets is a payout allowlist, not provenance; " +
|
|
222
244
|
"policy.sellerPayoutManifest fetches a seller-signed manifest from a caller-pinned HTTPS origin and is the only source of payee_payout_binding; " +
|
|
223
245
|
"policy.obligation checks a local settled-key ledger and cumulative spend against a grant. The gate does not persist either state.",
|
|
246
|
+
inspect_402:
|
|
247
|
+
"Read an x402 402 challenge BEFORE paying it. Pass a public endpoint URL (or the challenge you already have) " +
|
|
248
|
+
"and get back the price, token, network, payee, the bound resource, and a PASS / CAUTION / BLOCK verdict " +
|
|
249
|
+
"with typed reasons and a receipt. Use this when an agent is about to pay a server you do not control. " +
|
|
250
|
+
"The service fetches the challenge once, read-only: it never signs, pays, or settles. " +
|
|
251
|
+
"A recognized dollar stable (USDC, USDT, DAI, USDG) is named; a volatile asset gets a caution because it " +
|
|
252
|
+
"cannot be priced in USD. Free.",
|
|
253
|
+
directory_402:
|
|
254
|
+
"List the public x402 endpoints verify402 watches, with the price, network, payee, a protocol verdict " +
|
|
255
|
+
"(is the challenge well-formed?) and a sign verdict (should an agent sign it?), plus any changes " +
|
|
256
|
+
"since the previous check. Use it to see what the ecosystem is asking for before wiring an agent to it. Free.",
|
|
224
257
|
verify_arbitrage:
|
|
225
258
|
"Ask verify402 whether a cross-venue arbitrage opportunity is REAL, right now. " +
|
|
226
259
|
"Quotes come from Uniswap's canonical QuoterV2 and each DEX router at one pinned block. " +
|
|
@@ -318,8 +351,10 @@ async function main() {
|
|
|
318
351
|
};
|
|
319
352
|
try {
|
|
320
353
|
const res = await freeApi.post("/preflight", payload);
|
|
354
|
+
pingUsage("preflight_gate", true);
|
|
321
355
|
return { content: [{ type: "text", text: JSON.stringify(res.data, null, 2) }] };
|
|
322
356
|
} catch (e) {
|
|
357
|
+
pingUsage("preflight_gate", false);
|
|
323
358
|
const status = e.response?.status;
|
|
324
359
|
const body = e.response?.data;
|
|
325
360
|
return {
|
|
@@ -337,6 +372,68 @@ async function main() {
|
|
|
337
372
|
},
|
|
338
373
|
);
|
|
339
374
|
|
|
375
|
+
server.tool(
|
|
376
|
+
"inspect_402",
|
|
377
|
+
DESCRIPTIONS.inspect_402,
|
|
378
|
+
{
|
|
379
|
+
url: z.string().optional().describe("Public http(s) endpoint that answers with an x402 402 challenge. Only public hosts are fetched; localhost and private ranges are refused."),
|
|
380
|
+
method: z.enum(["GET", "POST"]).optional().describe("HTTP method for the probe (default GET). A POST sends an empty {} body."),
|
|
381
|
+
challenge: z.record(z.string(), z.unknown()).optional().describe("A 402 challenge you already have. Makes no request."),
|
|
382
|
+
header: z.string().optional().describe("The base64 PAYMENT-REQUIRED header value. Makes no request."),
|
|
383
|
+
target: z.string().optional().describe("The URL the challenge belongs to. Binds the challenge's resource so the verdict can check it."),
|
|
384
|
+
},
|
|
385
|
+
async (args) => {
|
|
386
|
+
const payload = {
|
|
387
|
+
url: args.url,
|
|
388
|
+
method: args.method,
|
|
389
|
+
challenge: args.challenge,
|
|
390
|
+
header: args.header,
|
|
391
|
+
target: args.target,
|
|
392
|
+
};
|
|
393
|
+
try {
|
|
394
|
+
const res = await freeApi.post("/inspect", payload);
|
|
395
|
+
pingUsage("inspect_402", true);
|
|
396
|
+
return { content: [{ type: "text", text: JSON.stringify(res.data, null, 2) }] };
|
|
397
|
+
} catch (e) {
|
|
398
|
+
pingUsage("inspect_402", false);
|
|
399
|
+
const status = e.response?.status;
|
|
400
|
+
const body = e.response?.data;
|
|
401
|
+
return {
|
|
402
|
+
isError: true,
|
|
403
|
+
content: [{
|
|
404
|
+
type: "text",
|
|
405
|
+
text: `inspect failed${status ? ` (${status})` : ""}: ${JSON.stringify(body ?? e.message)}. ` +
|
|
406
|
+
"No payment was attempted and nothing was signed.",
|
|
407
|
+
}],
|
|
408
|
+
};
|
|
409
|
+
}
|
|
410
|
+
},
|
|
411
|
+
);
|
|
412
|
+
|
|
413
|
+
server.tool(
|
|
414
|
+
"directory_402",
|
|
415
|
+
DESCRIPTIONS.directory_402,
|
|
416
|
+
{},
|
|
417
|
+
async () => {
|
|
418
|
+
try {
|
|
419
|
+
const res = await freeApi.get("/directory.json");
|
|
420
|
+
pingUsage("directory_402", true);
|
|
421
|
+
return { content: [{ type: "text", text: JSON.stringify(res.data, null, 2) }] };
|
|
422
|
+
} catch (e) {
|
|
423
|
+
pingUsage("directory_402", false);
|
|
424
|
+
const status = e.response?.status;
|
|
425
|
+
const body = e.response?.data;
|
|
426
|
+
return {
|
|
427
|
+
isError: true,
|
|
428
|
+
content: [{
|
|
429
|
+
type: "text",
|
|
430
|
+
text: `directory failed${status ? ` (${status})` : ""}: ${JSON.stringify(body ?? e.message)}.`,
|
|
431
|
+
}],
|
|
432
|
+
};
|
|
433
|
+
}
|
|
434
|
+
},
|
|
435
|
+
);
|
|
436
|
+
|
|
340
437
|
// Paid tools require a wallet. Without EVM_PRIVATE_KEY the server still
|
|
341
438
|
// exposes the free gate, so "install it and try it" never asks for a key.
|
|
342
439
|
if (paidApi) {
|
|
@@ -350,7 +447,9 @@ async function main() {
|
|
|
350
447
|
size: z.number().optional().describe("Trade size in whole base units, e.g. 100000 (default 100000)"),
|
|
351
448
|
},
|
|
352
449
|
async (args) => {
|
|
353
|
-
|
|
450
|
+
let res;
|
|
451
|
+
try {
|
|
452
|
+
res = await runPaidTool({
|
|
354
453
|
tool: "verify_arbitrage",
|
|
355
454
|
client: paidApi,
|
|
356
455
|
body: {
|
|
@@ -360,6 +459,11 @@ async function main() {
|
|
|
360
459
|
size: args.size ?? 100000,
|
|
361
460
|
},
|
|
362
461
|
});
|
|
462
|
+
pingUsage("verify_arbitrage", true);
|
|
463
|
+
} catch (err) {
|
|
464
|
+
pingUsage("verify_arbitrage", false);
|
|
465
|
+
throw err;
|
|
466
|
+
}
|
|
363
467
|
return { content: [{ type: "text", text: JSON.stringify(res.data, null, 2) }] };
|
|
364
468
|
},
|
|
365
469
|
);
|
|
@@ -374,7 +478,9 @@ async function main() {
|
|
|
374
478
|
offeredPriceUsd: z.number().optional().describe("Optional price per token someone offered you"),
|
|
375
479
|
},
|
|
376
480
|
async (args) => {
|
|
377
|
-
|
|
481
|
+
let res;
|
|
482
|
+
try {
|
|
483
|
+
res = await runPaidTool({
|
|
378
484
|
tool: "check_token_safety",
|
|
379
485
|
client: paidApi,
|
|
380
486
|
body: {
|
|
@@ -384,6 +490,11 @@ async function main() {
|
|
|
384
490
|
offeredPriceUsd: args.offeredPriceUsd ?? null,
|
|
385
491
|
},
|
|
386
492
|
});
|
|
493
|
+
pingUsage("check_token_safety", true);
|
|
494
|
+
} catch (err) {
|
|
495
|
+
pingUsage("check_token_safety", false);
|
|
496
|
+
throw err;
|
|
497
|
+
}
|
|
387
498
|
return { content: [{ type: "text", text: JSON.stringify(res.data, null, 2) }] };
|
|
388
499
|
},
|
|
389
500
|
);
|
|
@@ -398,7 +509,9 @@ async function main() {
|
|
|
398
509
|
chainId: z.number().int().describe("REQUIRED. 1 Ethereum, 42161 Arbitrum, 8453 Base. There is no default; omitting it returns 400 missing_chain."),
|
|
399
510
|
},
|
|
400
511
|
async (args) => {
|
|
401
|
-
|
|
512
|
+
let res;
|
|
513
|
+
try {
|
|
514
|
+
res = await runPaidTool({
|
|
402
515
|
tool: "get_best_route",
|
|
403
516
|
client: paidApi,
|
|
404
517
|
body: {
|
|
@@ -408,6 +521,11 @@ async function main() {
|
|
|
408
521
|
amountIn: args.amountIn,
|
|
409
522
|
},
|
|
410
523
|
});
|
|
524
|
+
pingUsage("get_best_route", true);
|
|
525
|
+
} catch (err) {
|
|
526
|
+
pingUsage("get_best_route", false);
|
|
527
|
+
throw err;
|
|
528
|
+
}
|
|
411
529
|
return { content: [{ type: "text", text: JSON.stringify(res.data, null, 2) }] };
|
|
412
530
|
},
|
|
413
531
|
);
|
|
@@ -424,7 +542,9 @@ async function main() {
|
|
|
424
542
|
chainId: z.number().int().describe("REQUIRED. 1 Ethereum, 42161 Arbitrum, 8453 Base. There is no default; omitting it returns 400 missing_chain."),
|
|
425
543
|
},
|
|
426
544
|
async (args) => {
|
|
427
|
-
|
|
545
|
+
let res;
|
|
546
|
+
try {
|
|
547
|
+
res = await runPaidTool({
|
|
428
548
|
tool: "verify_quote_fairness",
|
|
429
549
|
client: paidApi,
|
|
430
550
|
body: {
|
|
@@ -436,6 +556,11 @@ async function main() {
|
|
|
436
556
|
venueClaimed: args.venueClaimed ?? null,
|
|
437
557
|
},
|
|
438
558
|
});
|
|
559
|
+
pingUsage("verify_quote_fairness", true);
|
|
560
|
+
} catch (err) {
|
|
561
|
+
pingUsage("verify_quote_fairness", false);
|
|
562
|
+
throw err;
|
|
563
|
+
}
|
|
439
564
|
return { content: [{ type: "text", text: JSON.stringify(res.data, null, 2) }] };
|
|
440
565
|
},
|
|
441
566
|
);
|
|
@@ -451,7 +576,9 @@ async function main() {
|
|
|
451
576
|
maxRoundTripPct: z.number().optional().describe("Your round-trip cost tolerance, default 1%"),
|
|
452
577
|
},
|
|
453
578
|
async (args) => {
|
|
454
|
-
|
|
579
|
+
let res;
|
|
580
|
+
try {
|
|
581
|
+
res = await runPaidTool({
|
|
455
582
|
tool: "get_trade_depth",
|
|
456
583
|
client: paidApi,
|
|
457
584
|
body: {
|
|
@@ -462,6 +589,11 @@ async function main() {
|
|
|
462
589
|
maxRoundTripPct: args.maxRoundTripPct ?? 1.0,
|
|
463
590
|
},
|
|
464
591
|
});
|
|
592
|
+
pingUsage("get_trade_depth", true);
|
|
593
|
+
} catch (err) {
|
|
594
|
+
pingUsage("get_trade_depth", false);
|
|
595
|
+
throw err;
|
|
596
|
+
}
|
|
465
597
|
return { content: [{ type: "text", text: JSON.stringify(res.data, null, 2) }] };
|
|
466
598
|
},
|
|
467
599
|
);
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "verify402-mcp",
|
|
3
|
-
"version": "1.0
|
|
3
|
+
"version": "1.1.0",
|
|
4
4
|
"mcpName": "io.github.a32116150-ctrl/verify402-mcp",
|
|
5
5
|
"description": "MCP server for verify402: a free, fail-closed preflight gate before signing, plus five paid on-chain checks paid per call via x402.",
|
|
6
6
|
"type": "module",
|
|
@@ -9,16 +9,17 @@
|
|
|
9
9
|
},
|
|
10
10
|
"main": "index.mjs",
|
|
11
11
|
"files": [
|
|
12
|
-
"
|
|
12
|
+
".env.example",
|
|
13
13
|
"budget.mjs",
|
|
14
|
-
"payment-policy.mjs",
|
|
15
|
-
"paid-call.mjs",
|
|
16
|
-
"log.mjs",
|
|
17
14
|
"client-id.mjs",
|
|
18
|
-
"
|
|
19
|
-
".env.example",
|
|
15
|
+
"index.mjs",
|
|
20
16
|
"LICENSE",
|
|
21
|
-
"
|
|
17
|
+
"log.mjs",
|
|
18
|
+
"NOTICE",
|
|
19
|
+
"paid-call.mjs",
|
|
20
|
+
"payment-policy.mjs",
|
|
21
|
+
"README.md",
|
|
22
|
+
"x402-client.mjs"
|
|
22
23
|
],
|
|
23
24
|
"scripts": {
|
|
24
25
|
"start": "node index.mjs",
|
|
@@ -55,8 +56,6 @@
|
|
|
55
56
|
},
|
|
56
57
|
"dependencies": {
|
|
57
58
|
"@modelcontextprotocol/sdk": "^1.12.1",
|
|
58
|
-
"@x402/axios": "2.28.0",
|
|
59
|
-
"@x402/evm": "2.28.0",
|
|
60
59
|
"axios": "^1.13.2",
|
|
61
60
|
"dotenv": "^16.4.5",
|
|
62
61
|
"viem": "^2.39.0",
|
package/payment-policy.mjs
CHANGED
|
@@ -8,10 +8,10 @@
|
|
|
8
8
|
// - payTo to be the verify402 payee (default the EVM payTo);
|
|
9
9
|
// - the 402 resource to be on the configured server and a known paid route.
|
|
10
10
|
//
|
|
11
|
-
// The amount cap and the canonical-USDC allowlist are enforced
|
|
12
|
-
//
|
|
13
|
-
//
|
|
14
|
-
//
|
|
11
|
+
// The amount cap and the canonical-USDC allowlist are enforced by
|
|
12
|
+
// validatePaymentChallenge(), which runs before any signer is reached.
|
|
13
|
+
// Redirects are refused by the axios clients in index.mjs and
|
|
14
|
+
// first-payment.mjs.
|
|
15
15
|
//
|
|
16
16
|
// Mainnet is available only through an explicit VERIFY402_NETWORKS value. The
|
|
17
17
|
// demo default must never silently select Base mainnet.
|
|
@@ -24,10 +24,10 @@ export const DEFAULT_NETWORKS = [DEMO_NETWORK];
|
|
|
24
24
|
export const DEFAULT_PAY_TO = "0xAeEF086DD4e436c69d6d0F684b4c9F43392df9cb";
|
|
25
25
|
export const DEFAULT_PAID_ROUTES = ["/verify", "/safety", "/route", "/quotecheck", "/depth"];
|
|
26
26
|
|
|
27
|
-
// Hard upper bound for a single EIP-3009 authorization. The
|
|
28
|
-
// `validBefore = now + maxTimeoutSeconds`; an unbounded value hands the
|
|
29
|
-
// long-lived transferable authorization. 300 seconds is the documented
|
|
30
|
-
// matches the live verify402 challenge.
|
|
27
|
+
// Hard upper bound for a single EIP-3009 authorization. The exact-EVM payer
|
|
28
|
+
// signs `validBefore = now + maxTimeoutSeconds`; an unbounded value hands the
|
|
29
|
+
// payee a long-lived transferable authorization. 300 seconds is the documented
|
|
30
|
+
// cap and matches the live verify402 challenge.
|
|
31
31
|
export const MAX_TIMEOUT_SECONDS = 300;
|
|
32
32
|
|
|
33
33
|
// The canonical USDC contract for each network this bridge knows how to pay.
|
|
@@ -43,7 +43,7 @@ export const NETWORK_USDC = {
|
|
|
43
43
|
// EIP-712 domain parameters for the canonical USDC contract on each supported
|
|
44
44
|
// network. These are signing-relevant: a server that supplies a different
|
|
45
45
|
// `extra.name`/`extra.version` asks the wallet to sign a different token
|
|
46
|
-
// domain. Values
|
|
46
|
+
// domain. Values match the canonical USDC metadata the live server advertises.
|
|
47
47
|
export const NETWORK_USDC_DOMAIN = {
|
|
48
48
|
[DEMO_NETWORK]: { name: "USDC", version: "2" },
|
|
49
49
|
[MAINNET_NETWORK]: { name: "USD Coin", version: "2" },
|
|
@@ -51,7 +51,7 @@ export const NETWORK_USDC_DOMAIN = {
|
|
|
51
51
|
|
|
52
52
|
// The only networks the bridge will ever register a signer for. VERIFY402_NETWORKS
|
|
53
53
|
// is constrained to this map; an arbitrary eip155:<chainId> is refused rather
|
|
54
|
-
// than inferred from an asset
|
|
54
|
+
// than inferred from an asset a challenge happens to name.
|
|
55
55
|
export const SUPPORTED_PAYMENT_NETWORKS = new Set(Object.keys(NETWORK_USDC));
|
|
56
56
|
|
|
57
57
|
const EVM_ADDRESS_RE = /^0x[0-9a-fA-F]{40}$/;
|
|
@@ -111,8 +111,8 @@ function validateTimeoutSeconds(value) {
|
|
|
111
111
|
|
|
112
112
|
/**
|
|
113
113
|
* Validate the EIP-712 domain and transfer mode of an EVM requirement. The
|
|
114
|
-
*
|
|
115
|
-
*
|
|
114
|
+
* payer selects EIP-3009 unless `extra.assetTransferMethod === "permit2"`, so
|
|
115
|
+
* permit2 (and any unvalidated extension key) is refused here.
|
|
116
116
|
*/
|
|
117
117
|
function validateEvmExtra(requirement, index, expectedDomainByNetwork) {
|
|
118
118
|
const prefix = `402 accepts[${index}]`;
|
|
@@ -350,7 +350,7 @@ export function createPaymentPolicy({
|
|
|
350
350
|
paidRoutes: [...routes],
|
|
351
351
|
|
|
352
352
|
/**
|
|
353
|
-
*
|
|
353
|
+
* Payer policy: runs after the challenge is parsed and before selection.
|
|
354
354
|
* Returning an empty array would also fail, but a typed error is easier to
|
|
355
355
|
* debug and is surfaced to the caller as a refused payment.
|
|
356
356
|
*/
|
|
@@ -370,7 +370,7 @@ export function createPaymentPolicy({
|
|
|
370
370
|
},
|
|
371
371
|
|
|
372
372
|
/**
|
|
373
|
-
*
|
|
373
|
+
* Payer onBeforePaymentCreation hook: runs after selection and before
|
|
374
374
|
* the scheme creates a signature. Returning `{ abort: true }` fails closed.
|
|
375
375
|
*
|
|
376
376
|
* This is the resource/route layer of the policy. The full challenge and
|
|
@@ -441,7 +441,7 @@ export function createPaymentPolicy({
|
|
|
441
441
|
|
|
442
442
|
/**
|
|
443
443
|
* Build the pre-signature guard shared by every payer. It validates the whole
|
|
444
|
-
* 402 challenge, proves the
|
|
444
|
+
* 402 challenge, proves the client's selected requirement is the exact object that
|
|
445
445
|
* was validated, re-validates that object, and then applies the resource/route
|
|
446
446
|
* layer in policy.checkBeforeSign().
|
|
447
447
|
*
|
|
@@ -452,7 +452,7 @@ export function createPaymentPolicy({
|
|
|
452
452
|
* never signs a challenge that is not tied to locally known tool configuration.
|
|
453
453
|
*
|
|
454
454
|
* Returns a hook `(context) => { abort: true, reason } | undefined` suitable
|
|
455
|
-
* for
|
|
455
|
+
* for client.onBeforePaymentCreation().
|
|
456
456
|
*/
|
|
457
457
|
export function createPaymentGuard(policy, {
|
|
458
458
|
expectedResource,
|
|
@@ -516,7 +516,7 @@ export function createPaymentGuard(policy, {
|
|
|
516
516
|
return { abort: true, reason: "selected payment requirement changed after validation" };
|
|
517
517
|
}
|
|
518
518
|
|
|
519
|
-
// Reference identity: the
|
|
519
|
+
// Reference identity: the selector returns an element of
|
|
520
520
|
// paymentRequired.accepts, so a clone/substitution is refused here.
|
|
521
521
|
if (!Array.isArray(challenge.accepts) || !challenge.accepts.includes(selected)) {
|
|
522
522
|
return { abort: true, reason: "selected payment requirement is not from the 402 challenge" };
|
package/x402-client.mjs
ADDED
|
@@ -0,0 +1,342 @@
|
|
|
1
|
+
// Minimal x402 v2 payer implemented in this package, on viem.
|
|
2
|
+
//
|
|
3
|
+
// Why this exists: the published bridge used @x402/axios + @x402/evm. Both
|
|
4
|
+
// pull a nested zod 3.x copy that is covered by GHSA-mrhx-c7xc-m3w5 (a
|
|
5
|
+
// memory-exhaustion DoS) and there is no patched 3.x. npm ignores `overrides`
|
|
6
|
+
// from dependencies, so the audit banner could not be fixed downstream. This
|
|
7
|
+
// module keeps the exact wire format (PAYMENT-REQUIRED / PAYMENT-SIGNATURE /
|
|
8
|
+
// PAYMENT-RESPONSE, x402 v2, scheme "exact", EIP-3009 authorization) with no
|
|
9
|
+
// @x402 dependency at all.
|
|
10
|
+
//
|
|
11
|
+
// The API intentionally mirrors the narrow slice of the SDK the bridge used:
|
|
12
|
+
// x402Client.fromConfig({ policies })
|
|
13
|
+
// client.register(network, scheme) // one exact scheme per network
|
|
14
|
+
// client.onBeforePaymentCreation(hook) // fail-closed guard
|
|
15
|
+
// client.createPaymentPayload(challenge) // select -> guard -> sign
|
|
16
|
+
// wrapAxiosWithPayment(axiosInstance, client)
|
|
17
|
+
//
|
|
18
|
+
// Selection, policy, and the pre-signature guard stay in payment-policy.mjs,
|
|
19
|
+
// so every payer (installed bridge, standalone first-payment script, smoke
|
|
20
|
+
// test) makes the same decision. This file only moves bytes on the wire and
|
|
21
|
+
// signs the EIP-712 authorization.
|
|
22
|
+
|
|
23
|
+
import { randomBytes } from "node:crypto";
|
|
24
|
+
import { getAddress } from "viem";
|
|
25
|
+
|
|
26
|
+
export const PAYMENT_REQUIRED_HEADER = "PAYMENT-REQUIRED";
|
|
27
|
+
export const PAYMENT_SIGNATURE_HEADER = "PAYMENT-SIGNATURE";
|
|
28
|
+
export const PAYMENT_RESPONSE_HEADER = "PAYMENT-RESPONSE";
|
|
29
|
+
|
|
30
|
+
const BASE64_RE = /^[A-Za-z0-9+/]*={0,2}$/;
|
|
31
|
+
|
|
32
|
+
export function encodeBase64Json(value) {
|
|
33
|
+
return Buffer.from(JSON.stringify(value), "utf8").toString("base64");
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export function decodeBase64Json(header, label) {
|
|
37
|
+
const raw = String(header ?? "");
|
|
38
|
+
if (!BASE64_RE.test(raw)) throw new Error(`Invalid ${label} header`);
|
|
39
|
+
try {
|
|
40
|
+
return JSON.parse(Buffer.from(raw, "base64").toString("utf8"));
|
|
41
|
+
} catch {
|
|
42
|
+
throw new Error(`Invalid ${label} header`);
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export function encodePaymentRequiredHeader(paymentRequired) {
|
|
47
|
+
return encodeBase64Json(paymentRequired);
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export function decodePaymentRequiredHeader(header) {
|
|
51
|
+
return decodeBase64Json(header, "payment required");
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
export function encodePaymentSignatureHeader(paymentPayload) {
|
|
55
|
+
return encodeBase64Json(paymentPayload);
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
export function decodePaymentSignatureHeader(header) {
|
|
59
|
+
return decodeBase64Json(header, "payment signature");
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export function encodePaymentResponseHeader(paymentResponse) {
|
|
63
|
+
const buyerFacing = { ...paymentResponse };
|
|
64
|
+
delete buyerFacing.extensionResponses;
|
|
65
|
+
return encodeBase64Json(buyerFacing);
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
export function decodePaymentResponseHeader(header) {
|
|
69
|
+
return decodeBase64Json(header, "payment response");
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
// EIP-712 struct signed for an EIP-3009 transferWithAuthorization.
|
|
73
|
+
const TRANSFER_WITH_AUTHORIZATION_TYPES = {
|
|
74
|
+
TransferWithAuthorization: [
|
|
75
|
+
{ name: "from", type: "address" },
|
|
76
|
+
{ name: "to", type: "address" },
|
|
77
|
+
{ name: "value", type: "uint256" },
|
|
78
|
+
{ name: "validAfter", type: "uint256" },
|
|
79
|
+
{ name: "validBefore", type: "uint256" },
|
|
80
|
+
{ name: "nonce", type: "bytes32" },
|
|
81
|
+
],
|
|
82
|
+
};
|
|
83
|
+
|
|
84
|
+
function chainIdFromNetwork(network) {
|
|
85
|
+
const match = /^eip155:(\d+)$/.exec(String(network ?? ""));
|
|
86
|
+
if (!match) throw new Error(`Not an eip155 network: ${String(network)}`);
|
|
87
|
+
return Number(match[1]);
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/**
|
|
91
|
+
* The "exact" EVM scheme for one signer. createPaymentPayload() builds an
|
|
92
|
+
* EIP-3009 authorization capped by the requirement's maxTimeoutSeconds and
|
|
93
|
+
* signs it with the wallet's EIP-712 domain for the challenge's asset.
|
|
94
|
+
*
|
|
95
|
+
* Nothing here decides whether a payment is allowed: by the time this runs,
|
|
96
|
+
* validatePaymentChallenge() and the tool-bound guard have already passed.
|
|
97
|
+
*/
|
|
98
|
+
export function createExactEvmScheme(account) {
|
|
99
|
+
if (!account?.address || typeof account.signTypedData !== "function") {
|
|
100
|
+
throw new Error("createExactEvmScheme requires a viem account");
|
|
101
|
+
}
|
|
102
|
+
return {
|
|
103
|
+
scheme: "exact",
|
|
104
|
+
// Kept for API parity with the SDK's default-asset hint. Spend enforcement
|
|
105
|
+
// lives in payment-policy.mjs, not here.
|
|
106
|
+
findDefaultAsset: (_asset, network) => {
|
|
107
|
+
const address = /^eip155:84532$/.test(String(network))
|
|
108
|
+
? "0x036CbD53842c5426634e7929541eC2318f3dCF7e"
|
|
109
|
+
: /^eip155:8453$/.test(String(network))
|
|
110
|
+
? "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913"
|
|
111
|
+
: null;
|
|
112
|
+
return address ? { asset: address, decimals: 6, symbol: "USDC" } : null;
|
|
113
|
+
},
|
|
114
|
+
|
|
115
|
+
async createPaymentPayload(x402Version, requirement) {
|
|
116
|
+
const name = requirement?.extra?.name;
|
|
117
|
+
const version = requirement?.extra?.version;
|
|
118
|
+
if (!name || !version) {
|
|
119
|
+
throw new Error(
|
|
120
|
+
`EIP-712 domain parameters (name, version) are required in payment requirements for asset ${requirement?.asset}`,
|
|
121
|
+
);
|
|
122
|
+
}
|
|
123
|
+
const now = Math.floor(Date.now() / 1000);
|
|
124
|
+
const authorization = {
|
|
125
|
+
from: account.address,
|
|
126
|
+
to: getAddress(requirement.payTo),
|
|
127
|
+
value: requirement.amount,
|
|
128
|
+
// x402 v2 opens the window immediately; the cap is the deadline.
|
|
129
|
+
validAfter: "0",
|
|
130
|
+
validBefore: String(now + requirement.maxTimeoutSeconds),
|
|
131
|
+
nonce: `0x${randomBytes(32).toString("hex")}`,
|
|
132
|
+
};
|
|
133
|
+
const signature = await account.signTypedData({
|
|
134
|
+
domain: {
|
|
135
|
+
name,
|
|
136
|
+
version,
|
|
137
|
+
chainId: chainIdFromNetwork(requirement.network),
|
|
138
|
+
verifyingContract: getAddress(requirement.asset),
|
|
139
|
+
},
|
|
140
|
+
types: TRANSFER_WITH_AUTHORIZATION_TYPES,
|
|
141
|
+
primaryType: "TransferWithAuthorization",
|
|
142
|
+
message: {
|
|
143
|
+
from: getAddress(authorization.from),
|
|
144
|
+
to: getAddress(authorization.to),
|
|
145
|
+
value: BigInt(authorization.value),
|
|
146
|
+
validAfter: BigInt(authorization.validAfter),
|
|
147
|
+
validBefore: BigInt(authorization.validBefore),
|
|
148
|
+
nonce: authorization.nonce,
|
|
149
|
+
},
|
|
150
|
+
});
|
|
151
|
+
return {
|
|
152
|
+
x402Version,
|
|
153
|
+
payload: { authorization, signature },
|
|
154
|
+
};
|
|
155
|
+
},
|
|
156
|
+
};
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
/**
|
|
160
|
+
* x402 v2 client: selects one requirement for the registered network/scheme,
|
|
161
|
+
* runs every registered policy and pre-signature hook, then signs.
|
|
162
|
+
*
|
|
163
|
+
* Selection is deliberately boring: the first requirement that has a
|
|
164
|
+
* registered signer, then the policies narrow it. The guard in
|
|
165
|
+
* payment-policy.mjs re-validates the whole challenge afterwards.
|
|
166
|
+
*/
|
|
167
|
+
class X402Client {
|
|
168
|
+
constructor({ policies = [] } = {}) {
|
|
169
|
+
this.policies = Array.isArray(policies) ? policies : [];
|
|
170
|
+
this.beforeHooks = [];
|
|
171
|
+
this.schemes = new Map(); // network -> scheme (x402 v2 only)
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
static fromConfig(config = {}) {
|
|
175
|
+
return new X402Client(config);
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
register(network, scheme, x402Version = 2) {
|
|
179
|
+
if (x402Version !== 2) {
|
|
180
|
+
throw new Error(`register: unsupported x402 version ${x402Version}`);
|
|
181
|
+
}
|
|
182
|
+
this.schemes.set(String(network), scheme);
|
|
183
|
+
return this;
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
onBeforePaymentCreation(hook) {
|
|
187
|
+
if (typeof hook !== "function") throw new Error("onBeforePaymentCreation requires a function");
|
|
188
|
+
this.beforeHooks.push(hook);
|
|
189
|
+
return this;
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
selectPaymentRequirements(x402Version, requirements) {
|
|
193
|
+
if (x402Version !== 2) {
|
|
194
|
+
throw new Error(`No client registered for x402 version: ${x402Version}`);
|
|
195
|
+
}
|
|
196
|
+
if (!Array.isArray(requirements) || requirements.length === 0) {
|
|
197
|
+
throw new Error("402 challenge has no accepts[]");
|
|
198
|
+
}
|
|
199
|
+
let filtered = requirements.filter((requirement) => {
|
|
200
|
+
const scheme = this.schemes.get(String(requirement?.network));
|
|
201
|
+
return Boolean(scheme) && scheme.scheme === requirement?.scheme;
|
|
202
|
+
});
|
|
203
|
+
if (filtered.length === 0) {
|
|
204
|
+
throw new Error(
|
|
205
|
+
"No network/scheme registered for x402 version: 2 which comply with the payment requirements",
|
|
206
|
+
);
|
|
207
|
+
}
|
|
208
|
+
for (const policy of this.policies) {
|
|
209
|
+
filtered = policy(x402Version, filtered);
|
|
210
|
+
if (!Array.isArray(filtered) || filtered.length === 0) {
|
|
211
|
+
throw new Error("All payment requirements were filtered out by policies for x402 version: 2");
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
return filtered[0];
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
async createPaymentPayload(paymentRequired) {
|
|
218
|
+
if (paymentRequired?.x402Version !== 2) {
|
|
219
|
+
throw new Error(`No client registered for x402 version: ${paymentRequired?.x402Version}`);
|
|
220
|
+
}
|
|
221
|
+
const accepted = this.selectPaymentRequirements(2, paymentRequired.accepts);
|
|
222
|
+
const context = { paymentRequired, selectedRequirements: accepted };
|
|
223
|
+
for (const hook of this.beforeHooks) {
|
|
224
|
+
const result = await hook(context);
|
|
225
|
+
if (result && "abort" in result && result.abort) {
|
|
226
|
+
throw new Error(`Payment creation aborted: ${result.reason}`);
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
const scheme = this.schemes.get(String(accepted.network));
|
|
230
|
+
const partial = await scheme.createPaymentPayload(2, accepted);
|
|
231
|
+
return {
|
|
232
|
+
x402Version: 2,
|
|
233
|
+
payload: partial.payload,
|
|
234
|
+
resource: paymentRequired.resource,
|
|
235
|
+
accepted,
|
|
236
|
+
};
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
export const x402Client = { fromConfig: (config) => X402Client.fromConfig(config) };
|
|
241
|
+
|
|
242
|
+
function headerReader(headers) {
|
|
243
|
+
return (name) => {
|
|
244
|
+
if (!headers) return undefined;
|
|
245
|
+
if (typeof headers.get === "function") {
|
|
246
|
+
const value = headers.get(name);
|
|
247
|
+
if (typeof value === "string") return value;
|
|
248
|
+
}
|
|
249
|
+
const direct = headers[name] ?? headers[name.toLowerCase()];
|
|
250
|
+
return typeof direct === "string" ? direct : undefined;
|
|
251
|
+
};
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
function readPaymentRequired(response) {
|
|
255
|
+
const getHeader = headerReader(response?.headers);
|
|
256
|
+
const header = getHeader(PAYMENT_REQUIRED_HEADER);
|
|
257
|
+
if (header) return decodePaymentRequiredHeader(header);
|
|
258
|
+
const body = response?.data;
|
|
259
|
+
if (body && typeof body === "object" && body.x402Version === 1) return body;
|
|
260
|
+
throw new Error("Invalid payment required response");
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
function cloneHeaders(headers) {
|
|
264
|
+
const source = typeof headers?.toJSON === "function" ? headers.toJSON() : (headers ?? {});
|
|
265
|
+
const out = {};
|
|
266
|
+
for (const [key, value] of Object.entries(source)) {
|
|
267
|
+
if (value === undefined || value === null || typeof value === "function") continue;
|
|
268
|
+
out[key] = String(value);
|
|
269
|
+
}
|
|
270
|
+
return out;
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
// A 402 on the paid retry is a server answer, not a transport failure: let the
|
|
274
|
+
// caller read it (same as the x402 SDK wrapper).
|
|
275
|
+
function paidRetryConfig(config) {
|
|
276
|
+
const originalValidateStatus = config.validateStatus;
|
|
277
|
+
return {
|
|
278
|
+
...config,
|
|
279
|
+
headers: cloneHeaders(config.headers),
|
|
280
|
+
validateStatus: (status) =>
|
|
281
|
+
status === 402
|
|
282
|
+
? true
|
|
283
|
+
: originalValidateStatus
|
|
284
|
+
? originalValidateStatus(status)
|
|
285
|
+
: status >= 200 && status < 300,
|
|
286
|
+
};
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
/**
|
|
290
|
+
* Axios wrapper: on a 402, parse PAYMENT-REQUIRED, ask the client for a signed
|
|
291
|
+
* payload (policies + guard run there), and retry once with PAYMENT-SIGNATURE.
|
|
292
|
+
* The payment request is never retried twice, and a retry that is still 402 is
|
|
293
|
+
* returned to the caller instead of looping.
|
|
294
|
+
*/
|
|
295
|
+
export function wrapAxiosWithPayment(axiosInstance, client) {
|
|
296
|
+
axiosInstance.interceptors.response.use(
|
|
297
|
+
(response) => response,
|
|
298
|
+
async (error) => {
|
|
299
|
+
const response = error?.response;
|
|
300
|
+
if (!response || response.status !== 402) return Promise.reject(error);
|
|
301
|
+
|
|
302
|
+
const originalConfig = error.config;
|
|
303
|
+
if (!originalConfig || !originalConfig.headers) {
|
|
304
|
+
return Promise.reject(new Error("Missing axios request configuration"));
|
|
305
|
+
}
|
|
306
|
+
if (originalConfig.__is402Retry) return Promise.reject(error);
|
|
307
|
+
|
|
308
|
+
let paymentRequired;
|
|
309
|
+
try {
|
|
310
|
+
paymentRequired = readPaymentRequired(response);
|
|
311
|
+
} catch (parseError) {
|
|
312
|
+
return Promise.reject(
|
|
313
|
+
new Error(
|
|
314
|
+
`Failed to parse payment requirements: ${
|
|
315
|
+
parseError instanceof Error ? parseError.message : "Unknown error"
|
|
316
|
+
}`,
|
|
317
|
+
),
|
|
318
|
+
);
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
let paymentPayload;
|
|
322
|
+
try {
|
|
323
|
+
paymentPayload = await client.createPaymentPayload(paymentRequired);
|
|
324
|
+
} catch (paymentError) {
|
|
325
|
+
return Promise.reject(
|
|
326
|
+
new Error(
|
|
327
|
+
`Failed to create payment payload: ${
|
|
328
|
+
paymentError instanceof Error ? paymentError.message : "Unknown error"
|
|
329
|
+
}`,
|
|
330
|
+
),
|
|
331
|
+
);
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
const paidConfig = paidRetryConfig(originalConfig);
|
|
335
|
+
paidConfig.__is402Retry = true;
|
|
336
|
+
paidConfig.headers[PAYMENT_SIGNATURE_HEADER] = encodePaymentSignatureHeader(paymentPayload);
|
|
337
|
+
paidConfig.headers["Access-Control-Expose-Headers"] = "PAYMENT-RESPONSE,X-PAYMENT-RESPONSE";
|
|
338
|
+
return axiosInstance.request(paidConfig);
|
|
339
|
+
},
|
|
340
|
+
);
|
|
341
|
+
return axiosInstance;
|
|
342
|
+
}
|