@paidfor/x402-safe-fetch 0.4.0 → 0.6.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,64 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.6.0
4
+
5
+ - **A payment the seller rejects is no longer recorded as paid.** When the paid request is answered with HTTP 402
6
+ again and nothing settled (no settlement header, or one with `success: false`), as happens with a wallet that has
7
+ no USDC, the receipt now says `outcome: "payment_rejected"` and `paid: false` (it said `validator_failed` and
8
+ `paid: true`). The response is still returned, with status 402. No price is recorded in `prices.json`, no telemetry
9
+ row is sent in either version (before, a verified row reported `non_delivery` against the seller), and in team mode
10
+ the approval is reported as not paid (`paid: false`), so the team releases it instead of recording a settlement.
11
+ `reported_outcome` is `error`, the harness name for "not paid"; `proof` is null. A 402 whose settlement header
12
+ cannot be read is still treated as paid, since it may name a settlement.
13
+ - **Retrying a rejected payment.** The intent is kept in the new phase `rejected` with the signed nonce, deadline,
14
+ payer, network and asset, and a retry with the same `intentId` is allowed (before, it replayed the 402). Without
15
+ `team` or `authorize` the retry signs the same nonce again, so at most one of the two authorizations can ever
16
+ settle. A retry from another wallet, network or asset throws `IntentConflictError` and signs nothing (the same
17
+ nonce there would be a second authorization that could also settle). With an approval naming a different nonce,
18
+ the retry refuses with `refused_authorize` until the rejected authorization's deadline has passed. The deadline
19
+ only stops later use of the old signature; it does not show the old one was never used. `authorizationState(payer,
20
+ nonce)` on the USDC contract being `false` does; `true` means used or cancelled, and only the `AuthorizationUsed`
21
+ event with its USDC `Transfer` shows a payment. When the same nonce is signed again and rejected again, the intent
22
+ keeps the later of the two deadlines (an unknown one never passes). A new `intentId` signs a new nonce as before. See
23
+ "When the seller rejects the payment" in the README.
24
+ - New receipt field `valid_before`: the signed authorization's deadline, Unix seconds (null when nothing was signed).
25
+ `Outcome` gains `payment_rejected`. Both are additive; older receipts lack the field.
26
+ - **Team mode tells the team about local refusals.** A payment refused before the team is asked (`refused_verdict`,
27
+ `refused_ratio`, `refused_max_per_call`) is posted to `{origin}/v1/team/refusals` with the quote, the reason and
28
+ the verdict, so the ledger and the bill can count what was saved. Fire-and-forget: 2-second timeout, never awaited,
29
+ every failure (including a 404 from a server without the route) swallowed and never logged; the thrown error is
30
+ unchanged. The key goes only to the team origin.
31
+ - **`team.project`**, and `PAIDFOR_PROJECT` when team mode comes from `PAIDFOR_TEAM_KEY`: a project tag sent as
32
+ `project` on every authorize and refusal notice. A tag the server would refuse (it must be 1 to 64 letters, digits,
33
+ spaces or `. _ -` after trimming) throws when `safeFetch` is called. An empty `PAIDFOR_PROJECT` is ignored.
34
+ - **`telemetryNotice`**: `false` turns off the one-time notice about verified telemetry; a function receives it
35
+ instead of `logger.warn`. The default is unchanged.
36
+ - README: `verification_url` is live (the "not live yet" note is gone); the team section says
37
+ `npx -y @paidfor/mcp@latest`, as does the "wallet not registered" message; sample rows show
38
+ `x402-safe-fetch/<version>`. New outcome table.
39
+ - Exported: `cleanProject` and the types `TeamRefusalBody`, `TeamRefusalReason`.
40
+ - `client` in telemetry rows and the `X-Paidfor-Client` header is `x402-safe-fetch/0.6.0`.
41
+
42
+ ## 0.5.0
43
+
44
+ - **Team mode: `team: { key }`.** Budgets per wallet, human approvals and a ledger from a paidfor team account, with
45
+ one option. Every payment asks `{origin}/v1/team/authorize` (default origin `https://paidfor.dev`) before signing
46
+ and signs the minted nonce and deadline; anything but a clean approval throws `TeamRefusedError` (code
47
+ `refused_authorize`, with `decision`: `decline`, `needs_approval` with `approve_url` and `expires_at`,
48
+ `already_settled`, or `failed`) and signs nothing. Every approval's outcome is reported to `/v1/team/outcome`; a
49
+ report the server could not take is kept in `<receiptsDir>/team-outcomes` (in memory if the disk cannot take it)
50
+ and sent before the next payment. `receipt.team` carries the decision, the server's `warnings` and the report's
51
+ state. The key goes only to the team origin; a plain-http origin off this machine is refused.
52
+ - **`PAIDFOR_TEAM_KEY` turns team mode on** when `team` and `authorize` are both left out. If that variable is in
53
+ the environment of a program upgrading from 0.4.x, its payments now ask the team first; pass `team: false` to keep
54
+ the old behaviour. `team` and `authorize` together throw.
55
+ - Exported: `TeamRefusedError`, `TeamClient`, `outcomeFor`, `readDecision`, `isKeySafeOrigin`, `TEAM_ORIGIN` and the
56
+ types `TeamOptions`, `TeamDecision`, `TeamDecisionExtras`, `TeamWarning`, `TeamReceipt`, `TeamReportState`,
57
+ `TeamAuthorizeBody`, `TeamOutcomeBody`, `TeamClientOptions`.
58
+ `TeamClient` leaves bare queue entries (the `@paidfor/mcp` format, which names no key) untouched unless it is made
59
+ with `adoptBareEntries: true`; the `team` option never adopts them.
60
+ - `client` in telemetry rows and the `X-Paidfor-Client` header is `x402-safe-fetch/0.5.0`.
61
+
3
62
  ## 0.4.0
4
63
 
5
64
  - **`authorize`.** A new option: a callback asked after every local check and before anything is signed. An approval
package/README.md CHANGED
@@ -44,7 +44,9 @@ Payments are exact-scheme USDC on Base mainnet by default (`network: "eip155:845
44
44
  receipts directory before signing, and the signed nonce is written before the payment is sent. A retry with
45
45
  the same `intentId` and request returns the stored response and never signs again. A retry with the same
46
46
  `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.
47
+ stored, a retry throws `IntentIndeterminateError` instead of paying again. A payment the seller rejected
48
+ (`payment_rejected`, below) may be retried with the same `intentId` from the same wallet: it signs the same
49
+ nonce again, so at most one of the two authorizations can ever settle.
48
50
  3. **After the response.** The configured validators run on the paid response. `res.receipt` carries the intent
49
51
  id, quote, amount, reference price and its source, seller verdict, validator results, the settlement header,
50
52
  and the on-chain tx hash when the header carries it. The same receipt is written to the receipts directory as
@@ -64,6 +66,55 @@ Payments are exact-scheme USDC on Base mainnet by default (`network: "eip155:845
64
66
  | 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
67
  | 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 |
66
68
 
69
+ ## Outcomes
70
+
71
+ `res.receipt.outcome` (and `err.receipt.outcome` on a thrown error):
72
+
73
+ | `outcome` | What happened | `paid` | Returned or thrown |
74
+ | --- | --- | --- | --- |
75
+ | `ok` | Paid, and every validator passed. | `true` | Returned |
76
+ | `validator_failed` | Paid, and a validator failed (a non-2xx answer, an empty or truncated body, the wrong content type). | `true` | Returned |
77
+ | `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) |
78
+ | `paid_no_response` | Signed and maybe sent, and no response came back. | `true` if sent | Thrown |
79
+ | `refused_verdict`, `refused_ratio`, `refused_max_per_call`, `refused_authorize` | Refused before signing. | `false` | Thrown |
80
+ | `no_acceptable_quote` | No exact USDC quote on the configured network. | `false` | Thrown |
81
+ | `no_payment_required` | The resource answered without a 402. | `false` | Returned |
82
+ | `replayed` | The stored result of an earlier call with this `intentId`. | `false` | Returned |
83
+ | `error` | Anything else before signing (network, SDK). | `false` | Thrown |
84
+
85
+ ### When the seller rejects the payment
86
+
87
+ A `payment_rejected` receipt has `paid: false`, no `tx_hash`, no `proof`, and `error.code` `payment_rejected`.
88
+ No price is learnt from it, no telemetry row is sent (it says nothing about the seller), and in team mode the
89
+ approval is reported as not paid, so the team releases it.
90
+
91
+ The one real risk: the signed EIP-3009 authorization can still be used until its deadline, so whoever holds it (the
92
+ seller or its facilitator) could settle it later, for example once the wallet is funded, even though the seller
93
+ answered 402. The receipt keeps what you need to check: `payer`, `nonce` and `valid_before` (Unix seconds).
94
+
95
+ **The deadline is not a settlement check.** Once `valid_before` has passed, the old signature can no longer be used,
96
+ but that says nothing about whether it was used before then. Read `authorizationState(payer, nonce)` on the USDC
97
+ contract on Base: `false` after the deadline shows nothing moved and nothing ever can. `true` only says the nonce
98
+ can no longer be used: it was used **or cancelled** (USDC's `cancelAuthorization` sets it too). To count it as a
99
+ payment, find the `AuthorizationUsed(payer, nonce)` event and the USDC `Transfer` in the same transaction. When the
100
+ same nonce is signed again with a shorter deadline and rejected again, the receipt's `valid_before` is that newer
101
+ signature's; the intent file keeps the latest deadline of every signature under the nonce, and that is the one to
102
+ wait for. This client does not read
103
+ the chain, so that check is yours.
104
+
105
+ - Retrying with the same `intentId` from the same wallet, network and asset is allowed, because nothing was paid.
106
+ Without `team` or `authorize` the retry signs the same nonce, so at most one of the two authorizations can ever
107
+ move money. With `team` or `authorize` the approval names the nonce: the retry signs if it names the same nonce,
108
+ or, with a different nonce, only once the old deadline has passed (otherwise it refuses with `refused_authorize`
109
+ and says until when; the team server answers `released_not_expired` until then in any case). A different nonce
110
+ after the deadline is not covered by the one-nonce guarantee: check `authorizationState` first (`false`).
111
+ - A retry of that `intentId` from another wallet, on another network or for another asset throws
112
+ `IntentConflictError` and signs nothing: the same nonce there would be a separate authorization that could also
113
+ settle. So does a retry of an intent rejected by an earlier build, which did not record the payer.
114
+ - A new `intentId` is a new purchase with a new nonce. Only start one after the old deadline has passed and
115
+ `authorizationState(payer, nonce)` is `false` (both: before the deadline it could still be used; `true` needs the
116
+ `AuthorizationUsed` and `Transfer` check above to tell a payment from a cancellation).
117
+
67
118
  ## Receipts directory
68
119
 
69
120
  ```
@@ -76,9 +127,9 @@ Payments are exact-scheme USDC on Base mainnet by default (`network: "eip155:845
76
127
  ```
77
128
 
78
129
  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.
130
+ `telemetry: "verified"`, a `verification_url` of the form `{indexUrl}/telemetry/<payer>/<nonce>`, which shows
131
+ whether the index has verified your row on-chain (usually within about five minutes of the payment).
132
+ `reported_outcome` is the outcome under the harness names, as the row reports it.
82
133
 
83
134
  Keep this directory if you want the idempotency guarantee to survive restarts.
84
135
 
@@ -97,7 +148,7 @@ v1 row:
97
148
 
98
149
  ```json
99
150
  { "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" }
151
+ "amount_usdc": "0.010000", "latency_ms": 412, "validator_failures": [], "client": "x402-safe-fetch/<version>" }
101
152
  ```
102
153
 
103
154
  Both payloads and every field are documented in [docs/telemetry.md](docs/telemetry.md).
@@ -123,7 +174,7 @@ This is the whole message, for a paid call that got a 500:
123
174
  "amount_usdc": "0.002000",
124
175
  "latency_ms": 1840,
125
176
  "validator_failures": ["http_status:500"],
126
- "client": "x402-safe-fetch/0.3.0",
177
+ "client": "x402-safe-fetch/<version>",
127
178
  "proof": {
128
179
  "network": "eip155:8453",
129
180
  "scheme": "exact",
@@ -160,7 +211,8 @@ This is the whole message, for a paid call that got a 500:
160
211
  validator evidence are never sent.
161
212
  - **Refusals carry no proof.** A refused or unpaid call sends the row without `proof`; it is counted as a
162
213
  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.
214
+ about the seller. Nor does a `payment_rejected` call (0.6.0): nothing was paid, and a wallet that cannot pay is
215
+ not the seller's failure.
164
216
  - **Outcomes use the index's names:** `ok`, `non_delivery` (a non-2xx answer or a failed delivery validator after paying),
165
217
  `overcharge` (paid more than 1.1x the reference, possible only if you raised `maxOverListedRatio`),
166
218
  `wrong_goods`, `duplicate`, plus the client-only `refused_*`, `no_acceptable_quote`, `paid_no_response` and
@@ -169,7 +221,51 @@ This is the whole message, for a paid call that got a 500:
169
221
  default) sends nothing. `indexUrl: false` turns off the index lookup and all telemetry.
170
222
 
171
223
  The first time a receipts directory is used with `"verified"`, the client prints a one-line notice pointing
172
- here.
224
+ here, through `logger.warn` (stderr with the default console). `telemetryNotice: false` turns it off;
225
+ `telemetryNotice: (msg) => ...` sends it to your own function instead. Nothing else changes.
226
+
227
+ ## With a team account
228
+
229
+ A free [paidfor team account](https://paidfor.dev/team) adds budgets per wallet, human approvals and a ledger. Add
230
+ the team key, nothing else:
231
+
232
+ ```ts
233
+ const fetchWithPay = safeFetch(account, {
234
+ maxPerCallUsd: 0.5,
235
+ team: { key: process.env.PAIDFOR_TEAM_KEY! },
236
+ });
237
+ ```
238
+
239
+ What you get:
240
+
241
+ - Before signing, every payment asks `https://paidfor.dev/v1/team/authorize` and signs only with the nonce and
242
+ deadline the team minted. Anything but a clean approval pays nothing and throws `TeamRefusedError` (code
243
+ `refused_authorize`): a decline (`decision.reason`, `decision.message`), a payment waiting for a person
244
+ (`decision.approve_url` and `decision.expires_at`: show the link, then call again with the same `intentId`), an
245
+ intent the team already saw paid (`already_settled`), or a team that could not be asked (timeout, 5xx, an answer
246
+ it could not read). Your local caps still apply: a payment must pass both.
247
+ - Every approval's outcome, paid or not, is reported to the team's ledger. A report the server could not take is
248
+ kept in `<receiptsDir>/team-outcomes` and sent before the next payment (in memory, until the process ends, if
249
+ the disk cannot take it).
250
+ - `receipt.team` says what the team decided, carries any `warnings` the server sent, and `outcome_report` (`sent`,
251
+ `queued` or `rejected`).
252
+
253
+ - A payment this client refuses by itself before asking the team (`refused_verdict`, `refused_ratio`,
254
+ `refused_max_per_call`) is told to the team (`POST {origin}/v1/team/refusals`, with the quote, the reason and the
255
+ verdict), so the ledger and the bill can show what was saved. That notice is fire-and-forget: a 2-second timeout,
256
+ never awaited, every failure swallowed, and the error you get is the same either way.
257
+ - `project` (0.6.0) tags every payment, so the ledger and the bill can be read by project:
258
+ `team: { key, project: "research-q4" }`. A tag is 1 to 64 letters, digits, spaces or `. _ -`; anything else throws
259
+ when `safeFetch` is called.
260
+
261
+ The wallet must be registered to the team: on [paidfor.dev/team](https://paidfor.dev/team), or with
262
+ `npx -y @paidfor/mcp@latest init --wallet --link` (add `--key-file <path>` for a key file of your own). The key goes
263
+ only to the team origin, never to a seller, and is never logged. `team` also takes `origin` (https only, or
264
+ http on localhost), `authorizeTimeoutMs` (default 10000), `reportTimeoutMs` (default 5000) and `project`.
265
+
266
+ When `team` is left out and `PAIDFOR_TEAM_KEY` is set in the environment, team mode turns on by itself (a
267
+ 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
268
+ `authorize`, and with your own `authorize` the environment is not read.
173
269
 
174
270
  ## Ask before paying
175
271
 
@@ -221,10 +317,12 @@ own checks). Responses without a settlement (free calls, refusals) send nothing.
221
317
 
222
318
  | Error | `code` | Paid? |
223
319
  | --- | --- | --- |
224
- | `PaymentRefusedError` | `refused_verdict`, `refused_ratio`, `refused_max_per_call`, `refused_authorize` | No |
225
- | `IntentConflictError` | `intent_conflict` | No |
320
+ | `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 |
321
+ | `TeamRefusedError` (a `PaymentRefusedError`) | `refused_authorize`; `decision` says why | No |
322
+ | `IntentConflictError` | `intent_conflict` (also: a retry after `payment_rejected` from another wallet, network or asset) | No |
226
323
  | `IntentIndeterminateError` | `intent_indeterminate` | Maybe, earlier; never again |
227
324
  | `SafeFetchError` | `paid_no_response` | Signed and possibly settled; `receipt.nonce` identifies it |
325
+ | 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") |
228
326
  | `SafeFetchError` | `no_acceptable_quote`, `intent_in_flight`, `network`, `sdk` | No |
229
327
 
230
328
  ## Example
package/dist/errors.d.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import type { Receipt } from "./receipt.js";
2
+ import type { TeamDecision } from "./team.js";
2
3
  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
4
  /** Every error this package throws. `receipt` is set whenever a call got far enough to write one. */
4
5
  export declare class SafeFetchError extends Error {
@@ -15,6 +16,18 @@ export declare class PaymentRefusedError extends SafeFetchError {
15
16
  name: string;
16
17
  constructor(code: "refused_verdict" | "refused_ratio" | "refused_max_per_call" | "refused_authorize", message: string, sellerUrl: string | null, receipt?: Receipt);
17
18
  }
19
+ /**
20
+ * The team (the `team` option) did not approve this payment, or could not be asked. Nothing was paid. `decision` says
21
+ * why: `needs_approval` carries the `approve_url` to show a person (then call again with the same intentId),
22
+ * `already_settled` means this intent was paid before, `decline` carries the server's `reason`, `failed` means the
23
+ * team could not be asked. An `approve` here was unusable (malformed, or about to lapse) and is reported as not paid.
24
+ * Always code `refused_authorize`.
25
+ */
26
+ export declare class TeamRefusedError extends PaymentRefusedError {
27
+ readonly decision: TeamDecision;
28
+ name: string;
29
+ constructor(decision: TeamDecision, message: string, sellerUrl: string | null, receipt?: Receipt);
30
+ }
18
31
  /** Same intentId, different request. Nothing was sent. */
19
32
  export declare class IntentConflictError extends SafeFetchError {
20
33
  name: string;
package/dist/errors.js CHANGED
@@ -18,6 +18,21 @@ export class PaymentRefusedError extends SafeFetchError {
18
18
  this.sellerUrl = sellerUrl;
19
19
  }
20
20
  }
21
+ /**
22
+ * The team (the `team` option) did not approve this payment, or could not be asked. Nothing was paid. `decision` says
23
+ * why: `needs_approval` carries the `approve_url` to show a person (then call again with the same intentId),
24
+ * `already_settled` means this intent was paid before, `decline` carries the server's `reason`, `failed` means the
25
+ * team could not be asked. An `approve` here was unusable (malformed, or about to lapse) and is reported as not paid.
26
+ * Always code `refused_authorize`.
27
+ */
28
+ export class TeamRefusedError extends PaymentRefusedError {
29
+ decision;
30
+ name = "TeamRefusedError";
31
+ constructor(decision, message, sellerUrl, receipt) {
32
+ super("refused_authorize", message, sellerUrl, receipt);
33
+ this.decision = decision;
34
+ }
35
+ }
21
36
  /** Same intentId, different request. Nothing was sent. */
22
37
  export class IntentConflictError extends SafeFetchError {
23
38
  name = "IntentConflictError";
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
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
- export { SafeFetchError, PaymentRefusedError, IntentConflictError, IntentIndeterminateError, type SafeFetchErrorCode } from "./errors.js";
2
+ export { SafeFetchError, PaymentRefusedError, IntentConflictError, IntentIndeterminateError, TeamRefusedError, type SafeFetchErrorCode } from "./errors.js";
3
3
  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";
@@ -7,3 +7,4 @@ 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
9
  export { reportOnly, withPaidforReporting, withPaidforReportingAxios, buildTxOnlyPayload, settlementTx, type ReportOnlyOptions, type ReportOutcome, type TxOnlyPayload, type AxiosLike } from "./report-only.js";
10
+ 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,3 +1,4 @@
1
1
  export { safeFetch, hashRequest } from "./safe-fetch.js";
2
- export { SafeFetchError, PaymentRefusedError, IntentConflictError, IntentIndeterminateError } from "./errors.js";
2
+ export { SafeFetchError, PaymentRefusedError, IntentConflictError, IntentIndeterminateError, TeamRefusedError } from "./errors.js";
3
3
  export { reportOnly, withPaidforReporting, withPaidforReportingAxios, buildTxOnlyPayload, settlementTx } from "./report-only.js";
4
+ 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
@@ -2,9 +2,10 @@ import type { Verdict } from "./index-client.js";
2
2
  import type { ReferenceSource } from "./price.js";
3
3
  import type { TelemetryOutcome, TelemetryProof } from "./proof.js";
4
4
  import type { ValidatorName } from "./taxonomy.js";
5
+ import type { TeamReceipt } from "./team.js";
5
6
  import type { SettlementResponse } from "./x402/types.js";
6
7
  import type { ValidatorResult } from "./validators/types.js";
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
+ 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";
8
9
  export interface Receipt {
9
10
  v: 1;
10
11
  client: string;
@@ -16,7 +17,10 @@ export interface Receipt {
16
17
  finished_at: string;
17
18
  latency_ms: number;
18
19
  outcome: Outcome;
19
- /** True when a payment authorization was sent to the seller. */
20
+ /**
21
+ * True when a payment authorization was sent to the seller and the seller did not reject it. False for
22
+ * `payment_rejected` (sent, but answered HTTP 402 with no settlement): see `nonce` and `valid_before`.
23
+ */
20
24
  paid: boolean;
21
25
  /** True when this result was served from the intent store without contacting the seller. */
22
26
  replayed: boolean;
@@ -64,6 +68,11 @@ export interface Receipt {
64
68
  nonce: string | null;
65
69
  /** authorization.from of the signed payment, lowercase. */
66
70
  payer: string | null;
71
+ /**
72
+ * authorization.validBefore of the signed payment, Unix seconds: until then the authorization could still be
73
+ * settled by whoever holds it. Null when nothing was signed. (0.6.0; absent on older receipts.)
74
+ */
75
+ valid_before?: number | null;
67
76
  /** Proof of payment for a sent authorization (the `proof` of a v2 telemetry row). Null when nothing was sent. */
68
77
  proof: TelemetryProof | null;
69
78
  /** The outcome under the harness names, as a v2 telemetry row reports it. */
@@ -85,6 +94,11 @@ export interface Receipt {
85
94
  code: string;
86
95
  message: string;
87
96
  } | null;
97
+ /**
98
+ * Team mode only (the `team` option): what the team decided, its `warnings`, and what became of the outcome report.
99
+ * `outcome_report` is filled in after the receipt file is written, so it is on the returned receipt only.
100
+ */
101
+ team?: TeamReceipt;
88
102
  }
89
103
  /** One JSON file per call: <receiptsDir>/<timestamp>-<random>.json. Returns the file name. */
90
104
  export declare function writeReceipt(dir: string, r: Receipt): Promise<string>;
@@ -1,6 +1,7 @@
1
1
  import type { ClientEvmSigner } from "@x402/evm";
2
2
  import { type Verdict } from "./index-client.js";
3
3
  import { type Receipt } from "./receipt.js";
4
+ import { type TeamOptions } from "./team.js";
4
5
  import { type ValidatorName } from "./taxonomy.js";
5
6
  export type SafeNetwork = "eip155:8453" | "eip155:84532";
6
7
  export interface SafeFetchOptions {
@@ -31,12 +32,31 @@ export interface SafeFetchOptions {
31
32
  logger?: {
32
33
  warn(msg: string): void;
33
34
  };
35
+ /**
36
+ * The one-time notice that says what `telemetry: "verified"` sends. Default true: it goes to `logger.warn` (stderr
37
+ * with the default console). `false` never shows it; a function receives the text instead of `logger`. Useful in
38
+ * an MCP server, whose client may show anything on stderr as an error.
39
+ */
40
+ telemetryNotice?: boolean | ((msg: string) => void);
34
41
  /**
35
42
  * Asks someone else whether this payment may go ahead, after every local check has passed and before anything is
36
43
  * signed. An approval names the EIP-3009 nonce and `validBefore` to sign. Anything but a well-formed approval,
37
44
  * including a throw, is a `refused_authorize`: nothing is signed. Not asked for a free resource or a replay.
45
+ * The low-level hook behind `team`; passing both throws.
38
46
  */
39
47
  authorize?: (request: AuthorizeRequest) => Promise<AuthorizeAnswer>;
48
+ /**
49
+ * Team mode: a paidfor team account's budgets, approvals and ledger. Before signing, every payment asks
50
+ * `{origin}/v1/team/authorize` with the key and signs the nonce and deadline the team minted; anything but a clean
51
+ * approval pays nothing and throws TeamRefusedError. Every approval's outcome is reported to `/v1/team/outcome`; a
52
+ * report the server could not take is kept in `<receiptsDir>/team-outcomes` and sent before the next payment. A payment
53
+ * refused locally before the team is asked (verdict, ratio, per-call cap) is told to `/v1/team/refusals`,
54
+ * fire-and-forget. `project` tags every payment.
55
+ *
56
+ * When omitted (and `authorize` is not set), the key is read from the environment variable PAIDFOR_TEAM_KEY if it
57
+ * is set, and the project tag from PAIDFOR_PROJECT. `false` turns team mode off whatever the environment says. Passing `team` together with `authorize` throws.
58
+ */
59
+ team?: TeamOptions | false;
40
60
  }
41
61
  /** The quote `authorize` is asked about. `network` is CAIP-2. */
42
62
  export interface AuthorizeRequest {
@@ -58,7 +78,12 @@ export type AuthorizeAnswer = {
58
78
  message: string;
59
79
  };
60
80
  export interface CallOptions {
61
- /** Same intentId + same request: returns the stored result, never signs again. Same intentId + different request: throws. */
81
+ /**
82
+ * Same intentId + same request: returns the stored result, never signs again. Same intentId + different request: throws.
83
+ * After a `payment_rejected` the same intentId may be used again from the same wallet, network and asset; it signs
84
+ * the rejected authorization's nonce again, so at most one of the two can ever settle. Any other wallet, network or
85
+ * asset throws IntentConflictError.
86
+ */
62
87
  intentId?: string;
63
88
  }
64
89
  export type SafeResponse = Response & {