verify402-mcp 1.0.7 → 1.0.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -10,12 +10,12 @@ 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.7` is published to npm and
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` package is immutable; `1.0.5` and `1.0.4` are
18
- > also immutable, and `1.0.4` used Base mainnet by default. Do not republish or
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
21
  ## Tools
@@ -46,9 +46,13 @@ Two optional caller-supplied checks are forwarded as-is:
46
46
  - `payment.idempotencyKey` + `policy.obligation.settledKeys` rejects a key the
47
47
  caller already settled; `policy.obligation.spentUsd` + `grantUsd` rejects
48
48
  cumulative spend over the grant. The bridge does **not** persist this state.
49
- - `policy.sellerPayoutWallets` binds `payTo` to the seller's known payout
50
- addresses. A mismatch is BLOCK. This is a caller binding, not independent
51
- proof that the seller controls the wallet.
49
+ - `policy.sellerPayoutWallets` is a caller-supplied payout allowlist. A
50
+ mismatch is BLOCK, but a match is not provenance and never adds
51
+ `payee_payout_binding`.
52
+ - `policy.sellerPayoutManifest` fetches a seller-signed manifest from a
53
+ caller-pinned HTTPS origin outside the 402. Only a verified manifest whose
54
+ `payTo` list matches adds `payee_payout_binding`. The response includes
55
+ `payeeBinding` with the source, origin, signer, expiry, and manifest hash.
52
56
 
53
57
  The gate is advisory at this layer: the bridge does not hold the agent's
54
58
  transaction key and cannot stop an agent that ignores the answer. Enforcement
@@ -208,6 +212,10 @@ Once configured, your agent automatically sees the tools in its context. You can
208
212
  - `MAX_PAYMENT_USD` is enforced inside the x402 client, before a signature
209
213
  exists; removing it is a security regression. The caps limit what the bridge
210
214
  can authorize; they do **not** protect a compromised private key.
215
+ - The bridge sends `X-Verify402-Client: verify402-mcp/<version>` and the same
216
+ version in its User-Agent. This is an anonymous label for `/usage`, not an
217
+ account: it contains no wallet, key, or user id, and the server treats it as
218
+ self-declared and spoofable.
211
219
  - `preflight_gate` is a check, not a guarantee. Read `notChecked`: it does not
212
220
  screen recipient reputation or sanctions, audit contracts, simulate full
213
221
  balance deltas, audit the counterparty, independently prove payee ownership,
@@ -217,6 +225,36 @@ Once configured, your agent automatically sees the tools in its context. You can
217
225
  - Use the [reference executor](https://github.com/a32116150-ctrl/verify402/blob/master/examples/preflight-guard.mjs)
218
226
  when you want enforcement rather than advice.
219
227
 
228
+ ## Dependencies and `npm audit`
229
+
230
+ This package no longer depends on `@x402/axios` or `@x402/evm`. The x402 payer
231
+ (PAYMENT-REQUIRED / PAYMENT-SIGNATURE / PAYMENT-RESPONSE, scheme `exact`,
232
+ EIP-3009 authorization) is implemented here on `viem`, and the runtime
233
+ dependency list is: the MCP SDK, axios, dotenv, viem, zod 4.
234
+
235
+ Why: `@x402` 2.28.0 depended on `zod ^3.24.2`, which resolves into
236
+ [GHSA-mrhx-c7xc-m3w5](https://github.com/advisories/GHSA-mrhx-c7xc-m3w5)
237
+ (memory-exhaustion DoS while validating oversized arrays; the advisory covers
238
+ all zod < 4.6.6, and no patched 3.x exists). npm ignores `overrides` declared
239
+ inside a dependency, so installs of 1.0.8 and earlier showed a "high severity"
240
+ audit banner. The upstream request is
241
+ [x402-foundation/x402#3953](https://github.com/x402-foundation/x402/issues/3953).
242
+
243
+ The current package, installed from its tarball:
244
+
245
+ ```console
246
+ $ npm i verify402-mcp
247
+ added 123 packages
248
+ $ npm audit
249
+ found 0 vulnerabilities
250
+ ```
251
+
252
+ The bridge pays the same wire protocol. The only behavior change is cosmetic:
253
+ `npm ls @x402` shows nothing, and the install is 5 packages smaller. The
254
+ paid-call policy (network allowlist, configured payee, canonical USDC,
255
+ per-payment cap, tool-bound resource) is unchanged and still runs before any
256
+ signature exists, in `payment-policy.mjs`.
257
+
220
258
  ## Explicit mainnet configuration (not the public demo)
221
259
 
222
260
  Mainnet settlement is a separate deployment choice, not a bridge or demo
package/client-id.mjs ADDED
@@ -0,0 +1,17 @@
1
+ // One shared, anonymous client label for every request the bridge makes.
2
+ //
3
+ // This is not an identity: it contains no wallet, key, account, or user id, and
4
+ // the server treats it as a self-declared hint. Its only job is to let /usage
5
+ // separate bridge traffic from generic HTTP probes. The version comes from the
6
+ // package manifest so a release bump cannot leave the label stale.
7
+
8
+ import { readFileSync } from "node:fs";
9
+
10
+ const pkg = JSON.parse(readFileSync(new URL("./package.json", import.meta.url), "utf8"));
11
+
12
+ export const CLIENT_ID = "verify402-mcp";
13
+ export const VERSION = pkg.version;
14
+ export const CLIENT_HEADERS = Object.freeze({
15
+ "User-Agent": `${CLIENT_ID}/${VERSION}`,
16
+ "X-Verify402-Client": `${CLIENT_ID}/${VERSION}`,
17
+ });
package/index.mjs CHANGED
@@ -14,23 +14,26 @@
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
- // x402Client's spend controls enforce the USD cap and the default-asset
19
- // (USDC) allowlist; payment-policy.mjs then enforces the network allowlist,
20
- // the verify402 payee, and a known paid resource on the configured server.
21
- // Redirects are refused. An MCP server that signs anything any remote 402
22
- // asks for is a blank cheque. This one is not.
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 "@x402/axios";
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";
32
34
  import { installConsoleRedaction, logInfo, logError } from "./log.mjs";
33
35
  import { paidPost } from "./paid-call.mjs";
36
+ import { CLIENT_HEADERS, VERSION } from "./client-id.mjs";
34
37
  import { fileURLToPath } from "node:url";
35
38
  import { realpathSync } from "node:fs";
36
39
  import { AsyncLocalStorage } from "node:async_hooks";
@@ -42,27 +45,22 @@ installConsoleRedaction();
42
45
  const IS_MAIN = isMainModule();
43
46
  if (IS_MAIN) config();
44
47
 
45
- const VERSION = "1.0.7";
46
48
  const EVM_PRIVATE_KEY = process.env.EVM_PRIVATE_KEY;
47
49
  // Normalise once so the axios base URL, the payment policy prefix, and the
48
50
  // per-tool expected resource are all the same string (no trailing slash).
49
51
  const SERVER_URL = (process.env.VERIFY402_URL || "https://verify402.onrender.com")
50
52
  .trim()
51
53
  .replace(/\/+$/, "");
52
- // Tell the server which client made the call. This is a label, not an identity:
53
- // it helps separate MCP use from generic HTTP probes without collecting keys or
54
- // wallet addresses.
55
- const CLIENT_HEADERS = {
56
- "User-Agent": `verify402-mcp/${VERSION}`,
57
- "X-Verify402-Client": `mcp/${VERSION}`,
58
- };
54
+ // CLIENT_HEADERS is a label, not an identity: it helps /usage separate MCP
55
+ // calls from generic HTTP probes without collecting keys or wallet addresses.
59
56
  // Preflight is free, so it does not go through the paying client. Keeping the
60
57
  // two clients separate means a misconfigured 402 on a free route can never
61
58
  // turn into a signature.
62
59
  const freeApi = axios.create({ baseURL: SERVER_URL, timeout: 30_000, maxRedirects: 0, headers: CLIENT_HEADERS });
63
- // Spend guard: the x402 client refuses to SIGN any payment above this, before
64
- // a signature exists. Enforced inside x402Client (applySpendControls), not by
65
- // our own request code - so it cannot be bypassed by a caller.
60
+ // Spend guard: the payer refuses to SIGN any payment above this, before a
61
+ // signature exists. Enforced by the pre-signature guard in payment-policy.mjs
62
+ // (validatePaymentChallenge), not by request code - so it cannot be bypassed
63
+ // by a caller.
66
64
  const MAX_PAYMENT_USD = Number(process.env.MAX_PAYMENT_USD || 0.25);
67
65
 
68
66
  // Free-only mode is deliberate: an agent can install the bridge and call the
@@ -146,11 +144,11 @@ export function createBridgeClientFromEnv() {
146
144
  policies: [(version, requirements) => policy.filter(version, requirements)],
147
145
  });
148
146
  for (const network of policy.allowedNetworks) {
149
- client.register(network, new ExactEvmScheme(account));
147
+ client.register(network, createExactEvmScheme(account));
150
148
  }
151
149
  // Full-challenge guard (version, every EVM offer, canonical asset/domain,
152
150
  // payee, amount cap, timeout, EIP-3009) plus the resource/route layer. It
153
- // runs after the SDK has selected a requirement and before the signer.
151
+ // runs after the client has selected a requirement and before the signer.
154
152
  // The expected resource is resolved per invocation from the tool handler
155
153
  // context, never from the 402 challenge.
156
154
  client.onBeforePaymentCreation(
@@ -223,7 +221,8 @@ const DESCRIPTIONS = {
223
221
  "Free. Pass `from` (the wallet that will sign) to enable simulation and balance checks. For " +
224
222
  "kind=transaction, chainId is REQUIRED (400 missing_chain without it). For payment intents " +
225
223
  "with no `from` or no proof, the response is PASS with structural_only:true and names what was not checked. " +
226
- "Optional caller-supplied checks: policy.sellerPayoutWallets binds payTo to the seller's payout addresses; " +
224
+ "Optional caller-supplied checks: policy.sellerPayoutWallets is a payout allowlist, not provenance; " +
225
+ "policy.sellerPayoutManifest fetches a seller-signed manifest from a caller-pinned HTTPS origin and is the only source of payee_payout_binding; " +
227
226
  "policy.obligation checks a local settled-key ledger and cumulative spend against a grant. The gate does not persist either state.",
228
227
  verify_arbitrage:
229
228
  "Ask verify402 whether a cross-venue arbitrage opportunity is REAL, right now. " +
@@ -293,7 +292,11 @@ async function main() {
293
292
  allowedFacilitators: z.array(z.string()).optional().describe("Allowlist of x402 facilitators"),
294
293
  expectedResource: z.string().optional().describe("The exact resource URL the agent intends to pay for"),
295
294
  allowedResourceHosts: z.array(z.string()).optional().describe("Bare hostnames allowed in payment.resource; a foreign host is BLOCK"),
296
- sellerPayoutWallets: z.array(z.string()).optional().describe("Caller-supplied seller payout addresses; a payTo mismatch is BLOCK. This is a binding, not independent ownership proof"),
295
+ sellerPayoutWallets: z.array(z.string()).optional().describe("Caller-supplied seller payout allowlist; a payTo mismatch is BLOCK. This is not provenance and never adds payee_payout_binding"),
296
+ sellerPayoutManifest: z.object({
297
+ url: z.string().url().describe("HTTPS URL of a seller-signed manifest outside the 402"),
298
+ expectedSigner: z.string().optional().describe("Optional EVM address pin for the manifest signer"),
299
+ }).optional().describe("Seller-signed payout manifest; the only source of payee_payout_binding"),
297
300
  obligation: z.object({
298
301
  settledKeys: z.array(z.string()).optional().describe("Payment idempotency keys already settled"),
299
302
  spentUsd: z.number().nonnegative().optional().describe("Already spent under the grant, in USD"),
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "verify402-mcp",
3
- "version": "1.0.7",
3
+ "version": "1.0.9",
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,15 +9,17 @@
9
9
  },
10
10
  "main": "index.mjs",
11
11
  "files": [
12
- "index.mjs",
12
+ ".env.example",
13
13
  "budget.mjs",
14
- "payment-policy.mjs",
15
- "paid-call.mjs",
14
+ "client-id.mjs",
15
+ "index.mjs",
16
+ "LICENSE",
16
17
  "log.mjs",
18
+ "NOTICE",
19
+ "paid-call.mjs",
20
+ "payment-policy.mjs",
17
21
  "README.md",
18
- ".env.example",
19
- "LICENSE",
20
- "NOTICE"
22
+ "x402-client.mjs"
21
23
  ],
22
24
  "scripts": {
23
25
  "start": "node index.mjs",
@@ -54,8 +56,6 @@
54
56
  },
55
57
  "dependencies": {
56
58
  "@modelcontextprotocol/sdk": "^1.12.1",
57
- "@x402/axios": "2.28.0",
58
- "@x402/evm": "2.28.0",
59
59
  "axios": "^1.13.2",
60
60
  "dotenv": "^16.4.5",
61
61
  "viem": "^2.39.0",
@@ -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 both by
12
- // x402Client's spendControls and by validatePaymentChallenge(), which runs
13
- // before the signing hook in first-payment.mjs and index.mjs. Redirects are
14
- // refused by the axios clients in index.mjs and first-payment.mjs.
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 SDK signs
28
- // `validBefore = now + maxTimeoutSeconds`; an unbounded value hands the payee a
29
- // long-lived transferable authorization. 300 seconds is the documented cap and
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 mirror the installed @x402/evm default-asset table.
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 the SDK happens to recognise.
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
- * installed SDK selects EIP-3009 unless `extra.assetTransferMethod === "permit2"`,
115
- * so permit2 (and any unvalidated extension key) is refused here.
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
- * x402Client policy: runs after spend controls and before the selector.
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
- * x402Client onBeforePaymentCreation hook: runs after selection and before
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 SDK's selected requirement is the exact object that
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 x402Client.onBeforePaymentCreation().
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 SDK selector returns an element of
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" };
@@ -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
+ }