concordium-x402-guard 0.1.1 → 0.2.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.
package/README.md CHANGED
@@ -2,11 +2,24 @@
2
2
 
3
3
  Check an x402 seller on Concordium **before your agent pays it**. Wrap the `@x402/fetch` client your agent already uses; any payment it would make is checked first, and if a check fails the wallet is never asked to sign.
4
4
 
5
+ **No code, just a look** (Node 22+, nothing is paid, no wallet):
6
+
7
+ ```bash
8
+ npx concordium-x402-guard check https://web-gilt-phi-11.vercel.app/api/packs/rehearsal-btc-150k
9
+ npx concordium-x402-guard check https://mainsmarker.sites.tab.bot/x402/review --json '{"question":"Why is the sky blue?","answer":"Rayleigh scattering.","marks":10}'
10
+ ```
11
+
12
+ Exit code 0 means every check passed, 1 means refused, 2 means it could not run. Add `--network mainnet` for mainnet agents, `--json-out` for machine-readable output.
13
+
14
+ **In your agent:**
15
+
5
16
  ```bash
6
- npm install concordium-x402-guard @x402/fetch @x402/concordium
17
+ npm install concordium-x402-guard @x402/fetch @x402/core @x402/concordium
7
18
  ```
8
19
 
9
- The package is **ESM only** (Node 22+): use a `.mjs` file or `"type": "module"` in your package.json. `require()` is not supported. In TypeScript, add `@types/node` (the public types use `Buffer`).
20
+ `@x402/fetch` and `@x402/core` are peer dependencies, so the guard wraps the very `x402Client` your agent already has (one copy, your version). `@x402/concordium` is only for the payment scheme in the example below.
21
+
22
+ The package is **ESM only** and needs Node 22 or newer: use a `.mjs` file or `"type": "module"` in your package.json. `require()` is not supported. In TypeScript, add `@types/node` (the public types use `Buffer`).
10
23
 
11
24
  ```ts
12
25
  import { x402Client } from "@x402/fetch";
@@ -62,14 +75,22 @@ The site the agent called is the one checked (never the 402's own `resource.url`
62
75
 
63
76
  - MainsMarker, agent #990 (testnet, another team): all checks pass; paid and received the service.
64
77
  - x402 Doctor, agent #5120 (**mainnet**): all checks pass, including its Base `payTo` bound in CIS-8 through its `external_reference`.
65
- - vet402, agent #1268 (testnet): refused at check 5, because its `payTo` is not its registered wallet.
78
+ - Oracle Scout, agent #1253 (testnet, another team): all checks pass.
79
+ - vet402, agent #1268, and its test sellers S2 and S3 (testnet): refused at check 5, because the `payTo` is not the registered wallet. S3 takes payment and returns nothing.
80
+ - Clear to Pay (testnet): refused at check 1, no Agent Card on its site.
66
81
 
67
82
  Output of those runs: <https://github.com/jiahaoc040-ai/veriflow/tree/main/docs/evidence>.
68
83
 
69
84
  ## Changes
70
85
 
86
+ 0.2.1: the `npx` command is actually included (0.2.0 was published without it).
87
+
88
+ 0.2.0: `npx concordium-x402-guard check <url>`; `@x402/fetch` and `@x402/core` are peer dependencies; Node 22+ declared; an Agent Card host name that resolves to a private address is refused.
89
+
71
90
  0.1.1: payment network pinned to the configured network; badge sub-checks enforced; Agent Card fetched only from public https hosts and only after the record is confirmed; payTo compared alias-aware; CIS-8 owner compared in code (owner or agentWallet); strict secp256k1 key types; retries see `error.cause`, timeouts and HTTP status; registry responses capped, no redirects; clear error for a wrong `network`; delivery verdicts case-insensitive and capped. Thanks to an outside review for every one of these.
72
91
 
92
+ Tests: 28 unit tests (`npm test`, no network: fake registry, node, cards and delivery records), run in CI.
93
+
73
94
  ## Networks
74
95
 
75
96
  | | Agent Registry | CIS-8 | Public node |
@@ -0,0 +1,3 @@
1
+ #!/usr/bin/env node
2
+ // Kept in git so npm sees the bin file before the build; the CLI itself is dist/cli.js
3
+ import "../dist/cli.js";
package/dist/cli.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
package/dist/cli.js ADDED
@@ -0,0 +1,49 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * npx concordium-x402-guard check <url> [--method POST] [--json '<body>'] [--network testnet|mainnet]
4
+ * [--reputation off|advisory|block-no|require-go] [--pay-network <caip2>] [--json-out]
5
+ * Reads the seller's 402 and runs the checks. No wallet, nothing is paid. Exit code 0 = checks pass, 1 = refused, 2 = usage/error.
6
+ */
7
+ import { checkSellerAt, summarize } from "./guard.js";
8
+ import { concordiumGuardDeps } from "./deps.js";
9
+ const USAGE = `usage: npx concordium-x402-guard check <https-url> [--method GET|POST] [--json '<body>'] [--network testnet|mainnet]
10
+ [--reputation off|advisory|block-no|require-go] [--pay-network <caip2>] [--json-out]
11
+ Reads the seller's x402 402 answer and checks the seller on Concordium. No wallet; nothing is paid.`;
12
+ const [cmd, url, ...rest] = process.argv.slice(2);
13
+ const opt = (n) => {
14
+ const i = rest.indexOf(`--${n}`);
15
+ return i >= 0 ? rest[i + 1] : undefined;
16
+ };
17
+ if (cmd !== "check" || !url || !/^https?:\/\//.test(url) || rest.includes("--help")) {
18
+ console.error(USAGE);
19
+ process.exit(2);
20
+ }
21
+ const network = (opt("network") ?? "testnet");
22
+ const reputation = opt("reputation");
23
+ if (reputation && !["off", "advisory", "block-no", "require-go"].includes(reputation)) {
24
+ console.error(USAGE);
25
+ process.exit(2);
26
+ }
27
+ const body = opt("json");
28
+ const init = { method: (opt("method") ?? (body ? "POST" : "GET")).toUpperCase(), ...(body ? { body, headers: { "content-type": "application/json" } } : {}) };
29
+ const why = (x) => (x instanceof Error ? `${x.message}${x.cause ? ` (${why(x.cause)})` : ""}` : String(x));
30
+ try {
31
+ const deps = concordiumGuardDeps({ network });
32
+ const { verdict, options, picked } = await checkSellerAt(url, init, deps, reputation ? { reputation } : {}, opt("pay-network"));
33
+ if (rest.includes("--json-out")) {
34
+ console.log(JSON.stringify({ ...verdict, summary: summarize(verdict), picked, options }, null, 2));
35
+ }
36
+ else {
37
+ const amount = (a) => (a.asset === "CCD" ? `${Number(a.amount) / 1e6} CCD` : `${a.amount ?? "?"} ${a.asset ?? ""} (smallest unit)`);
38
+ console.log(`${url} asks to be paid: ${options.map((a) => `${amount(a)} on ${a.network} to ${a.payTo}`).join(" | ")}`);
39
+ console.log(`checking the ${amount(picked)} option on ${picked.network} against Concordium ${network} (nothing is paid)\n`);
40
+ console.log(`Seller behind ${verdict.origin}${verdict.tokenId ? `: agent #${verdict.tokenId}` : ""}`);
41
+ verdict.checks.forEach((c, i) => console.log(` ${c.ok ? "✓" : "✗"} ${i + 1}. ${c.name}\n ${c.detail}`));
42
+ console.log(`\n${verdict.ok ? "✅" : "⛔"} ${summarize(verdict)}`);
43
+ }
44
+ process.exit(verdict.ok ? 0 : 1);
45
+ }
46
+ catch (e) {
47
+ console.error(`${url}: ${why(e)}`);
48
+ process.exit(2);
49
+ }
package/dist/seller.d.ts CHANGED
@@ -60,10 +60,17 @@ export declare function verifySeller(opts: {
60
60
  }): Promise<SellerVerdict>;
61
61
  /** One-line summary for people */
62
62
  export declare function summarize(v: SellerVerdict): string;
63
+ /** A loopback, private, carrier-grade NAT, link-local or unique-local address (IPv4 or IPv6, literal) */
64
+ export declare function isPrivateAddress(host: string): boolean;
63
65
  /**
64
66
  * An Agent Card URL the buyer may fetch: https to a public host name or address. Loopback, private and link-local
65
- * addresses written as literals are refused (a host name that resolves to one is not checked here).
67
+ * addresses written as literals are refused here; `cardHostIsPublic` also checks what a host name resolves to.
66
68
  */
67
69
  export declare function cardUrlAllowed(url: string, allowLocalHttp?: boolean): void;
70
+ /**
71
+ * A host name in an on-chain agent_uri must not resolve to a private address either (the owner can point its name anywhere).
72
+ * A name that does not resolve is left to the fetch, which then fails. (DNS can still change between this lookup and the fetch.)
73
+ */
74
+ export declare function cardHostIsPublic(url: string): Promise<void>;
68
75
  /** Same Concordium account, aliases included; false for anything that is not an account address */
69
76
  export declare function sameAccountSafe(a: string, b: string): boolean;
package/dist/seller.js CHANGED
@@ -134,6 +134,8 @@ export async function verifySeller(opts) {
134
134
  if (!rec.agent_uri)
135
135
  throw new Error("no agent_uri on-chain");
136
136
  cardUrlAllowed(rec.agent_uri, opts.allowLocalHttpCards === true);
137
+ if (opts.allowLocalHttpCards !== true)
138
+ await cardHostIsPublic(rec.agent_uri);
137
139
  const r = await f(rec.agent_uri, { redirect: "error", signal: AbortSignal.timeout(10_000) });
138
140
  if (!r.ok)
139
141
  throw new Error(`HTTP ${r.status}`);
@@ -172,9 +174,18 @@ export function summarize(v) {
172
174
  ? `seller verified: agent #${v.tokenId} (${v.tokenAddress}), owner ${v.owner}, ${v.checks[4]?.name.includes("CIS-8") ? "paying an EVM address bound to it in CIS-8" : "paying its on-chain wallet"}`
173
175
  : `refused to pay: ${bad.map((c) => `${c.name} — ${c.detail}`).join("; ")}`;
174
176
  }
177
+ /** A loopback, private, carrier-grade NAT, link-local or unique-local address (IPv4 or IPv6, literal) */
178
+ export function isPrivateAddress(host) {
179
+ const h = host.replace(/^\[|\]$/g, "").toLowerCase();
180
+ if (h === "localhost" || h.endsWith(".localhost") || h === "::1" || h === "::" || h === "0.0.0.0")
181
+ return true;
182
+ if (/^(10\.|127\.|0\.|169\.254\.|192\.168\.|172\.(1[6-9]|2\d|3[01])\.|100\.(6[4-9]|[7-9]\d|1[01]\d|12[0-7])\.)/.test(h))
183
+ return true;
184
+ return h.includes(":") && (/^(fc|fd|fe8|fe9|fea|feb)/.test(h) || h.startsWith("::ffff:"));
185
+ }
175
186
  /**
176
187
  * An Agent Card URL the buyer may fetch: https to a public host name or address. Loopback, private and link-local
177
- * addresses written as literals are refused (a host name that resolves to one is not checked here).
188
+ * addresses written as literals are refused here; `cardHostIsPublic` also checks what a host name resolves to.
178
189
  */
179
190
  export function cardUrlAllowed(url, allowLocalHttp = false) {
180
191
  let u;
@@ -190,11 +201,28 @@ export function cardUrlAllowed(url, allowLocalHttp = false) {
190
201
  return;
191
202
  if (u.protocol !== "https:")
192
203
  throw new Error(`agent_uri is not https: ${url.slice(0, 80)}`);
193
- const privateV4 = /^(10\.|127\.|0\.|169\.254\.|192\.168\.|172\.(1[6-9]|2\d|3[01])\.|100\.(6[4-9]|[7-9]\d|1[01]\d|12[0-7])\.)/.test(host);
194
- const privateV6 = host.includes(":") && (host === "::1" || /^(fc|fd|fe8|fe9|fea|feb)/.test(host) || host.startsWith("::ffff:"));
195
- if (local || privateV4 || privateV6)
204
+ if (isPrivateAddress(host))
196
205
  throw new Error(`agent_uri points at a local or private address: ${host}`);
197
206
  }
207
+ /**
208
+ * A host name in an on-chain agent_uri must not resolve to a private address either (the owner can point its name anywhere).
209
+ * A name that does not resolve is left to the fetch, which then fails. (DNS can still change between this lookup and the fetch.)
210
+ */
211
+ export async function cardHostIsPublic(url) {
212
+ const host = new URL(url).hostname.replace(/^\[|\]$/g, "");
213
+ if (/^[\d.]+$/.test(host) || host.includes(":"))
214
+ return; // literals were checked by cardUrlAllowed
215
+ let addrs;
216
+ try {
217
+ addrs = await (await import("node:dns/promises")).lookup(host, { all: true, verbatim: true });
218
+ }
219
+ catch {
220
+ return;
221
+ }
222
+ const bad = addrs.find((a) => isPrivateAddress(a.address));
223
+ if (bad)
224
+ throw new Error(`agent_uri host ${host} resolves to a private address`);
225
+ }
198
226
  /** Same Concordium account, aliases included; false for anything that is not an account address */
199
227
  export function sameAccountSafe(a, b) {
200
228
  try {
package/package.json CHANGED
@@ -1,11 +1,14 @@
1
1
  {
2
2
  "name": "concordium-x402-guard",
3
- "version": "0.1.1",
3
+ "version": "0.2.1",
4
4
  "description": "Check an x402 seller on Concordium before your agent pays it: Agent Registry badge, Active, Agent Card hash, payTo bound to the agent on-chain (CIS-8004 / CIS-8).",
5
5
  "license": "MIT",
6
6
  "type": "module",
7
7
  "main": "./dist/index.js",
8
8
  "types": "./dist/index.d.ts",
9
+ "bin": {
10
+ "concordium-x402-guard": "bin/concordium-x402-guard.js"
11
+ },
9
12
  "exports": {
10
13
  ".": {
11
14
  "types": "./dist/index.d.ts",
@@ -14,11 +17,12 @@
14
17
  },
15
18
  "files": [
16
19
  "dist",
20
+ "bin",
17
21
  "README.md",
18
22
  "LICENSE"
19
23
  ],
20
24
  "engines": {
21
- "node": ">=20"
25
+ "node": ">=22"
22
26
  },
23
27
  "repository": {
24
28
  "type": "git",
@@ -42,12 +46,16 @@
42
46
  "dependencies": {
43
47
  "@concordium/web-sdk": "^12.0.2",
44
48
  "@noble/curves": "^1.9.7",
45
- "@noble/hashes": "^1.8.0",
49
+ "@noble/hashes": "^1.8.0"
50
+ },
51
+ "peerDependencies": {
46
52
  "@x402/core": "^2.31.0",
47
53
  "@x402/fetch": "^2.31.0"
48
54
  },
49
55
  "devDependencies": {
50
56
  "@types/node": "^26.6.6",
57
+ "@x402/core": "^2.31.0",
58
+ "@x402/fetch": "^2.31.0",
51
59
  "tsx": "^4.23.15",
52
60
  "typescript": "^7.0.2"
53
61
  },