@paidfor/x402-safe-fetch 0.1.0 → 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/CHANGELOG.md ADDED
@@ -0,0 +1,34 @@
1
+ # Changelog
2
+
3
+ ## 0.2.1
4
+
5
+ - **Path for sellers the index has never measured.** With `telemetry: "verified"`, when the pre-pay index check
6
+ answered `unknown`, that call's v2 row adds `path`: the plain URL path (no query string or fragment, at most
7
+ 512 characters), so the index can put the seller on its candidate list and buy it itself. For known sellers
8
+ `path` is absent and `path_hash` is unchanged; `"anonymous"` never sends it. See docs/telemetry.md.
9
+ - `client` in telemetry rows is `x402-safe-fetch/0.2.1`.
10
+
11
+ ## 0.2.0
12
+
13
+ - **Verified telemetry.** `telemetry` takes a third value, `"verified"`, which sends a v2 row: the outcome under
14
+ the index's harness names (`ok`, `non_delivery`, `overcharge`, `wrong_goods`, `duplicate`, plus the client-only
15
+ refusals, `paid_no_response` and `error`) and, for a paid call, a `proof` (network, scheme, asset, pay-to,
16
+ payer, nonce, tx hash, settled time, response sha256, the seller's declared timeout) that the index can check
17
+ against Base. Refused calls send no proof. `"anonymous"` still sends the v1 row with no address; the default
18
+ is still `"off"`. A one-time console notice on the first `"verified"` run points at the README section
19
+ "What verified telemetry sends and why".
20
+ - **Receipts** gain `payer`, `proof`, `reported_outcome`, `verification_url`
21
+ (`{indexUrl}/telemetry/<payer>/<nonce>`, `"verified"` only; 404 until the index serves it) and
22
+ `response.sha256`.
23
+ - **Fix:** v1 settlement headers with `"errorReason": null` (what real v1 facilitators send on success) failed
24
+ to parse, so the receipt lost the transaction hash. The optional settlement fields now accept null.
25
+ - `"verified"` requires an https `indexUrl` (loopback allowed for local testing); telemetry POSTs never follow
26
+ redirects.
27
+ - `client` in telemetry rows is `x402-safe-fetch/0.2.0`.
28
+ - `examples/conway-topup.ts` uses `telemetry: "verified"`.
29
+
30
+ No breaking changes: `safeFetch(wallet, options)` and the returned function keep their signatures.
31
+
32
+ ## 0.1.0
33
+
34
+ First release.
package/README.md CHANGED
@@ -2,7 +2,8 @@
2
2
 
3
3
  A drop-in wrapper around the official [`@x402/fetch`](https://www.npmjs.com/package/@x402/fetch) client (2.28.x)
4
4
  that protects the buyer before and after paying. It refuses overpriced quotes and sellers rated "avoid", never
5
- pays twice for the same intent, and checks what it bought.
5
+ pays twice for the same intent, and checks what it bought. No account, no key, nothing to sign up for: not to
6
+ install it, not to read the index, and not to contribute telemetry.
6
7
 
7
8
  This is the client-side half of the x402 seller index at [paidfor.dev](https://paidfor.dev).
8
9
 
@@ -19,7 +20,7 @@ const fetchWithPay = safeFetch(walletClient, {
19
20
  refuseVerdicts: ["avoid"], // consult the index; "caution" is allowed but logged
20
21
  indexUrl: "https://paidfor.dev/v1",
21
22
  validators: ["http_status", "non_empty", "content_type", "not_truncated"],
22
- telemetry: "anonymous", // or "off" (the default)
23
+ telemetry: "verified", // or "anonymous" (no proof of payment) or "off" (the default)
23
24
  receiptsDir: "./.x402-receipts",
24
25
  });
25
26
 
@@ -48,7 +49,7 @@ Payments are exact-scheme USDC on Base mainnet by default (`network: "eip155:845
48
49
  id, quote, amount, reference price and its source, seller verdict, validator results, the settlement header,
49
50
  and the on-chain tx hash when the header carries it. The same receipt is written to the receipts directory as
50
51
  one JSON file per call.
51
- 4. **Telemetry, when enabled.** One outcome-only POST, fire-and-forget. See below.
52
+ 4. **Telemetry, when enabled.** One POST per call, fire-and-forget. See below.
52
53
 
53
54
  ## What it blocks and what it does not
54
55
 
@@ -71,22 +72,100 @@ Payments are exact-scheme USDC on Base mainnet by default (`network: "eip155:845
71
72
  intents/<sha256(intentId)>.json idempotency state and the stored response
72
73
  prices.json last price paid per resource (method + origin + path)
73
74
  debug.log telemetry failures, local only
75
+ .verified-telemetry-notice marks that the one-time "verified" notice was shown
74
76
  ```
75
77
 
78
+ Each receipt for a paid call has a `proof` (the same object a verified telemetry row carries) and, with
79
+ `telemetry: "verified"`, a `verification_url` of the form `{indexUrl}/telemetry/<payer>/<nonce>`, where you can
80
+ later see whether the index verified your row on-chain. **That route is not live yet: until the index ships it,
81
+ the URL answers 404.** `reported_outcome` is the outcome under the harness names, as the row reports it.
82
+
76
83
  Keep this directory if you want the idempotency guarantee to survive restarts.
77
84
 
78
85
  ## Telemetry
79
86
 
80
- Off by default. With `telemetry: "anonymous"`, each call that got a 402 posts exactly this to
81
- `{indexUrl}/telemetry`, with a 1-second timeout, never awaited, every failure swallowed:
87
+ Three settings. Every one is fire-and-forget: a 1-second timeout, never awaited, every failure swallowed and
88
+ only counted in `debug.log`. Nothing is sent for free resources (no 402) or for replays of a stored intent.
89
+
90
+ | `telemetry` | Sends |
91
+ | --- | --- |
92
+ | `"off"` (default) | Nothing. |
93
+ | `"anonymous"` | A v1 row: the outcome, amount, latency and validator names. No wallet address, no proof. |
94
+ | `"verified"` | A v2 row: the same fields with the outcome under the index's names, plus a proof of payment the index checks on Base. |
95
+
96
+ v1 row:
82
97
 
83
98
  ```json
84
99
  { "v": 1, "host": "api.example.com", "path_hash": "<sha256 hex of the path>", "outcome": "ok",
85
- "amount_usdc": "0.010000", "latency_ms": 412, "validator_failures": [], "client": "x402-safe-fetch/0.1.0" }
100
+ "amount_usdc": "0.010000", "latency_ms": 412, "validator_failures": [], "client": "x402-safe-fetch/0.2.1" }
101
+ ```
102
+
103
+ Both payloads and every field are documented in [docs/telemetry.md](docs/telemetry.md).
104
+
105
+ ## What verified telemetry sends and why
106
+
107
+ paidfor.dev measures sellers with its own wallet, which cannot cover the whole market. With
108
+ `telemetry: "verified"`, each of your purchases becomes a data point the index can trust, because it can prove
109
+ on-chain that you actually paid: it looks up the `AuthorizationUsed(payer, nonce)` event and the matching USDC
110
+ `Transfer` on Base. Rows that do not verify are stored but never counted.
111
+
112
+ > **Status:** paidfor.dev verifies v2 rows on Base within about five minutes; `verification_url` shows the
113
+ > result for each row.
114
+
115
+ This is the whole message, for a paid call that got a 500:
116
+
117
+ ```json
118
+ {
119
+ "v": 2,
120
+ "host": "api.example.com",
121
+ "path_hash": "<sha256 hex of the URL path without trailing slash>",
122
+ "outcome": "non_delivery",
123
+ "amount_usdc": "0.002000",
124
+ "latency_ms": 1840,
125
+ "validator_failures": ["http_status:500"],
126
+ "client": "x402-safe-fetch/0.2.1",
127
+ "proof": {
128
+ "network": "eip155:8453",
129
+ "scheme": "exact",
130
+ "asset": "0x833589fcd6edb6e08f4c7c32d4f71b54bda02913",
131
+ "pay_to": "<seller pay-to address, lowercase>",
132
+ "payer": "<your wallet address, lowercase>",
133
+ "nonce": "<32-byte EIP-3009 authorization nonce>",
134
+ "tx_hash": "<settlement transaction hash, or null if the seller's header had none>",
135
+ "settled_at": "2026-10-29T10:12:03.000Z",
136
+ "response_sha256": "<sha256 hex of the response body, or null>",
137
+ "declared_timeout_s": 60
138
+ }
139
+ }
86
140
  ```
87
141
 
88
- No bodies, no wallet address, no request parameters, no intent id. The field list and the privacy promise are in
89
- [docs/telemetry.md](docs/telemetry.md).
142
+ - **What the payer address adds.** Every settled x402 payment is already a public USDC transfer from your
143
+ address to the seller's pay-to address, with this nonce, on Base; the address, the amount and the seller's
144
+ pay-to are readable by anyone. What the row adds is the link from that payment to the seller host, the path
145
+ hash, the outcome you observed, the validator failures and the response hash. Use `"verified"` only if you
146
+ are comfortable with that association; `"anonymous"` sends the outcome without it.
147
+ - **The plain path, for unknown sellers only (0.2.1).** When the index answered `unknown` before paying (it has
148
+ never measured that seller), the row also carries `"path": "/v1/quote"`: the URL path, never the query string
149
+ or fragment. The index keeps the host and path of a verified payment to such a seller so it can buy that
150
+ seller itself at its next scheduled run, and lists it at paidfor.dev/candidates. For every seller the index
151
+ knows, only `path_hash` is sent, as before. `"anonymous"` never sends a path.
152
+ - **Keyless ingest, https only.** `POST {indexUrl}/telemetry` needs no account and no key, and the index stores
153
+ no IP address or identity with the row. With `"verified"`, `safeFetch` refuses a plain-http `indexUrl`
154
+ (loopback excepted, for local testing), and telemetry never follows a redirect.
155
+ - **Bodies and request parameters never leave your machine.** The path is hashed, the query string is dropped
156
+ before hashing, and the response is represented only by its sha256. Headers, request bodies, the intent id and
157
+ validator evidence are never sent.
158
+ - **Refusals carry no proof.** A refused or unpaid call sends the row without `proof`; it is counted as a
159
+ refusal, never in a failure rate.
160
+ - **Outcomes use the index's names:** `ok`, `non_delivery` (a non-2xx answer or a failed delivery validator after paying),
161
+ `overcharge` (paid more than 1.1x the reference, possible only if you raised `maxOverListedRatio`),
162
+ `wrong_goods`, `duplicate`, plus the client-only `refused_*`, `no_acceptable_quote`, `paid_no_response` and
163
+ `error`.
164
+ - **Turning it off.** `telemetry: "anonymous"` sends the v1 row without any address; `telemetry: "off"` (the
165
+ default) sends nothing. `indexUrl: false` turns off the index lookup and all telemetry.
166
+
167
+ The first time a receipts directory is used with `"verified"`, the client prints a one-line notice pointing
168
+ here.
90
169
 
91
170
  ## Errors
92
171
 
@@ -19,6 +19,8 @@ export interface IndexCheck {
19
19
  /** Listed price for this exact resource, USDC decimal string, when the index has one. */
20
20
  listed_price_usdc: string | null;
21
21
  }
22
+ /** `note` when the index answered and said `unknown`: it has never measured this seller (not a timeout or an error). */
23
+ export declare const UNKNOWN_SELLER_NOTE = "verdict unknown";
22
24
  /** Seller page on the site that hosts the index: https://paidfor.dev/v1 -> https://paidfor.dev/seller/<host>. */
23
25
  export declare function sellerPageUrl(indexUrl: string, host: string): string;
24
26
  /** Strip query and fragment: the index matches on host + path and never needs request parameters. */
@@ -1,4 +1,6 @@
1
1
  const VERDICTS = ["avoid", "caution", "ok", "unknown"];
2
+ /** `note` when the index answered and said `unknown`: it has never measured this seller (not a timeout or an error). */
3
+ export const UNKNOWN_SELLER_NOTE = "verdict unknown";
2
4
  const str = (v) => (typeof v === "string" && v.trim() !== "" ? v : null);
3
5
  const obj = (v) => (v && typeof v === "object" && !Array.isArray(v) ? v : null);
4
6
  /** Seller page on the site that hosts the index: https://paidfor.dev/v1 -> https://paidfor.dev/seller/<host>. */
@@ -35,7 +37,7 @@ export function parseCheck(body, indexUrl, resourceUrl) {
35
37
  listed_price_usdc: str(resource?.listed_price_usdc),
36
38
  };
37
39
  if (verdict === "unknown")
38
- out.note = rawVerdict ? "verdict unknown" : "no verdict in response";
40
+ out.note = rawVerdict ? UNKNOWN_SELLER_NOTE : "no verdict in response";
39
41
  return out;
40
42
  }
41
43
  export async function checkIndex(indexUrl, resourceUrl, o = {}) {
package/dist/index.d.ts CHANGED
@@ -4,4 +4,5 @@ export type { Receipt, Outcome } from "./receipt.js";
4
4
  export type { Verdict, IndexCheck } from "./index-client.js";
5
5
  export type { ValidatorName } from "./taxonomy.js";
6
6
  export type { ValidatorResult } from "./validators/types.js";
7
- export type { TelemetryPayload } from "./telemetry.js";
7
+ export type { TelemetryPayload, TelemetryPayloadV2 } from "./telemetry.js";
8
+ export type { TelemetryProof, TelemetryOutcome } from "./proof.js";
@@ -0,0 +1,71 @@
1
+ /**
2
+ * Proof of payment and harness outcome names for the v2 ("verified") telemetry row. The contract is the
3
+ * "Telemetry v2 payload" block (docs/telemetry.md). Everything here comes from what the client already has:
4
+ * the authorization it signed, the seller's settlement header, the paid response body and the 402 quote.
5
+ *
6
+ * The outcome mapping follows x402-audit src/classify.ts precedence for a paid call:
7
+ * duplicate > non_delivery > wrong_goods > overcharge > ok.
8
+ */
9
+ import type { Outcome } from "./receipt.js";
10
+ import type { DecodedSettlement } from "./x402/settlement.js";
11
+ export interface TelemetryProof {
12
+ network: string;
13
+ scheme: string;
14
+ asset: string;
15
+ pay_to: string;
16
+ payer: string;
17
+ nonce: string;
18
+ tx_hash: string | null;
19
+ settled_at: string;
20
+ response_sha256: string | null;
21
+ declared_timeout_s: number;
22
+ }
23
+ export type TelemetryOutcome = "ok" | "non_delivery" | "overcharge" | "wrong_goods" | "duplicate" | "refused_verdict" | "refused_ratio" | "refused_max_per_call" | "no_acceptable_quote" | "paid_no_response" | "validator_failed" | "error";
24
+ /** Outcomes where nothing was paid. Their rows never carry proof and are counted as refusals, not failures. */
25
+ export declare const REFUSED_OUTCOMES: ReadonlySet<string>;
26
+ /** The ratio the harness and this client's default use for "over the reference". */
27
+ export declare const DEFAULT_MAX_RATIO = 1.1;
28
+ export interface ProofInput {
29
+ /** CAIP-2 network of the signed authorization, e.g. "eip155:8453". */
30
+ network: string;
31
+ scheme: string;
32
+ asset: string;
33
+ payTo: string;
34
+ /** authorization.from */
35
+ payer: string;
36
+ /** authorization.nonce */
37
+ nonce: string;
38
+ settlement: DecodedSettlement;
39
+ /** When the paid response headers arrived, or when the paid request was sent if none did. */
40
+ settledAt: number;
41
+ responseSha256: string | null;
42
+ declaredTimeoutS: number;
43
+ }
44
+ /** Returns null when a signed field is not in the contract's form, so a malformed row is never sent. */
45
+ export declare function buildProof(i: ProofInput): TelemetryProof | null;
46
+ export interface OutcomeInput {
47
+ /** The client outcome on the receipt. */
48
+ outcome: Outcome;
49
+ /** HTTP status of the paid response, when one came back. */
50
+ status?: number;
51
+ /** Names of failed validators. */
52
+ validatorFailures: readonly string[];
53
+ /** `success` from the settlement header; null when there was no parseable header. */
54
+ settlementSuccess: boolean | null;
55
+ /**
56
+ * Settlements observed for this intent. Defaults to 0 when the header says the settlement failed, else 1.
57
+ * The client sends one paid request per intent, so it can only pass more than 1 if it ever sees a second.
58
+ */
59
+ settlements?: number;
60
+ amountAtomic?: bigint;
61
+ referenceAtomic?: bigint;
62
+ }
63
+ /**
64
+ * Client outcome to the harness name for a v2 row. Refusals and client-only outcomes pass through unchanged.
65
+ * A paid call with a response is classified like x402-audit: no settlement and a non-2xx answer is the seller
66
+ * rejecting the payment (harness `not_paid`, sent as `error`); otherwise delivery validators, then goods
67
+ * validators, then price. A header without `success: false` counts as settled: the index checks the chain.
68
+ */
69
+ export declare function harnessOutcome(i: OutcomeInput): TelemetryOutcome;
70
+ /** v2 `validator_failures`: names, with the status on http_status ("http_status:500") as in the contract. */
71
+ export declare function failureLabels(names: readonly string[], status: number | undefined): string[];
package/dist/proof.js ADDED
@@ -0,0 +1,66 @@
1
+ import { exceedsRatio } from "./price.js";
2
+ /** Outcomes where nothing was paid. Their rows never carry proof and are counted as refusals, not failures. */
3
+ export const REFUSED_OUTCOMES = new Set(["refused_verdict", "refused_ratio", "refused_max_per_call", "no_acceptable_quote"]);
4
+ /** The ratio the harness and this client's default use for "over the reference". */
5
+ export const DEFAULT_MAX_RATIO = 1.1;
6
+ /** x402-audit DELIVERY_VALIDATORS and GOODS_VALIDATORS. This client ships only the delivery four. */
7
+ const DELIVERY_VALIDATORS = ["http_status", "non_empty", "content_type", "not_truncated"];
8
+ const GOODS_VALIDATORS = ["json_schema", "entity_matches", "freshness"];
9
+ const ADDRESS_RE = /^0x[0-9a-f]{40}$/;
10
+ const BYTES32_RE = /^0x[0-9a-f]{64}$/;
11
+ /** Returns null when a signed field is not in the contract's form, so a malformed row is never sent. */
12
+ export function buildProof(i) {
13
+ const asset = i.asset.toLowerCase();
14
+ const payTo = i.payTo.toLowerCase();
15
+ const payer = i.payer.toLowerCase();
16
+ const nonce = i.nonce.toLowerCase();
17
+ if (!ADDRESS_RE.test(asset) || !ADDRESS_RE.test(payTo) || !ADDRESS_RE.test(payer) || !BYTES32_RE.test(nonce))
18
+ return null;
19
+ if (!/^eip155:\d+$/.test(i.network) || !Number.isInteger(i.declaredTimeoutS) || i.declaredTimeoutS < 0)
20
+ return null;
21
+ const tx = i.settlement.parsed?.transaction?.toLowerCase();
22
+ const sha = i.responseSha256?.toLowerCase() ?? null;
23
+ return {
24
+ network: i.network,
25
+ scheme: i.scheme,
26
+ asset,
27
+ pay_to: payTo,
28
+ payer,
29
+ nonce,
30
+ tx_hash: tx !== undefined && BYTES32_RE.test(tx) ? tx : null,
31
+ settled_at: new Date(i.settledAt).toISOString(),
32
+ response_sha256: sha !== null && /^[0-9a-f]{64}$/.test(sha) ? sha : null,
33
+ declared_timeout_s: i.declaredTimeoutS,
34
+ };
35
+ }
36
+ /**
37
+ * Client outcome to the harness name for a v2 row. Refusals and client-only outcomes pass through unchanged.
38
+ * A paid call with a response is classified like x402-audit: no settlement and a non-2xx answer is the seller
39
+ * rejecting the payment (harness `not_paid`, sent as `error`); otherwise delivery validators, then goods
40
+ * validators, then price. A header without `success: false` counts as settled: the index checks the chain.
41
+ */
42
+ export function harnessOutcome(i) {
43
+ if (i.outcome !== "ok" && i.outcome !== "validator_failed") {
44
+ return i.outcome === "replayed" || i.outcome === "no_payment_required" ? "error" : i.outcome;
45
+ }
46
+ const failed = new Set(i.validatorFailures);
47
+ const delivered = i.status !== undefined ? i.status >= 200 && i.status < 300 : !failed.has("http_status");
48
+ const n = i.settlements ?? (i.settlementSuccess === false ? 0 : 1);
49
+ if (n === 0 && !delivered)
50
+ return "error";
51
+ if (n > 1)
52
+ return "duplicate";
53
+ // A paid non-2xx is non-delivery even when the caller turned http_status off.
54
+ if (!delivered || DELIVERY_VALIDATORS.some((v) => failed.has(v)))
55
+ return "non_delivery";
56
+ if (GOODS_VALIDATORS.some((v) => failed.has(v)))
57
+ return "wrong_goods";
58
+ if (i.amountAtomic !== undefined && i.referenceAtomic !== undefined && exceedsRatio(i.amountAtomic, i.referenceAtomic, DEFAULT_MAX_RATIO)) {
59
+ return "overcharge";
60
+ }
61
+ return "ok";
62
+ }
63
+ /** v2 `validator_failures`: names, with the status on http_status ("http_status:500") as in the contract. */
64
+ export function failureLabels(names, status) {
65
+ return names.map((n) => (n === "http_status" && status !== undefined ? `${n}:${status}` : n));
66
+ }
package/dist/receipt.d.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  import type { Verdict } from "./index-client.js";
2
2
  import type { ReferenceSource } from "./price.js";
3
+ import type { TelemetryOutcome, TelemetryProof } from "./proof.js";
3
4
  import type { ValidatorName } from "./taxonomy.js";
4
5
  import type { SettlementResponse } from "./x402/types.js";
5
6
  import type { ValidatorResult } from "./validators/types.js";
@@ -61,11 +62,24 @@ export interface Receipt {
61
62
  };
62
63
  tx_hash: string | null;
63
64
  nonce: string | null;
65
+ /** authorization.from of the signed payment, lowercase. */
66
+ payer: string | null;
67
+ /** Proof of payment for a sent authorization (the `proof` of a v2 telemetry row). Null when nothing was sent. */
68
+ proof: TelemetryProof | null;
69
+ /** The outcome under the harness names, as a v2 telemetry row reports it. */
70
+ reported_outcome: TelemetryOutcome | null;
71
+ /**
72
+ * {indexUrl}/telemetry/<payer>/<nonce>: whether the index verified this purchase on-chain. Set only when
73
+ * telemetry is "verified" and a proof was sent.
74
+ */
75
+ verification_url: string | null;
64
76
  response: {
65
77
  status: number;
66
78
  content_type: string | null;
67
79
  bytes_inspected: number;
68
80
  body_truncated_for_validation: boolean;
81
+ /** sha256 hex of the response body; null when it was longer than the validator cap and not fully read. */
82
+ sha256: string | null;
69
83
  } | null;
70
84
  error: {
71
85
  code: string;
@@ -14,8 +14,11 @@ export interface SafeFetchOptions {
14
14
  indexUrl?: string | false;
15
15
  /** Validators to run on paid responses. Default: all four. */
16
16
  validators?: ValidatorName[];
17
- /** Default "off". "anonymous" posts the outcome-only payload in docs/telemetry.md. */
18
- telemetry?: "anonymous" | "off";
17
+ /**
18
+ * Default "off". "anonymous" posts the outcome-only v1 payload in docs/telemetry.md. "verified" posts the v2
19
+ * payload: the same fields plus a proof of payment (payer, nonce, pay-to, tx hash) the index checks on Base.
20
+ */
21
+ telemetry?: "anonymous" | "verified" | "off";
19
22
  /** Receipts, intents, price book and debug log. Default "./.x402-receipts" (resolved once, at creation). */
20
23
  receiptsDir?: string;
21
24
  /** Default Base mainnet. Only USDC on this network is paid. */
@@ -9,19 +9,20 @@
9
9
  * so wrapFetchWithPayment never re-signs.
10
10
  */
11
11
  import { createHash, randomUUID } from "node:crypto";
12
- import { readFile } from "node:fs/promises";
12
+ import { access, mkdir, readFile, writeFile } from "node:fs/promises";
13
13
  import { join, resolve } from "node:path";
14
14
  import { x402Client } from "@x402/core/client";
15
15
  import { registerExactEvmScheme } from "@x402/evm/exact/client";
16
16
  import { wrapFetchWithPayment } from "@x402/fetch";
17
17
  import { readBodyTee } from "./body.js";
18
18
  import { IntentIndeterminateError, PaymentRefusedError, SafeFetchError } from "./errors.js";
19
- import { checkIndex } from "./index-client.js";
19
+ import { UNKNOWN_SELLER_NOTE, checkIndex } from "./index-client.js";
20
20
  import { IntentStore } from "./intents.js";
21
21
  import { PriceBook, USDC_BY_NETWORK, atomicToUsdc, exceedsRatio, quoteRatio, resourceKey, usdToAtomic, usdcStringToAtomic } from "./price.js";
22
+ import { DEFAULT_MAX_RATIO, REFUSED_OUTCOMES, buildProof, failureLabels, harnessOutcome } from "./proof.js";
22
23
  import { writeReceipt } from "./receipt.js";
23
24
  import { ALL_VALIDATORS, MAX_BODY_BYTES } from "./taxonomy.js";
24
- import { CLIENT_ID, buildPayload, sendTelemetry } from "./telemetry.js";
25
+ import { CLIENT_ID, buildPayload, buildPayloadV2, sendTelemetry } from "./telemetry.js";
25
26
  import { runAllValidators, validatorsByName } from "./validators/index.js";
26
27
  import { buildResponseRecord, headersToRecord } from "./x402/http.js";
27
28
  import { quoteFromResponse } from "./x402/quote.js";
@@ -67,11 +68,23 @@ function wrapResponse(status, statusText, headers, body, url, receipt) {
67
68
  return res;
68
69
  }
69
70
  const TX_HASH_RE = /^0x[0-9a-fA-F]{64}$/;
71
+ /** Verified rows carry the payer and nonce, so they only go over https, or to this machine. */
72
+ function isSecureOrLoopback(url) {
73
+ try {
74
+ const u = new URL(url);
75
+ if (u.protocol === "https:")
76
+ return true;
77
+ return u.protocol === "http:" && ["localhost", "127.0.0.1", "[::1]"].includes(u.hostname);
78
+ }
79
+ catch {
80
+ return false;
81
+ }
82
+ }
70
83
  export function safeFetch(wallet, options) {
71
84
  if (!options || typeof options.maxPerCallUsd !== "number" || !(options.maxPerCallUsd > 0)) {
72
85
  throw new TypeError("safeFetch: options.maxPerCallUsd must be a positive number");
73
86
  }
74
- const maxRatio = options.maxOverListedRatio ?? 1.1;
87
+ const maxRatio = options.maxOverListedRatio ?? DEFAULT_MAX_RATIO;
75
88
  if (!(Number.isFinite(maxRatio) && maxRatio > 0))
76
89
  throw new TypeError("safeFetch: maxOverListedRatio must be a positive number");
77
90
  const network = options.network ?? "eip155:8453";
@@ -82,7 +95,10 @@ export function safeFetch(wallet, options) {
82
95
  const indexUrl = options.indexUrl === false ? undefined : (options.indexUrl ?? "https://paidfor.dev/v1").replace(/\/$/, "");
83
96
  const refuseVerdicts = new Set(options.refuseVerdicts ?? ["avoid"]);
84
97
  const validators = validatorsByName(options.validators ?? [...ALL_VALIDATORS]);
85
- const telemetryOn = options.telemetry === "anonymous" && indexUrl !== undefined;
98
+ if (options.telemetry === "verified" && indexUrl !== undefined && !isSecureOrLoopback(indexUrl)) {
99
+ throw new TypeError(`safeFetch: telemetry "verified" needs an https indexUrl (or a loopback one for local testing), got ${indexUrl}`);
100
+ }
101
+ const telemetry = indexUrl !== undefined && (options.telemetry === "anonymous" || options.telemetry === "verified") ? options.telemetry : "off";
86
102
  const receiptsDir = resolve(options.receiptsDir ?? "./.x402-receipts");
87
103
  const baseFetch = options.fetch ?? globalThis.fetch;
88
104
  const indexTimeoutMs = options.indexTimeoutMs ?? 2000;
@@ -98,6 +114,30 @@ export function safeFetch(wallet, options) {
98
114
  /* ignore */
99
115
  }
100
116
  };
117
+ if (telemetry === "verified")
118
+ void verifiedNotice();
119
+ /** Once per receipts directory: say what verified telemetry sends and where it is documented. */
120
+ async function verifiedNotice() {
121
+ const marker = join(receiptsDir, ".verified-telemetry-notice");
122
+ try {
123
+ await access(marker);
124
+ return;
125
+ }
126
+ catch {
127
+ /* first run */
128
+ }
129
+ warn('telemetry: "verified" sends each purchase outcome with its proof of payment (payer address, nonce, pay-to, tx hash) ' +
130
+ `to ${indexUrl}/telemetry so the index can check it on Base. No bodies, request parameters, IP or identity. ` +
131
+ 'See "What verified telemetry sends and why": https://www.npmjs.com/package/@paidfor/x402-safe-fetch#what-verified-telemetry-sends-and-why ' +
132
+ '(set telemetry: "anonymous" or "off" to change it). Shown once.');
133
+ try {
134
+ await mkdir(receiptsDir, { recursive: true });
135
+ await writeFile(marker, `${new Date().toISOString()}\n`);
136
+ }
137
+ catch {
138
+ /* shown again next run; harmless */
139
+ }
140
+ }
101
141
  /** Write the receipt; a local disk failure after paying must not hide the response from the caller. */
102
142
  async function persistReceipt(r) {
103
143
  try {
@@ -109,15 +149,58 @@ export function safeFetch(wallet, options) {
109
149
  }
110
150
  }
111
151
  function emitTelemetry(r) {
112
- if (!telemetryOn || !indexUrl)
152
+ if (telemetry === "off" || !indexUrl)
113
153
  return;
114
154
  try {
115
- void sendTelemetry(indexUrl, buildPayload({ url: r.url, outcome: r.outcome, amountUsdc: r.amount_usdc, latencyMs: r.latency_ms, validatorFailures: r.validator_failures }), { receiptsDir, fetchImpl: baseFetch });
155
+ const payload = telemetry === "verified"
156
+ ? buildPayloadV2({
157
+ url: r.url,
158
+ outcome: r.reported_outcome ?? "error",
159
+ amountUsdc: r.amount_usdc,
160
+ latencyMs: r.latency_ms,
161
+ validatorFailures: failureLabels(r.validator_failures, r.response?.status),
162
+ proof: r.proof,
163
+ unknownSeller: r.index_note === UNKNOWN_SELLER_NOTE,
164
+ })
165
+ : buildPayload({ url: r.url, outcome: r.outcome, amountUsdc: r.amount_usdc, latencyMs: r.latency_ms, validatorFailures: r.validator_failures });
166
+ void sendTelemetry(indexUrl, payload, { receiptsDir, fetchImpl: baseFetch });
116
167
  }
117
168
  catch {
118
169
  /* never on the purchase path */
119
170
  }
120
171
  }
172
+ /**
173
+ * Fill proof, reported_outcome and verification_url once the outcome is final. Proof only for a sent
174
+ * authorization; a refused outcome never carries one.
175
+ */
176
+ function attachProof(r, settledAt, settlement) {
177
+ const refAtomic = r.reference ? usdcStringToAtomic(r.reference.amount_usdc) : undefined;
178
+ r.reported_outcome = harnessOutcome({
179
+ outcome: r.outcome,
180
+ ...(r.response ? { status: r.response.status } : {}),
181
+ validatorFailures: r.validator_failures,
182
+ settlementSuccess: settlement.parsed ? settlement.parsed.success : null,
183
+ ...(r.quote ? { amountAtomic: BigInt(r.quote.amount_atomic) } : {}),
184
+ ...(refAtomic !== undefined ? { referenceAtomic: refAtomic } : {}),
185
+ });
186
+ if (!r.paid || REFUSED_OUTCOMES.has(r.reported_outcome) || !r.quote || !r.payer || !r.nonce || settledAt === undefined)
187
+ return;
188
+ r.proof = buildProof({
189
+ network,
190
+ scheme: r.quote.scheme,
191
+ asset: r.quote.asset,
192
+ payTo: r.quote.pay_to,
193
+ payer: r.payer,
194
+ nonce: r.nonce,
195
+ settlement,
196
+ settledAt,
197
+ responseSha256: r.response?.sha256 ?? null,
198
+ declaredTimeoutS: r.quote.max_timeout_seconds,
199
+ });
200
+ if (r.proof && telemetry === "verified" && indexUrl) {
201
+ r.verification_url = `${indexUrl}/telemetry/${r.proof.payer}/${r.proof.nonce}`;
202
+ }
203
+ }
121
204
  function baseReceipt(req, intentId, requestHash, t0) {
122
205
  let host = null;
123
206
  try {
@@ -152,6 +235,10 @@ export function safeFetch(wallet, options) {
152
235
  settlement: { header: null, version: null, parsed: null, parse_error: null },
153
236
  tx_hash: null,
154
237
  nonce: null,
238
+ payer: null,
239
+ proof: null,
240
+ reported_outcome: null,
241
+ verification_url: null,
155
242
  response: null,
156
243
  error: null,
157
244
  };
@@ -186,6 +273,10 @@ export function safeFetch(wallet, options) {
186
273
  r.validator_failures = original.validator_failures;
187
274
  r.tx_hash = original.tx_hash;
188
275
  r.nonce = original.nonce;
276
+ r.payer = original.payer ?? null;
277
+ r.proof = original.proof ?? null;
278
+ r.reported_outcome = original.reported_outcome ?? null;
279
+ r.verification_url = original.verification_url ?? null;
189
280
  r.settlement = original.settlement;
190
281
  r.response = original.response;
191
282
  }
@@ -336,6 +427,7 @@ export function safeFetch(wallet, options) {
336
427
  throw new Error(failure.message);
337
428
  }
338
429
  r.nonce = String(a.nonce);
430
+ r.payer = String(a.from).toLowerCase();
339
431
  r.amount_usdc = atomicToUsdc(BigInt(value));
340
432
  try {
341
433
  await lease.update({ phase: "signed", nonce: r.nonce, amount_atomic: value, pay_to: to });
@@ -400,6 +492,7 @@ export function safeFetch(wallet, options) {
400
492
  if (refusal) {
401
493
  finish(r, t0, refusal.code);
402
494
  r.error = { code: refusal.code, message: refusal.message };
495
+ attachProof(r, undefined, {});
403
496
  await lease.update({ phase: "refused" }).catch(() => undefined);
404
497
  await persistReceipt(r);
405
498
  emitTelemetry(r);
@@ -411,6 +504,7 @@ export function safeFetch(wallet, options) {
411
504
  finish(r, t0, "paid_no_response");
412
505
  const message = `x402-safe-fetch: payment for ${req.url} was signed (nonce ${r.nonce})${sent ? " and sent" : ""}, but no response came back: ${errMsg(e)}. Retrying intent ${r.intent_id} will not sign again.`;
413
506
  r.error = { code: "paid_no_response", message };
507
+ attachProof(r, paidStart, {});
414
508
  await persistReceipt(r);
415
509
  emitTelemetry(r);
416
510
  throw new SafeFetchError("paid_no_response", message, r, { cause: e });
@@ -434,6 +528,7 @@ export function safeFetch(wallet, options) {
434
528
  }
435
529
  finish(r, t0, code === "no_acceptable_quote" ? "no_acceptable_quote" : "error");
436
530
  r.error = { code, message };
531
+ attachProof(r, undefined, {});
437
532
  await lease.update({ phase: "failed_unpaid" }).catch(() => undefined);
438
533
  await persistReceipt(r);
439
534
  if (quoteResult)
@@ -458,7 +553,13 @@ export function safeFetch(wallet, options) {
458
553
  }, validators);
459
554
  r.validators = results;
460
555
  r.validator_failures = Object.entries(results).filter(([, v]) => v.status === "fail").map(([k]) => k);
461
- r.response = { status: res.status, content_type: res.headers.get("content-type"), bytes_inspected: record.body.length, body_truncated_for_validation: read.truncatedByUs };
556
+ r.response = {
557
+ status: res.status,
558
+ content_type: res.headers.get("content-type"),
559
+ bytes_inspected: record.body.length,
560
+ body_truncated_for_validation: read.truncatedByUs,
561
+ sha256: read.truncatedByUs ? null : sha256(record.body),
562
+ };
462
563
  if (paidCount === 0) {
463
564
  // Free resource: no 402, nothing signed.
464
565
  await settleIndex();
@@ -473,6 +574,7 @@ export function safeFetch(wallet, options) {
473
574
  const tx = st.parsed?.transaction;
474
575
  r.tx_hash = typeof tx === "string" && TX_HASH_RE.test(tx) ? tx : null;
475
576
  finish(r, t0, r.validator_failures.length ? "validator_failed" : "ok");
577
+ attachProof(r, paidHeadersAt ?? Date.now(), st);
476
578
  const receiptFile = await persistReceipt(r);
477
579
  const stored = {
478
580
  url: res.url || req.url,
@@ -1,4 +1,5 @@
1
- export declare const CLIENT_ID = "x402-safe-fetch/0.1.0";
1
+ import type { TelemetryOutcome, TelemetryProof } from "./proof.js";
2
+ export declare const CLIENT_ID = "x402-safe-fetch/0.2.1";
2
3
  export interface TelemetryPayload {
3
4
  v: 1;
4
5
  host: string;
@@ -18,8 +19,36 @@ export declare function buildPayload(i: {
18
19
  latencyMs: number;
19
20
  validatorFailures: string[];
20
21
  }): TelemetryPayload;
22
+ export interface TelemetryPayloadV2 {
23
+ v: 2;
24
+ host: string;
25
+ path_hash: string;
26
+ outcome: TelemetryOutcome;
27
+ amount_usdc: string;
28
+ latency_ms: number;
29
+ validator_failures: string[];
30
+ client: typeof CLIENT_ID;
31
+ /** Present only when an authorization was signed and sent. Never on a refused outcome. */
32
+ proof?: TelemetryProof;
33
+ /** The plain URL path (no query string or fragment), only when the index answered `unknown` for this seller. */
34
+ path?: string;
35
+ }
36
+ /** Longest path sent; a longer one is left out rather than risk the row. */
37
+ export declare const MAX_PATH_LENGTH = 512;
38
+ /** The URL path exactly as it is hashed for path_hash, before the trailing slash is removed. Null past MAX_PATH_LENGTH. */
39
+ export declare function plainPath(url: string): string | null;
40
+ export declare function buildPayloadV2(i: {
41
+ url: string;
42
+ outcome: TelemetryOutcome;
43
+ amountUsdc: string;
44
+ latencyMs: number;
45
+ validatorFailures: string[];
46
+ proof: TelemetryProof | null;
47
+ /** The pre-pay index check answered `unknown`: send the plain path for this call. */
48
+ unknownSeller?: boolean;
49
+ }): TelemetryPayloadV2;
21
50
  /** Never awaited by callers, never throws, never rejects. Returns the promise only so tests can wait on it. */
22
- export declare function sendTelemetry(indexUrl: string, payload: TelemetryPayload, o: {
51
+ export declare function sendTelemetry(indexUrl: string, payload: TelemetryPayload | TelemetryPayloadV2, o: {
23
52
  receiptsDir: string;
24
53
  fetchImpl?: typeof globalThis.fetch;
25
54
  }): Promise<void>;
package/dist/telemetry.js CHANGED
@@ -1,12 +1,15 @@
1
1
  /**
2
- * Anonymous outcome telemetry. Exactly the payload in docs/telemetry.md: no bodies, no wallet address,
3
- * no request parameters, no intent id. Fire-and-forget with a 1 s timeout; failures are only counted
4
- * in <receiptsDir>/debug.log.
2
+ * Outcome telemetry. Exactly the payloads in docs/telemetry.md. "anonymous" sends v1: no bodies, no wallet
3
+ * address, no request parameters, no intent id. "verified" sends v2: the v1 fields with harness outcome names,
4
+ * plus `proof` (payer, nonce, pay-to, tx hash) for paid calls so the index can check the payment on Base, and the
5
+ * plain `path` only when the index answered `unknown` before paying, so it can buy that seller itself.
6
+ * Fire-and-forget with a 1 s timeout; failures are only counted in <receiptsDir>/debug.log.
5
7
  */
6
8
  import { createHash } from "node:crypto";
7
9
  import { appendFile, mkdir } from "node:fs/promises";
8
10
  import { join } from "node:path";
9
- export const CLIENT_ID = "x402-safe-fetch/0.1.0";
11
+ import { REFUSED_OUTCOMES } from "./proof.js";
12
+ export const CLIENT_ID = "x402-safe-fetch/0.2.1";
10
13
  /** sha256 hex of the URL path with any trailing slash removed. Query string and fragment never enter it. */
11
14
  export function pathHash(url) {
12
15
  const p = new URL(url).pathname.replace(/\/$/, "") || "/";
@@ -24,6 +27,28 @@ export function buildPayload(i) {
24
27
  client: CLIENT_ID,
25
28
  };
26
29
  }
30
+ /** Longest path sent; a longer one is left out rather than risk the row. */
31
+ export const MAX_PATH_LENGTH = 512;
32
+ /** The URL path exactly as it is hashed for path_hash, before the trailing slash is removed. Null past MAX_PATH_LENGTH. */
33
+ export function plainPath(url) {
34
+ const p = new URL(url).pathname || "/";
35
+ return p.length <= MAX_PATH_LENGTH ? p : null;
36
+ }
37
+ export function buildPayloadV2(i) {
38
+ const p = {
39
+ ...buildPayload({ ...i, outcome: i.outcome }),
40
+ v: 2,
41
+ outcome: i.outcome,
42
+ };
43
+ if (i.proof && !REFUSED_OUTCOMES.has(i.outcome))
44
+ p.proof = { ...i.proof };
45
+ if (i.unknownSeller) {
46
+ const path = plainPath(i.url);
47
+ if (path)
48
+ p.path = path;
49
+ }
50
+ return p;
51
+ }
27
52
  let failures = 0;
28
53
  /** Never awaited by callers, never throws, never rejects. Returns the promise only so tests can wait on it. */
29
54
  export function sendTelemetry(indexUrl, payload, o) {
@@ -45,6 +70,8 @@ export function sendTelemetry(indexUrl, payload, o) {
45
70
  headers: { "content-type": "application/json" },
46
71
  body: JSON.stringify(payload),
47
72
  signal: AbortSignal.timeout(1000),
73
+ // The route answers directly; never let a redirect carry the row somewhere else (or to plain http).
74
+ redirect: "error",
48
75
  });
49
76
  res.body?.cancel().catch(() => undefined);
50
77
  if (!res.ok)
@@ -77,15 +77,19 @@ export declare const PaymentPayloadSchema: z.ZodObject<{
77
77
  extensions: z.ZodNullable<z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>>;
78
78
  }, z.core.$loose>;
79
79
  export type PaymentPayload = z.infer<typeof PaymentPayloadSchema>;
80
- /** Body of PAYMENT-RESPONSE / X-PAYMENT-RESPONSE (SettleResponse, notes §6). */
80
+ /**
81
+ * Body of PAYMENT-RESPONSE / X-PAYMENT-RESPONSE (SettleResponse, notes §6). The optional fields accept null:
82
+ * real v1 facilitators send `"errorReason": null` on success (every v1 header in the harness database does),
83
+ * and rejecting that would drop the transaction hash. Diverges from x402-audit, which still uses .optional().
84
+ */
81
85
  export declare const SettlementResponseSchema: z.ZodObject<{
82
86
  success: z.ZodBoolean;
83
87
  transaction: z.ZodString;
84
88
  network: z.ZodString;
85
- payer: z.ZodOptional<z.ZodString>;
86
- errorReason: z.ZodOptional<z.ZodString>;
87
- errorMessage: z.ZodOptional<z.ZodString>;
88
- amount: z.ZodOptional<z.ZodString>;
89
+ payer: z.ZodOptional<z.ZodNullable<z.ZodString>>;
90
+ errorReason: z.ZodOptional<z.ZodNullable<z.ZodString>>;
91
+ errorMessage: z.ZodOptional<z.ZodNullable<z.ZodString>>;
92
+ amount: z.ZodOptional<z.ZodNullable<z.ZodString>>;
89
93
  }, z.core.$loose>;
90
94
  export type SettlementResponse = z.infer<typeof SettlementResponseSchema>;
91
95
  export declare const PaymentRequirementsV1Schema: z.ZodObject<{
@@ -50,15 +50,19 @@ export const PaymentPayloadSchema = z.looseObject({
50
50
  payload: AnyRecord,
51
51
  extensions: OptionalAny,
52
52
  });
53
- /** Body of PAYMENT-RESPONSE / X-PAYMENT-RESPONSE (SettleResponse, notes §6). */
53
+ /**
54
+ * Body of PAYMENT-RESPONSE / X-PAYMENT-RESPONSE (SettleResponse, notes §6). The optional fields accept null:
55
+ * real v1 facilitators send `"errorReason": null` on success (every v1 header in the harness database does),
56
+ * and rejecting that would drop the transaction hash. Diverges from x402-audit, which still uses .optional().
57
+ */
54
58
  export const SettlementResponseSchema = z.looseObject({
55
59
  success: z.boolean(),
56
60
  transaction: z.string(),
57
61
  network: z.string(),
58
- payer: z.string().optional(),
59
- errorReason: z.string().optional(),
60
- errorMessage: z.string().optional(),
61
- amount: z.string().optional(),
62
+ payer: z.string().nullish(),
63
+ errorReason: z.string().nullish(),
64
+ errorMessage: z.string().nullish(),
65
+ amount: z.string().nullish(),
62
66
  });
63
67
  // ---- v1 (deprecated protocol; 402 JSON body) ----
64
68
  export const PaymentRequirementsV1Schema = z.looseObject({
package/docs/telemetry.md CHANGED
@@ -1,11 +1,13 @@
1
1
  # Telemetry
2
2
 
3
- Telemetry is **off by default**. Turn it on with `telemetry: "anonymous"`.
3
+ Telemetry is **off by default**. `telemetry: "anonymous"` sends a v1 row (below). `telemetry: "verified"` sends a
4
+ v2 row: the v1 fields plus a proof of payment (see "Version 2" at the end).
4
5
 
5
6
  When it is on, each call that received an HTTP 402 sends one JSON object to `POST {indexUrl}/telemetry`
6
7
  (by default `https://paidfor.dev/v1/telemetry`). That object is the whole message. Nothing else is sent.
8
+ No account and no key are needed to send it.
7
9
 
8
- ## The exact payload
10
+ ## The exact payload (v1, `"anonymous"`)
9
11
 
10
12
  ```json
11
13
  {
@@ -16,7 +18,7 @@ When it is on, each call that received an HTTP 402 sends one JSON object to `POS
16
18
  "amount_usdc": "0.010000",
17
19
  "latency_ms": 412,
18
20
  "validator_failures": [],
19
- "client": "x402-safe-fetch/0.1.0"
21
+ "client": "x402-safe-fetch/0.2.1"
20
22
  }
21
23
  ```
22
24
 
@@ -29,9 +31,9 @@ When it is on, each call that received an HTTP 402 sends one JSON object to `POS
29
31
  | `amount_usdc` | Amount of the signed authorization as a 6-decimal string. `"0.000000"` when nothing was signed. |
30
32
  | `latency_ms` | Wall time of the call in milliseconds, rounded. |
31
33
  | `validator_failures` | Names of the validators that failed, for example `["http_status"]`. Names only, no evidence. |
32
- | `client` | Always `x402-safe-fetch/0.1.0` for this version. |
34
+ | `client` | `x402-safe-fetch/<version>`, `x402-safe-fetch/0.2.1` for this version. |
33
35
 
34
- ## What is never sent
36
+ ## What is never sent (v1)
35
37
 
36
38
  - Request or response bodies, headers, or any part of them.
37
39
  - Query strings, request parameters, or the unhashed path.
@@ -51,8 +53,84 @@ Calls to free resources (no 402) and replays of a stored intent send nothing.
51
53
  ## The promise
52
54
 
53
55
  This client sends paidfor.dev the outcome of a purchase and nothing that identifies the buyer, the wallet,
54
- or what was bought beyond the seller host and a path hash. If a future version needs to send more, it will
55
- bump `v`, list the new fields here, and stay opt-in.
56
+ or what was bought beyond the seller host and a path hash. The exceptions are opt-in and listed here: v2
57
+ (`"verified"`) adds the proof of payment, and from 0.2.1 the plain path for a seller the index has never
58
+ measured. If a future version needs to send more, it will list the new fields here and stay opt-in.
59
+
60
+ ## Version 2 (`"verified"`)
61
+
62
+ Additive over v1. `v` is `2`, `outcome` uses the harness names, `validator_failures` carries the status on
63
+ `http_status` (`"http_status:500"`), and a paid call adds `proof`:
64
+
65
+ ```json
66
+ {
67
+ "v": 2,
68
+ "host": "api.vapinetwork.ai",
69
+ "path_hash": "<sha256 hex of the URL path without trailing slash>",
70
+ "outcome": "non_delivery",
71
+ "amount_usdc": "0.002000",
72
+ "latency_ms": 1840,
73
+ "validator_failures": ["http_status:500"],
74
+ "client": "x402-safe-fetch/0.2.1",
75
+ "proof": {
76
+ "network": "eip155:8453",
77
+ "scheme": "exact",
78
+ "asset": "0x833589fcd6edb6e08f4c7c32d4f71b54bda02913",
79
+ "pay_to": "0x<seller pay-to, lowercase>",
80
+ "payer": "0x<client wallet, lowercase>",
81
+ "nonce": "0x<32-byte EIP-3009 authorization nonce>",
82
+ "tx_hash": "0x<settlement transaction hash, or null if the settlement header had none>",
83
+ "settled_at": "2026-10-29T10:12:03.000Z",
84
+ "response_sha256": "<hex of the paid response body, or null>",
85
+ "declared_timeout_s": 60
86
+ }
87
+ }
88
+ ```
89
+
90
+ | Field | Source in the client |
91
+ | --- | --- |
92
+ | `proof.network`, `scheme`, `asset`, `pay_to` | The payment requirements the client signed against (CAIP-2 network, lowercase addresses). |
93
+ | `proof.payer`, `proof.nonce` | `from` and `nonce` of the EIP-3009 authorization the client signed. |
94
+ | `proof.tx_hash` | `transaction` from the seller's `PAYMENT-RESPONSE` (x402 v2) or `X-PAYMENT-RESPONSE` (v1) header, when it is a 32-byte hash; otherwise `null`. |
95
+ | `proof.settled_at` | When the paid response's headers arrived; when none did, when the paid request was sent. |
96
+ | `proof.response_sha256` | sha256 of the paid response body; `null` when there was none or it was longer than the 2 MB validator cap. |
97
+ | `proof.declared_timeout_s` | `maxTimeoutSeconds` from the seller's 402. |
98
+
99
+ Outcomes (`outcome`), mapped like the harness classifier, first match wins:
100
+
101
+ | v2 outcome | When |
102
+ | --- | --- |
103
+ | `duplicate` | More than one settlement observed for one intent. The client sends one paid request per intent, so in practice it never sees this. |
104
+ | `error` | The settlement header says `success: false` and the answer was not 2xx: the seller rejected the payment (the harness's `not_paid`). Proof is still sent, so the index can confirm nothing moved. |
105
+ | `non_delivery` | A non-2xx answer after the payment (even with `http_status` turned off), or `non_empty`, `content_type` or `not_truncated` failed. |
106
+ | `wrong_goods` | A schema, entity or freshness validator failed. This client ships none of them, so it does not send this today. |
107
+ | `overcharge` | Paid more than 1.1x the reference (index listed price, else the last price paid). Only possible if `maxOverListedRatio` was raised. |
108
+ | `ok` | None of the above. |
109
+ | `refused_verdict`, `refused_ratio`, `refused_max_per_call`, `no_acceptable_quote` | Refused; nothing was signed. **No `proof`.** |
110
+ | `paid_no_response`, `error` | Signed and sent with no response (with `proof`, `tx_hash` null), or failed before signing (no `proof`). |
111
+
112
+ ### `path` (0.2.1): only for sellers the index has never measured
113
+
114
+ When the pre-pay `GET {indexUrl}/check` answered and its verdict was `unknown` (the index has no data on the
115
+ seller; not a timeout or an error), that call's v2 row adds one field:
116
+
117
+ ```json
118
+ "path": "/v1/quote"
119
+ ```
120
+
121
+ the URL path exactly as it was hashed for `path_hash` (no query string, no fragment; left out when longer than
122
+ 512 characters). For any seller the index knows, `path` is absent and `path_hash` is unchanged. The index keeps
123
+ the host and path of a verified payment to such a seller on its candidate list (`GET {indexUrl}/candidates`) so
124
+ it can buy the seller itself at its next scheduled run, and drops the path from the stored row once the payment
125
+ is checked. These are public API endpoints; the index already saw the same origin and path in the pre-pay
126
+ lookup. `"anonymous"` (v1) never sends it.
127
+
128
+ `validator_failed` stays a v1-only outcome. The payer address, amount and pay-to are public on-chain for every
129
+ settled payment; the v2 row adds the link from that payment to the seller host, path hash, outcome, validator
130
+ failures and response hash. Bodies, request parameters, headers, the intent id and validator evidence are never
131
+ sent in either version. `"verified"` requires an https `indexUrl` (loopback excepted), and no telemetry request
132
+ follows a redirect. Each receipt stores the same `proof` and, in `"verified"` mode,
133
+ `verification_url` = `{indexUrl}/telemetry/<payer>/<nonce>` (404 until the index serves that route).
56
134
 
57
135
  ## The other request: the index lookup
58
136
 
@@ -60,6 +60,10 @@ const fetchWithPay = safeFetch(wallet, {
60
60
  maxPerCallUsd: 10,
61
61
  validators: ["http_status", "non_empty", "content_type", "not_truncated"],
62
62
  indexUrl: false, // the example runs offline; leave the default (https://paidfor.dev/v1) in production
63
+ // Report each outcome with its proof of payment, so paidfor.dev can verify on Base that this paid 500 really
64
+ // happened and count it against the seller. Sends no bodies or request parameters; the payer address is already
65
+ // public on-chain. Needs indexUrl (sends nothing here, offline). "anonymous" drops the proof, "off" sends nothing.
66
+ telemetry: "verified",
63
67
  network: "eip155:84532",
64
68
  receiptsDir: await mkdtemp(join(tmpdir(), "conway-receipts-")),
65
69
  });
@@ -74,7 +78,7 @@ for (let tick = 1; tick <= 5; tick++) {
74
78
  const r = res.receipt;
75
79
  console.log(
76
80
  `tick ${tick}: HTTP ${res.status} ${r.replayed ? "replayed stored result, nothing signed" : `paid ${r.amount_usdc} USDC, tx ${r.tx_hash}`}` +
77
- ` validator failures: ${r.validator_failures.join(", ") || "none"}`,
81
+ ` validator failures: ${r.validator_failures.join(", ") || "none"} reported as: ${r.reported_outcome}`,
78
82
  );
79
83
  if (r.validator_failures.includes("http_status")) {
80
84
  // Paid but not delivered: stop retrying the payment and escalate with the receipt (it has the tx hash).
package/package.json CHANGED
@@ -1,27 +1,41 @@
1
1
  {
2
2
  "name": "@paidfor/x402-safe-fetch",
3
- "version": "0.1.0",
3
+ "version": "0.2.1",
4
4
  "description": "Drop-in wrapper around @x402/fetch that refuses overpriced quotes and bad sellers, never pays twice for one intent, and checks what it bought.",
5
5
  "type": "module",
6
6
  "license": "MIT",
7
7
  "author": "Sarmad Siddiki",
8
8
  "homepage": "https://paidfor.dev",
9
- "keywords": ["x402", "fetch", "payments", "usdc", "base", "idempotency", "agents"],
10
- "engines": { "node": ">=20.3" },
9
+ "keywords": [
10
+ "x402",
11
+ "fetch",
12
+ "payments",
13
+ "usdc",
14
+ "base",
15
+ "idempotency",
16
+ "agents"
17
+ ],
18
+ "engines": {
19
+ "node": ">=20.3"
20
+ },
11
21
  "exports": {
12
- ".": { "types": "./dist/index.d.ts", "import": "./dist/index.js" },
22
+ ".": {
23
+ "types": "./dist/index.d.ts",
24
+ "import": "./dist/index.js"
25
+ },
13
26
  "./package.json": "./package.json"
14
27
  },
15
28
  "main": "./dist/index.js",
16
29
  "types": "./dist/index.d.ts",
17
- "files": ["dist", "README.md", "LICENSE", "docs", "examples"],
30
+ "files": [
31
+ "dist",
32
+ "README.md",
33
+ "CHANGELOG.md",
34
+ "LICENSE",
35
+ "docs",
36
+ "examples"
37
+ ],
18
38
  "sideEffects": false,
19
- "scripts": {
20
- "build": "rm -rf dist && tsc -p tsconfig.build.json",
21
- "typecheck": "tsc -p tsconfig.json --noEmit",
22
- "test": "vitest run",
23
- "prepublishOnly": "pnpm build && pnpm typecheck && pnpm test"
24
- },
25
39
  "dependencies": {
26
40
  "@x402/core": "~2.28.0",
27
41
  "@x402/evm": "~2.28.0",
@@ -35,5 +49,9 @@
35
49
  "viem": "^2.48.11",
36
50
  "vitest": "^5.0.5"
37
51
  },
38
- "packageManager": "pnpm@10.34.8"
39
- }
52
+ "scripts": {
53
+ "build": "rm -rf dist && tsc -p tsconfig.build.json",
54
+ "typecheck": "tsc -p tsconfig.json --noEmit",
55
+ "test": "vitest run"
56
+ }
57
+ }