@paidfor/x402-safe-fetch 0.2.2 → 0.4.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/CHANGELOG.md CHANGED
@@ -1,5 +1,20 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.4.0
4
+
5
+ - **`authorize`.** A new option: a callback asked after every local check and before anything is signed. An approval
6
+ names the EIP-3009 nonce and `validBefore` to sign. Anything else, including a throw or an approval with under ten
7
+ seconds left, refuses with `refused_authorize` and signs nothing. Without the option nothing changes.
8
+ - `client` in telemetry rows and the `X-Paidfor-Client` header is `x402-safe-fetch/0.4.0`.
9
+
10
+ ## 0.3.0
11
+
12
+ - **Report-only mode.** `reportOnly()`, `withPaidforReporting(fetchWithPayment)` for `x402-fetch` 1.x and
13
+ `@x402/fetch` 2.x, and `withPaidforReportingAxios(instance)` for `x402-axios` 1.x and `@x402/axios` 2.x: keep your
14
+ own x402 client and wallet, add one line, and every paid call sends the tx_only row (docs/telemetry.md) with the
15
+ settlement transaction hash. No pre-pay check, no guard; the index reads the payer and amount from Base.
16
+ - `client` in telemetry rows and the `X-Paidfor-Client` header is `x402-safe-fetch/0.3.0`.
17
+
3
18
  ## 0.2.2
4
19
 
5
20
  - **Client header.** Every request to the index (`GET {indexUrl}/check` and `POST {indexUrl}/telemetry`) sends
package/README.md CHANGED
@@ -97,7 +97,7 @@ v1 row:
97
97
 
98
98
  ```json
99
99
  { "v": 1, "host": "api.example.com", "path_hash": "<sha256 hex of the path>", "outcome": "ok",
100
- "amount_usdc": "0.010000", "latency_ms": 412, "validator_failures": [], "client": "x402-safe-fetch/0.2.2" }
100
+ "amount_usdc": "0.010000", "latency_ms": 412, "validator_failures": [], "client": "x402-safe-fetch/0.3.0" }
101
101
  ```
102
102
 
103
103
  Both payloads and every field are documented in [docs/telemetry.md](docs/telemetry.md).
@@ -123,7 +123,7 @@ This is the whole message, for a paid call that got a 500:
123
123
  "amount_usdc": "0.002000",
124
124
  "latency_ms": 1840,
125
125
  "validator_failures": ["http_status:500"],
126
- "client": "x402-safe-fetch/0.2.2",
126
+ "client": "x402-safe-fetch/0.3.0",
127
127
  "proof": {
128
128
  "network": "eip155:8453",
129
129
  "scheme": "exact",
@@ -159,7 +159,8 @@ This is the whole message, for a paid call that got a 500:
159
159
  before hashing, and the response is represented only by its sha256. Headers, request bodies, the intent id and
160
160
  validator evidence are never sent.
161
161
  - **Refusals carry no proof.** A refused or unpaid call sends the row without `proof`; it is counted as a
162
- refusal, never in a failure rate.
162
+ refusal, never in a failure rate. A refusal by `authorize` sends no row at all: a buyer's own rule says nothing
163
+ about the seller.
163
164
  - **Outcomes use the index's names:** `ok`, `non_delivery` (a non-2xx answer or a failed delivery validator after paying),
164
165
  `overcharge` (paid more than 1.1x the reference, possible only if you raised `maxOverListedRatio`),
165
166
  `wrong_goods`, `duplicate`, plus the client-only `refused_*`, `no_acceptable_quote`, `paid_no_response` and
@@ -170,11 +171,57 @@ This is the whole message, for a paid call that got a 500:
170
171
  The first time a receipts directory is used with `"verified"`, the client prints a one-line notice pointing
171
172
  here.
172
173
 
174
+ ## Ask before paying
175
+
176
+ `authorize` asks a service of yours (a budget, a person) about each payment, after the local checks and before anything
177
+ is signed. It fails closed: a throw, or anything but a well-formed approval, refuses with `refused_authorize`.
178
+
179
+ ```ts
180
+ const fetchWithPay = safeFetch(account, {
181
+ maxPerCallUsd: 0.5,
182
+ authorize: async (q) => {
183
+ const d = await askYourPolicyServer(q); // q: intentId, url, payer, payTo, amountAtomic, network, asset, scheme
184
+ return d.ok ? { approve: true, nonce: d.ref, validBefore: d.deadline } : { approve: false, message: d.why };
185
+ },
186
+ });
187
+ ```
188
+
189
+ The payment is signed with that `nonce` (32 bytes of hex) and `validBefore` (Unix seconds), so the approval can be found
190
+ on chain. A refusal by `authorize` sends no telemetry.
191
+
192
+ ## Report-only: keep your own x402 client, add one line
193
+
194
+ Already paying with Coinbase's `x402-fetch` / `@x402/fetch` or `x402-axios` / `@x402/axios`? Keep your wallet and your
195
+ setup; wrap the result and every paid call reports its outcome to the index. No pre-pay check, no guard, no key, no
196
+ account: report-only sends the [tx_only row](docs/telemetry.md#tx_only-report-only) after the payment you already made.
197
+
198
+ ```ts
199
+ import { wrapFetchWithPayment } from "x402-fetch"; // or "@x402/fetch"
200
+ import { withPaidforReporting } from "@paidfor/x402-safe-fetch";
201
+
202
+ const fetchWithPay = withPaidforReporting(wrapFetchWithPayment(fetch, wallet)); // the one added line
203
+ ```
204
+
205
+ ```ts
206
+ import axios from "axios";
207
+ import { withPaymentInterceptor } from "x402-axios"; // or wrapAxiosWithPayment from "@x402/axios"
208
+ import { withPaidforReportingAxios } from "@paidfor/x402-safe-fetch";
209
+
210
+ const api = withPaidforReportingAxios(withPaymentInterceptor(axios.create({ baseURL }), wallet));
211
+ ```
212
+
213
+ The wrapped fetch (or instance) behaves exactly as before. After each response that carries a settlement on Base
214
+ (`PAYMENT-RESPONSE` or `X-PAYMENT-RESPONSE`), it posts the host, the plain path, `ok` for a 2xx or `non_delivery`
215
+ otherwise, the status, and the settlement transaction hash, without waiting and never throwing. The index reads the
216
+ payer and the amount from that transaction on Base and counts the report in the seller's reported series only once it
217
+ is verified. Pass `classify` to set the outcome yourself (or return `null` and call `reportOnly().report()` after your
218
+ own checks). Responses without a settlement (free calls, refusals) send nothing.
219
+
173
220
  ## Errors
174
221
 
175
222
  | Error | `code` | Paid? |
176
223
  | --- | --- | --- |
177
- | `PaymentRefusedError` | `refused_verdict`, `refused_ratio`, `refused_max_per_call` | No |
224
+ | `PaymentRefusedError` | `refused_verdict`, `refused_ratio`, `refused_max_per_call`, `refused_authorize` | No |
178
225
  | `IntentConflictError` | `intent_conflict` | No |
179
226
  | `IntentIndeterminateError` | `intent_indeterminate` | Maybe, earlier; never again |
180
227
  | `SafeFetchError` | `paid_no_response` | Signed and possibly settled; `receipt.nonce` identifies it |
package/dist/errors.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import type { Receipt } from "./receipt.js";
2
- export type SafeFetchErrorCode = "refused_verdict" | "refused_ratio" | "refused_max_per_call" | "no_acceptable_quote" | "intent_conflict" | "intent_indeterminate" | "intent_in_flight" | "paid_no_response" | "network" | "sdk";
2
+ export type SafeFetchErrorCode = "refused_verdict" | "refused_ratio" | "refused_max_per_call" | "refused_authorize" | "no_acceptable_quote" | "intent_conflict" | "intent_indeterminate" | "intent_in_flight" | "paid_no_response" | "network" | "sdk";
3
3
  /** Every error this package throws. `receipt` is set whenever a call got far enough to write one. */
4
4
  export declare class SafeFetchError extends Error {
5
5
  readonly code: SafeFetchErrorCode;
@@ -9,11 +9,11 @@ export declare class SafeFetchError extends Error {
9
9
  cause?: unknown;
10
10
  });
11
11
  }
12
- /** Refused before any signature: seller verdict, price ratio, or per-call cap. Nothing was paid. */
12
+ /** Refused before any signature: seller verdict, price ratio, per-call cap, or `authorize`. Nothing was paid. */
13
13
  export declare class PaymentRefusedError extends SafeFetchError {
14
14
  readonly sellerUrl: string | null;
15
15
  name: string;
16
- constructor(code: "refused_verdict" | "refused_ratio" | "refused_max_per_call", message: string, sellerUrl: string | null, receipt?: Receipt);
16
+ constructor(code: "refused_verdict" | "refused_ratio" | "refused_max_per_call" | "refused_authorize", message: string, sellerUrl: string | null, receipt?: Receipt);
17
17
  }
18
18
  /** Same intentId, different request. Nothing was sent. */
19
19
  export declare class IntentConflictError extends SafeFetchError {
package/dist/errors.js CHANGED
@@ -9,7 +9,7 @@ export class SafeFetchError extends Error {
9
9
  this.receipt = receipt;
10
10
  }
11
11
  }
12
- /** Refused before any signature: seller verdict, price ratio, or per-call cap. Nothing was paid. */
12
+ /** Refused before any signature: seller verdict, price ratio, per-call cap, or `authorize`. Nothing was paid. */
13
13
  export class PaymentRefusedError extends SafeFetchError {
14
14
  sellerUrl;
15
15
  name = "PaymentRefusedError";
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- export { safeFetch, hashRequest, type SafeFetch, type SafeFetchOptions, type SafeResponse, type CallOptions, type WalletLike, type SafeNetwork } from "./safe-fetch.js";
1
+ export { safeFetch, hashRequest, type SafeFetch, type SafeFetchOptions, type SafeResponse, type CallOptions, type WalletLike, type SafeNetwork, type AuthorizeRequest, type AuthorizeAnswer } from "./safe-fetch.js";
2
2
  export { SafeFetchError, PaymentRefusedError, IntentConflictError, IntentIndeterminateError, type SafeFetchErrorCode } from "./errors.js";
3
3
  export type { Receipt, Outcome } from "./receipt.js";
4
4
  export type { Verdict, IndexCheck } from "./index-client.js";
@@ -6,3 +6,4 @@ export type { ValidatorName } from "./taxonomy.js";
6
6
  export type { ValidatorResult } from "./validators/types.js";
7
7
  export type { TelemetryPayload, TelemetryPayloadV2 } from "./telemetry.js";
8
8
  export type { TelemetryProof, TelemetryOutcome } from "./proof.js";
9
+ export { reportOnly, withPaidforReporting, withPaidforReportingAxios, buildTxOnlyPayload, settlementTx, type ReportOnlyOptions, type ReportOutcome, type TxOnlyPayload, type AxiosLike } from "./report-only.js";
package/dist/index.js CHANGED
@@ -1,2 +1,3 @@
1
1
  export { safeFetch, hashRequest } from "./safe-fetch.js";
2
2
  export { SafeFetchError, PaymentRefusedError, IntentConflictError, IntentIndeterminateError } from "./errors.js";
3
+ export { reportOnly, withPaidforReporting, withPaidforReportingAxios, buildTxOnlyPayload, settlementTx } from "./report-only.js";
package/dist/proof.d.ts CHANGED
@@ -20,7 +20,7 @@ export interface TelemetryProof {
20
20
  response_sha256: string | null;
21
21
  declared_timeout_s: number;
22
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";
23
+ export type TelemetryOutcome = "ok" | "non_delivery" | "overcharge" | "wrong_goods" | "duplicate" | "refused_verdict" | "refused_ratio" | "refused_max_per_call" | "refused_authorize" | "no_acceptable_quote" | "paid_no_response" | "validator_failed" | "error";
24
24
  /** Outcomes where nothing was paid. Their rows never carry proof and are counted as refusals, not failures. */
25
25
  export declare const REFUSED_OUTCOMES: ReadonlySet<string>;
26
26
  /** The ratio the harness and this client's default use for "over the reference". */
package/dist/proof.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import { exceedsRatio } from "./price.js";
2
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"]);
3
+ export const REFUSED_OUTCOMES = new Set(["refused_verdict", "refused_ratio", "refused_max_per_call", "refused_authorize", "no_acceptable_quote"]);
4
4
  /** The ratio the harness and this client's default use for "over the reference". */
5
5
  export const DEFAULT_MAX_RATIO = 1.1;
6
6
  /** x402-audit DELIVERY_VALIDATORS and GOODS_VALIDATORS. This client ships only the delivery four. */
package/dist/receipt.d.ts CHANGED
@@ -4,7 +4,7 @@ import type { TelemetryOutcome, TelemetryProof } from "./proof.js";
4
4
  import type { ValidatorName } from "./taxonomy.js";
5
5
  import type { SettlementResponse } from "./x402/types.js";
6
6
  import type { ValidatorResult } from "./validators/types.js";
7
- export type Outcome = "ok" | "validator_failed" | "refused_verdict" | "refused_ratio" | "refused_max_per_call" | "no_acceptable_quote" | "no_payment_required" | "paid_no_response" | "replayed" | "error";
7
+ export type Outcome = "ok" | "validator_failed" | "refused_verdict" | "refused_ratio" | "refused_max_per_call" | "refused_authorize" | "no_acceptable_quote" | "no_payment_required" | "paid_no_response" | "replayed" | "error";
8
8
  export interface Receipt {
9
9
  v: 1;
10
10
  client: string;
@@ -0,0 +1,98 @@
1
+ import type { TelemetryOutcome } from "./proof.js";
2
+ import { CLIENT_ID } from "./telemetry.js";
3
+ export declare const DEFAULT_INDEX_URL = "https://paidfor.dev/v1";
4
+ /** The index checks the transaction on Base before it answers, so this waits longer than the 1 s of the other rows. */
5
+ export declare const REPORT_TIMEOUT_MS = 10000;
6
+ export type ReportOutcome = Extract<TelemetryOutcome, "ok" | "non_delivery" | "wrong_goods" | "overcharge" | "duplicate">;
7
+ /** The tx_only row, exactly as docs/telemetry.md lists it. */
8
+ export interface TxOnlyPayload {
9
+ v: 2;
10
+ proof_level: "tx_only";
11
+ host: string;
12
+ path?: string;
13
+ path_hash: string;
14
+ outcome: ReportOutcome;
15
+ amount_usdc?: string;
16
+ latency_ms: number;
17
+ validator_failures: string[];
18
+ client: typeof CLIENT_ID;
19
+ proof: {
20
+ network: "eip155:8453";
21
+ tx_hash: string;
22
+ };
23
+ }
24
+ export interface ReportOnlyOptions {
25
+ /** Default https://paidfor.dev/v1. https only (loopback excepted), like "verified" telemetry. */
26
+ indexUrl?: string;
27
+ /** Where failed reports are counted (debug.log); nothing is written when omitted. */
28
+ receiptsDir?: string;
29
+ fetch?: typeof globalThis.fetch;
30
+ /**
31
+ * Decides the outcome from the paid response; default `ok` for 2xx, `non_delivery` otherwise. Return null to skip the
32
+ * report (for example when your own validation runs later and you call `report()` yourself).
33
+ */
34
+ classify?: (r: {
35
+ url: string;
36
+ status: number;
37
+ }) => ReportOutcome | null;
38
+ /** Called with the index's answer (or the error) for each report sent; for logs and tests. */
39
+ onReport?: (r: {
40
+ tx_hash: string;
41
+ status: number | null;
42
+ body: unknown;
43
+ error?: string;
44
+ }) => void;
45
+ }
46
+ /** The settlement transaction hash on Base from a response's headers, or null when there is none (nothing was paid). */
47
+ export declare function settlementTx(headers: Record<string, string>): string | null;
48
+ export declare function buildTxOnlyPayload(i: {
49
+ url: string;
50
+ tx_hash: string;
51
+ outcome: ReportOutcome;
52
+ status?: number | undefined;
53
+ quotedUsdc?: string | number | undefined;
54
+ latencyMs?: number | undefined;
55
+ }): TxOnlyPayload;
56
+ /**
57
+ * The report-only reporter. `report()` sends one row for one paid response and never throws; it returns the promise
58
+ * only so callers and tests can wait. One transaction is reported once per reporter (the index dedupes across
59
+ * channels anyway).
60
+ */
61
+ export declare function reportOnly(o?: ReportOnlyOptions): {
62
+ /**
63
+ * Report one paid response. `headers` are the response headers (a Headers object or a plain record); without a
64
+ * Base settlement transaction in them nothing is sent. `outcome` overrides the classifier.
65
+ */
66
+ report(i: {
67
+ url: string;
68
+ status: number;
69
+ headers: Headers | Record<string, unknown>;
70
+ outcome?: ReportOutcome;
71
+ quotedUsdc?: string | number;
72
+ latencyMs?: number;
73
+ }): Promise<void>;
74
+ failureCount: () => number;
75
+ };
76
+ type FetchLike = (input: any, init?: any) => Promise<Response>;
77
+ /**
78
+ * One added line on an x402-fetch setup: `const fetchWithPay = withPaidforReporting(wrapFetchWithPayment(fetch, wallet))`.
79
+ * The returned fetch behaves exactly like the one passed in; after each response that carries a settlement on Base it
80
+ * reports the outcome (2xx `ok`, else `non_delivery`) without waiting.
81
+ */
82
+ export declare function withPaidforReporting<F extends FetchLike>(fetchWithPayment: F, o?: ReportOnlyOptions): F;
83
+ /** The parts of an Axios instance the interceptor uses (no axios import, so axios stays the caller's dependency). */
84
+ export interface AxiosLike {
85
+ interceptors: {
86
+ response: {
87
+ use(onFulfilled: (r: any) => any, onRejected: (e: any) => any): unknown;
88
+ };
89
+ };
90
+ getUri?(config?: any): string;
91
+ }
92
+ /**
93
+ * One added line on an x402-axios setup: `withPaidforReportingAxios(withPaymentInterceptor(axios.create(), wallet))`
94
+ * (or `wrapAxiosWithPayment` from `@x402/axios`). Adds one response interceptor that reports each paid response,
95
+ * successful or not, and passes everything through unchanged. Returns the same instance.
96
+ */
97
+ export declare function withPaidforReportingAxios<A extends AxiosLike>(instance: A, o?: ReportOnlyOptions): A;
98
+ export {};
@@ -0,0 +1,181 @@
1
+ /**
2
+ * Report-only mode: no pre-pay check, no guard, no wallet. After a payment the caller made with their own x402 client,
3
+ * send the index the tx_only telemetry row (docs/telemetry.md, "tx_only"): host, path, outcome, the quote if known, and
4
+ * the settlement transaction hash from the seller's PAYMENT-RESPONSE / X-PAYMENT-RESPONSE header. The index reads the
5
+ * payer and the amount from that transaction on Base. Fire-and-forget: a report never delays or fails the caller's
6
+ * request, and failures are only counted in <receiptsDir>/debug.log when a receiptsDir is given.
7
+ *
8
+ * withPaidforReporting(fetchWithPayment) wraps the fetch returned by `x402-fetch` (1.x) or `@x402/fetch` (2.x)
9
+ * `wrapFetchWithPayment`; withPaidforReportingAxios(instance) adds a response interceptor to an instance wrapped by
10
+ * `x402-axios` `withPaymentInterceptor` or `@x402/axios` `wrapAxiosWithPayment`. Both read only the response status
11
+ * and the settlement header, never a body.
12
+ */
13
+ import { appendFile, mkdir } from "node:fs/promises";
14
+ import { join } from "node:path";
15
+ import { CLIENT_HEADER, CLIENT_ID, pathHash, plainPath } from "./telemetry.js";
16
+ import { decodeSettlementHeader } from "./x402/settlement.js";
17
+ export const DEFAULT_INDEX_URL = "https://paidfor.dev/v1";
18
+ /** The index checks the transaction on Base before it answers, so this waits longer than the 1 s of the other rows. */
19
+ export const REPORT_TIMEOUT_MS = 10_000;
20
+ const TX_RE = /^0x[0-9a-f]{64}$/;
21
+ /** x402 v1 names Base "base"; v2 uses CAIP-2. The index counts Base mainnet only. */
22
+ const BASE_NETWORKS = new Set(["base", "eip155:8453"]);
23
+ /** The settlement transaction hash on Base from a response's headers, or null when there is none (nothing was paid). */
24
+ export function settlementTx(headers) {
25
+ const s = decodeSettlementHeader(headers);
26
+ const tx = s.parsed?.transaction?.toLowerCase();
27
+ if (!s.parsed || s.parsed.success === false || !tx || !TX_RE.test(tx))
28
+ return null;
29
+ if (s.parsed.network && !BASE_NETWORKS.has(s.parsed.network))
30
+ return null;
31
+ return tx;
32
+ }
33
+ export function buildTxOnlyPayload(i) {
34
+ const u = new URL(i.url);
35
+ const path = plainPath(i.url);
36
+ const quoted = i.quotedUsdc === undefined ? NaN : Number(i.quotedUsdc);
37
+ return {
38
+ v: 2,
39
+ proof_level: "tx_only",
40
+ host: u.hostname.toLowerCase(),
41
+ ...(path ? { path } : {}),
42
+ path_hash: pathHash(i.url),
43
+ outcome: i.outcome,
44
+ ...(Number.isFinite(quoted) && quoted > 0 ? { amount_usdc: quoted.toFixed(6) } : {}),
45
+ latency_ms: Math.max(0, Math.round(i.latencyMs ?? 0)),
46
+ validator_failures: i.status !== undefined && (i.status < 200 || i.status > 299) ? [`http_status:${i.status}`] : [],
47
+ client: CLIENT_ID,
48
+ proof: { network: "eip155:8453", tx_hash: i.tx_hash.toLowerCase() },
49
+ };
50
+ }
51
+ const defaultClassify = ({ status }) => (status >= 200 && status < 300 ? "ok" : "non_delivery");
52
+ function assertIndexUrl(indexUrl) {
53
+ const u = new URL(indexUrl);
54
+ const loopback = ["localhost", "127.0.0.1", "[::1]"].includes(u.hostname);
55
+ if (u.protocol !== "https:" && !(u.protocol === "http:" && loopback))
56
+ throw new Error(`reportOnly: indexUrl must be https (got ${indexUrl})`);
57
+ }
58
+ /**
59
+ * The report-only reporter. `report()` sends one row for one paid response and never throws; it returns the promise
60
+ * only so callers and tests can wait. One transaction is reported once per reporter (the index dedupes across
61
+ * channels anyway).
62
+ */
63
+ export function reportOnly(o = {}) {
64
+ const indexUrl = (o.indexUrl ?? DEFAULT_INDEX_URL).replace(/\/$/, "");
65
+ assertIndexUrl(indexUrl);
66
+ const fetchImpl = o.fetch ?? globalThis.fetch;
67
+ const sent = new Set();
68
+ let failures = 0;
69
+ const logFailure = async (why) => {
70
+ failures++;
71
+ if (!o.receiptsDir)
72
+ return;
73
+ try {
74
+ await mkdir(o.receiptsDir, { recursive: true });
75
+ await appendFile(join(o.receiptsDir, "debug.log"), `${new Date().toISOString()} report_failed count=${failures} ${why}\n`);
76
+ }
77
+ catch {
78
+ /* swallowed */
79
+ }
80
+ };
81
+ async function send(payload) {
82
+ const tx = payload.proof.tx_hash;
83
+ try {
84
+ const res = await fetchImpl(`${indexUrl}/telemetry`, {
85
+ method: "POST",
86
+ headers: { "content-type": "application/json", [CLIENT_HEADER]: CLIENT_ID },
87
+ body: JSON.stringify(payload),
88
+ signal: AbortSignal.timeout(REPORT_TIMEOUT_MS),
89
+ redirect: "error",
90
+ });
91
+ const body = await res.json().catch(() => null);
92
+ if (!res.ok)
93
+ await logFailure(`http ${res.status}`);
94
+ o.onReport?.({ tx_hash: tx, status: res.status, body });
95
+ }
96
+ catch (e) {
97
+ const error = e instanceof Error ? `${e.name}: ${e.message}` : String(e);
98
+ await logFailure(error);
99
+ o.onReport?.({ tx_hash: tx, status: null, body: null, error });
100
+ }
101
+ }
102
+ return {
103
+ /**
104
+ * Report one paid response. `headers` are the response headers (a Headers object or a plain record); without a
105
+ * Base settlement transaction in them nothing is sent. `outcome` overrides the classifier.
106
+ */
107
+ report(i) {
108
+ return (async () => {
109
+ const rec = {};
110
+ if (typeof i.headers.forEach === "function" && typeof i.headers.get === "function")
111
+ i.headers.forEach((v, k) => (rec[k] = v));
112
+ else
113
+ for (const [k, v] of Object.entries(i.headers))
114
+ if (typeof v === "string")
115
+ rec[k] = v;
116
+ const tx = settlementTx(rec);
117
+ if (!tx || sent.has(tx))
118
+ return;
119
+ const outcome = i.outcome ?? (o.classify ?? defaultClassify)({ url: i.url, status: i.status });
120
+ if (!outcome)
121
+ return;
122
+ sent.add(tx);
123
+ if (sent.size > 10_000)
124
+ sent.delete(sent.values().next().value);
125
+ await send(buildTxOnlyPayload({ url: i.url, tx_hash: tx, outcome, status: i.status, quotedUsdc: i.quotedUsdc, latencyMs: i.latencyMs }));
126
+ })().catch(() => undefined);
127
+ },
128
+ failureCount: () => failures,
129
+ };
130
+ }
131
+ const urlOf = (input) => (typeof input === "string" ? input : input instanceof URL ? input.href : input.url);
132
+ /**
133
+ * One added line on an x402-fetch setup: `const fetchWithPay = withPaidforReporting(wrapFetchWithPayment(fetch, wallet))`.
134
+ * The returned fetch behaves exactly like the one passed in; after each response that carries a settlement on Base it
135
+ * reports the outcome (2xx `ok`, else `non_delivery`) without waiting.
136
+ */
137
+ export function withPaidforReporting(fetchWithPayment, o = {}) {
138
+ const r = reportOnly(o);
139
+ const wrapped = async (input, init) => {
140
+ const started = Date.now();
141
+ const res = await fetchWithPayment(input, init);
142
+ void r.report({ url: res.url || urlOf(input), status: res.status, headers: res.headers, latencyMs: Date.now() - started });
143
+ return res;
144
+ };
145
+ return wrapped;
146
+ }
147
+ /**
148
+ * One added line on an x402-axios setup: `withPaidforReportingAxios(withPaymentInterceptor(axios.create(), wallet))`
149
+ * (or `wrapAxiosWithPayment` from `@x402/axios`). Adds one response interceptor that reports each paid response,
150
+ * successful or not, and passes everything through unchanged. Returns the same instance.
151
+ */
152
+ export function withPaidforReportingAxios(instance, o = {}) {
153
+ const r = reportOnly(o);
154
+ const seen = (res) => {
155
+ if (!res || typeof res.status !== "number")
156
+ return;
157
+ const h = res.headers;
158
+ const headers = typeof h?.toJSON === "function" ? h.toJSON() : (h ?? {});
159
+ const url = res.request?.res?.responseUrl ?? res.request?.responseURL ?? (res.config ? safeUri(instance, res.config) : undefined);
160
+ if (url)
161
+ void r.report({ url, status: res.status, headers });
162
+ };
163
+ instance.interceptors.response.use((res) => {
164
+ seen(res);
165
+ return res;
166
+ }, (err) => {
167
+ seen(err?.response);
168
+ return Promise.reject(err);
169
+ });
170
+ return instance;
171
+ }
172
+ function safeUri(instance, config) {
173
+ try {
174
+ if (instance.getUri)
175
+ return instance.getUri(config);
176
+ return config.baseURL ? new URL(config.url ?? "", config.baseURL).href : config.url;
177
+ }
178
+ catch {
179
+ return undefined;
180
+ }
181
+ }
@@ -31,7 +31,32 @@ export interface SafeFetchOptions {
31
31
  logger?: {
32
32
  warn(msg: string): void;
33
33
  };
34
+ /**
35
+ * Asks someone else whether this payment may go ahead, after every local check has passed and before anything is
36
+ * signed. An approval names the EIP-3009 nonce and `validBefore` to sign. Anything but a well-formed approval,
37
+ * including a throw, is a `refused_authorize`: nothing is signed. Not asked for a free resource or a replay.
38
+ */
39
+ authorize?: (request: AuthorizeRequest) => Promise<AuthorizeAnswer>;
34
40
  }
41
+ /** The quote `authorize` is asked about. `network` is CAIP-2. */
42
+ export interface AuthorizeRequest {
43
+ intentId: string;
44
+ url: string;
45
+ payer: string;
46
+ payTo: string;
47
+ amountAtomic: string;
48
+ network: string;
49
+ asset: string;
50
+ scheme: string;
51
+ }
52
+ export type AuthorizeAnswer = {
53
+ approve: true; /** 32 bytes of 0x-hex. */
54
+ nonce: `0x${string}`; /** Unix seconds. */
55
+ validBefore: number;
56
+ } | {
57
+ approve: false;
58
+ message: string;
59
+ };
35
60
  export interface CallOptions {
36
61
  /** Same intentId + same request: returns the stored result, never signs again. Same intentId + different request: throws. */
37
62
  intentId?: string;
@@ -28,6 +28,8 @@ import { buildResponseRecord, headersToRecord } from "./x402/http.js";
28
28
  import { quoteFromResponse } from "./x402/quote.js";
29
29
  import { decodeSettlementHeader } from "./x402/settlement.js";
30
30
  import { HEADERS, PaymentRequirementsSchema, PaymentRequirementsV1Schema, ResourceInfoSchema, caip2Network, errMsg, normalizeV1, normalizeV2, } from "./x402/types.js";
31
+ /** A facilitator refuses an authorization about to lapse, so an approval with less than this left is not signed. */
32
+ const MIN_AUTH_SECONDS_LEFT = 10;
31
33
  function toSigner(w) {
32
34
  if (w && typeof w.address === "string" && typeof w.signTypedData === "function")
33
35
  return w;
@@ -292,6 +294,8 @@ export function safeFetch(wallet, options) {
292
294
  let quote;
293
295
  let approved;
294
296
  let refusal;
297
+ let auth;
298
+ let authSigned = false;
295
299
  let failure;
296
300
  let signingStarted = false;
297
301
  let signedRecorded = false;
@@ -313,7 +317,21 @@ export function safeFetch(wallet, options) {
313
317
  typeof q.asset === "string" &&
314
318
  q.asset.toLowerCase() === usdc &&
315
319
  (q.extra?.assetTransferMethod ?? "eip3009") === "eip3009");
316
- registerExactEvmScheme(client, { signer, networks: [network], policies: [policy] });
320
+ // With `authorize` the approval decides the nonce and deadline; the SDK has no way to take them, so they are set
321
+ // here at signing and on the signed payload in onAfterPaymentCreation.
322
+ const schemeSigner = !options.authorize
323
+ ? signer
324
+ : {
325
+ address: signer.address,
326
+ signTypedData: async (m) => {
327
+ if (!auth || m.primaryType !== "TransferWithAuthorization")
328
+ throw new Error("x402-safe-fetch: refusing to sign without an approval");
329
+ const signature = await signer.signTypedData({ ...m, message: { ...m.message, nonce: auth.nonce, validBefore: auth.validBefore } });
330
+ authSigned = true;
331
+ return signature;
332
+ },
333
+ };
334
+ registerExactEvmScheme(client, { signer: schemeSigner, networks: [network], policies: [policy] });
317
335
  client.onBeforePaymentCreation(async ({ paymentRequired, selectedRequirements }) => {
318
336
  signingStarted = true;
319
337
  let norm;
@@ -398,6 +416,24 @@ export function safeFetch(wallet, options) {
398
416
  };
399
417
  return { abort: true, reason: refusal.message };
400
418
  }
419
+ // 4. Last, so a payment refused above never takes up a reservation with whoever approves it.
420
+ if (options.authorize) {
421
+ let answer;
422
+ try {
423
+ answer = await options.authorize({ intentId: r.intent_id, url: req.url, payer: signer.address, payTo: norm.payTo, amountAtomic: amount.toString(), network: caip2Network(norm), asset: norm.asset, scheme: norm.scheme });
424
+ }
425
+ catch (e) {
426
+ answer = { approve: false, message: `could not get an approval: ${errMsg(e)}` };
427
+ }
428
+ if (answer?.approve === true && !(/^0x[0-9a-fA-F]{64}$/.test(answer.nonce) && Number.isSafeInteger(answer.validBefore) && answer.validBefore - Date.now() / 1000 >= MIN_AUTH_SECONDS_LEFT)) {
429
+ answer = { approve: false, message: "the approval was malformed or about to lapse" };
430
+ }
431
+ if (answer?.approve !== true) {
432
+ refusal = { code: "refused_authorize", message: `refused to pay ${usd} for ${req.url}: ${answer?.message ?? "no approval"}`, sellerUrl: i.seller_url };
433
+ return { abort: true, reason: refusal.message };
434
+ }
435
+ auth = { nonce: answer.nonce, validBefore: BigInt(answer.validBefore) };
436
+ }
401
437
  approved = amount;
402
438
  try {
403
439
  await lease.update({ phase: "signing", amount_atomic: amount.toString(), pay_to: norm.payTo });
@@ -426,6 +462,14 @@ export function safeFetch(wallet, options) {
426
462
  failure = { code: "sdk", message: `signed to ${to} does not match requirements.payTo ${quote?.payTo}` };
427
463
  throw new Error(failure.message);
428
464
  }
465
+ if (auth) {
466
+ if (!authSigned) {
467
+ failure = { code: "sdk", message: "the payment was not signed with the approval's nonce" };
468
+ throw new Error(failure.message);
469
+ }
470
+ a.nonce = auth.nonce;
471
+ a.validBefore = auth.validBefore.toString();
472
+ }
429
473
  r.nonce = String(a.nonce);
430
474
  r.payer = String(a.from).toLowerCase();
431
475
  r.amount_usdc = atomicToUsdc(BigInt(value));
@@ -495,7 +539,9 @@ export function safeFetch(wallet, options) {
495
539
  attachProof(r, undefined, {});
496
540
  await lease.update({ phase: "refused" }).catch(() => undefined);
497
541
  await persistReceipt(r);
498
- emitTelemetry(r);
542
+ // A buyer's own rule says nothing about the seller, so it is not reported to the index.
543
+ if (refusal.code !== "refused_authorize")
544
+ emitTelemetry(r);
499
545
  throw new PaymentRefusedError(refusal.code, `x402-safe-fetch ${refusal.message}`, refusal.sellerUrl, r);
500
546
  }
501
547
  if (signedRecorded) {
@@ -1,5 +1,5 @@
1
1
  import type { TelemetryOutcome, TelemetryProof } from "./proof.js";
2
- export declare const CLIENT_ID = "x402-safe-fetch/0.2.2";
2
+ export declare const CLIENT_ID = "x402-safe-fetch/0.4.0";
3
3
  /** Sent on every request to the index so it can count calls per client. Carries only CLIENT_ID. */
4
4
  export declare const CLIENT_HEADER = "X-Paidfor-Client";
5
5
  export interface TelemetryPayload {
package/dist/telemetry.js CHANGED
@@ -9,7 +9,7 @@ import { createHash } from "node:crypto";
9
9
  import { appendFile, mkdir } from "node:fs/promises";
10
10
  import { join } from "node:path";
11
11
  import { REFUSED_OUTCOMES } from "./proof.js";
12
- export const CLIENT_ID = "x402-safe-fetch/0.2.2";
12
+ export const CLIENT_ID = "x402-safe-fetch/0.4.0";
13
13
  /** Sent on every request to the index so it can count calls per client. Carries only CLIENT_ID. */
14
14
  export const CLIENT_HEADER = "X-Paidfor-Client";
15
15
  /** sha256 hex of the URL path with any trailing slash removed. Query string and fragment never enter it. */
package/docs/telemetry.md CHANGED
@@ -1,7 +1,8 @@
1
1
  # Telemetry
2
2
 
3
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
+ v2 row: the v1 fields plus a proof of payment (see "Version 2"). The report-only adapters send the tx_only row (see
5
+ "tx_only (report-only)").
5
6
 
6
7
  When it is on, each call that received an HTTP 402 sends one JSON object to `POST {indexUrl}/telemetry`
7
8
  (by default `https://paidfor.dev/v1/telemetry`). That object is the whole message. Nothing else is sent.
@@ -18,7 +19,7 @@ No account and no key are needed to send it.
18
19
  "amount_usdc": "0.010000",
19
20
  "latency_ms": 412,
20
21
  "validator_failures": [],
21
- "client": "x402-safe-fetch/0.2.2"
22
+ "client": "x402-safe-fetch/0.3.0"
22
23
  }
23
24
  ```
24
25
 
@@ -31,7 +32,7 @@ No account and no key are needed to send it.
31
32
  | `amount_usdc` | Amount of the signed authorization as a 6-decimal string. `"0.000000"` when nothing was signed. |
32
33
  | `latency_ms` | Wall time of the call in milliseconds, rounded. |
33
34
  | `validator_failures` | Names of the validators that failed, for example `["http_status"]`. Names only, no evidence. |
34
- | `client` | `x402-safe-fetch/<version>`, `x402-safe-fetch/0.2.2` for this version. |
35
+ | `client` | `x402-safe-fetch/<version>`, `x402-safe-fetch/0.3.0` for this version. |
35
36
 
36
37
  ## What is never sent (v1)
37
38
 
@@ -73,7 +74,7 @@ Additive over v1. `v` is `2`, `outcome` uses the harness names, `validator_failu
73
74
  "amount_usdc": "0.002000",
74
75
  "latency_ms": 1840,
75
76
  "validator_failures": ["http_status:500"],
76
- "client": "x402-safe-fetch/0.2.2",
77
+ "client": "x402-safe-fetch/0.3.0",
77
78
  "proof": {
78
79
  "network": "eip155:8453",
79
80
  "scheme": "exact",
@@ -108,7 +109,7 @@ Outcomes (`outcome`), mapped like the harness classifier, first match wins:
108
109
  | `wrong_goods` | A schema, entity or freshness validator failed. This client ships none of them, so it does not send this today. |
109
110
  | `overcharge` | Paid more than 1.1x the reference (index listed price, else the last price paid). Only possible if `maxOverListedRatio` was raised. |
110
111
  | `ok` | None of the above. |
111
- | `refused_verdict`, `refused_ratio`, `refused_max_per_call`, `no_acceptable_quote` | Refused; nothing was signed. **No `proof`.** |
112
+ | `refused_verdict`, `refused_ratio`, `refused_max_per_call`, `no_acceptable_quote` | Refused; nothing was signed. **No `proof`.** A refusal by the `authorize` option (`refused_authorize` on the receipt) sends no row at all. |
112
113
  | `paid_no_response`, `error` | Signed and sent with no response (with `proof`, `tx_hash` null), or failed before signing (no `proof`). |
113
114
 
114
115
  ### `path` (0.2.1): only for sellers the index has never measured
@@ -134,6 +135,44 @@ sent in either version. `"verified"` requires an https `indexUrl` (loopback exce
134
135
  follows a redirect. Each receipt stores the same `proof` and, in `"verified"` mode,
135
136
  `verification_url` = `{indexUrl}/telemetry/<payer>/<nonce>` (404 until the index serves that route).
136
137
 
138
+ ## tx_only (report-only)
139
+
140
+ From 0.3.0, `withPaidforReporting`, `withPaidforReportingAxios` and `reportOnly()` report payments made by another
141
+ x402 client with the caller's own wallet. Nothing is signed or checked before paying; after a response that carries a
142
+ Base settlement header, one object goes to `POST {indexUrl}/telemetry` (default `https://paidfor.dev/v1`):
143
+
144
+ ```json
145
+ {
146
+ "v": 2,
147
+ "proof_level": "tx_only",
148
+ "host": "api.example.com",
149
+ "path": "/v1/quote",
150
+ "path_hash": "<sha256 hex of the URL path without trailing slash>",
151
+ "outcome": "ok",
152
+ "latency_ms": 412,
153
+ "validator_failures": [],
154
+ "client": "x402-safe-fetch/0.3.0",
155
+ "proof": { "network": "eip155:8453", "tx_hash": "0x<settlement transaction hash>" }
156
+ }
157
+ ```
158
+
159
+ | Field | Source |
160
+ | --- | --- |
161
+ | `host`, `path`, `path_hash` | The response URL: hostname lowercased; the plain path (no query string or fragment; left out past 512 characters) and its hash as in v1. |
162
+ | `outcome` | `ok` for a 2xx, `non_delivery` otherwise; or what your `classify` returns (`ok`, `non_delivery`, `wrong_goods`, `overcharge`, `duplicate`). |
163
+ | `amount_usdc` | Only when you pass `quotedUsdc` to `report()`: the quote, so the index can check the amount moved is plausible. |
164
+ | `latency_ms` | Wall time of the wrapped call. |
165
+ | `validator_failures` | `["http_status:<status>"]` for a non-2xx, else empty. |
166
+ | `proof.tx_hash` | `transaction` from `PAYMENT-RESPONSE` (x402 v2) or `X-PAYMENT-RESPONSE` (v1), only with `success` not false and network `eip155:8453` or `base`. |
167
+
168
+ No payer, pay-to, nonce, amount or signature is sent: the index reads the payer, the recipient and the amount from the
169
+ transaction on Base, and the report counts only once that transaction is a USDC transfer to the seller. The index
170
+ answers `verified`, `pending` or a 422 with the reason; one transaction is one row across every channel. The request
171
+ carries `X-Paidfor-Client: x402-safe-fetch/0.3.0`, waits up to 10 seconds (the index checks the chain before
172
+ answering), never follows a redirect, and needs an https `indexUrl` (loopback excepted). Failures are counted in
173
+ `<receiptsDir>/debug.log` when you pass a `receiptsDir`, otherwise nowhere. The same row is what the paidfor MCP tool
174
+ `report_x402_payment` and the paidfor skill send.
175
+
137
176
  ## The other request: the index lookup
138
177
 
139
178
  Separately from telemetry, when `indexUrl` is set the client asks `GET {indexUrl}/check?url=` before paying.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@paidfor/x402-safe-fetch",
3
- "version": "0.2.2",
3
+ "version": "0.4.0",
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",