@paidfor/x402-safe-fetch 0.5.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 +39 -0
- package/README.md +75 -13
- package/dist/index.d.ts +1 -1
- package/dist/index.js +1 -1
- package/dist/intents.d.ts +19 -1
- package/dist/intents.js +7 -0
- package/dist/proof.js +2 -1
- package/dist/receipt.d.ts +10 -2
- package/dist/safe-fetch.d.ts +16 -3
- package/dist/safe-fetch.js +164 -18
- package/dist/team.d.ts +25 -0
- package/dist/team.js +29 -1
- package/dist/telemetry.d.ts +1 -1
- package/dist/telemetry.js +1 -1
- package/docs/telemetry.md +10 -8
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,44 @@
|
|
|
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
|
+
|
|
3
42
|
## 0.5.0
|
|
4
43
|
|
|
5
44
|
- **Team mode: `team: { key }`.** Budgets per wallet, human approvals and a ledger from a paidfor team account, with
|
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>`,
|
|
80
|
-
|
|
81
|
-
|
|
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
|
|
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
|
|
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,8 @@ 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.
|
|
173
226
|
|
|
174
227
|
## With a team account
|
|
175
228
|
|
|
@@ -197,13 +250,21 @@ What you get:
|
|
|
197
250
|
- `receipt.team` says what the team decided, carries any `warnings` the server sent, and `outcome_report` (`sent`,
|
|
198
251
|
`queued` or `rejected`).
|
|
199
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
|
+
|
|
200
261
|
The wallet must be registered to the team: on [paidfor.dev/team](https://paidfor.dev/team), or with
|
|
201
|
-
`npx -y @paidfor/mcp@
|
|
262
|
+
`npx -y @paidfor/mcp@latest init --wallet --link` (add `--key-file <path>` for a key file of your own). The key goes
|
|
202
263
|
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)
|
|
264
|
+
http on localhost), `authorizeTimeoutMs` (default 10000), `reportTimeoutMs` (default 5000) and `project`.
|
|
204
265
|
|
|
205
266
|
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
|
|
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
|
|
207
268
|
`authorize`, and with your own `authorize` the environment is not read.
|
|
208
269
|
|
|
209
270
|
## Ask before paying
|
|
@@ -256,11 +317,12 @@ own checks). Responses without a settlement (free calls, refusals) send nothing.
|
|
|
256
317
|
|
|
257
318
|
| Error | `code` | Paid? |
|
|
258
319
|
| --- | --- | --- |
|
|
259
|
-
| `PaymentRefusedError` | `refused_verdict`, `refused_ratio`, `refused_max_per_call`, `refused_authorize` | 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 |
|
|
260
321
|
| `TeamRefusedError` (a `PaymentRefusedError`) | `refused_authorize`; `decision` says why | No |
|
|
261
|
-
| `IntentConflictError` | `intent_conflict` | No |
|
|
322
|
+
| `IntentConflictError` | `intent_conflict` (also: a retry after `payment_rejected` from another wallet, network or asset) | No |
|
|
262
323
|
| `IntentIndeterminateError` | `intent_indeterminate` | Maybe, earlier; never again |
|
|
263
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") |
|
|
264
326
|
| `SafeFetchError` | `no_acceptable_quote`, `intent_in_flight`, `network`, `sdk` | No |
|
|
265
327
|
|
|
266
328
|
## Example
|
package/dist/index.d.ts
CHANGED
|
@@ -7,4 +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, TEAM_ORIGIN, type TeamOptions, type TeamDecision, type TeamDecisionExtras, type TeamWarning, type TeamReceipt, type TeamReportState, type TeamAuthorizeBody, type TeamOutcomeBody, type TeamClientOptions } from "./team.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,4 +1,4 @@
|
|
|
1
1
|
export { safeFetch, hashRequest } from "./safe-fetch.js";
|
|
2
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, TEAM_ORIGIN } from "./team.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
|
-
|
|
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,7 @@ 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
9
|
export interface Receipt {
|
|
10
10
|
v: 1;
|
|
11
11
|
client: string;
|
|
@@ -17,7 +17,10 @@ export interface Receipt {
|
|
|
17
17
|
finished_at: string;
|
|
18
18
|
latency_ms: number;
|
|
19
19
|
outcome: Outcome;
|
|
20
|
-
/**
|
|
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
|
+
*/
|
|
21
24
|
paid: boolean;
|
|
22
25
|
/** True when this result was served from the intent store without contacting the seller. */
|
|
23
26
|
replayed: boolean;
|
|
@@ -65,6 +68,11 @@ export interface Receipt {
|
|
|
65
68
|
nonce: string | null;
|
|
66
69
|
/** authorization.from of the signed payment, lowercase. */
|
|
67
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;
|
|
68
76
|
/** Proof of payment for a sent authorization (the `proof` of a v2 telemetry row). Null when nothing was sent. */
|
|
69
77
|
proof: TelemetryProof | null;
|
|
70
78
|
/** The outcome under the harness names, as a v2 telemetry row reports it. */
|
package/dist/safe-fetch.d.ts
CHANGED
|
@@ -32,6 +32,12 @@ export interface SafeFetchOptions {
|
|
|
32
32
|
logger?: {
|
|
33
33
|
warn(msg: string): void;
|
|
34
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);
|
|
35
41
|
/**
|
|
36
42
|
* Asks someone else whether this payment may go ahead, after every local check has passed and before anything is
|
|
37
43
|
* signed. An approval names the EIP-3009 nonce and `validBefore` to sign. Anything but a well-formed approval,
|
|
@@ -43,10 +49,12 @@ export interface SafeFetchOptions {
|
|
|
43
49
|
* Team mode: a paidfor team account's budgets, approvals and ledger. Before signing, every payment asks
|
|
44
50
|
* `{origin}/v1/team/authorize` with the key and signs the nonce and deadline the team minted; anything but a clean
|
|
45
51
|
* approval pays nothing and throws TeamRefusedError. Every approval's outcome is reported to `/v1/team/outcome`; a
|
|
46
|
-
* report the server could not take is kept in `<receiptsDir>/team-outcomes` and sent before the next payment.
|
|
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.
|
|
47
55
|
*
|
|
48
56
|
* When omitted (and `authorize` is not set), the key is read from the environment variable PAIDFOR_TEAM_KEY if it
|
|
49
|
-
* is set. `false` turns team mode off whatever the environment says. Passing `team` together with `authorize` throws.
|
|
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.
|
|
50
58
|
*/
|
|
51
59
|
team?: TeamOptions | false;
|
|
52
60
|
}
|
|
@@ -70,7 +78,12 @@ export type AuthorizeAnswer = {
|
|
|
70
78
|
message: string;
|
|
71
79
|
};
|
|
72
80
|
export interface CallOptions {
|
|
73
|
-
/**
|
|
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
|
+
*/
|
|
74
87
|
intentId?: string;
|
|
75
88
|
}
|
|
76
89
|
export type SafeResponse = Response & {
|
package/dist/safe-fetch.js
CHANGED
|
@@ -15,13 +15,13 @@ import { x402Client } from "@x402/core/client";
|
|
|
15
15
|
import { registerExactEvmScheme } from "@x402/evm/exact/client";
|
|
16
16
|
import { wrapFetchWithPayment } from "@x402/fetch";
|
|
17
17
|
import { readBodyTee } from "./body.js";
|
|
18
|
-
import { IntentIndeterminateError, PaymentRefusedError, SafeFetchError, TeamRefusedError } from "./errors.js";
|
|
18
|
+
import { IntentConflictError, IntentIndeterminateError, PaymentRefusedError, SafeFetchError, TeamRefusedError } from "./errors.js";
|
|
19
19
|
import { UNKNOWN_SELLER_NOTE, checkIndex } from "./index-client.js";
|
|
20
20
|
import { IntentStore } from "./intents.js";
|
|
21
21
|
import { PriceBook, USDC_BY_NETWORK, atomicToUsdc, exceedsRatio, quoteRatio, resourceKey, usdToAtomic, usdcStringToAtomic } from "./price.js";
|
|
22
22
|
import { DEFAULT_MAX_RATIO, REFUSED_OUTCOMES, buildProof, failureLabels, harnessOutcome } from "./proof.js";
|
|
23
23
|
import { writeReceipt } from "./receipt.js";
|
|
24
|
-
import { TEAM_ORIGIN, TeamClient, outcomeFor } from "./team.js";
|
|
24
|
+
import { PROJECT_RULE, TEAM_ORIGIN, TeamClient, cleanProject, outcomeFor } from "./team.js";
|
|
25
25
|
import { ALL_VALIDATORS, MAX_BODY_BYTES } from "./taxonomy.js";
|
|
26
26
|
import { CLIENT_ID, buildPayload, buildPayloadV2, sendTelemetry } from "./telemetry.js";
|
|
27
27
|
import { runAllValidators, validatorsByName } from "./validators/index.js";
|
|
@@ -72,23 +72,40 @@ function wrapResponse(status, statusText, headers, body, url, receipt) {
|
|
|
72
72
|
}
|
|
73
73
|
const TX_HASH_RE = /^0x[0-9a-fA-F]{64}$/;
|
|
74
74
|
let envNoticeShown = false;
|
|
75
|
-
/**
|
|
75
|
+
/** A project tag as the server takes it, or a TypeError naming where the bad one came from. */
|
|
76
|
+
function projectTag(v, from) {
|
|
77
|
+
const p = cleanProject(v);
|
|
78
|
+
if (p === null)
|
|
79
|
+
throw new TypeError(`safeFetch: ${from} ${JSON.stringify(v)} is not a project tag: ${PROJECT_RULE}`);
|
|
80
|
+
return p;
|
|
81
|
+
}
|
|
82
|
+
/** `team`, or PAIDFOR_TEAM_KEY (and PAIDFOR_PROJECT) when neither `team` nor `authorize` is given. */
|
|
76
83
|
function resolveTeam(o) {
|
|
77
84
|
if (o.team === false)
|
|
78
85
|
return undefined;
|
|
79
86
|
if (o.team !== undefined) {
|
|
80
87
|
if (!o.team || typeof o.team !== "object" || typeof o.team.key !== "string" || !o.team.key.trim()) {
|
|
81
|
-
throw new TypeError("safeFetch: team must be { key: string, origin?: string } or false");
|
|
88
|
+
throw new TypeError("safeFetch: team must be { key: string, origin?: string, project?: string } or false");
|
|
82
89
|
}
|
|
83
90
|
if (o.authorize)
|
|
84
91
|
throw new TypeError("safeFetch: pass team or authorize, not both (team supplies its own authorize)");
|
|
85
|
-
|
|
92
|
+
const project = o.team.project === undefined ? undefined : projectTag(o.team.project, "team.project");
|
|
93
|
+
return { team: o.team, fromEnv: false, project };
|
|
86
94
|
}
|
|
87
95
|
if (o.authorize)
|
|
88
96
|
return undefined; // the caller asks someone itself; the environment is not consulted
|
|
89
|
-
const
|
|
90
|
-
|
|
97
|
+
const env = typeof process !== "undefined" ? process.env : undefined;
|
|
98
|
+
const key = env?.PAIDFOR_TEAM_KEY?.trim();
|
|
99
|
+
if (!key)
|
|
100
|
+
return undefined;
|
|
101
|
+
// An empty PAIDFOR_PROJECT is the same as none; anything else must be a tag the server takes.
|
|
102
|
+
const rawProject = env?.PAIDFOR_PROJECT;
|
|
103
|
+
const project = rawProject === undefined || !rawProject.trim() ? undefined : projectTag(rawProject, "PAIDFOR_PROJECT");
|
|
104
|
+
return { team: { key }, fromEnv: true, project };
|
|
91
105
|
}
|
|
106
|
+
/** Refusals the client makes by itself before the team is asked; the team is told about them (POST /v1/team/refusals). */
|
|
107
|
+
const LOCAL_REFUSALS = new Set(["refused_verdict", "refused_ratio", "refused_max_per_call"]);
|
|
108
|
+
const NONCE_RE = /^0x[0-9a-fA-F]{64}$/;
|
|
92
109
|
function teamReceipt(origin, d) {
|
|
93
110
|
return {
|
|
94
111
|
origin,
|
|
@@ -169,7 +186,8 @@ export function safeFetch(wallet, options) {
|
|
|
169
186
|
/* ignore */
|
|
170
187
|
}
|
|
171
188
|
};
|
|
172
|
-
|
|
189
|
+
const noticeOpt = options.telemetryNotice ?? true;
|
|
190
|
+
if (telemetry === "verified" && noticeOpt !== false)
|
|
173
191
|
void verifiedNotice();
|
|
174
192
|
const team = teamConf
|
|
175
193
|
? new TeamClient({
|
|
@@ -196,10 +214,20 @@ export function safeFetch(wallet, options) {
|
|
|
196
214
|
catch {
|
|
197
215
|
/* first run */
|
|
198
216
|
}
|
|
199
|
-
|
|
217
|
+
const text = 'telemetry: "verified" sends each purchase outcome with its proof of payment (payer address, nonce, pay-to, tx hash) ' +
|
|
200
218
|
`to ${indexUrl}/telemetry so the index can check it on Base. No bodies, request parameters, IP or identity. ` +
|
|
201
219
|
'See "What verified telemetry sends and why": https://www.npmjs.com/package/@paidfor/x402-safe-fetch#what-verified-telemetry-sends-and-why ' +
|
|
202
|
-
'(set telemetry: "anonymous" or "off" to change it). Shown once.'
|
|
220
|
+
'(set telemetry: "anonymous" or "off" to change it). Shown once.';
|
|
221
|
+
if (typeof noticeOpt === "function") {
|
|
222
|
+
try {
|
|
223
|
+
noticeOpt(`x402-safe-fetch: ${text}`);
|
|
224
|
+
}
|
|
225
|
+
catch {
|
|
226
|
+
/* ignore */
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
else
|
|
230
|
+
warn(text);
|
|
203
231
|
try {
|
|
204
232
|
await mkdir(receiptsDir, { recursive: true });
|
|
205
233
|
await writeFile(marker, `${new Date().toISOString()}\n`);
|
|
@@ -221,6 +249,9 @@ export function safeFetch(wallet, options) {
|
|
|
221
249
|
function emitTelemetry(r) {
|
|
222
250
|
if (telemetry === "off" || !indexUrl)
|
|
223
251
|
return;
|
|
252
|
+
// Nothing was paid and the seller is not at fault for a wallet that cannot pay; the contract has no outcome for it.
|
|
253
|
+
if (r.outcome === "payment_rejected")
|
|
254
|
+
return;
|
|
224
255
|
try {
|
|
225
256
|
const payload = telemetry === "verified"
|
|
226
257
|
? buildPayloadV2({
|
|
@@ -306,6 +337,7 @@ export function safeFetch(wallet, options) {
|
|
|
306
337
|
tx_hash: null,
|
|
307
338
|
nonce: null,
|
|
308
339
|
payer: null,
|
|
340
|
+
valid_before: null,
|
|
309
341
|
proof: null,
|
|
310
342
|
reported_outcome: null,
|
|
311
343
|
verification_url: null,
|
|
@@ -344,6 +376,7 @@ export function safeFetch(wallet, options) {
|
|
|
344
376
|
r.tx_hash = original.tx_hash;
|
|
345
377
|
r.nonce = original.nonce;
|
|
346
378
|
r.payer = original.payer ?? null;
|
|
379
|
+
r.valid_before = original.valid_before ?? null;
|
|
347
380
|
r.proof = original.proof ?? null;
|
|
348
381
|
r.reported_outcome = original.reported_outcome ?? null;
|
|
349
382
|
r.verification_url = original.verification_url ?? null;
|
|
@@ -362,7 +395,10 @@ export function safeFetch(wallet, options) {
|
|
|
362
395
|
let quote;
|
|
363
396
|
let approved;
|
|
364
397
|
let refusal;
|
|
398
|
+
// The nonce (and, from an approval, the deadline) to sign instead of the SDK's own.
|
|
365
399
|
let auth;
|
|
400
|
+
// An earlier attempt of this intent was signed and rejected; that authorization may still be settled until its deadline.
|
|
401
|
+
const priorRejected = lease.record.rejected;
|
|
366
402
|
let authSigned = false;
|
|
367
403
|
let failure;
|
|
368
404
|
let signingStarted = false;
|
|
@@ -385,16 +421,18 @@ export function safeFetch(wallet, options) {
|
|
|
385
421
|
typeof q.asset === "string" &&
|
|
386
422
|
q.asset.toLowerCase() === usdc &&
|
|
387
423
|
(q.extra?.assetTransferMethod ?? "eip3009") === "eip3009");
|
|
388
|
-
// With `authorize` the approval decides the nonce and deadline;
|
|
389
|
-
// here at signing and on the signed payload in
|
|
390
|
-
|
|
424
|
+
// With `authorize` the approval decides the nonce and deadline; after a rejected payment the old nonce is signed
|
|
425
|
+
// again. The SDK has no way to take either, so they are set here at signing and on the signed payload in
|
|
426
|
+
// onAfterPaymentCreation.
|
|
427
|
+
const schemeSigner = !authorize && !priorRejected
|
|
391
428
|
? signer
|
|
392
429
|
: {
|
|
393
430
|
address: signer.address,
|
|
394
431
|
signTypedData: async (m) => {
|
|
395
432
|
if (!auth || m.primaryType !== "TransferWithAuthorization")
|
|
396
433
|
throw new Error("x402-safe-fetch: refusing to sign without an approval");
|
|
397
|
-
const
|
|
434
|
+
const message = { ...m.message, nonce: auth.nonce, ...(auth.validBefore !== undefined ? { validBefore: auth.validBefore } : {}) };
|
|
435
|
+
const signature = await signer.signTypedData({ ...m, message });
|
|
398
436
|
authSigned = true;
|
|
399
437
|
return signature;
|
|
400
438
|
},
|
|
@@ -484,7 +522,34 @@ export function safeFetch(wallet, options) {
|
|
|
484
522
|
};
|
|
485
523
|
return { abort: true, reason: refusal.message };
|
|
486
524
|
}
|
|
487
|
-
// 4.
|
|
525
|
+
// 4. A rejected authorization of this intent is reused only by the same payer, on the same network, for the same
|
|
526
|
+
// asset. EIP-3009 nonces are per payer and per token contract: the same nonce signed by another wallet, on another
|
|
527
|
+
// chain or for another token is a separate authorization, and both could settle. A changed pay-to or amount does
|
|
528
|
+
// not break this (one payer, one token, one nonce: only one of the two can ever be used), so it is allowed.
|
|
529
|
+
// Checked before the approval is asked for, so a refused retry holds no reservation.
|
|
530
|
+
if (priorRejected) {
|
|
531
|
+
const differs = [];
|
|
532
|
+
if (!priorRejected.payer)
|
|
533
|
+
differs.push("the payer was not recorded (an intent file from before 0.6.0)");
|
|
534
|
+
else {
|
|
535
|
+
if (priorRejected.payer.toLowerCase() !== signer.address.toLowerCase())
|
|
536
|
+
differs.push(`payer ${priorRejected.payer} vs this wallet ${signer.address.toLowerCase()}`);
|
|
537
|
+
if (priorRejected.network !== caip2Network(norm))
|
|
538
|
+
differs.push(`network ${priorRejected.network ?? "unknown"} vs ${caip2Network(norm)}`);
|
|
539
|
+
if ((priorRejected.asset ?? "").toLowerCase() !== norm.asset.toLowerCase())
|
|
540
|
+
differs.push(`asset ${priorRejected.asset ?? "unknown"} vs ${norm.asset.toLowerCase()}`);
|
|
541
|
+
}
|
|
542
|
+
if (differs.length) {
|
|
543
|
+
failure = {
|
|
544
|
+
code: "intent_conflict",
|
|
545
|
+
message: `intent ${r.intent_id} has a rejected authorization (nonce ${priorRejected.nonce}) that cannot be reused here: ${differs.join("; ")}. ` +
|
|
546
|
+
"Nothing was signed. Check on chain that the old authorization was not used (authorizationState(payer, nonce) on the USDC contract is false; " +
|
|
547
|
+
"true means used or cancelled, and only its AuthorizationUsed event and USDC Transfer show a payment), then use a new intentId.",
|
|
548
|
+
};
|
|
549
|
+
return { abort: true, reason: failure.message };
|
|
550
|
+
}
|
|
551
|
+
}
|
|
552
|
+
// 5. Last, so a payment refused above never takes up a reservation with whoever approves it.
|
|
488
553
|
if (authorize) {
|
|
489
554
|
let answer;
|
|
490
555
|
try {
|
|
@@ -502,6 +567,28 @@ export function safeFetch(wallet, options) {
|
|
|
502
567
|
}
|
|
503
568
|
auth = { nonce: answer.nonce, validBefore: BigInt(answer.validBefore) };
|
|
504
569
|
}
|
|
570
|
+
// 6. A rejected authorization of this intent can still be used until its deadline. Signing its nonce again (same
|
|
571
|
+
// payer, network and asset, checked above) means at most one of the two can ever move money. An approval with
|
|
572
|
+
// another nonce waits for that deadline; the deadline only stops later use of the old signature and does not show
|
|
573
|
+
// that it was never used. authorizationState(payer, nonce) false on chain shows that; true means used or cancelled,
|
|
574
|
+
// and only the AuthorizationUsed event with its USDC Transfer shows a payment (see the README).
|
|
575
|
+
if (priorRejected) {
|
|
576
|
+
if (!NONCE_RE.test(priorRejected.nonce)) {
|
|
577
|
+
failure = { code: "sdk", message: `intent ${r.intent_id} has a rejected authorization with an unreadable nonce; not signing again. Use a new intentId after checking the chain.` };
|
|
578
|
+
return { abort: true, reason: failure.message };
|
|
579
|
+
}
|
|
580
|
+
if (!auth)
|
|
581
|
+
auth = { nonce: priorRejected.nonce };
|
|
582
|
+
else if (auth.nonce.toLowerCase() !== priorRejected.nonce.toLowerCase() && (priorRejected.valid_before === null || priorRejected.valid_before > Date.now() / 1000)) {
|
|
583
|
+
const until = priorRejected.valid_before === null ? "an unknown deadline" : unixTime(priorRejected.valid_before);
|
|
584
|
+
refusal = {
|
|
585
|
+
code: "refused_authorize",
|
|
586
|
+
message: `refused to pay ${usd} for ${req.url}: an earlier payment for intent ${r.intent_id} (nonce ${priorRejected.nonce}) was rejected by the seller but can still be settled until ${until}, and the approval names a different nonce. Call again after that time, once authorizationState(payer, nonce) on the USDC contract is false (never used): the deadline alone does not show that.`,
|
|
587
|
+
sellerUrl: i.seller_url,
|
|
588
|
+
};
|
|
589
|
+
return { abort: true, reason: refusal.message };
|
|
590
|
+
}
|
|
591
|
+
}
|
|
505
592
|
approved = amount;
|
|
506
593
|
try {
|
|
507
594
|
await lease.update({ phase: "signing", amount_atomic: amount.toString(), pay_to: norm.payTo });
|
|
@@ -536,9 +623,12 @@ export function safeFetch(wallet, options) {
|
|
|
536
623
|
throw new Error(failure.message);
|
|
537
624
|
}
|
|
538
625
|
a.nonce = auth.nonce;
|
|
539
|
-
|
|
626
|
+
if (auth.validBefore !== undefined)
|
|
627
|
+
a.validBefore = auth.validBefore.toString();
|
|
540
628
|
}
|
|
541
629
|
r.nonce = String(a.nonce);
|
|
630
|
+
const vb = Number(a.validBefore);
|
|
631
|
+
r.valid_before = Number.isSafeInteger(vb) ? vb : null;
|
|
542
632
|
r.payer = String(a.from).toLowerCase();
|
|
543
633
|
r.amount_usdc = atomicToUsdc(BigInt(value));
|
|
544
634
|
try {
|
|
@@ -647,6 +737,8 @@ export function safeFetch(wallet, options) {
|
|
|
647
737
|
await persistReceipt(r);
|
|
648
738
|
if (quoteResult)
|
|
649
739
|
emitTelemetry(r);
|
|
740
|
+
if (code === "intent_conflict")
|
|
741
|
+
throw new IntentConflictError(code, `x402-safe-fetch: ${message}`, r, { cause: e });
|
|
650
742
|
throw new SafeFetchError(code, `x402-safe-fetch: ${message}`, r, { cause: e });
|
|
651
743
|
}
|
|
652
744
|
// Response in hand. Read up to MAX_BODY_BYTES for the validators; the caller still gets the full body.
|
|
@@ -682,9 +774,44 @@ export function safeFetch(wallet, options) {
|
|
|
682
774
|
await persistReceipt(r);
|
|
683
775
|
return wrapResponse(res.status, res.statusText, res.headers, read.callerBody, res.url || req.url, r);
|
|
684
776
|
}
|
|
685
|
-
r.paid = true;
|
|
686
777
|
const st = decodeSettlementHeader(record.headers);
|
|
687
778
|
r.settlement = { header: st.raw ?? null, version: st.version ?? null, parsed: st.parsed ?? null, parse_error: st.parseError ?? null };
|
|
779
|
+
// The seller answered the paid request with another 402 and settled nothing (no settlement header, or one saying
|
|
780
|
+
// it failed): an empty wallet, an expired or refused authorization. Nothing was paid. An unreadable header is not
|
|
781
|
+
// taken as a rejection, since it may name a settlement.
|
|
782
|
+
if (res.status === 402 && (st.raw === undefined || st.parsed?.success === false)) {
|
|
783
|
+
finish(r, t0, "payment_rejected");
|
|
784
|
+
const why = st.parsed?.errorReason ? ` (${String(st.parsed.errorReason).slice(0, 200)})` : "";
|
|
785
|
+
// The same nonce signed again keeps the LATER of the two deadlines: the seller may still hold the earlier
|
|
786
|
+
// signature, and until it lapses no other nonce may be signed. Unknown (null) on either side never passes. A
|
|
787
|
+
// different amount or pay-to on the earlier signature does not matter: one payer, one token, one nonce, so only
|
|
788
|
+
// one of the signatures under it can ever settle; the deadline is the only thing that has to be carried over.
|
|
789
|
+
const sameNonce = priorRejected !== undefined && r.nonce !== null && priorRejected.nonce.toLowerCase() === r.nonce.toLowerCase();
|
|
790
|
+
const newVb = r.valid_before ?? null;
|
|
791
|
+
const keptVb = !sameNonce ? newVb : priorRejected.valid_before === null || newVb === null ? null : Math.max(priorRejected.valid_before, newVb);
|
|
792
|
+
const until = keptVb !== null ? unixTime(keptVb) : "an unknown deadline";
|
|
793
|
+
r.error = {
|
|
794
|
+
code: "payment_rejected",
|
|
795
|
+
message: `the seller answered the paid request for ${req.url} with HTTP 402${why} and settled nothing, so nothing was paid. ` +
|
|
796
|
+
`The signed authorization (payer ${r.payer}, nonce ${r.nonce}) can still be used until ${until}; that deadline only ` +
|
|
797
|
+
"stops later use. authorizationState(payer, nonce) on the USDC contract is false while the nonce was never used; " +
|
|
798
|
+
"true means used or cancelled, so look for its AuthorizationUsed event and USDC Transfer before counting it as paid. " +
|
|
799
|
+
`Calling again with intent ${r.intent_id} from the same wallet signs that same nonce, so at most one of the two can settle.`,
|
|
800
|
+
};
|
|
801
|
+
attachProof(r, undefined, st);
|
|
802
|
+
await persistReceipt(r);
|
|
803
|
+
try {
|
|
804
|
+
await lease.update({
|
|
805
|
+
phase: "rejected",
|
|
806
|
+
rejected: { nonce: r.nonce ?? "", valid_before: keptVb, payer: r.payer ?? "", network, asset: (r.quote?.asset ?? "").toLowerCase() },
|
|
807
|
+
});
|
|
808
|
+
}
|
|
809
|
+
catch (e) {
|
|
810
|
+
warn(`rejected payment for intent ${r.intent_id} could not be recorded (${errMsg(e)}); a retry with this intentId will refuse rather than sign again`);
|
|
811
|
+
}
|
|
812
|
+
return wrapResponse(res.status, res.statusText, res.headers, read.callerBody, res.url || req.url, r);
|
|
813
|
+
}
|
|
814
|
+
r.paid = true;
|
|
688
815
|
const tx = st.parsed?.transaction;
|
|
689
816
|
r.tx_hash = typeof tx === "string" && TX_HASH_RE.test(tx) ? tx : null;
|
|
690
817
|
finish(r, t0, r.validator_failures.length ? "validator_failed" : "ok");
|
|
@@ -733,9 +860,10 @@ export function safeFetch(wallet, options) {
|
|
|
733
860
|
};
|
|
734
861
|
/** live() with the team asked before signing, and every approval's outcome reported after. */
|
|
735
862
|
async function teamLive(team, lease, req, r, t0) {
|
|
863
|
+
const project = teamConf?.project;
|
|
736
864
|
let decision;
|
|
737
865
|
const authorize = async (q) => {
|
|
738
|
-
const d = await team.authorize({ wallet: q.payer, intent_id: q.intentId, resource_url: q.url, pay_to: q.payTo, amount_atomic: q.amountAtomic, network: q.network, asset: q.asset, scheme: q.scheme, protocol: "x402" });
|
|
866
|
+
const d = await team.authorize({ wallet: q.payer, intent_id: q.intentId, resource_url: q.url, pay_to: q.payTo, amount_atomic: q.amountAtomic, network: q.network, asset: q.asset, scheme: q.scheme, protocol: "x402", ...(project ? { project } : {}) });
|
|
739
867
|
decision = d;
|
|
740
868
|
r.team = teamReceipt(team.origin, d);
|
|
741
869
|
return d.kind === "approve" ? { approve: true, nonce: d.auth_ref, validBefore: d.valid_before } : { approve: false, message: teamMessage(d, q.intentId) };
|
|
@@ -757,6 +885,24 @@ export function safeFetch(wallet, options) {
|
|
|
757
885
|
res = await live(lease, req, r, t0, authorize);
|
|
758
886
|
}
|
|
759
887
|
catch (e) {
|
|
888
|
+
if (e instanceof PaymentRefusedError && LOCAL_REFUSALS.has(e.code) && e.receipt?.quote) {
|
|
889
|
+
// Refused before the team was asked: tell it, so the ledger counts what was saved. Never awaited, never thrown.
|
|
890
|
+
const q = e.receipt.quote;
|
|
891
|
+
void team.reportRefusal({
|
|
892
|
+
wallet: signer.address,
|
|
893
|
+
intent_id: e.receipt.intent_id,
|
|
894
|
+
resource_url: e.receipt.url,
|
|
895
|
+
pay_to: q.pay_to,
|
|
896
|
+
amount_atomic: q.amount_atomic,
|
|
897
|
+
network,
|
|
898
|
+
asset: q.asset,
|
|
899
|
+
scheme: q.scheme,
|
|
900
|
+
protocol: "x402",
|
|
901
|
+
reason: e.code,
|
|
902
|
+
verdict: e.receipt.seller.verdict,
|
|
903
|
+
...(project ? { project } : {}),
|
|
904
|
+
});
|
|
905
|
+
}
|
|
760
906
|
await settle(e instanceof SafeFetchError ? e.receipt : undefined);
|
|
761
907
|
if (decision && e instanceof PaymentRefusedError && e.code === "refused_authorize") {
|
|
762
908
|
throw new TeamRefusedError(decision, e.message, e.sellerUrl, e.receipt);
|
package/dist/team.d.ts
CHANGED
|
@@ -2,6 +2,11 @@ import type { Receipt } from "./receipt.js";
|
|
|
2
2
|
export declare const TEAM_ORIGIN = "https://paidfor.dev";
|
|
3
3
|
export declare const AUTHORIZE_TIMEOUT_MS = 10000;
|
|
4
4
|
export declare const REPORT_TIMEOUT_MS = 5000;
|
|
5
|
+
/** How long a refusal notice may take. Never awaited by a payment. */
|
|
6
|
+
export declare const REFUSAL_TIMEOUT_MS = 2000;
|
|
7
|
+
export declare const PROJECT_RULE = "a project tag is 1 to 64 letters, digits, spaces or . _ - (for example \"research-q4\")";
|
|
8
|
+
/** The tag made canonical (trimmed), or null when the server would refuse it. */
|
|
9
|
+
export declare function cleanProject(v: unknown): string | null;
|
|
5
10
|
/** `team` in SafeFetchOptions. */
|
|
6
11
|
export interface TeamOptions {
|
|
7
12
|
/** The team key, `pft_...`. Sent only to `origin`, as `Authorization: Bearer`, never to a seller and never logged. */
|
|
@@ -12,6 +17,12 @@ export interface TeamOptions {
|
|
|
12
17
|
authorizeTimeoutMs?: number;
|
|
13
18
|
/** How long each outcome report may take. Default 5000 ms. */
|
|
14
19
|
reportTimeoutMs?: number;
|
|
20
|
+
/**
|
|
21
|
+
* A project tag sent with every authorize (and refusal notice), so the ledger and the bill can be read by project.
|
|
22
|
+
* 1 to 64 letters, digits, spaces or . _ - after trimming; anything else throws when the client is made. When team
|
|
23
|
+
* mode comes from PAIDFOR_TEAM_KEY, PAIDFOR_PROJECT is read instead.
|
|
24
|
+
*/
|
|
25
|
+
project?: string;
|
|
15
26
|
}
|
|
16
27
|
/** A notice a newer server may attach to a decision, such as a budget nearly used up. */
|
|
17
28
|
export interface TeamWarning {
|
|
@@ -62,6 +73,14 @@ export type TeamAuthorizeBody = {
|
|
|
62
73
|
asset: string;
|
|
63
74
|
scheme: string;
|
|
64
75
|
protocol: "x402";
|
|
76
|
+
project?: string;
|
|
77
|
+
};
|
|
78
|
+
/** What the client refused by itself, before asking the team (`POST /v1/team/refusals`). */
|
|
79
|
+
export type TeamRefusalReason = "refused_verdict" | "refused_ratio" | "refused_max_per_call";
|
|
80
|
+
export type TeamRefusalBody = Omit<TeamAuthorizeBody, "project"> & {
|
|
81
|
+
reason: TeamRefusalReason;
|
|
82
|
+
verdict?: "avoid" | "caution" | "ok" | "unknown";
|
|
83
|
+
project?: string;
|
|
65
84
|
};
|
|
66
85
|
export type TeamOutcomeBody = {
|
|
67
86
|
wallet: string;
|
|
@@ -139,6 +158,12 @@ export declare class TeamClient {
|
|
|
139
158
|
private post;
|
|
140
159
|
/** Never throws: anything but a 200 with a readable decision is { kind: "failed" }. */
|
|
141
160
|
authorize(body: TeamAuthorizeBody): Promise<TeamDecision>;
|
|
161
|
+
/**
|
|
162
|
+
* Tell the team about a payment this client refused before asking it, so the ledger and the bill can count what was
|
|
163
|
+
* saved. Fire-and-forget: one try, a 2 s timeout, every failure (a 404 from a server without the route included)
|
|
164
|
+
* swallowed and never logged. Never throws or rejects; the promise is returned only so tests can wait on it.
|
|
165
|
+
*/
|
|
166
|
+
reportRefusal(body: TeamRefusalBody): Promise<void>;
|
|
142
167
|
/** One try. "retry" means the server could not take it now; a 4xx will never be taken, so it is not kept. */
|
|
143
168
|
private send;
|
|
144
169
|
private queueName;
|
package/dist/team.js
CHANGED
|
@@ -17,10 +17,25 @@ import { join } from "node:path";
|
|
|
17
17
|
export const TEAM_ORIGIN = "https://paidfor.dev";
|
|
18
18
|
export const AUTHORIZE_TIMEOUT_MS = 10_000;
|
|
19
19
|
export const REPORT_TIMEOUT_MS = 5_000;
|
|
20
|
+
/** How long a refusal notice may take. Never awaited by a payment. */
|
|
21
|
+
export const REFUSAL_TIMEOUT_MS = 2_000;
|
|
20
22
|
/** The words the server takes for a paid outcome. */
|
|
21
23
|
const PAID_OUTCOMES = ["ok", "non_delivery", "wrong_goods", "overcharge", "duplicate", "paid_no_response"];
|
|
22
24
|
/** Shown when the team does not know the wallet. */
|
|
23
|
-
const MCP_INIT = "npx -y @paidfor/mcp@
|
|
25
|
+
const MCP_INIT = "npx -y @paidfor/mcp@latest init --wallet --link";
|
|
26
|
+
/**
|
|
27
|
+
* The server's rule for a project tag (paidfor lib/team/project.ts): trimmed, then 1 to 64 letters, digits, spaces or
|
|
28
|
+
* . _ -. A tag the server would refuse is refused here, when the client is made, instead of on every payment.
|
|
29
|
+
*/
|
|
30
|
+
const PROJECT_RE = /^[A-Za-z0-9._ -]{1,64}$/;
|
|
31
|
+
export const PROJECT_RULE = 'a project tag is 1 to 64 letters, digits, spaces or . _ - (for example "research-q4")';
|
|
32
|
+
/** The tag made canonical (trimmed), or null when the server would refuse it. */
|
|
33
|
+
export function cleanProject(v) {
|
|
34
|
+
if (typeof v !== "string")
|
|
35
|
+
return null;
|
|
36
|
+
const t = v.trim();
|
|
37
|
+
return PROJECT_RE.test(t) ? t : null;
|
|
38
|
+
}
|
|
24
39
|
/** What to report for a payment that was approved, from its receipt. */
|
|
25
40
|
export function outcomeFor(r, wallet, authRef) {
|
|
26
41
|
const base = { wallet, intent_id: r.intent_id, auth_ref: authRef };
|
|
@@ -160,6 +175,19 @@ export class TeamClient {
|
|
|
160
175
|
}
|
|
161
176
|
return res.status === 200 ? readDecision(parsed) : failedStatus(res.status, parsed, body.wallet, this.origin);
|
|
162
177
|
}
|
|
178
|
+
/**
|
|
179
|
+
* Tell the team about a payment this client refused before asking it, so the ledger and the bill can count what was
|
|
180
|
+
* saved. Fire-and-forget: one try, a 2 s timeout, every failure (a 404 from a server without the route included)
|
|
181
|
+
* swallowed and never logged. Never throws or rejects; the promise is returned only so tests can wait on it.
|
|
182
|
+
*/
|
|
183
|
+
reportRefusal(body) {
|
|
184
|
+
try {
|
|
185
|
+
return this.post("/v1/team/refusals", body, REFUSAL_TIMEOUT_MS).then((res) => void res.body?.cancel().catch(() => undefined), () => undefined).catch(() => undefined);
|
|
186
|
+
}
|
|
187
|
+
catch {
|
|
188
|
+
return Promise.resolve();
|
|
189
|
+
}
|
|
190
|
+
}
|
|
163
191
|
/** One try. "retry" means the server could not take it now; a 4xx will never be taken, so it is not kept. */
|
|
164
192
|
async send(body) {
|
|
165
193
|
try {
|
package/dist/telemetry.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { TelemetryOutcome, TelemetryProof } from "./proof.js";
|
|
2
|
-
export declare const CLIENT_ID = "x402-safe-fetch/0.
|
|
2
|
+
export declare const CLIENT_ID = "x402-safe-fetch/0.6.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.
|
|
12
|
+
export const CLIENT_ID = "x402-safe-fetch/0.6.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
|
@@ -19,7 +19,7 @@ No account and no key are needed to send it.
|
|
|
19
19
|
"amount_usdc": "0.010000",
|
|
20
20
|
"latency_ms": 412,
|
|
21
21
|
"validator_failures": [],
|
|
22
|
-
"client": "x402-safe-fetch
|
|
22
|
+
"client": "x402-safe-fetch/<version>"
|
|
23
23
|
}
|
|
24
24
|
```
|
|
25
25
|
|
|
@@ -32,7 +32,7 @@ No account and no key are needed to send it.
|
|
|
32
32
|
| `amount_usdc` | Amount of the signed authorization as a 6-decimal string. `"0.000000"` when nothing was signed. |
|
|
33
33
|
| `latency_ms` | Wall time of the call in milliseconds, rounded. |
|
|
34
34
|
| `validator_failures` | Names of the validators that failed, for example `["http_status"]`. Names only, no evidence. |
|
|
35
|
-
| `client` | `x402-safe-fetch/<version>`, `x402-safe-fetch/0.
|
|
35
|
+
| `client` | `x402-safe-fetch/<version>`, for example `x402-safe-fetch/0.6.0`. |
|
|
36
36
|
|
|
37
37
|
## What is never sent (v1)
|
|
38
38
|
|
|
@@ -42,7 +42,9 @@ No account and no key are needed to send it.
|
|
|
42
42
|
- The `intentId`, the request hash, or anything that links two calls together.
|
|
43
43
|
- Validator evidence, error messages, or seller response text.
|
|
44
44
|
|
|
45
|
-
Calls to free resources (no 402) and replays of a stored intent send nothing.
|
|
45
|
+
Calls to free resources (no 402) and replays of a stored intent send nothing. Nor does a payment the seller
|
|
46
|
+
rejected (receipt outcome `payment_rejected`, from 0.6.0: the paid request answered 402 again and nothing settled),
|
|
47
|
+
in either version: nothing was paid, and the row would otherwise read as a failure of the seller.
|
|
46
48
|
|
|
47
49
|
## How it is sent
|
|
48
50
|
|
|
@@ -74,7 +76,7 @@ Additive over v1. `v` is `2`, `outcome` uses the harness names, `validator_failu
|
|
|
74
76
|
"amount_usdc": "0.002000",
|
|
75
77
|
"latency_ms": 1840,
|
|
76
78
|
"validator_failures": ["http_status:500"],
|
|
77
|
-
"client": "x402-safe-fetch
|
|
79
|
+
"client": "x402-safe-fetch/<version>",
|
|
78
80
|
"proof": {
|
|
79
81
|
"network": "eip155:8453",
|
|
80
82
|
"scheme": "exact",
|
|
@@ -104,7 +106,7 @@ Outcomes (`outcome`), mapped like the harness classifier, first match wins:
|
|
|
104
106
|
| v2 outcome | When |
|
|
105
107
|
| --- | --- |
|
|
106
108
|
| `duplicate` | More than one settlement observed for one intent. The client sends one paid request per intent, so in practice it never sees this. |
|
|
107
|
-
| `error` | The settlement header says `success: false` and the answer was
|
|
109
|
+
| `error` | The settlement header says `success: false` and the answer was neither 2xx nor 402: the seller rejected the payment (the harness's `not_paid`). Proof is still sent, so the index can confirm nothing moved. A 402 with no settlement, or with `success: false`, is `payment_rejected` on the receipt and sends no row (0.6.0). |
|
|
108
110
|
| `non_delivery` | A non-2xx answer after the payment (even with `http_status` turned off), or `non_empty`, `content_type` or `not_truncated` failed. |
|
|
109
111
|
| `wrong_goods` | A schema, entity or freshness validator failed. This client ships none of them, so it does not send this today. |
|
|
110
112
|
| `overcharge` | Paid more than 1.1x the reference (index listed price, else the last price paid). Only possible if `maxOverListedRatio` was raised. |
|
|
@@ -133,7 +135,7 @@ settled payment; the v2 row adds the link from that payment to the seller host,
|
|
|
133
135
|
failures and response hash. Bodies, request parameters, headers, the intent id and validator evidence are never
|
|
134
136
|
sent in either version. `"verified"` requires an https `indexUrl` (loopback excepted), and no telemetry request
|
|
135
137
|
follows a redirect. Each receipt stores the same `proof` and, in `"verified"` mode,
|
|
136
|
-
`verification_url` = `{indexUrl}/telemetry/<payer>/<nonce
|
|
138
|
+
`verification_url` = `{indexUrl}/telemetry/<payer>/<nonce>`, which shows whether the index verified the row.
|
|
137
139
|
|
|
138
140
|
## tx_only (report-only)
|
|
139
141
|
|
|
@@ -151,7 +153,7 @@ Base settlement header, one object goes to `POST {indexUrl}/telemetry` (default
|
|
|
151
153
|
"outcome": "ok",
|
|
152
154
|
"latency_ms": 412,
|
|
153
155
|
"validator_failures": [],
|
|
154
|
-
"client": "x402-safe-fetch
|
|
156
|
+
"client": "x402-safe-fetch/<version>",
|
|
155
157
|
"proof": { "network": "eip155:8453", "tx_hash": "0x<settlement transaction hash>" }
|
|
156
158
|
}
|
|
157
159
|
```
|
|
@@ -168,7 +170,7 @@ Base settlement header, one object goes to `POST {indexUrl}/telemetry` (default
|
|
|
168
170
|
No payer, pay-to, nonce, amount or signature is sent: the index reads the payer, the recipient and the amount from the
|
|
169
171
|
transaction on Base, and the report counts only once that transaction is a USDC transfer to the seller. The index
|
|
170
172
|
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
|
|
173
|
+
carries `X-Paidfor-Client: x402-safe-fetch/<version>`, waits up to 10 seconds (the index checks the chain before
|
|
172
174
|
answering), never follows a redirect, and needs an https `indexUrl` (loopback excepted). Failures are counted in
|
|
173
175
|
`<receiptsDir>/debug.log` when you pass a `receiptsDir`, otherwise nowhere. The same row is what the paidfor MCP tool
|
|
174
176
|
`report_x402_payment` and the paidfor skill send.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@paidfor/x402-safe-fetch",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.6.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",
|