concordium-x402-guard 0.1.0 → 0.2.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/README.md +60 -9
- package/dist/cis8.js +5 -1
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +49 -0
- package/dist/deps.d.ts +17 -3
- package/dist/deps.js +101 -14
- package/dist/guard.d.ts +15 -2
- package/dist/guard.js +14 -10
- package/dist/index.d.ts +3 -3
- package/dist/index.js +2 -2
- package/dist/seller.d.ts +16 -0
- package/dist/seller.js +70 -7
- package/package.json +10 -3
package/README.md
CHANGED
|
@@ -2,18 +2,50 @@
|
|
|
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
|
+
|
|
16
|
+
```bash
|
|
17
|
+
npm install concordium-x402-guard @x402/fetch @x402/core @x402/concordium
|
|
18
|
+
```
|
|
19
|
+
|
|
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`).
|
|
23
|
+
|
|
5
24
|
```ts
|
|
6
25
|
import { x402Client } from "@x402/fetch";
|
|
26
|
+
import { ExactConcordiumScheme } from "@x402/concordium/exact/client";
|
|
7
27
|
import { protect, concordiumGuardDeps } from "concordium-x402-guard";
|
|
8
28
|
|
|
9
|
-
const
|
|
29
|
+
const TESTNET = "ccd:4221332d34e1694168c2a0c0b3fd0f27";
|
|
30
|
+
// Your client as today: at least one scheme registered for the network you pay on, or no payment can be made at all
|
|
31
|
+
const client = x402Client.fromConfig({
|
|
32
|
+
schemes: [{ network: TESTNET, client: new ExactConcordiumScheme({ accountAddress, signer }) }],
|
|
33
|
+
spendControls: { allowedAssets: [{ network: TESTNET, asset: "CCD", maxAmountPerPayment: "2000000" }] },
|
|
34
|
+
});
|
|
10
35
|
const guarded = protect(client, concordiumGuardDeps({ network: "testnet" })); // or "mainnet"
|
|
11
36
|
|
|
12
37
|
const { response, verdict, error } = await guarded.fetch("https://seller.example/x402/thing", { method: "POST", body });
|
|
13
|
-
if (!response)
|
|
38
|
+
if (!response) {
|
|
39
|
+
if (verdict && !verdict.ok) console.log("refused, nothing signed:", verdict.checks); // check by check
|
|
40
|
+
else console.error("request failed before the guard ran:", error); // e.g. no scheme for this network, spend limit
|
|
41
|
+
}
|
|
14
42
|
```
|
|
15
43
|
|
|
16
|
-
|
|
44
|
+
How a refusal looks: `response` is undefined, `verdict.ok` is false with every check listed, and `error` is also set (x402's "Payment creation aborted: refused to pay: …"). If `verdict` is undefined, the guard never saw a payment (a non-402 answer, or the x402 client failed first). `protect` accepts any `x402Client` from `@x402/fetch`, ESM or CommonJS build.
|
|
45
|
+
|
|
46
|
+
`network` is the **Concordium** network the checks read: `"testnet"` or `"mainnet"` (default testnet); anything else throws. It also pins what can be paid: a Concordium payment only on that network, an EVM payment only on its Base chain (Base Sepolia for testnet, Base for mainnet). A testnet agent never approves a mainnet payment.
|
|
47
|
+
|
|
48
|
+
No payment, just a look: `checkSellerAt(url, init, concordiumGuardDeps())` returns the verdict for the seller behind an x402 endpoint. It reads an x402 **v2** 402 (the `PAYMENT-REQUIRED` header); a v1 body-only 402 is not supported there.
|
|
17
49
|
|
|
18
50
|
## What it checks
|
|
19
51
|
|
|
@@ -21,12 +53,21 @@ No payment, just a look: `checkSellerAt(url, init, concordiumGuardDeps())` retur
|
|
|
21
53
|
|---|---|---|
|
|
22
54
|
| 1 | The site you called advertises a Verified by Concordium badge in its Agent Card | the seller's `/.well-known/agent-card.json` |
|
|
23
55
|
| 2 | That badge's agent is registered and **Active** in the CIS-8004 Agent Registry | a Concordium node (the hosted registry service only resolves the badge to a token id; if the two disagree, no payment) |
|
|
24
|
-
| 3 | Concordium's official badge check passes (identity-verified owner) | the hosted Agent Registry service |
|
|
25
|
-
| 4 | The Agent Card's own SHA-256 equals the hash pinned on-chain | the card URL on-chain, hashed here |
|
|
26
|
-
| 5 | `payTo` is the agent's on-chain `agentWallet
|
|
27
|
-
| 6 | Optional
|
|
56
|
+
| 3 | Concordium's official badge check passes, every sub-check included (identity-verified owner) | the hosted Agent Registry service |
|
|
57
|
+
| 4 | The Agent Card's own SHA-256 equals the hash pinned on-chain | the card URL on-chain (https on a public host only, at most 64 KB, no redirects), hashed here |
|
|
58
|
+
| 5 | `payTo` is the agent's on-chain `agentWallet` (any alias of that account); for an EVM `payTo`, its key is bound in the CIS-8 External Key Registry to the agent's owner or to its `agentWallet` (key from the 402's `extra.cis8` or the agent's own `external_reference`) | a Concordium node |
|
|
59
|
+
| 6 | Optional: an independent delivery record from vet402 (another team's service, testnet only) | `vet402-concordium.fly.dev` |
|
|
60
|
+
|
|
61
|
+
Checks 1–5 fail closed: an unreachable node or registry, a changed card or a revoked binding means no payment. Reads are retried three times on a dropped connection, a timeout, a 429 or a 5xx.
|
|
28
62
|
|
|
29
|
-
|
|
63
|
+
Check 6 is a third party's opinion, so it is **not** fail-closed by default. `reputation` in the policy (third argument of `protect`) decides:
|
|
64
|
+
|
|
65
|
+
| mode | blocks when | default |
|
|
66
|
+
|---|---|---|
|
|
67
|
+
| `"off"` | never (not asked) | mainnet (vet402 records testnet only) |
|
|
68
|
+
| `"block-no"` | the record says `no` (proven non-delivery); `unproven` or an unreachable service does not block | testnet |
|
|
69
|
+
| `"require-go"` | anything but `go`, including no answer: fail-closed | |
|
|
70
|
+
| `"advisory"` | never; the verdict is only reported | |
|
|
30
71
|
|
|
31
72
|
The site the agent called is the one checked (never the 402's own `resource.url`), and payments started outside `guarded.fetch` are refused.
|
|
32
73
|
|
|
@@ -34,10 +75,20 @@ The site the agent called is the one checked (never the 402's own `resource.url`
|
|
|
34
75
|
|
|
35
76
|
- MainsMarker, agent #990 (testnet, another team): all checks pass; paid and received the service.
|
|
36
77
|
- x402 Doctor, agent #5120 (**mainnet**): all checks pass, including its Base `payTo` bound in CIS-8 through its `external_reference`.
|
|
37
|
-
-
|
|
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.
|
|
38
81
|
|
|
39
82
|
Output of those runs: <https://github.com/jiahaoc040-ai/veriflow/tree/main/docs/evidence>.
|
|
40
83
|
|
|
84
|
+
## Changes
|
|
85
|
+
|
|
86
|
+
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.
|
|
87
|
+
|
|
88
|
+
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.
|
|
89
|
+
|
|
90
|
+
Tests: 28 unit tests (`npm test`, no network: fake registry, node, cards and delivery records), run in CI.
|
|
91
|
+
|
|
41
92
|
## Networks
|
|
42
93
|
|
|
43
94
|
| | Agent Registry | CIS-8 | Public node |
|
package/dist/cis8.js
CHANGED
|
@@ -27,7 +27,11 @@ export function encodeExternalKey(k) {
|
|
|
27
27
|
export function sameExternalKey(got, asked) {
|
|
28
28
|
if (got.namespace !== asked.namespace)
|
|
29
29
|
return false;
|
|
30
|
-
|
|
30
|
+
// Only the two secp256k1 key types are compared as points; any other "secp256k1…" name is not one of them
|
|
31
|
+
const SECP = ["secp256k1-compressed", "secp256k1-uncompressed"];
|
|
32
|
+
if (SECP.includes(got.keyType) || SECP.includes(asked.keyType)) {
|
|
33
|
+
if (!SECP.includes(got.keyType) || !SECP.includes(asked.keyType))
|
|
34
|
+
return false;
|
|
31
35
|
try {
|
|
32
36
|
return compressed(got.publicKey).equals(compressed(asked.publicKey));
|
|
33
37
|
}
|
package/dist/cli.d.ts
ADDED
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/deps.d.ts
CHANGED
|
@@ -8,10 +8,16 @@ import { type NetworkName } from "./networks.js";
|
|
|
8
8
|
import type { GuardDeps } from "./guard.js";
|
|
9
9
|
import type { RegistryCall } from "./seller.js";
|
|
10
10
|
export declare const DEFAULT_REGISTRY_MCP = "https://agent-registry-mcp.concordium.com/mcp";
|
|
11
|
-
/** Call one tool of the hosted Agent Registry MCP service (JSON-RPC over HTTP) */
|
|
11
|
+
/** Call one tool of the hosted Agent Registry MCP service (JSON-RPC over HTTP). No redirects, a capped body, HTTP 429/5xx thrown as such */
|
|
12
12
|
export declare function registryMcp(url?: string, f?: typeof fetch): RegistryCall;
|
|
13
|
-
/**
|
|
14
|
-
export declare
|
|
13
|
+
/** A retryable HTTP answer (429 or 5xx) */
|
|
14
|
+
export declare class HttpStatusError extends Error {
|
|
15
|
+
readonly status: number;
|
|
16
|
+
constructor(status: number);
|
|
17
|
+
}
|
|
18
|
+
export declare function isTransient(e: unknown): boolean;
|
|
19
|
+
/** Retry a read on a dropped connection, a timeout, a 429 or a 5xx, three tries in all; anything else is thrown at once. `onTransient` runs before each retry (e.g. to drop a dead connection) */
|
|
20
|
+
export declare function retrying<T>(f: () => Promise<T>, tries?: number, waitMs?: number, onTransient?: () => void): Promise<T>;
|
|
15
21
|
export type DepsOptions = {
|
|
16
22
|
network?: NetworkName;
|
|
17
23
|
/** Your own node client; default: Concordium's public node for the network */
|
|
@@ -19,4 +25,12 @@ export type DepsOptions = {
|
|
|
19
25
|
registryMcpUrl?: string;
|
|
20
26
|
fetch?: typeof fetch;
|
|
21
27
|
};
|
|
28
|
+
/**
|
|
29
|
+
* Whom a CIS-8 binding may name: the agent's owner, or its agentWallet (the payout account the owner set on-chain;
|
|
30
|
+
* an operator may keep its EVM key under that account). Anything else is refused. Alias-aware.
|
|
31
|
+
*/
|
|
32
|
+
export declare function boundAs(bound: string, agent: {
|
|
33
|
+
owner?: string;
|
|
34
|
+
wallet?: string;
|
|
35
|
+
}): "owner" | "agentWallet" | undefined;
|
|
22
36
|
export declare function concordiumGuardDeps(o?: DepsOptions): GuardDeps;
|
package/dist/deps.js
CHANGED
|
@@ -9,7 +9,27 @@ import { NETWORKS } from "./networks.js";
|
|
|
9
9
|
import { readAgent, sameAccount } from "./agent-record.js";
|
|
10
10
|
import { checkEvmBinding, ownerOfKey, uncompressed, EVM_KEY_TYPE } from "./cis8.js";
|
|
11
11
|
export const DEFAULT_REGISTRY_MCP = "https://agent-registry-mcp.concordium.com/mcp";
|
|
12
|
-
/**
|
|
12
|
+
/** Read a response body, refusing more than `max` bytes */
|
|
13
|
+
async function textCapped(res, max = 256 * 1024) {
|
|
14
|
+
const reader = res.body?.getReader();
|
|
15
|
+
if (!reader)
|
|
16
|
+
return "";
|
|
17
|
+
const parts = [];
|
|
18
|
+
let n = 0;
|
|
19
|
+
for (;;) {
|
|
20
|
+
const { done, value } = await reader.read();
|
|
21
|
+
if (done)
|
|
22
|
+
break;
|
|
23
|
+
n += value.byteLength;
|
|
24
|
+
if (n > max) {
|
|
25
|
+
await reader.cancel().catch(() => { });
|
|
26
|
+
throw new Error(`registry response over ${max} bytes`);
|
|
27
|
+
}
|
|
28
|
+
parts.push(value);
|
|
29
|
+
}
|
|
30
|
+
return Buffer.concat(parts).toString("utf8");
|
|
31
|
+
}
|
|
32
|
+
/** Call one tool of the hosted Agent Registry MCP service (JSON-RPC over HTTP). No redirects, a capped body, HTTP 429/5xx thrown as such */
|
|
13
33
|
export function registryMcp(url = DEFAULT_REGISTRY_MCP, f = fetch) {
|
|
14
34
|
return async (name, args) => {
|
|
15
35
|
const res = await f(url, {
|
|
@@ -17,8 +37,17 @@ export function registryMcp(url = DEFAULT_REGISTRY_MCP, f = fetch) {
|
|
|
17
37
|
headers: { "Content-Type": "application/json", Accept: "application/json, text/event-stream" },
|
|
18
38
|
body: JSON.stringify({ jsonrpc: "2.0", id: Date.now(), method: "tools/call", params: { name, arguments: args } }),
|
|
19
39
|
signal: AbortSignal.timeout(20_000),
|
|
40
|
+
redirect: "error",
|
|
20
41
|
});
|
|
21
|
-
|
|
42
|
+
if (res.status === 429 || res.status >= 500) {
|
|
43
|
+
await res.body?.cancel().catch(() => { });
|
|
44
|
+
throw new HttpStatusError(res.status);
|
|
45
|
+
}
|
|
46
|
+
if (!res.ok) {
|
|
47
|
+
await res.body?.cancel().catch(() => { });
|
|
48
|
+
throw new Error(`${name}: registry answered HTTP ${res.status}`);
|
|
49
|
+
}
|
|
50
|
+
const text = await textCapped(res);
|
|
22
51
|
const jsonText = text.trim().startsWith("{") ? text : (text.match(/^data: (.*)$/m)?.[1] ?? text);
|
|
23
52
|
const msg = JSON.parse(jsonText);
|
|
24
53
|
if (msg.error)
|
|
@@ -34,24 +63,77 @@ export function registryMcp(url = DEFAULT_REGISTRY_MCP, f = fetch) {
|
|
|
34
63
|
}
|
|
35
64
|
};
|
|
36
65
|
}
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
66
|
+
/** A retryable HTTP answer (429 or 5xx) */
|
|
67
|
+
export class HttpStatusError extends Error {
|
|
68
|
+
status;
|
|
69
|
+
constructor(status) {
|
|
70
|
+
super(`HTTP ${status}`);
|
|
71
|
+
this.status = status;
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
/** Socket and gRPC failures that are worth another try. Matched on the error's code and message and on its cause (Node's fetch puts ECONNREFUSED etc. there) */
|
|
75
|
+
const TRANSIENT_TEXT = /ETIMEDOUT|ECONNRESET|ECONNREFUSED|EPIPE|ENOTFOUND|EAI_AGAIN|UND_ERR_\w+|UNAVAILABLE|DEADLINE_EXCEEDED|deadline|socket hang up|No connection established|aborted due to timeout|TimeoutError/i;
|
|
76
|
+
export function isTransient(e) {
|
|
77
|
+
if (e instanceof HttpStatusError)
|
|
78
|
+
return true;
|
|
79
|
+
const parts = [];
|
|
80
|
+
let cur = e;
|
|
81
|
+
for (let depth = 0; cur && depth < 4; depth++) {
|
|
82
|
+
if (cur instanceof Error)
|
|
83
|
+
parts.push(cur.name, cur.message);
|
|
84
|
+
else
|
|
85
|
+
parts.push(String(cur));
|
|
86
|
+
const c = cur.code;
|
|
87
|
+
if (c !== undefined)
|
|
88
|
+
parts.push(String(c));
|
|
89
|
+
// gRPC status 14 = UNAVAILABLE, 4 = DEADLINE_EXCEEDED
|
|
90
|
+
if (c === 14 || c === 4)
|
|
91
|
+
return true;
|
|
92
|
+
cur = cur.cause;
|
|
93
|
+
}
|
|
94
|
+
return TRANSIENT_TEXT.test(parts.join(" "));
|
|
95
|
+
}
|
|
96
|
+
/** Retry a read on a dropped connection, a timeout, a 429 or a 5xx, three tries in all; anything else is thrown at once. `onTransient` runs before each retry (e.g. to drop a dead connection) */
|
|
97
|
+
export async function retrying(f, tries = 3, waitMs = 1500, onTransient) {
|
|
40
98
|
for (let i = 1;; i++) {
|
|
41
99
|
try {
|
|
42
100
|
return await f();
|
|
43
101
|
}
|
|
44
102
|
catch (e) {
|
|
45
|
-
if (i >= tries || !
|
|
103
|
+
if (i >= tries || !isTransient(e))
|
|
46
104
|
throw e;
|
|
105
|
+
onTransient?.();
|
|
47
106
|
await new Promise((r) => setTimeout(r, waitMs * i));
|
|
48
107
|
}
|
|
49
108
|
}
|
|
50
109
|
}
|
|
110
|
+
/**
|
|
111
|
+
* Whom a CIS-8 binding may name: the agent's owner, or its agentWallet (the payout account the owner set on-chain;
|
|
112
|
+
* an operator may keep its EVM key under that account). Anything else is refused. Alias-aware.
|
|
113
|
+
*/
|
|
114
|
+
export function boundAs(bound, agent) {
|
|
115
|
+
const same = (a, b) => { try {
|
|
116
|
+
return sameAccount(a, b);
|
|
117
|
+
}
|
|
118
|
+
catch {
|
|
119
|
+
return false;
|
|
120
|
+
} };
|
|
121
|
+
if (agent.owner && same(bound, agent.owner))
|
|
122
|
+
return "owner";
|
|
123
|
+
if (agent.wallet && same(bound, agent.wallet))
|
|
124
|
+
return "agentWallet";
|
|
125
|
+
return undefined;
|
|
126
|
+
}
|
|
51
127
|
export function concordiumGuardDeps(o = {}) {
|
|
52
|
-
const
|
|
128
|
+
const name = o.network ?? "testnet";
|
|
129
|
+
if (!Object.prototype.hasOwnProperty.call(NETWORKS, name))
|
|
130
|
+
throw new Error(`concordiumGuardDeps: network must be "testnet" or "mainnet", got ${JSON.stringify(name)} (this is the Concordium network the checks read, not an x402 network id)`);
|
|
131
|
+
const net = NETWORKS[name];
|
|
53
132
|
let client = o.grpc;
|
|
54
133
|
const grpc = () => (client ??= new ConcordiumGRPCNodeClient(net.grpc.host, net.grpc.port, credentials.createSsl(), { timeout: 20_000 }));
|
|
134
|
+
// A dead channel is not dialed again: after a transient error the next try gets a new client (unless you passed your own)
|
|
135
|
+
const resetGrpc = () => { if (!o.grpc)
|
|
136
|
+
client = undefined; };
|
|
55
137
|
const registryAddr = ContractAddress.create(net.agentRegistry.index, net.agentRegistry.subindex);
|
|
56
138
|
const cis8Addr = ContractAddress.create(net.cis8Registry.index, net.cis8Registry.subindex);
|
|
57
139
|
const cis8Text = `<${net.cis8Registry.index},${net.cis8Registry.subindex}>`;
|
|
@@ -81,20 +163,25 @@ export function concordiumGuardDeps(o = {}) {
|
|
|
81
163
|
return { name, ok: false, detail: `the agent's external key is not a valid secp256k1 point: ${e instanceof Error ? e.message : e}` };
|
|
82
164
|
}
|
|
83
165
|
}
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
166
|
+
// Read who the key is bound to, then require that account to be the agent's owner, or its agentWallet (the account the agent
|
|
167
|
+
// is paid into, which the owner set on-chain). Compared in code, never by matching an error message
|
|
168
|
+
const r = await checkEvmBinding({ address: req.payTo, publicKey: key.publicKey, namespace: req.network }, (k) => retrying(() => ownerOfKey(grpc(), cis8Addr, k), 3, 1500, resetGrpc), sameAccount);
|
|
169
|
+
if (!r.ok)
|
|
170
|
+
return { name, ok: false, detail: `${r.reason} (key from ${key.from})` };
|
|
171
|
+
const as = boundAs(r.owner, agent);
|
|
172
|
+
if (!as)
|
|
173
|
+
return { name, ok: false, detail: `${req.payTo} is bound to ${r.owner}, which is neither the agent's owner ${agent.owner ?? "(none)"} nor its agentWallet ${agent.wallet ?? "(none)"} (key from ${key.from})` };
|
|
174
|
+
return { name, ok: true, detail: `${req.payTo} is bound to ${r.owner} (the agent's ${as}) in CIS-8 ${cis8Text} (key from ${key.from})` };
|
|
89
175
|
};
|
|
90
176
|
return {
|
|
91
177
|
registryNetwork: net.name,
|
|
92
178
|
concordiumNetwork: net.caip2,
|
|
93
179
|
registryAddress: `${net.agentRegistry.index}.${net.agentRegistry.subindex}`,
|
|
94
|
-
registry: (
|
|
95
|
-
readAgent: (id) => retrying(() => readAgent(grpc(), registryAddr, id)),
|
|
180
|
+
registry: (tool, args) => retrying(() => call(tool, args)),
|
|
181
|
+
readAgent: (id) => retrying(() => readAgent(grpc(), registryAddr, id), 3, 1500, resetGrpc),
|
|
96
182
|
evmPayToCheck,
|
|
97
183
|
isEvmNetwork: (n) => n.startsWith("eip155:"),
|
|
184
|
+
evmNetworks: [net.evmNetwork],
|
|
98
185
|
fetch: o.fetch,
|
|
99
186
|
};
|
|
100
187
|
}
|
package/dist/guard.d.ts
CHANGED
|
@@ -1,4 +1,3 @@
|
|
|
1
|
-
import { type x402Client } from "@x402/fetch";
|
|
2
1
|
import { type Check, type RegistryCall, type SellerVerdict } from "./seller.js";
|
|
3
2
|
import type { AgentOnChain } from "./agent-record.js";
|
|
4
3
|
/** The part of an x402 payment option the guard looks at */
|
|
@@ -38,6 +37,10 @@ export type GuardDeps = {
|
|
|
38
37
|
externalRef?: AgentOnChain["externalRef"] | undefined;
|
|
39
38
|
}) => Promise<Check>;
|
|
40
39
|
isEvmNetwork?: (network: string) => boolean;
|
|
40
|
+
/** EVM networks a payout may be on (e.g. Base for this Concordium network); any other EVM network is refused */
|
|
41
|
+
evmNetworks?: string[];
|
|
42
|
+
/** Tests only: allow Agent Cards on http://127.0.0.1 */
|
|
43
|
+
allowLocalHttpCards?: boolean;
|
|
41
44
|
fetch?: typeof fetch;
|
|
42
45
|
};
|
|
43
46
|
export type GuardVerdict = SellerVerdict & {
|
|
@@ -71,7 +74,17 @@ export declare function summarize(v: GuardVerdict): string;
|
|
|
71
74
|
* Wrap an x402 client: every payment it would make through the returned fetch is checked first.
|
|
72
75
|
* Payments attempted outside the guarded fetch (no known origin) are refused.
|
|
73
76
|
*/
|
|
74
|
-
|
|
77
|
+
/** The part of an x402 client the guard needs (any @x402/fetch x402Client, ESM or CommonJS build) */
|
|
78
|
+
export type GuardableClient = {
|
|
79
|
+
onBeforePaymentCreation: (hook: (ctx: {
|
|
80
|
+
paymentRequired: any;
|
|
81
|
+
selectedRequirements: any;
|
|
82
|
+
}) => Promise<void | {
|
|
83
|
+
abort: true;
|
|
84
|
+
reason: string;
|
|
85
|
+
}>) => unknown;
|
|
86
|
+
};
|
|
87
|
+
export declare function protect(client: GuardableClient, deps: GuardDeps, policy?: GuardPolicy, onVerdict?: (v: GuardVerdict) => void): {
|
|
75
88
|
/** fetch that pays only checked sellers. Returns the response (if any), the verdict (if a payment was needed) and the error (if any) */
|
|
76
89
|
fetch(url: string, init?: RequestInit): Promise<{
|
|
77
90
|
response?: Response;
|
package/dist/guard.js
CHANGED
|
@@ -16,13 +16,14 @@
|
|
|
16
16
|
* 6. (optional) an independent delivery record: vet402, another team's service, says whether the seller delivered when paid
|
|
17
17
|
*
|
|
18
18
|
* If a check fails the wallet is never asked to sign. Checks 1–5 fail closed: an unreachable node or registry means no payment.
|
|
19
|
-
* Check 6 is a third party's opinion, not chain state, so the policy decides how much it counts
|
|
20
|
-
* non-delivery
|
|
19
|
+
* Check 6 is a third party's opinion, not chain state, so the policy decides how much it counts. Default on testnet "block-no":
|
|
20
|
+
* only a proven non-delivery (verdict "no") blocks; "unproven" or an unreachable service does NOT block, so check 6 is not
|
|
21
|
+
* fail-closed (use "require-go" for that). Default off on mainnet (the service records testnet only).
|
|
21
22
|
*/
|
|
22
23
|
import { AsyncLocalStorage } from "node:async_hooks";
|
|
23
24
|
import { wrapFetchWithPayment } from "@x402/fetch";
|
|
24
25
|
import { decodePaymentRequiredHeader } from "@x402/core/http";
|
|
25
|
-
import { AGENT_EXTENSION, summarize as summarizeSeller, verifySeller } from "./seller.js";
|
|
26
|
+
import { AGENT_EXTENSION, readCapped, summarize as summarizeSeller, verifySeller } from "./seller.js";
|
|
26
27
|
export const DEFAULT_REPUTATION_URL = "https://vet402-concordium.fly.dev";
|
|
27
28
|
const REPUTATION_CHECK = "independent delivery record (vet402, another team's service)";
|
|
28
29
|
/** What the 402's concordium-agent extension names: "unnamed", "mismatch" (another network or registry), or "<tokenId>|<badge>" */
|
|
@@ -40,13 +41,13 @@ export async function deliveryRecord(tokenId, base, f = fetch) {
|
|
|
40
41
|
const r = await f(`${base.replace(/\/$/, "")}/check?agent=${encodeURIComponent(tokenId)}`, { redirect: "error", signal: AbortSignal.timeout(10_000) });
|
|
41
42
|
if (!r.ok)
|
|
42
43
|
return { verdict: "unreachable", detail: `HTTP ${r.status}` };
|
|
43
|
-
const j = (await r.
|
|
44
|
-
const verdict = typeof j?.vet402?.verdict === "string" ? j.vet402.verdict : "unreadable";
|
|
44
|
+
const j = JSON.parse((await readCapped(r, 64 * 1024)).toString("utf8"));
|
|
45
|
+
const verdict = typeof j?.vet402?.verdict === "string" ? j.vet402.verdict.trim().toLowerCase() : "unreadable";
|
|
45
46
|
const why = j?.trust_summary?.line ?? j?.vet402?.reason ?? "";
|
|
46
47
|
return { verdict, detail: `verdict "${verdict}"${typeof j?.vet402?.N === "number" ? ` from ${j.vet402.N} paid request(s)` : ""}${why ? `: ${why}` : ""}` };
|
|
47
48
|
}
|
|
48
49
|
catch (e) {
|
|
49
|
-
return { verdict: "unreachable", detail: e instanceof Error ? e.message : String(e) };
|
|
50
|
+
return { verdict: "unreachable", detail: `no usable answer from the delivery record service: ${e instanceof Error ? e.message : String(e)}` };
|
|
50
51
|
}
|
|
51
52
|
}
|
|
52
53
|
/** Does this record pass under the policy? */
|
|
@@ -64,6 +65,12 @@ export function reputationPasses(verdict, mode) {
|
|
|
64
65
|
export async function checkSellerFor(target, deps, policy = {}) {
|
|
65
66
|
const { origin, req } = target;
|
|
66
67
|
const evm = deps.isEvmNetwork?.(req.network) ?? req.network.startsWith("eip155:");
|
|
68
|
+
// The payment must be on the network these checks read: a testnet agent proves nothing about a mainnet or other-chain payout
|
|
69
|
+
const wrongNetwork = evm
|
|
70
|
+
? deps.evmNetworks && !deps.evmNetworks.includes(req.network) ? `this guard checks EVM payouts on ${deps.evmNetworks.join(", ")}, not ${req.network}` : undefined
|
|
71
|
+
: req.network !== deps.concordiumNetwork ? `this guard reads Concordium ${deps.registryNetwork} (${deps.concordiumNetwork}); the 402 asks for a payment on ${req.network}` : undefined;
|
|
72
|
+
if (wrongNetwork)
|
|
73
|
+
return { origin, ok: false, payTo: req.payTo, checks: [{ name: "payment is on the network the guard checks", ok: false, detail: wrongNetwork }] };
|
|
67
74
|
// The agent always lives on Concordium: when paying on EVM, the 402 names it on the Concordium network
|
|
68
75
|
const named = namedAgentOf(target.paymentRequired, evm ? deps.concordiumNetwork : req.network, deps.registryAddress);
|
|
69
76
|
if (named === "mismatch" || (named === "unnamed" && policy.requireNamedAgent)) {
|
|
@@ -93,6 +100,7 @@ export async function checkSellerFor(target, deps, policy = {}) {
|
|
|
93
100
|
expectTokenId: named.includes("|") ? named.split("|")[0] : undefined,
|
|
94
101
|
expectBadge: named.includes("|") ? named.split("|")[1] || undefined : undefined,
|
|
95
102
|
payToCheck: evm ? deps.evmPayToCheck(req) : undefined,
|
|
103
|
+
allowLocalHttpCards: deps.allowLocalHttpCards,
|
|
96
104
|
});
|
|
97
105
|
const out = { ...base, origin };
|
|
98
106
|
// vet402 records testnet only: on another network its answer would be about a different agent with the same number
|
|
@@ -116,10 +124,6 @@ export function summarize(v) {
|
|
|
116
124
|
}
|
|
117
125
|
return v.reputation && v.ok ? `${s}; delivery record: ${v.reputation.verdict}` : s;
|
|
118
126
|
}
|
|
119
|
-
/**
|
|
120
|
-
* Wrap an x402 client: every payment it would make through the returned fetch is checked first.
|
|
121
|
-
* Payments attempted outside the guarded fetch (no known origin) are refused.
|
|
122
|
-
*/
|
|
123
127
|
export function protect(client, deps, policy = {}, onVerdict) {
|
|
124
128
|
const als = new AsyncLocalStorage();
|
|
125
129
|
client.onBeforePaymentCreation(async ({ selectedRequirements, paymentRequired }) => {
|
package/dist/index.d.ts
CHANGED
|
@@ -6,10 +6,10 @@
|
|
|
6
6
|
* const { response, verdict } = await guarded.fetch(url, init);
|
|
7
7
|
*/
|
|
8
8
|
export { protect, checkSellerFor, checkSellerAt, summarize, namedAgentOf, deliveryRecord, reputationPasses, DEFAULT_REPUTATION_URL } from "./guard.js";
|
|
9
|
-
export type { GuardDeps, GuardPolicy, GuardVerdict, Requirement, ReputationMode, PaymentRequiredLike } from "./guard.js";
|
|
10
|
-
export { verifySeller, badgeTokenAddress, BADGE_EXTENSION, AGENT_EXTENSION } from "./seller.js";
|
|
9
|
+
export type { GuardDeps, GuardableClient, GuardPolicy, GuardVerdict, Requirement, ReputationMode, PaymentRequiredLike } from "./guard.js";
|
|
10
|
+
export { verifySeller, badgeTokenAddress, cardUrlAllowed, sameAccountSafe, BADGE_EXTENSION, AGENT_EXTENSION } from "./seller.js";
|
|
11
11
|
export type { Check, SellerVerdict, RegistryCall } from "./seller.js";
|
|
12
|
-
export { concordiumGuardDeps, registryMcp, retrying, DEFAULT_REGISTRY_MCP } from "./deps.js";
|
|
12
|
+
export { concordiumGuardDeps, registryMcp, retrying, isTransient, boundAs, HttpStatusError, DEFAULT_REGISTRY_MCP } from "./deps.js";
|
|
13
13
|
export type { DepsOptions } from "./deps.js";
|
|
14
14
|
export { NETWORKS } from "./networks.js";
|
|
15
15
|
export type { ConcordiumNetwork, NetworkName } from "./networks.js";
|
package/dist/index.js
CHANGED
|
@@ -6,8 +6,8 @@
|
|
|
6
6
|
* const { response, verdict } = await guarded.fetch(url, init);
|
|
7
7
|
*/
|
|
8
8
|
export { protect, checkSellerFor, checkSellerAt, summarize, namedAgentOf, deliveryRecord, reputationPasses, DEFAULT_REPUTATION_URL } from "./guard.js";
|
|
9
|
-
export { verifySeller, badgeTokenAddress, BADGE_EXTENSION, AGENT_EXTENSION } from "./seller.js";
|
|
10
|
-
export { concordiumGuardDeps, registryMcp, retrying, DEFAULT_REGISTRY_MCP } from "./deps.js";
|
|
9
|
+
export { verifySeller, badgeTokenAddress, cardUrlAllowed, sameAccountSafe, BADGE_EXTENSION, AGENT_EXTENSION } from "./seller.js";
|
|
10
|
+
export { concordiumGuardDeps, registryMcp, retrying, isTransient, boundAs, HttpStatusError, DEFAULT_REGISTRY_MCP } from "./deps.js";
|
|
11
11
|
export { NETWORKS } from "./networks.js";
|
|
12
12
|
export { readAgent, decodeAgentOf, encodeAgentTokenId, sameAccount } from "./agent-record.js";
|
|
13
13
|
export { checkEvmBinding, ownerOfKey, evmAddressOf, uncompressed, compressed, sameExternalKey, EVM_KEY_TYPE } from "./cis8.js";
|
package/dist/seller.d.ts
CHANGED
|
@@ -55,6 +55,22 @@ export declare function verifySeller(opts: {
|
|
|
55
55
|
wallet?: string;
|
|
56
56
|
externalRef?: AgentOnChain["externalRef"] | undefined;
|
|
57
57
|
}) => Promise<Check>;
|
|
58
|
+
/** Tests only: allow an Agent Card at http://127.0.0.1 or http://localhost */
|
|
59
|
+
allowLocalHttpCards?: boolean;
|
|
58
60
|
}): Promise<SellerVerdict>;
|
|
59
61
|
/** One-line summary for people */
|
|
60
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;
|
|
65
|
+
/**
|
|
66
|
+
* An Agent Card URL the buyer may fetch: https to a public host name or address. Loopback, private and link-local
|
|
67
|
+
* addresses written as literals are refused here; `cardHostIsPublic` also checks what a host name resolves to.
|
|
68
|
+
*/
|
|
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>;
|
|
75
|
+
/** Same Concordium account, aliases included; false for anything that is not an account address */
|
|
76
|
+
export declare function sameAccountSafe(a: string, b: string): boolean;
|
package/dist/seller.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { createHash } from "node:crypto";
|
|
2
|
+
import { AccountAddress } from "@concordium/web-sdk";
|
|
2
3
|
export const BADGE_EXTENSION = "https://docs.concordium.com/a2a-extensions/concordium-badge/v1";
|
|
3
4
|
/** Top-level x402 PaymentRequired extension: names the agent being paid (only a pointer; the wallet is read from the chain) */
|
|
4
5
|
export const AGENT_EXTENSION = "concordium-agent";
|
|
@@ -118,20 +119,23 @@ export async function verifySeller(opts) {
|
|
|
118
119
|
const failed = Object.entries(b?.checks ?? {}).filter(([, v]) => v === false).map(([k]) => k);
|
|
119
120
|
checks.push({
|
|
120
121
|
name: "official badge check passes (identity-verified owner)",
|
|
121
|
-
|
|
122
|
-
|
|
122
|
+
// Every sub-check must pass too, not only the summary flag
|
|
123
|
+
ok: b?.badge_valid === true && failed.length === 0,
|
|
124
|
+
detail: b?.badge_valid && failed.length === 0 ? `${Object.keys(b.checks ?? {}).length} checks passed` : `failed: ${[...failed, ...(b?.issues ?? []).map((i) => (typeof i === "string" ? i : i?.message ? `${i.field ?? ""}: ${i.message}` : JSON.stringify(i)))].join(", ") || "badge not valid"}`,
|
|
123
125
|
});
|
|
124
126
|
}
|
|
125
127
|
catch (e) {
|
|
126
128
|
checks.push({ name: "official badge check passes (identity-verified owner)", ok: false, detail: `registry unreachable: ${err(e)}` });
|
|
127
129
|
}
|
|
128
|
-
// 4. Download the card and hash it ourselves
|
|
130
|
+
// 4. Download the card and hash it ourselves (only for a record the node confirmed: never fetch an address from an unconfirmed record)
|
|
129
131
|
try {
|
|
132
|
+
if (problems.length > 0)
|
|
133
|
+
throw new Error("skipped: the agent record could not be confirmed (see check 2)");
|
|
130
134
|
if (!rec.agent_uri)
|
|
131
135
|
throw new Error("no agent_uri on-chain");
|
|
132
|
-
|
|
133
|
-
if (
|
|
134
|
-
|
|
136
|
+
cardUrlAllowed(rec.agent_uri, opts.allowLocalHttpCards === true);
|
|
137
|
+
if (opts.allowLocalHttpCards !== true)
|
|
138
|
+
await cardHostIsPublic(rec.agent_uri);
|
|
135
139
|
const r = await f(rec.agent_uri, { redirect: "error", signal: AbortSignal.timeout(10_000) });
|
|
136
140
|
if (!r.ok)
|
|
137
141
|
throw new Error(`HTTP ${r.status}`);
|
|
@@ -157,7 +161,8 @@ export async function verifySeller(opts) {
|
|
|
157
161
|
}
|
|
158
162
|
checks.push({
|
|
159
163
|
name: "payTo is the agent's on-chain wallet",
|
|
160
|
-
|
|
164
|
+
// Concordium account aliases (same first 29 bytes) are the same account
|
|
165
|
+
ok: !!rec.agent_wallet && sameAccountSafe(rec.agent_wallet, opts.payTo),
|
|
161
166
|
detail: `payTo ${opts.payTo}, on-chain agentWallet ${rec.agent_wallet || "not set"}`,
|
|
162
167
|
});
|
|
163
168
|
return done();
|
|
@@ -169,3 +174,61 @@ export function summarize(v) {
|
|
|
169
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"}`
|
|
170
175
|
: `refused to pay: ${bad.map((c) => `${c.name} — ${c.detail}`).join("; ")}`;
|
|
171
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
|
+
}
|
|
186
|
+
/**
|
|
187
|
+
* An Agent Card URL the buyer may fetch: https to a public host name or address. Loopback, private and link-local
|
|
188
|
+
* addresses written as literals are refused here; `cardHostIsPublic` also checks what a host name resolves to.
|
|
189
|
+
*/
|
|
190
|
+
export function cardUrlAllowed(url, allowLocalHttp = false) {
|
|
191
|
+
let u;
|
|
192
|
+
try {
|
|
193
|
+
u = new URL(url);
|
|
194
|
+
}
|
|
195
|
+
catch {
|
|
196
|
+
throw new Error(`agent_uri is not a URL: ${url.slice(0, 80)}`);
|
|
197
|
+
}
|
|
198
|
+
const host = u.hostname.replace(/^\[|\]$/g, "").toLowerCase();
|
|
199
|
+
const local = host === "localhost" || host.endsWith(".localhost") || /^127\./.test(host) || host === "::1";
|
|
200
|
+
if (allowLocalHttp && u.protocol === "http:" && local)
|
|
201
|
+
return;
|
|
202
|
+
if (u.protocol !== "https:")
|
|
203
|
+
throw new Error(`agent_uri is not https: ${url.slice(0, 80)}`);
|
|
204
|
+
if (isPrivateAddress(host))
|
|
205
|
+
throw new Error(`agent_uri points at a local or private address: ${host}`);
|
|
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
|
+
}
|
|
226
|
+
/** Same Concordium account, aliases included; false for anything that is not an account address */
|
|
227
|
+
export function sameAccountSafe(a, b) {
|
|
228
|
+
try {
|
|
229
|
+
return Buffer.from(AccountAddress.fromBase58(a).decodedAddress).subarray(0, 29).equals(Buffer.from(AccountAddress.fromBase58(b).decodedAddress).subarray(0, 29));
|
|
230
|
+
}
|
|
231
|
+
catch {
|
|
232
|
+
return false;
|
|
233
|
+
}
|
|
234
|
+
}
|
package/package.json
CHANGED
|
@@ -1,11 +1,14 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "concordium-x402-guard",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.2.0",
|
|
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": "./dist/cli.js"
|
|
11
|
+
},
|
|
9
12
|
"exports": {
|
|
10
13
|
".": {
|
|
11
14
|
"types": "./dist/index.d.ts",
|
|
@@ -18,7 +21,7 @@
|
|
|
18
21
|
"LICENSE"
|
|
19
22
|
],
|
|
20
23
|
"engines": {
|
|
21
|
-
"node": ">=
|
|
24
|
+
"node": ">=22"
|
|
22
25
|
},
|
|
23
26
|
"repository": {
|
|
24
27
|
"type": "git",
|
|
@@ -42,12 +45,16 @@
|
|
|
42
45
|
"dependencies": {
|
|
43
46
|
"@concordium/web-sdk": "^12.0.2",
|
|
44
47
|
"@noble/curves": "^1.9.7",
|
|
45
|
-
"@noble/hashes": "^1.8.0"
|
|
48
|
+
"@noble/hashes": "^1.8.0"
|
|
49
|
+
},
|
|
50
|
+
"peerDependencies": {
|
|
46
51
|
"@x402/core": "^2.31.0",
|
|
47
52
|
"@x402/fetch": "^2.31.0"
|
|
48
53
|
},
|
|
49
54
|
"devDependencies": {
|
|
50
55
|
"@types/node": "^26.6.6",
|
|
56
|
+
"@x402/core": "^2.31.0",
|
|
57
|
+
"@x402/fetch": "^2.31.0",
|
|
51
58
|
"tsx": "^4.23.15",
|
|
52
59
|
"typescript": "^7.0.2"
|
|
53
60
|
},
|