x402-trust-guard 0.1.2 → 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 CHANGED
@@ -14,12 +14,19 @@ const pay = wrapFetchWithPayment(fetch, client);
14
14
  await pay("https://api.some-seller.com/v1/data"); // throws instead of paying if the seller looks unsafe
15
15
  ```
16
16
 
17
- Before your client signs a payment, the guard asks the [x402 Trust Board](https://benmcalillycreative.github.io/x402-trust-board/)
17
+ Before your client signs a payment, the guard asks the [Settle Watch](https://settlewatch.com/)
18
18
  about the endpoint and the address it wants paid, and **stops the payment** when the answer is `avoid`:
19
19
 
20
20
  - the endpoint switched to a different wallet, or asks to be paid at a burn address
21
21
  - the address isn't in the payout proof the seller published (a hijacked server can change where money goes; it can't change the seller's DNS)
22
22
 
23
+ It also reads the seller's payout proof straight from DNS (`_x402-payto` TXT records), so an address swapped
24
+ on a compromised server is caught even between the board's refreshes, without asking anyone. The lookup is
25
+ cached by the record's TTL (at most 24 hours) and only repeated live when the quoted address isn't in the
26
+ cached set, so the normal path adds no DNS round trip. A legitimate rotation passes that re-check (as
27
+ `caution`, until the board catches up); a swapped address doesn't. If DNS can't be reached, it never blocks
28
+ on that alone. [Cache policy](https://github.com/benmcalillycreative/x402-trust-board/blob/main/docs/payout-proof-spec.md#61-caching).
29
+
23
30
  Price problems (asking well above the listing), flaky uptime, low grades and thin history come back as `caution`,
24
31
  which you can choose to block too (`onCaution: "block"`).
25
32
 
@@ -41,6 +48,8 @@ withTrustGuard(client, {
41
48
  onUnknown: "allow", // "allow" | "block": a seller the board has never seen
42
49
  onError: "allow", // "allow" | "block": the check itself failed (network, board down)
43
50
  cacheSeconds: 86400,
51
+ dnsProofs: true, // read the seller's DNS payout proof live (cached by its TTL)
52
+ onProofMismatch: "block", // "allow" only for sellers that quote a fresh address for every payment
44
53
  onResult: (r) => console.log(r.verdict, r.url, r.reasons),
45
54
  });
46
55
  ```
@@ -48,12 +57,12 @@ withTrustGuard(client, {
48
57
  `checkFree(url, payTo?)` checks one URL yourself, for free, and returns the full result.
49
58
 
50
59
  What each verdict is based on, and what a pre-payment check can't promise (it never pays, so it can't test delivery):
51
- [method and limits](https://benmcalillycreative.github.io/x402-trust-board/method.html).
60
+ [method and limits](https://settlewatch.com/method.html).
52
61
 
53
62
  ## Also available
54
63
 
55
- - **HTTP:** `GET https://check.benmcalilly.com/v1/check?url=…&payTo=…` ($0.01, x402)
56
- - **MCP:** add `https://check.benmcalilly.com/mcp` as a remote MCP server; tool `check_payment`, 100 free checks a day
57
- - **Sellers:** prove your payout address with a DNS record and a signature: [how](https://benmcalillycreative.github.io/x402-trust-board/verify.html)
64
+ - **HTTP:** `GET https://api.settlewatch.com/v1/check?url=…&payTo=…` ($0.01, x402)
65
+ - **MCP:** add `https://api.settlewatch.com/mcp` as a remote MCP server; tool `check_payment`, 100 free checks a day
66
+ - **Sellers:** prove your payout address with a DNS record and a signature: [how](https://settlewatch.com/verify.html)
58
67
 
59
68
  MIT licensed.
package/index.d.ts CHANGED
@@ -8,6 +8,8 @@ export interface CheckResult {
8
8
  seller: Record<string, unknown> | null;
9
9
  pay_to: { address: string; proven_by_seller: string | null; matches_listing: boolean | null; contradicts_seller_proof: boolean } | null;
10
10
  board: string;
11
+ /** Present when the seller's DNS payout proof was read live: none | match | mismatch | error. */
12
+ dns_live?: "none" | "match" | "mismatch" | "error";
11
13
  }
12
14
  export interface GuardOptions {
13
15
  mode?: "paid" | "free";
@@ -15,6 +17,12 @@ export interface GuardOptions {
15
17
  onUnknown?: "allow" | "block";
16
18
  onError?: "allow" | "block";
17
19
  cacheSeconds?: number;
20
+ /** Read the seller's _x402-payto DNS proof live (cached by its TTL, at most 24h). Default true. */
21
+ dnsProofs?: boolean;
22
+ /** When the seller's DNS proof doesn't list the quoted address. Default "block". */
23
+ onProofMismatch?: "block" | "allow";
24
+ /** DNS-over-HTTPS JSON endpoint. Default Cloudflare. */
25
+ doh?: string;
18
26
  onResult?: (result: CheckResult | { url: string; verdict: "error"; reasons: string[] }) => void;
19
27
  fetch?: typeof fetch;
20
28
  api?: string;
package/index.js CHANGED
@@ -4,14 +4,20 @@
4
4
  // withTrustGuard(client); // client = your x402Client
5
5
  // const pay = wrapFetchWithPayment(fetch, client);
6
6
  //
7
- // Before every payment the client is about to sign, the guard asks the x402 Trust Board whether
7
+ // Before every payment the client is about to sign, the guard asks Settle Watch whether
8
8
  // the endpoint and the address it wants paid look safe, and stops the payment on "avoid"
9
9
  // (a switched or burn wallet, a 10x overcharge, an address that contradicts the seller's own
10
10
  // payout proof). Answers are cached, so each endpoint is checked at most once a day.
11
+ //
12
+ // It also reads the seller's payout proof from DNS itself (_x402-payto TXT records, see
13
+ // docs/payout-proof-spec.md), so a payTo swapped on a compromised server is caught even between the
14
+ // board's refreshes. That lookup is cached by the record's TTL (at most 24 hours) and only repeated
15
+ // live when the quoted address isn't in the cached set: no DNS round trip on the normal path.
11
16
  import { parseTarget, verdict } from "./verdict.js";
17
+ import { ProofCache, reconcile, withProof } from "./proofs.js";
12
18
 
13
- export const DEFAULT_API = "https://check.benmcalilly.com";
14
- export const DEFAULT_BOARD = "https://benmcalillycreative.github.io/x402-trust-board/";
19
+ export const DEFAULT_API = "https://api.settlewatch.com";
20
+ export const DEFAULT_BOARD = "https://settlewatch.com/";
15
21
 
16
22
  export class PaymentBlocked extends Error {
17
23
  constructor(result) {
@@ -32,6 +38,10 @@ export class PaymentBlocked extends Error {
32
38
  * @param {"allow"|"block"} [opts.onUnknown="allow"] sellers the board has never seen
33
39
  * @param {"allow"|"block"} [opts.onError="allow"] the check itself failed (network, board down)
34
40
  * @param {number} [opts.cacheSeconds=86400]
41
+ * @param {boolean} [opts.dnsProofs=true] check the seller's DNS payout proof live (cached by its TTL)
42
+ * @param {"block"|"allow"} [opts.onProofMismatch="block"] the seller's DNS proof doesn't list the address
43
+ * (use "allow" only for sellers that quote a fresh address for every payment)
44
+ * @param {string} [opts.doh] DNS-over-HTTPS JSON endpoint (default Cloudflare)
35
45
  * @param {(result: object) => void} [opts.onResult] called with every verdict (for logging)
36
46
  * @param {typeof fetch} [opts.fetch]
37
47
  * @param {string} [opts.api]
@@ -40,9 +50,11 @@ export class PaymentBlocked extends Error {
40
50
  export function withTrustGuard(client, opts = {}) {
41
51
  const o = {
42
52
  mode: "paid", onCaution: "allow", onUnknown: "allow", onError: "allow", cacheSeconds: 86400,
53
+ dnsProofs: true, onProofMismatch: "block",
43
54
  api: DEFAULT_API, board: DEFAULT_BOARD, fetch: globalThis.fetch, ...opts,
44
55
  };
45
56
  const cache = new Map();
57
+ const proofs = new ProofCache({ fetch: o.fetch, doh: o.doh, verify: verifySig });
46
58
  let paidFetch = null;
47
59
 
48
60
  async function lookup(target, payTo) {
@@ -50,7 +62,14 @@ export function withTrustGuard(client, opts = {}) {
50
62
  const res = await o.fetch(`${o.board}seller/${target.host}.json`);
51
63
  if (res.status === 404) return verdict(target, null, payTo, o.board);
52
64
  if (!res.ok) throw new Error(`board returned HTTP ${res.status}`);
53
- return verdict(target, await res.json(), payTo, o.board);
65
+ const seller = await res.json();
66
+ const result = verdict(target, seller, payTo, o.board);
67
+ // The board's file says the address contradicts the seller's proof: ask DNS live, the seller may have rotated.
68
+ if (o.dnsProofs && result.pay_to?.contradicts_seller_proof) {
69
+ const live = await proofs.check(target.host, payTo, { fresh: true });
70
+ return reconcile(result, live, (p) => verdict(target, withProof(seller, p), payTo, o.board));
71
+ }
72
+ return result;
54
73
  }
55
74
  if (!paidFetch) {
56
75
  const { wrapFetchWithPayment } = await import("@x402/fetch");
@@ -77,14 +96,24 @@ export function withTrustGuard(client, opts = {}) {
77
96
  client.onBeforePaymentCreation(async ({ paymentRequired, selectedRequirements }) => {
78
97
  const url = paymentRequired?.resource?.url;
79
98
  if (!url || url.startsWith(o.api)) return; // never check the checker
99
+ const payTo = selectedRequirements?.payTo;
100
+ const target = parseTarget(url);
101
+ // The seller's own DNS proof, read live (cached by TTL). A mismatch blocks without asking anyone else.
102
+ const live = o.dnsProofs && target ? await proofs.check(target.host, payTo) : null;
103
+ if (live?.status === "mismatch") {
104
+ const result = reconcile({ url, host: target.host, verdict: "avoid", reasons: [], pay_to: { address: payTo } }, live);
105
+ o.onResult?.(result);
106
+ if (o.onProofMismatch === "block") return { abort: true, reason: new PaymentBlocked(result).message };
107
+ }
80
108
  let result;
81
109
  try {
82
- result = await check(url, selectedRequirements?.payTo);
110
+ result = await check(url, payTo);
83
111
  } catch (e) {
84
112
  o.onResult?.({ url, verdict: "error", reasons: [String(e.message || e)] });
85
113
  return o.onError === "block" ? { abort: true, reason: `trust check failed: ${e.message || e}` } : undefined;
86
114
  }
87
115
  if (!result) return;
116
+ if (live && live.status !== "mismatch") result = reconcile(result, live);
88
117
  o.onResult?.(result);
89
118
  const block =
90
119
  result.verdict === "avoid" ||
@@ -95,6 +124,17 @@ export function withTrustGuard(client, opts = {}) {
95
124
  return client;
96
125
  }
97
126
 
127
+ // Signature check for DNS proofs, when viem is installed (it comes with @x402/evm). A smart-contract
128
+ // wallet's signature doesn't recover to its address without a chain call: that counts as unknown, not invalid.
129
+ let viem;
130
+ async function verifySig(address, message, signature) {
131
+ if (!address.startsWith("0x")) return null;
132
+ if (viem === undefined) viem = await import("viem").catch(() => null);
133
+ if (!viem) return null;
134
+ const who = await viem.recoverMessageAddress({ message, signature });
135
+ return who.toLowerCase() === address.toLowerCase() ? true : null;
136
+ }
137
+
98
138
  /** Check one URL yourself (free mode, no payment). */
99
139
  export async function checkFree(url, payTo, { board = DEFAULT_BOARD, fetch: f = globalThis.fetch } = {}) {
100
140
  const target = parseTarget(url);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "x402-trust-guard",
3
- "version": "0.1.2",
3
+ "version": "0.2.0",
4
4
  "description": "Check an x402 seller before your agent pays it: blocks switched or burn wallets, big overcharges and payout addresses the seller never proved. One line on top of @x402/fetch.",
5
5
  "type": "module",
6
6
  "main": "index.js",
@@ -15,6 +15,7 @@
15
15
  "index.js",
16
16
  "index.d.ts",
17
17
  "verdict.js",
18
+ "proofs.js",
18
19
  "README.md",
19
20
  "LICENSE"
20
21
  ],
@@ -29,7 +30,7 @@
29
30
  "mpp"
30
31
  ],
31
32
  "license": "MIT",
32
- "homepage": "https://benmcalillycreative.github.io/x402-trust-board/",
33
+ "homepage": "https://settlewatch.com/",
33
34
  "repository": {
34
35
  "type": "git",
35
36
  "url": "git+https://github.com/benmcalillycreative/x402-trust-board.git",
package/proofs.js ADDED
@@ -0,0 +1,176 @@
1
+ // Live payout-proof checks (docs/payout-proof-spec.md), shared by the check API and x402-trust-guard.
2
+ // packages/x402-trust-guard/proofs.js must stay a copy of this file (a test enforces it).
3
+ //
4
+ // Cache policy (spec section 6.1): keep a domain's proof set for min(record TTL, 24h). A quoted payTo
5
+ // that's in the set costs nothing. Only an address that isn't in it triggers a fresh DNS lookup before
6
+ // deciding, and those re-checks are rate-limited per domain so a hostile server can't make the client
7
+ // hammer DNS. A legitimate rotation passes the re-check; a swapped address on a compromised server
8
+ // fails it, because the attacker can't change the domain's DNS.
9
+
10
+ export const DOH = "https://cloudflare-dns.com/dns-query";
11
+ export const MAX_SECONDS = 86400;
12
+ export const MIN_SECONDS = 60;
13
+ export const RECHECK_SECONDS = 60;
14
+
15
+ // Hosting platforms where many unrelated people share one parent domain: a record there proves nothing
16
+ // about a customer's subdomain (spec 3.1). Same list as the board's x402trust/payout.py.
17
+ export const SHARED_SUFFIXES = [
18
+ "workers.dev", "pages.dev", "onrender.com", "vercel.app", "netlify.app", "fly.dev",
19
+ "up.railway.app", "railway.app", "herokuapp.com", "github.io", "hf.space", "sslip.io",
20
+ "nip.io", "run.app", "appspot.com", "amazonaws.com", "cloudfront.net", "azurewebsites.net",
21
+ "duckdns.org", "ngrok.app", "ngrok-free.app", "replit.app", "repl.co", "deno.dev",
22
+ "supabase.co", "firebaseapp.com", "web.app", "elestio.app", "base44.app",
23
+ ];
24
+ const TWO_PART = ["co.uk", "org.uk", "com.au", "net.au", "co.jp", "com.br", "co.nz", "co.in", "com.mx"];
25
+
26
+ const norm = (a) => String(a || "").trim().toLowerCase();
27
+
28
+ /** The host and its parents a DNS proof could sit on; empty for IPs and shared hosting. */
29
+ export function dnsNames(host) {
30
+ const h = norm(host).replace(/\.$/, "");
31
+ if (!h.includes(".") || /^[0-9.]+$/.test(h) || h.includes(":")) return [];
32
+ if (SHARED_SUFFIXES.some((s) => h === s || h.endsWith("." + s))) return [];
33
+ const labels = h.split(".");
34
+ const out = [];
35
+ for (let i = 0; i < labels.length - 1; i++) {
36
+ const name = labels.slice(i).join(".");
37
+ if (TWO_PART.includes(name)) break;
38
+ out.push(name);
39
+ }
40
+ return out;
41
+ }
42
+
43
+ /** The signed message (spec section 4). */
44
+ export const message = (domain, address, issued) =>
45
+ `x402 payout verification\n\nDomain: ${norm(domain)}\nPay-to: ${address.startsWith("0x") ? norm(address) : address}\nIssued: ${issued}`;
46
+
47
+ /** One DoH TXT answer's data -> the record text, joining its character strings (signatures exceed 255 bytes). */
48
+ export function joinTxt(data) {
49
+ const parts = [...String(data).matchAll(/"((?:[^"\\]|\\.)*)"/g)].map((m) => m[1].replace(/\\(.)/g, "$1"));
50
+ return parts.length ? parts.join("") : String(data);
51
+ }
52
+
53
+ export function parseRecord(text, domain) {
54
+ const f = {};
55
+ for (const part of text.split(";")) {
56
+ const i = part.indexOf("=");
57
+ if (i > 0) f[part.slice(0, i).trim().toLowerCase()] = part.slice(i + 1).trim();
58
+ }
59
+ if (f.v !== "x402payto1" || !f.a) return null;
60
+ return { domain, address: f.a, issued: f.d || null, signature: f.s || null };
61
+ }
62
+
63
+ /**
64
+ * Per-process cache of live DNS proofs.
65
+ * fetch fetch implementation
66
+ * doh DNS-over-HTTPS JSON endpoint (Cloudflare and Google style ?name=&type=TXT)
67
+ * verify optional async (address, message, signature) => true | false | null. true makes the level
68
+ * "dns_signed"; anything else leaves it "dns" (a smart-contract wallet can't be checked
69
+ * without a chain call, so a signature that doesn't recover is never treated as a mismatch).
70
+ */
71
+ export class ProofCache {
72
+ constructor({ fetch: f = globalThis.fetch, doh = DOH, verify = null, now = () => Date.now() } = {}) {
73
+ this.fetch = (...args) => f(...args); // unbound: Workers reject fetch called as a method
74
+ this.doh = doh; this.verify = verify; this.now = now;
75
+ this.entries = new Map(); // host -> { proofs: Map(address -> level), until, fetchedAt }
76
+ }
77
+
78
+ async query(name) {
79
+ const res = await this.fetch(`${this.doh}?name=${encodeURIComponent(`_x402-payto.${name}`)}&type=TXT`,
80
+ { headers: { accept: "application/dns-json" } });
81
+ if (!res.ok) throw new Error(`DNS-over-HTTPS returned HTTP ${res.status}`);
82
+ const j = await res.json();
83
+ if (j.Status !== 0 && j.Status !== 3) throw new Error(`DNS lookup failed (status ${j.Status})`);
84
+ const answers = (j.Answer || []).filter((a) => a.type === 16);
85
+ const ttl = Math.min(...answers.map((a) => a.TTL), ...(j.Authority || []).map((a) => a.TTL), MAX_SECONDS);
86
+ return { records: answers.map((a) => parseRecord(joinTxt(a.data), name)).filter(Boolean), ttl };
87
+ }
88
+
89
+ async load(host) {
90
+ const proofs = new Map();
91
+ let ttl = MAX_SECONDS;
92
+ for (const name of dnsNames(host)) {
93
+ const r = await this.query(name);
94
+ ttl = Math.min(ttl, r.ttl);
95
+ for (const rec of r.records) {
96
+ let level = "dns";
97
+ if (rec.signature && rec.issued && this.verify) {
98
+ try {
99
+ if ((await this.verify(rec.address, message(rec.domain, rec.address, rec.issued), rec.signature)) === true) level = "dns_signed";
100
+ } catch { /* unverifiable here; still a DNS proof */ }
101
+ }
102
+ const key = norm(rec.address);
103
+ if (proofs.get(key) !== "dns_signed") proofs.set(key, level);
104
+ }
105
+ }
106
+ const now = this.now();
107
+ const entry = { proofs, fetchedAt: now, until: now + Math.max(MIN_SECONDS, Math.min(ttl, MAX_SECONDS)) * 1000 };
108
+ this.entries.set(norm(host), entry);
109
+ return entry;
110
+ }
111
+
112
+ /**
113
+ * Is payTo in the seller's live DNS proofs?
114
+ * { status: "none" } no DNS proof (absence proves nothing), or shared hosting
115
+ * { status: "match", level } it's proven
116
+ * { status: "mismatch", proven, rechecked } proofs exist and this address isn't in them
117
+ * { status: "error", error } DNS couldn't be read; decide on other evidence
118
+ * fresh: true skips the cache (still rate-limited per domain).
119
+ */
120
+ async check(host, payTo, { fresh = false } = {}) {
121
+ if (!payTo || !dnsNames(host).length) return { status: "none" };
122
+ const key = norm(host);
123
+ try {
124
+ let entry = this.entries.get(key);
125
+ const canRefetch = !entry || this.now() - entry.fetchedAt >= RECHECK_SECONDS * 1000;
126
+ let rechecked = false;
127
+ if (!entry || this.now() >= entry.until || (fresh && canRefetch)) {
128
+ entry = await this.load(host);
129
+ rechecked = true;
130
+ }
131
+ if (!entry.proofs.size) return { status: "none" };
132
+ if (entry.proofs.has(norm(payTo))) return { status: "match", level: entry.proofs.get(norm(payTo)) };
133
+ if (!rechecked && canRefetch) {
134
+ entry = await this.load(host); // the only path that pays for a live lookup
135
+ rechecked = true;
136
+ if (entry.proofs.has(norm(payTo))) return { status: "match", level: entry.proofs.get(norm(payTo)) };
137
+ if (!entry.proofs.size) return { status: "none" };
138
+ }
139
+ return { status: "mismatch", proven: [...entry.proofs.keys()], rechecked };
140
+ } catch (e) {
141
+ return { status: "error", error: String(e.message || e) };
142
+ }
143
+ }
144
+ }
145
+
146
+ const PROOF_REASON = "The address you're about to pay isn't in the payout proof this seller published.";
147
+ const ROTATED = "The seller's DNS payout proof lists this address now (it changed after the board's last check).";
148
+
149
+ /** The board's seller data with one more proof, for rebuilding a verdict after a live match. */
150
+ export const withProof = (seller, proof) =>
151
+ seller ? { ...seller, payout: { ...(seller.payout || {}), proofs: [...(seller.payout?.proofs || []), proof] } } : seller;
152
+
153
+ /**
154
+ * Combine a verdict built from the board's data (refreshed every few hours) with a live DNS check.
155
+ * - The board saw a contradiction, but the address is in the seller's DNS proof now (a rotation since
156
+ * the board's last look): rebuild the verdict with that proof (rerun), and answer no better than
157
+ * "caution". Without rerun the board's answer stands.
158
+ * - The board saw nothing wrong, but the live DNS proof doesn't list the address: "avoid".
159
+ */
160
+ export function reconcile(result, live, rerun = null) {
161
+ if (!result || !result.pay_to || !live) return result;
162
+ if (live.status === "match" && result.pay_to.contradicts_seller_proof) {
163
+ if (!rerun) return { ...result, dns_live: live.status };
164
+ const out = rerun({ address: result.pay_to.address, level: live.level });
165
+ return { ...out, verdict: out.verdict === "ok" ? "caution" : out.verdict, reasons: [...(out.reasons || []), ROTATED],
166
+ dns_live: live.status };
167
+ }
168
+ const out = { ...result, reasons: [...(result.reasons || [])], pay_to: { ...result.pay_to }, dns_live: live.status };
169
+ if (live.status === "match" && !out.pay_to.proven_by_seller) out.pay_to.proven_by_seller = live.level;
170
+ if (live.status === "mismatch") {
171
+ out.pay_to.contradicts_seller_proof = true;
172
+ if (!out.reasons.includes(PROOF_REASON)) out.reasons.push(PROOF_REASON);
173
+ out.verdict = "avoid";
174
+ }
175
+ return out;
176
+ }