@paidfor/x402-safe-fetch 0.5.0 → 0.7.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,89 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.7.0
4
+
5
+ > **Upgrading turns reporting on.** Through 0.6.0 `telemetry` was `"off"` by default and a from-code payment told the
6
+ > index nothing. From this release, every priced call reports its outcome to the index with its proof of payment
7
+ > (the v2 row in docs/telemetry.md: payer, nonce, pay-to, tx hash; never bodies, request parameters, IP or identity),
8
+ > with no options. If you used the default, you start reporting when you upgrade. Issue
9
+ > [sarmadahsan/paidfor-index#41](https://github.com/sarmadahsan/paidfor-index/issues/41).
10
+
11
+ - **Reporting is on by default, and the account decides who can turn it off.** paidfor is free because these
12
+ reports are what the index is made from. With no account, or a team key on the Free plan, reporting cannot be
13
+ turned off. A team on a paid plan turns it off on its account page, and every client holding one of its keys follows
14
+ that from its next payment: the server says so in every `/v1/team/authorize` answer (`telemetry.report`), which
15
+ the client asks before each payment anyway. When it cannot tell (an older server, no field, a local refusal before
16
+ the team was first asked), it reports.
17
+ - **`telemetry: "anonymous"` and `"off"` are no longer honoured on their own.** They still type-check. Without a
18
+ paid account that turned reporting off, verified rows are still sent and one line says so, once per process, with
19
+ the plans page; `telemetryNotice: false` does not hide that line. Nothing throws. `safeFetch` no longer sends the v1
20
+ row; the index still accepts it from older versions. A paid team's account switch wins over `telemetry: "verified"`.
21
+ - **A plain-http `indexUrl`** (not loopback) gets no rows by default, and one line says so; an explicit
22
+ `telemetry: "verified"` still throws, as before.
23
+ - **The one-time notice** now says reporting is on, why, and who can turn it off. It is shown once per receipts
24
+ directory, as before, also with no options.
25
+ - Unchanged: `indexUrl: false` sends nothing (and checks no seller); the report-only adapters
26
+ (`withPaidforReporting`, `withPaidforReportingAxios`, `report()`) exist only to report and have no switch; refusals
27
+ carry no proof and are counted by reason. This is open source: opting out through the account is a paid feature, not
28
+ the only way out.
29
+ - `TeamDecision` carries `telemetry?: "verified" | "off"`, and `TeamClient.telemetryReport()` returns what the last
30
+ authorize answer said.
31
+ - **Usable content in another format than declared is a warning, not a failed delivery** (paidfor-index issue 40).
32
+ When the seller declares one type and answers with usable content in another (`application/json` declared, the
33
+ article sent as `text/markdown`; JSON labelled `text/plain`), or with no `Content-Type` header, the receipt's
34
+ outcome is now `ok` (it was `validator_failed`), `reported_outcome` is `ok` (it was `non_delivery`), and the
35
+ `content_type` validator says `pass` with `reason` `content_type_mismatch` or `missing_content_type` and
36
+ `evidence.warning: true`. New receipt field `warnings` says it in words, with the declared and received types. The
37
+ v2 telemetry row adds `warnings: ["content_type_mismatch"]` only when there is one (see docs/telemetry.md); rows
38
+ without warnings are unchanged. The price is recorded in `prices.json` as for any `ok` call.
39
+ - It stays a failure when the answer has the shape of an error rather than of content: an HTML page, by its
40
+ `Content-Type` or its first bytes (new reason `html_body`), where HTML was not declared (an HTML label over a body that parses as JSON is JSON mislabelled: a warning); an undeclared
41
+ `application/problem+json` document; a body that should be JSON and does not parse (`body_not_json`, now also for
42
+ broken JSON labelled as another type or sent with no header). The JSON family (`application/json`, `text/json`, any
43
+ `+json` type) is one format: a declared `application/vnd.api+json` answered with `application/json` passes without
44
+ a warning (it failed before). Empty, truncated and non-2xx answers fail as before.
45
+ - New exports: `WARNING_REASONS` and `isFormatWarning` (validators), `ReceiptWarning` and `receiptWarnings` (receipt).
46
+ All additive; older receipts have no `warnings` field.
47
+
48
+ ## 0.6.0
49
+
50
+ - **A payment the seller rejects is no longer recorded as paid.** When the paid request is answered with HTTP 402
51
+ again and nothing settled (no settlement header, or one with `success: false`), as happens with a wallet that has
52
+ no USDC, the receipt now says `outcome: "payment_rejected"` and `paid: false` (it said `validator_failed` and
53
+ `paid: true`). The response is still returned, with status 402. No price is recorded in `prices.json`, no telemetry
54
+ row is sent in either version (before, a verified row reported `non_delivery` against the seller), and in team mode
55
+ the approval is reported as not paid (`paid: false`), so the team releases it instead of recording a settlement.
56
+ `reported_outcome` is `error`, the harness name for "not paid"; `proof` is null. A 402 whose settlement header
57
+ cannot be read is still treated as paid, since it may name a settlement.
58
+ - **Retrying a rejected payment.** The intent is kept in the new phase `rejected` with the signed nonce, deadline,
59
+ payer, network and asset, and a retry with the same `intentId` is allowed (before, it replayed the 402). Without
60
+ `team` or `authorize` the retry signs the same nonce again, so at most one of the two authorizations can ever
61
+ settle. A retry from another wallet, network or asset throws `IntentConflictError` and signs nothing (the same
62
+ nonce there would be a second authorization that could also settle). With an approval naming a different nonce,
63
+ the retry refuses with `refused_authorize` until the rejected authorization's deadline has passed. The deadline
64
+ only stops later use of the old signature; it does not show the old one was never used. `authorizationState(payer,
65
+ nonce)` on the USDC contract being `false` does; `true` means used or cancelled, and only the `AuthorizationUsed`
66
+ event with its USDC `Transfer` shows a payment. When the same nonce is signed again and rejected again, the intent
67
+ keeps the later of the two deadlines (an unknown one never passes). A new `intentId` signs a new nonce as before. See
68
+ "When the seller rejects the payment" in the README.
69
+ - New receipt field `valid_before`: the signed authorization's deadline, Unix seconds (null when nothing was signed).
70
+ `Outcome` gains `payment_rejected`. Both are additive; older receipts lack the field.
71
+ - **Team mode tells the team about local refusals.** A payment refused before the team is asked (`refused_verdict`,
72
+ `refused_ratio`, `refused_max_per_call`) is posted to `{origin}/v1/team/refusals` with the quote, the reason and
73
+ the verdict, so the ledger and the bill can count what was saved. Fire-and-forget: 2-second timeout, never awaited,
74
+ every failure (including a 404 from a server without the route) swallowed and never logged; the thrown error is
75
+ unchanged. The key goes only to the team origin.
76
+ - **`team.project`**, and `PAIDFOR_PROJECT` when team mode comes from `PAIDFOR_TEAM_KEY`: a project tag sent as
77
+ `project` on every authorize and refusal notice. A tag the server would refuse (it must be 1 to 64 letters, digits,
78
+ spaces or `. _ -` after trimming) throws when `safeFetch` is called. An empty `PAIDFOR_PROJECT` is ignored.
79
+ - **`telemetryNotice`**: `false` turns off the one-time notice about verified telemetry; a function receives it
80
+ instead of `logger.warn`. The default is unchanged.
81
+ - README: `verification_url` is live (the "not live yet" note is gone); the team section says
82
+ `npx -y @paidfor/mcp@latest`, as does the "wallet not registered" message; sample rows show
83
+ `x402-safe-fetch/<version>`. New outcome table.
84
+ - Exported: `cleanProject` and the types `TeamRefusalBody`, `TeamRefusalReason`.
85
+ - `client` in telemetry rows and the `X-Paidfor-Client` header is `x402-safe-fetch/0.6.0`.
86
+
3
87
  ## 0.5.0
4
88
 
5
89
  - **Team mode: `team: { key }`.** Budgets per wallet, human approvals and a ledger from a paidfor team account, with
package/README.md CHANGED
@@ -3,7 +3,11 @@
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
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
+ install it, not to read the index, and not to contribute to it.
7
+
8
+ **It reports each purchase outcome to the index by default**, with its proof of payment (see
9
+ [Telemetry](#telemetry)). That is the deal that keeps paidfor free: the index is made from these reports. Only a team
10
+ account on a paid plan can turn reporting off.
7
11
 
8
12
  This is the client-side half of the x402 seller index at [paidfor.dev](https://paidfor.dev).
9
13
 
@@ -20,7 +24,7 @@ const fetchWithPay = safeFetch(walletClient, {
20
24
  refuseVerdicts: ["avoid"], // consult the index; "caution" is allowed but logged
21
25
  indexUrl: "https://paidfor.dev/v1",
22
26
  validators: ["http_status", "non_empty", "content_type", "not_truncated"],
23
- telemetry: "verified", // or "anonymous" (no proof of payment) or "off" (the default)
27
+ // Reporting to the index is on by default; only a paid team account turns it off (see Telemetry).
24
28
  receiptsDir: "./.x402-receipts",
25
29
  });
26
30
 
@@ -44,12 +48,14 @@ Payments are exact-scheme USDC on Base mainnet by default (`network: "eip155:845
44
48
  receipts directory before signing, and the signed nonce is written before the payment is sent. A retry with
45
49
  the same `intentId` and request returns the stored response and never signs again. A retry with the same
46
50
  `intentId` and a different request throws `IntentConflictError`. If a payment was signed but no response was
47
- stored, a retry throws `IntentIndeterminateError` instead of paying again.
51
+ stored, a retry throws `IntentIndeterminateError` instead of paying again. A payment the seller rejected
52
+ (`payment_rejected`, below) may be retried with the same `intentId` from the same wallet: it signs the same
53
+ nonce again, so at most one of the two authorizations can ever settle.
48
54
  3. **After the response.** The configured validators run on the paid response. `res.receipt` carries the intent
49
55
  id, quote, amount, reference price and its source, seller verdict, validator results, the settlement header,
50
56
  and the on-chain tx hash when the header carries it. The same receipt is written to the receipts directory as
51
57
  one JSON file per call.
52
- 4. **Telemetry, when enabled.** One POST per call, fire-and-forget. See below.
58
+ 4. **Telemetry.** One POST per call to the index, fire-and-forget, on by default. See below.
53
59
 
54
60
  ## What it blocks and what it does not
55
61
 
@@ -62,7 +68,76 @@ Payments are exact-scheme USDC on Base mainnet by default (`network: "eip155:845
62
68
  | Paying twice for the same `intentId`, across restarts and concurrent processes | Duplicates when each retry uses a new `intentId` (pass a stable one) |
63
69
  | Re-signing after a timeout or crash once a payment was signed | Recovering that money: the call fails with the nonce so you can check the chain |
64
70
  | Non-USDC assets, other networks, non-`exact` schemes, and redirects of the paid request | A seller that settles and then serves wrong or stale content that still passes the four validators |
65
- | Silent non-delivery: a paid 4xx/5xx, empty, wrong content type or truncated body is flagged in the receipt | Getting the money back: validators report failures, they do not refund or dispute |
71
+ | Silent non-delivery: a paid 4xx/5xx, empty or truncated body, or an HTML page in place of the declared type, is flagged in the receipt | Getting the money back: validators report failures, they do not refund or dispute |
72
+
73
+ ## Outcomes
74
+
75
+ `res.receipt.outcome` (and `err.receipt.outcome` on a thrown error):
76
+
77
+ | `outcome` | What happened | `paid` | Returned or thrown |
78
+ | --- | --- | --- | --- |
79
+ | `ok` | Paid, and every validator passed. A usable answer in another format than the seller declared is `ok` with a warning in `warnings` (0.7.0). | `true` | Returned |
80
+ | `validator_failed` | Paid, and a validator failed (a non-2xx answer, an empty or truncated body, an HTML or error page in place of the declared type, JSON that does not parse). | `true` | Returned |
81
+ | `payment_rejected` (0.6.0) | The signed payment was sent and the seller answered HTTP 402 again, with no settlement header or one saying it failed: usually a wallet without enough USDC. Nothing settled. | `false` | Returned (status 402) |
82
+ | `paid_no_response` | Signed and maybe sent, and no response came back. | `true` if sent | Thrown |
83
+ | `refused_verdict`, `refused_ratio`, `refused_max_per_call`, `refused_authorize` | Refused before signing. | `false` | Thrown |
84
+ | `no_acceptable_quote` | No exact USDC quote on the configured network. | `false` | Thrown |
85
+ | `no_payment_required` | The resource answered without a 402. | `false` | Returned |
86
+ | `replayed` | The stored result of an earlier call with this `intentId`. | `false` | Returned |
87
+ | `error` | Anything else before signing (network, SDK). | `false` | Thrown |
88
+
89
+ ### Format warnings (0.7.0)
90
+
91
+ A paid answer whose content is usable but whose format differs from what the seller declared in its 402 (the seller
92
+ declares `application/json` and sends the article as `text/markdown`, or JSON labelled `text/plain`), or that has no
93
+ `Content-Type` header, is not a failed delivery. The receipt's outcome is `ok`, the `content_type` validator says
94
+ `pass` with `reason` `content_type_mismatch` (or `missing_content_type`) and `evidence.warning: true`, and
95
+ `receipt.warnings` says it in words:
96
+
97
+ ```json
98
+ [{ "code": "content_type_mismatch", "validator": "content_type", "declared": "application/json", "received": "text/markdown",
99
+ "message": "the seller declared application/json and the response is text/markdown; the content is returned as sent and the call is not counted as a failure" }]
100
+ ```
101
+
102
+ It stays a failure (`validator_failed`) when the answer has the shape of an error rather than of content: an HTML page
103
+ (by its `Content-Type` or its first bytes) where HTML was not declared (an HTML label over a body that parses as JSON is
104
+ JSON mislabelled, so a warning), an undeclared `application/problem+json`
105
+ document, or a body that should be JSON and does not parse. A different `+json` type or parameters (`; charset=utf-8`)
106
+ are the same format and raise no warning. A seller that declares no type is judged against `application/json`.
107
+ Empty, truncated and non-2xx answers fail as before.
108
+
109
+ ### When the seller rejects the payment
110
+
111
+ A `payment_rejected` receipt has `paid: false`, no `tx_hash`, no `proof`, and `error.code` `payment_rejected`.
112
+ No price is learnt from it, no telemetry row is sent (it says nothing about the seller), and in team mode the
113
+ approval is reported as not paid, so the team releases it.
114
+
115
+ The one real risk: the signed EIP-3009 authorization can still be used until its deadline, so whoever holds it (the
116
+ seller or its facilitator) could settle it later, for example once the wallet is funded, even though the seller
117
+ answered 402. The receipt keeps what you need to check: `payer`, `nonce` and `valid_before` (Unix seconds).
118
+
119
+ **The deadline is not a settlement check.** Once `valid_before` has passed, the old signature can no longer be used,
120
+ but that says nothing about whether it was used before then. Read `authorizationState(payer, nonce)` on the USDC
121
+ contract on Base: `false` after the deadline shows nothing moved and nothing ever can. `true` only says the nonce
122
+ can no longer be used: it was used **or cancelled** (USDC's `cancelAuthorization` sets it too). To count it as a
123
+ payment, find the `AuthorizationUsed(payer, nonce)` event and the USDC `Transfer` in the same transaction. When the
124
+ same nonce is signed again with a shorter deadline and rejected again, the receipt's `valid_before` is that newer
125
+ signature's; the intent file keeps the latest deadline of every signature under the nonce, and that is the one to
126
+ wait for. This client does not read
127
+ the chain, so that check is yours.
128
+
129
+ - Retrying with the same `intentId` from the same wallet, network and asset is allowed, because nothing was paid.
130
+ Without `team` or `authorize` the retry signs the same nonce, so at most one of the two authorizations can ever
131
+ move money. With `team` or `authorize` the approval names the nonce: the retry signs if it names the same nonce,
132
+ or, with a different nonce, only once the old deadline has passed (otherwise it refuses with `refused_authorize`
133
+ and says until when; the team server answers `released_not_expired` until then in any case). A different nonce
134
+ after the deadline is not covered by the one-nonce guarantee: check `authorizationState` first (`false`).
135
+ - A retry of that `intentId` from another wallet, on another network or for another asset throws
136
+ `IntentConflictError` and signs nothing: the same nonce there would be a separate authorization that could also
137
+ settle. So does a retry of an intent rejected by an earlier build, which did not record the payer.
138
+ - A new `intentId` is a new purchase with a new nonce. Only start one after the old deadline has passed and
139
+ `authorizationState(payer, nonce)` is `false` (both: before the deadline it could still be used; `true` needs the
140
+ `AuthorizationUsed` and `Transfer` check above to tell a payment from a cancellation).
66
141
 
67
142
  ## Receipts directory
68
143
 
@@ -72,40 +147,50 @@ Payments are exact-scheme USDC on Base mainnet by default (`network: "eip155:845
72
147
  intents/<sha256(intentId)>.json idempotency state and the stored response
73
148
  prices.json last price paid per resource (method + origin + path)
74
149
  debug.log telemetry failures, local only
75
- .verified-telemetry-notice marks that the one-time "verified" notice was shown
150
+ .verified-telemetry-notice marks that the one-time reporting notice was shown
76
151
  ```
77
152
 
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.
153
+ Each receipt for a paid call has a `proof` (the same object a verified telemetry row carries) and, when the row was
154
+ sent, a `verification_url` of the form `{indexUrl}/telemetry/<payer>/<nonce>`, which shows
155
+ whether the index has verified your row on-chain (usually within about five minutes of the payment).
156
+ `reported_outcome` is the outcome under the harness names, as the row reports it.
82
157
 
83
158
  Keep this directory if you want the idempotency guarantee to survive restarts.
84
159
 
85
160
  ## Telemetry
86
161
 
87
- Three settings. Every one is fire-and-forget: a 1-second timeout, never awaited, every failure swallowed and
162
+ **On by default.** Every priced call sends one v2 row to the index: the outcome under the index's names, the
163
+ seller host, a sha256 of the path, the amount, latency and validator names, and for a paid call a proof of payment
164
+ the index checks on Base (below). Fire-and-forget: a 1-second timeout, never awaited, every failure swallowed and
88
165
  only counted in `debug.log`. Nothing is sent for free resources (no 402) or for replays of a stored intent.
89
166
 
90
- | `telemetry` | Sends |
167
+ **Who can turn it off.** paidfor is free because these reports are what the index is made from. So the account
168
+ decides, not a local flag:
169
+
170
+ | You use the library | Reporting |
91
171
  | --- | --- |
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. |
172
+ | With no account | On. It cannot be turned off. |
173
+ | With a team key on the Free plan | On. It cannot be turned off. |
174
+ | With a team key on a paid plan (Team, Platform) | On, unless the team turns it off on its [account page](https://paidfor.dev/team). Every client holding one of the team's keys follows that switch from its next payment. |
95
175
 
96
- v1 row:
176
+ In team mode the server says which applies in every `/v1/team/authorize` answer (`telemetry.report`), which the
177
+ client asks before each payment anyway: there is no extra request. When it cannot tell (an older server, an answer
178
+ without the field, a refusal before the team was first asked), it reports.
97
179
 
98
- ```json
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.3.0" }
101
- ```
180
+ `telemetry: "anonymous"` and `telemetry: "off"` still type-check, but are requests the client cannot grant on its
181
+ own: without a paid account that turned reporting off, verified rows are still sent and one line says so, once per
182
+ process. From this release on, the v1 ("anonymous") row is no longer sent; the index still accepts it from older versions.
183
+
184
+ **Plainly:** this is open source. You can edit your copy, point `indexUrl` at another index, or set
185
+ `indexUrl: false`, which sends nothing and also turns off the seller check before paying. Opting out through the
186
+ account is a paid feature, not the only way out. It is the way that keeps the protections.
102
187
 
103
- Both payloads and every field are documented in [docs/telemetry.md](docs/telemetry.md).
188
+ Every field is documented in [docs/telemetry.md](docs/telemetry.md).
104
189
 
105
190
  ## What verified telemetry sends and why
106
191
 
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
192
+ paidfor.dev measures sellers with its own wallet, which cannot cover the whole market. With reporting on, each of
193
+ your purchases becomes a data point the index can trust, because it can prove
109
194
  on-chain that you actually paid: it looks up the `AuthorizationUsed(payer, nonce)` event and the matching USDC
110
195
  `Transfer` on Base. Rows that do not verify are stored but never counted.
111
196
 
@@ -123,7 +208,7 @@ This is the whole message, for a paid call that got a 500:
123
208
  "amount_usdc": "0.002000",
124
209
  "latency_ms": 1840,
125
210
  "validator_failures": ["http_status:500"],
126
- "client": "x402-safe-fetch/0.3.0",
211
+ "client": "x402-safe-fetch/<version>",
127
212
  "proof": {
128
213
  "network": "eip155:8453",
129
214
  "scheme": "exact",
@@ -142,16 +227,17 @@ This is the whole message, for a paid call that got a 500:
142
227
  - **What the payer address adds.** Every settled x402 payment is already a public USDC transfer from your
143
228
  address to the seller's pay-to address, with this nonce, on Base; the address, the amount and the seller's
144
229
  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.
230
+ hash, the outcome you observed, the validator failures and the response hash. If you are not comfortable with
231
+ that association, use a team account on a paid plan and turn reporting off, or `indexUrl: false` (above).
147
232
  - **The plain path, for unknown sellers only (0.2.1).** When the index answered `unknown` before paying (it has
148
233
  never measured that seller), the row also carries `"path": "/v1/quote"`: the URL path, never the query string
149
234
  or fragment. The index keeps the host and path of a verified payment to such a seller so it can buy that
150
235
  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.
236
+ knows, only `path_hash` is sent, as before.
152
237
  - **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.
238
+ no IP address or identity with the row. A row goes only to an https `indexUrl` (loopback excepted, for local
239
+ testing): with a plain-http one, nothing is sent and one line says so (an explicit `telemetry: "verified"` makes
240
+ it throw instead), and telemetry never follows a redirect.
155
241
  - **Client header (0.2.2).** Every request to the index, the pre-pay check and the telemetry POST, carries
156
242
  `X-Paidfor-Client: x402-safe-fetch/<version>`: the package name and version, nothing else. The index uses it
157
243
  only to count calls per client.
@@ -160,16 +246,20 @@ This is the whole message, for a paid call that got a 500:
160
246
  validator evidence are never sent.
161
247
  - **Refusals carry no proof.** A refused or unpaid call sends the row without `proof`; it is counted as a
162
248
  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.
249
+ about the seller. Nor does a `payment_rejected` call (0.6.0): nothing was paid, and a wallet that cannot pay is
250
+ not the seller's failure.
164
251
  - **Outcomes use the index's names:** `ok`, `non_delivery` (a non-2xx answer or a failed delivery validator after paying),
165
252
  `overcharge` (paid more than 1.1x the reference, possible only if you raised `maxOverListedRatio`),
166
253
  `wrong_goods`, `duplicate`, plus the client-only `refused_*`, `no_acceptable_quote`, `paid_no_response` and
167
254
  `error`.
168
- - **Turning it off.** `telemetry: "anonymous"` sends the v1 row without any address; `telemetry: "off"` (the
169
- default) sends nothing. `indexUrl: false` turns off the index lookup and all telemetry.
255
+ - **Turning it off.** See [who can turn it off](#telemetry): a team account on a paid plan, on its account page.
256
+ `indexUrl: false` turns off the index lookup and all telemetry.
170
257
 
171
- The first time a receipts directory is used with `"verified"`, the client prints a one-line notice pointing
172
- here.
258
+ The first time a receipts directory is used with reporting on, the client prints a one-line notice pointing
259
+ here, through `logger.warn` (stderr with the default console). `telemetryNotice: false` turns it off;
260
+ `telemetryNotice: (msg) => ...` sends it to your own function instead. Nothing else changes. The line that
261
+ `"anonymous"` or `"off"` was not honoured is never silenced: `telemetryNotice: false` does not hide it, and a
262
+ function receives it.
173
263
 
174
264
  ## With a team account
175
265
 
@@ -197,13 +287,21 @@ What you get:
197
287
  - `receipt.team` says what the team decided, carries any `warnings` the server sent, and `outcome_report` (`sent`,
198
288
  `queued` or `rejected`).
199
289
 
290
+ - A payment this client refuses by itself before asking the team (`refused_verdict`, `refused_ratio`,
291
+ `refused_max_per_call`) is told to the team (`POST {origin}/v1/team/refusals`, with the quote, the reason and the
292
+ verdict), so the ledger and the bill can show what was saved. That notice is fire-and-forget: a 2-second timeout,
293
+ never awaited, every failure swallowed, and the error you get is the same either way.
294
+ - `project` (0.6.0) tags every payment, so the ledger and the bill can be read by project:
295
+ `team: { key, project: "research-q4" }`. A tag is 1 to 64 letters, digits, spaces or `. _ -`; anything else throws
296
+ when `safeFetch` is called.
297
+
200
298
  The wallet must be registered to the team: on [paidfor.dev/team](https://paidfor.dev/team), or with
201
- `npx -y @paidfor/mcp@0.7.0 init --wallet --link` (add `--key-file <path>` for a key file of your own). The key goes
299
+ `npx -y @paidfor/mcp@latest init --wallet --link` (add `--key-file <path>` for a key file of your own). The key goes
202
300
  only to the team origin, never to a seller, and is never logged. `team` also takes `origin` (https only, or
203
- http on localhost), `authorizeTimeoutMs` (default 10000) and `reportTimeoutMs` (default 5000).
301
+ http on localhost), `authorizeTimeoutMs` (default 10000), `reportTimeoutMs` (default 5000) and `project`.
204
302
 
205
303
  When `team` is left out and `PAIDFOR_TEAM_KEY` is set in the environment, team mode turns on by itself (a
206
- one-line notice says so); `team: false` turns it off. `team` and `authorize` together throw: `team` supplies its own
304
+ one-line notice says so), and `PAIDFOR_PROJECT`, when set, is the project tag; `team: false` turns it off. `team` and `authorize` together throw: `team` supplies its own
207
305
  `authorize`, and with your own `authorize` the environment is not read.
208
306
 
209
307
  ## Ask before paying
@@ -256,11 +354,12 @@ own checks). Responses without a settlement (free calls, refusals) send nothing.
256
354
 
257
355
  | Error | `code` | Paid? |
258
356
  | --- | --- | --- |
259
- | `PaymentRefusedError` | `refused_verdict`, `refused_ratio`, `refused_max_per_call`, `refused_authorize` | No |
357
+ | `PaymentRefusedError` | `refused_verdict`, `refused_ratio`, `refused_max_per_call`, `refused_authorize` (also: a retry after `payment_rejected` whose approval names a new nonce before the old deadline) | No |
260
358
  | `TeamRefusedError` (a `PaymentRefusedError`) | `refused_authorize`; `decision` says why | No |
261
- | `IntentConflictError` | `intent_conflict` | No |
359
+ | `IntentConflictError` | `intent_conflict` (also: a retry after `payment_rejected` from another wallet, network or asset) | No |
262
360
  | `IntentIndeterminateError` | `intent_indeterminate` | Maybe, earlier; never again |
263
361
  | `SafeFetchError` | `paid_no_response` | Signed and possibly settled; `receipt.nonce` identifies it |
362
+ | none: returned with status 402 | `receipt.outcome` `payment_rejected` | No; the authorization stays valid until `receipt.valid_before` (see "When the seller rejects the payment") |
264
363
  | `SafeFetchError` | `no_acceptable_quote`, `intent_in_flight`, `network`, `sdk` | No |
265
364
 
266
365
  ## Example
package/dist/index.d.ts CHANGED
@@ -1,10 +1,12 @@
1
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, TeamRefusedError, type SafeFetchErrorCode } from "./errors.js";
3
- export type { Receipt, Outcome } from "./receipt.js";
3
+ export type { Receipt, Outcome, ReceiptWarning } from "./receipt.js";
4
+ export { receiptWarnings } from "./receipt.js";
5
+ export { WARNING_REASONS, isFormatWarning, type WarningReason } from "./validators/content_type.js";
4
6
  export type { Verdict, IndexCheck } from "./index-client.js";
5
7
  export type { ValidatorName } from "./taxonomy.js";
6
8
  export type { ValidatorResult } from "./validators/types.js";
7
9
  export type { TelemetryPayload, TelemetryPayloadV2 } from "./telemetry.js";
8
10
  export type { TelemetryProof, TelemetryOutcome } from "./proof.js";
9
11
  export { reportOnly, withPaidforReporting, withPaidforReportingAxios, buildTxOnlyPayload, settlementTx, type ReportOnlyOptions, type ReportOutcome, type TxOnlyPayload, type AxiosLike } from "./report-only.js";
10
- export { TeamClient, outcomeFor, readDecision, isKeySafeOrigin, TEAM_ORIGIN, type TeamOptions, type TeamDecision, type TeamDecisionExtras, type TeamWarning, type TeamReceipt, type TeamReportState, type TeamAuthorizeBody, type TeamOutcomeBody, type TeamClientOptions } from "./team.js";
12
+ export { TeamClient, outcomeFor, readDecision, isKeySafeOrigin, cleanProject, TEAM_ORIGIN, type TeamOptions, type TeamRefusalBody, type TeamRefusalReason, type TeamDecision, type TeamDecisionExtras, type TeamWarning, type TeamReceipt, type TeamReportState, type TeamAuthorizeBody, type TeamOutcomeBody, type TeamClientOptions } from "./team.js";
package/dist/index.js CHANGED
@@ -1,4 +1,6 @@
1
1
  export { safeFetch, hashRequest } from "./safe-fetch.js";
2
2
  export { SafeFetchError, PaymentRefusedError, IntentConflictError, IntentIndeterminateError, TeamRefusedError } from "./errors.js";
3
+ export { receiptWarnings } from "./receipt.js";
4
+ export { WARNING_REASONS, isFormatWarning } from "./validators/content_type.js";
3
5
  export { reportOnly, withPaidforReporting, withPaidforReportingAxios, buildTxOnlyPayload, settlementTx } from "./report-only.js";
4
- export { TeamClient, outcomeFor, readDecision, isKeySafeOrigin, TEAM_ORIGIN } from "./team.js";
6
+ export { TeamClient, outcomeFor, readDecision, isKeySafeOrigin, cleanProject, TEAM_ORIGIN } from "./team.js";
package/dist/intents.d.ts CHANGED
@@ -1,4 +1,20 @@
1
- export type IntentPhase = "reserved" | "signing" | "signed" | "completed" | "unpaid" | "refused" | "failed_unpaid";
1
+ export type IntentPhase = "reserved" | "signing" | "signed" | "completed" | "unpaid" | "refused" | "failed_unpaid" | "rejected";
2
+ /**
3
+ * A signed authorization the seller rejected. It can be used until `valid_before` (Unix seconds; null if unknown). Its
4
+ * nonce is reused only by the same payer, network and asset: an EIP-3009 nonce is spent once per payer per token
5
+ * contract, so the same nonce from another wallet, chain or token would be a second authorization that could also
6
+ * settle. Records from before 0.6.0's fix have no payer and are never reused.
7
+ */
8
+ export interface RejectedAuthorization {
9
+ nonce: string;
10
+ valid_before: number | null;
11
+ /** authorization.from, lowercase. */
12
+ payer?: string;
13
+ /** CAIP-2. */
14
+ network?: string;
15
+ /** Token contract, lowercase. */
16
+ asset?: string;
17
+ }
2
18
  export interface StoredResponse {
3
19
  url: string;
4
20
  status: number;
@@ -21,6 +37,8 @@ export interface IntentRecord {
21
37
  pay_to?: string;
22
38
  receipt_file?: string;
23
39
  response?: StoredResponse;
40
+ /** The last authorization for this intent the seller rejected, kept across attempts. */
41
+ rejected?: RejectedAuthorization;
24
42
  }
25
43
  export interface IntentLease {
26
44
  record: IntentRecord;
package/dist/intents.js CHANGED
@@ -9,6 +9,11 @@
9
9
  * `signed` is written before the paid request is sent, and a failed write aborts the send)
10
10
  * signed authorization signed; paid request about to go -> a retry throws IntentIndeterminateError, never re-signs
11
11
  * completed paid response stored -> a retry returns the stored response, never re-signs
12
+ * rejected signed and sent, and the seller answered 402 with no settlement -> a retry may proceed, but the
13
+ * signed nonce, payer, network and asset are kept in `rejected` (carried over every later attempt): a
14
+ * retry by the same payer on the same network and asset signs that same nonce, or, with an approval
15
+ * naming another nonce, only once the old one's deadline has passed; any other payer, network or
16
+ * asset is refused
12
17
  * unpaid / refused / failed_unpaid -> a retry may proceed (nothing was signed)
13
18
  */
14
19
  import { createHash } from "node:crypto";
@@ -123,6 +128,8 @@ export class IntentStore {
123
128
  attempts: (prior?.attempts ?? 0) + 1,
124
129
  created_at: prior?.created_at ?? ts,
125
130
  updated_at: ts,
131
+ // A rejected authorization may still be settled until its deadline: every later attempt must know its nonce.
132
+ ...(prior?.rejected ? { rejected: prior.rejected } : {}),
126
133
  };
127
134
  await writeJsonDurable(file, record);
128
135
  }
package/dist/proof.js CHANGED
@@ -41,7 +41,8 @@ export function buildProof(i) {
41
41
  */
42
42
  export function harnessOutcome(i) {
43
43
  if (i.outcome !== "ok" && i.outcome !== "validator_failed") {
44
- return i.outcome === "replayed" || i.outcome === "no_payment_required" ? "error" : i.outcome;
44
+ // payment_rejected is the harness's not_paid, which a v2 row names `error`. The client sends no row for it.
45
+ return i.outcome === "replayed" || i.outcome === "no_payment_required" || i.outcome === "payment_rejected" ? "error" : i.outcome;
45
46
  }
46
47
  const failed = new Set(i.validatorFailures);
47
48
  const delivered = i.status !== undefined ? i.status >= 200 && i.status < 300 : !failed.has("http_status");
package/dist/receipt.d.ts CHANGED
@@ -5,7 +5,21 @@ import type { ValidatorName } from "./taxonomy.js";
5
5
  import type { TeamReceipt } from "./team.js";
6
6
  import type { SettlementResponse } from "./x402/types.js";
7
7
  import type { ValidatorResult } from "./validators/types.js";
8
- 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
+ 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" | "payment_rejected" | "replayed" | "error";
9
+ /**
10
+ * Something the caller should know about a call that did not fail it (0.7.0). Today only the format rule: the paid
11
+ * answer is usable but in another format than the seller declared (`content_type_mismatch`), or carried no
12
+ * Content-Type header (`missing_content_type`). The outcome stays `ok`.
13
+ */
14
+ export interface ReceiptWarning {
15
+ code: "content_type_mismatch" | "missing_content_type";
16
+ validator: ValidatorName;
17
+ /** The media type the seller declared in its 402; null when it declared none (application/json was expected). */
18
+ declared: string | null;
19
+ /** The media type of the response; null when it had no Content-Type header. */
20
+ received: string | null;
21
+ message: string;
22
+ }
9
23
  export interface Receipt {
10
24
  v: 1;
11
25
  client: string;
@@ -17,7 +31,10 @@ export interface Receipt {
17
31
  finished_at: string;
18
32
  latency_ms: number;
19
33
  outcome: Outcome;
20
- /** True when a payment authorization was sent to the seller. */
34
+ /**
35
+ * True when a payment authorization was sent to the seller and the seller did not reject it. False for
36
+ * `payment_rejected` (sent, but answered HTTP 402 with no settlement): see `nonce` and `valid_before`.
37
+ */
21
38
  paid: boolean;
22
39
  /** True when this result was served from the intent store without contacting the seller. */
23
40
  replayed: boolean;
@@ -55,6 +72,8 @@ export interface Receipt {
55
72
  index_note: string | null;
56
73
  validators: Partial<Record<ValidatorName, ValidatorResult>>;
57
74
  validator_failures: ValidatorName[];
75
+ /** Warnings that did not fail the call (0.7.0; absent on older receipts). See ReceiptWarning. */
76
+ warnings?: ReceiptWarning[];
58
77
  settlement: {
59
78
  header: string | null;
60
79
  version: 1 | 2 | null;
@@ -65,6 +84,11 @@ export interface Receipt {
65
84
  nonce: string | null;
66
85
  /** authorization.from of the signed payment, lowercase. */
67
86
  payer: string | null;
87
+ /**
88
+ * authorization.validBefore of the signed payment, Unix seconds: until then the authorization could still be
89
+ * settled by whoever holds it. Null when nothing was signed. (0.6.0; absent on older receipts.)
90
+ */
91
+ valid_before?: number | null;
68
92
  /** Proof of payment for a sent authorization (the `proof` of a v2 telemetry row). Null when nothing was sent. */
69
93
  proof: TelemetryProof | null;
70
94
  /** The outcome under the harness names, as a v2 telemetry row reports it. */
@@ -92,5 +116,7 @@ export interface Receipt {
92
116
  */
93
117
  team?: TeamReceipt;
94
118
  }
119
+ /** The receipt's `warnings` from the validator results: a content_type pass with a format warning. */
120
+ export declare function receiptWarnings(results: Partial<Record<ValidatorName, ValidatorResult>>): ReceiptWarning[];
95
121
  /** One JSON file per call: <receiptsDir>/<timestamp>-<random>.json. Returns the file name. */
96
122
  export declare function writeReceipt(dir: string, r: Receipt): Promise<string>;
package/dist/receipt.js CHANGED
@@ -1,6 +1,26 @@
1
1
  import { randomBytes } from "node:crypto";
2
2
  import { join } from "node:path";
3
3
  import { writeJsonDurable } from "./fsutil.js";
4
+ import { isFormatWarning } from "./validators/content_type.js";
5
+ /** The receipt's `warnings` from the validator results: a content_type pass with a format warning. */
6
+ export function receiptWarnings(results) {
7
+ const out = [];
8
+ const ct = results.content_type;
9
+ if (isFormatWarning(ct)) {
10
+ const declared = ct.evidence.expected_source === "requirements" && typeof ct.evidence.expected === "string" ? ct.evidence.expected : null;
11
+ const received = typeof ct.evidence.actual === "string" ? ct.evidence.actual : null;
12
+ const want = declared ? `the seller declared ${declared}` : "the seller declared no type (application/json was expected)";
13
+ const got = received ? `the response is ${received}` : "the response has no Content-Type header";
14
+ out.push({
15
+ code: ct.reason,
16
+ validator: "content_type",
17
+ declared,
18
+ received,
19
+ message: `${want} and ${got}; the content is returned as sent and the call is not counted as a failure`,
20
+ });
21
+ }
22
+ return out;
23
+ }
4
24
  /** One JSON file per call: <receiptsDir>/<timestamp>-<random>.json. Returns the file name. */
5
25
  export async function writeReceipt(dir, r) {
6
26
  const name = `${r.started_at.replace(/[:.]/g, "-")}-${randomBytes(3).toString("hex")}.json`;