@paidfor/x402-safe-fetch 0.3.0 → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +7 -0
- package/README.md +21 -2
- package/dist/errors.d.ts +3 -3
- package/dist/errors.js +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/proof.d.ts +1 -1
- package/dist/proof.js +1 -1
- package/dist/receipt.d.ts +1 -1
- package/dist/safe-fetch.d.ts +25 -0
- package/dist/safe-fetch.js +48 -2
- package/dist/telemetry.d.ts +1 -1
- package/dist/telemetry.js +1 -1
- package/docs/telemetry.md +1 -1
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,12 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.4.0
|
|
4
|
+
|
|
5
|
+
- **`authorize`.** A new option: a callback asked after every local check and before anything is signed. An approval
|
|
6
|
+
names the EIP-3009 nonce and `validBefore` to sign. Anything else, including a throw or an approval with under ten
|
|
7
|
+
seconds left, refuses with `refused_authorize` and signs nothing. Without the option nothing changes.
|
|
8
|
+
- `client` in telemetry rows and the `X-Paidfor-Client` header is `x402-safe-fetch/0.4.0`.
|
|
9
|
+
|
|
3
10
|
## 0.3.0
|
|
4
11
|
|
|
5
12
|
- **Report-only mode.** `reportOnly()`, `withPaidforReporting(fetchWithPayment)` for `x402-fetch` 1.x and
|
package/README.md
CHANGED
|
@@ -159,7 +159,8 @@ This is the whole message, for a paid call that got a 500:
|
|
|
159
159
|
before hashing, and the response is represented only by its sha256. Headers, request bodies, the intent id and
|
|
160
160
|
validator evidence are never sent.
|
|
161
161
|
- **Refusals carry no proof.** A refused or unpaid call sends the row without `proof`; it is counted as a
|
|
162
|
-
refusal, never in a failure rate.
|
|
162
|
+
refusal, never in a failure rate. A refusal by `authorize` sends no row at all: a buyer's own rule says nothing
|
|
163
|
+
about the seller.
|
|
163
164
|
- **Outcomes use the index's names:** `ok`, `non_delivery` (a non-2xx answer or a failed delivery validator after paying),
|
|
164
165
|
`overcharge` (paid more than 1.1x the reference, possible only if you raised `maxOverListedRatio`),
|
|
165
166
|
`wrong_goods`, `duplicate`, plus the client-only `refused_*`, `no_acceptable_quote`, `paid_no_response` and
|
|
@@ -170,6 +171,24 @@ This is the whole message, for a paid call that got a 500:
|
|
|
170
171
|
The first time a receipts directory is used with `"verified"`, the client prints a one-line notice pointing
|
|
171
172
|
here.
|
|
172
173
|
|
|
174
|
+
## Ask before paying
|
|
175
|
+
|
|
176
|
+
`authorize` asks a service of yours (a budget, a person) about each payment, after the local checks and before anything
|
|
177
|
+
is signed. It fails closed: a throw, or anything but a well-formed approval, refuses with `refused_authorize`.
|
|
178
|
+
|
|
179
|
+
```ts
|
|
180
|
+
const fetchWithPay = safeFetch(account, {
|
|
181
|
+
maxPerCallUsd: 0.5,
|
|
182
|
+
authorize: async (q) => {
|
|
183
|
+
const d = await askYourPolicyServer(q); // q: intentId, url, payer, payTo, amountAtomic, network, asset, scheme
|
|
184
|
+
return d.ok ? { approve: true, nonce: d.ref, validBefore: d.deadline } : { approve: false, message: d.why };
|
|
185
|
+
},
|
|
186
|
+
});
|
|
187
|
+
```
|
|
188
|
+
|
|
189
|
+
The payment is signed with that `nonce` (32 bytes of hex) and `validBefore` (Unix seconds), so the approval can be found
|
|
190
|
+
on chain. A refusal by `authorize` sends no telemetry.
|
|
191
|
+
|
|
173
192
|
## Report-only: keep your own x402 client, add one line
|
|
174
193
|
|
|
175
194
|
Already paying with Coinbase's `x402-fetch` / `@x402/fetch` or `x402-axios` / `@x402/axios`? Keep your wallet and your
|
|
@@ -202,7 +221,7 @@ own checks). Responses without a settlement (free calls, refusals) send nothing.
|
|
|
202
221
|
|
|
203
222
|
| Error | `code` | Paid? |
|
|
204
223
|
| --- | --- | --- |
|
|
205
|
-
| `PaymentRefusedError` | `refused_verdict`, `refused_ratio`, `refused_max_per_call` | No |
|
|
224
|
+
| `PaymentRefusedError` | `refused_verdict`, `refused_ratio`, `refused_max_per_call`, `refused_authorize` | No |
|
|
206
225
|
| `IntentConflictError` | `intent_conflict` | No |
|
|
207
226
|
| `IntentIndeterminateError` | `intent_indeterminate` | Maybe, earlier; never again |
|
|
208
227
|
| `SafeFetchError` | `paid_no_response` | Signed and possibly settled; `receipt.nonce` identifies it |
|
package/dist/errors.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { Receipt } from "./receipt.js";
|
|
2
|
-
export type SafeFetchErrorCode = "refused_verdict" | "refused_ratio" | "refused_max_per_call" | "no_acceptable_quote" | "intent_conflict" | "intent_indeterminate" | "intent_in_flight" | "paid_no_response" | "network" | "sdk";
|
|
2
|
+
export type SafeFetchErrorCode = "refused_verdict" | "refused_ratio" | "refused_max_per_call" | "refused_authorize" | "no_acceptable_quote" | "intent_conflict" | "intent_indeterminate" | "intent_in_flight" | "paid_no_response" | "network" | "sdk";
|
|
3
3
|
/** Every error this package throws. `receipt` is set whenever a call got far enough to write one. */
|
|
4
4
|
export declare class SafeFetchError extends Error {
|
|
5
5
|
readonly code: SafeFetchErrorCode;
|
|
@@ -9,11 +9,11 @@ export declare class SafeFetchError extends Error {
|
|
|
9
9
|
cause?: unknown;
|
|
10
10
|
});
|
|
11
11
|
}
|
|
12
|
-
/** Refused before any signature: seller verdict, price ratio,
|
|
12
|
+
/** Refused before any signature: seller verdict, price ratio, per-call cap, or `authorize`. Nothing was paid. */
|
|
13
13
|
export declare class PaymentRefusedError extends SafeFetchError {
|
|
14
14
|
readonly sellerUrl: string | null;
|
|
15
15
|
name: string;
|
|
16
|
-
constructor(code: "refused_verdict" | "refused_ratio" | "refused_max_per_call", message: string, sellerUrl: string | null, receipt?: Receipt);
|
|
16
|
+
constructor(code: "refused_verdict" | "refused_ratio" | "refused_max_per_call" | "refused_authorize", message: string, sellerUrl: string | null, receipt?: Receipt);
|
|
17
17
|
}
|
|
18
18
|
/** Same intentId, different request. Nothing was sent. */
|
|
19
19
|
export declare class IntentConflictError extends SafeFetchError {
|
package/dist/errors.js
CHANGED
|
@@ -9,7 +9,7 @@ export class SafeFetchError extends Error {
|
|
|
9
9
|
this.receipt = receipt;
|
|
10
10
|
}
|
|
11
11
|
}
|
|
12
|
-
/** Refused before any signature: seller verdict, price ratio,
|
|
12
|
+
/** Refused before any signature: seller verdict, price ratio, per-call cap, or `authorize`. Nothing was paid. */
|
|
13
13
|
export class PaymentRefusedError extends SafeFetchError {
|
|
14
14
|
sellerUrl;
|
|
15
15
|
name = "PaymentRefusedError";
|
package/dist/index.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export { safeFetch, hashRequest, type SafeFetch, type SafeFetchOptions, type SafeResponse, type CallOptions, type WalletLike, type SafeNetwork } from "./safe-fetch.js";
|
|
1
|
+
export { safeFetch, hashRequest, type SafeFetch, type SafeFetchOptions, type SafeResponse, type CallOptions, type WalletLike, type SafeNetwork, type AuthorizeRequest, type AuthorizeAnswer } from "./safe-fetch.js";
|
|
2
2
|
export { SafeFetchError, PaymentRefusedError, IntentConflictError, IntentIndeterminateError, type SafeFetchErrorCode } from "./errors.js";
|
|
3
3
|
export type { Receipt, Outcome } from "./receipt.js";
|
|
4
4
|
export type { Verdict, IndexCheck } from "./index-client.js";
|
package/dist/proof.d.ts
CHANGED
|
@@ -20,7 +20,7 @@ export interface TelemetryProof {
|
|
|
20
20
|
response_sha256: string | null;
|
|
21
21
|
declared_timeout_s: number;
|
|
22
22
|
}
|
|
23
|
-
export type TelemetryOutcome = "ok" | "non_delivery" | "overcharge" | "wrong_goods" | "duplicate" | "refused_verdict" | "refused_ratio" | "refused_max_per_call" | "no_acceptable_quote" | "paid_no_response" | "validator_failed" | "error";
|
|
23
|
+
export type TelemetryOutcome = "ok" | "non_delivery" | "overcharge" | "wrong_goods" | "duplicate" | "refused_verdict" | "refused_ratio" | "refused_max_per_call" | "refused_authorize" | "no_acceptable_quote" | "paid_no_response" | "validator_failed" | "error";
|
|
24
24
|
/** Outcomes where nothing was paid. Their rows never carry proof and are counted as refusals, not failures. */
|
|
25
25
|
export declare const REFUSED_OUTCOMES: ReadonlySet<string>;
|
|
26
26
|
/** The ratio the harness and this client's default use for "over the reference". */
|
package/dist/proof.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { exceedsRatio } from "./price.js";
|
|
2
2
|
/** Outcomes where nothing was paid. Their rows never carry proof and are counted as refusals, not failures. */
|
|
3
|
-
export const REFUSED_OUTCOMES = new Set(["refused_verdict", "refused_ratio", "refused_max_per_call", "no_acceptable_quote"]);
|
|
3
|
+
export const REFUSED_OUTCOMES = new Set(["refused_verdict", "refused_ratio", "refused_max_per_call", "refused_authorize", "no_acceptable_quote"]);
|
|
4
4
|
/** The ratio the harness and this client's default use for "over the reference". */
|
|
5
5
|
export const DEFAULT_MAX_RATIO = 1.1;
|
|
6
6
|
/** x402-audit DELIVERY_VALIDATORS and GOODS_VALIDATORS. This client ships only the delivery four. */
|
package/dist/receipt.d.ts
CHANGED
|
@@ -4,7 +4,7 @@ import type { TelemetryOutcome, TelemetryProof } from "./proof.js";
|
|
|
4
4
|
import type { ValidatorName } from "./taxonomy.js";
|
|
5
5
|
import type { SettlementResponse } from "./x402/types.js";
|
|
6
6
|
import type { ValidatorResult } from "./validators/types.js";
|
|
7
|
-
export type Outcome = "ok" | "validator_failed" | "refused_verdict" | "refused_ratio" | "refused_max_per_call" | "no_acceptable_quote" | "no_payment_required" | "paid_no_response" | "replayed" | "error";
|
|
7
|
+
export type Outcome = "ok" | "validator_failed" | "refused_verdict" | "refused_ratio" | "refused_max_per_call" | "refused_authorize" | "no_acceptable_quote" | "no_payment_required" | "paid_no_response" | "replayed" | "error";
|
|
8
8
|
export interface Receipt {
|
|
9
9
|
v: 1;
|
|
10
10
|
client: string;
|
package/dist/safe-fetch.d.ts
CHANGED
|
@@ -31,7 +31,32 @@ export interface SafeFetchOptions {
|
|
|
31
31
|
logger?: {
|
|
32
32
|
warn(msg: string): void;
|
|
33
33
|
};
|
|
34
|
+
/**
|
|
35
|
+
* Asks someone else whether this payment may go ahead, after every local check has passed and before anything is
|
|
36
|
+
* signed. An approval names the EIP-3009 nonce and `validBefore` to sign. Anything but a well-formed approval,
|
|
37
|
+
* including a throw, is a `refused_authorize`: nothing is signed. Not asked for a free resource or a replay.
|
|
38
|
+
*/
|
|
39
|
+
authorize?: (request: AuthorizeRequest) => Promise<AuthorizeAnswer>;
|
|
34
40
|
}
|
|
41
|
+
/** The quote `authorize` is asked about. `network` is CAIP-2. */
|
|
42
|
+
export interface AuthorizeRequest {
|
|
43
|
+
intentId: string;
|
|
44
|
+
url: string;
|
|
45
|
+
payer: string;
|
|
46
|
+
payTo: string;
|
|
47
|
+
amountAtomic: string;
|
|
48
|
+
network: string;
|
|
49
|
+
asset: string;
|
|
50
|
+
scheme: string;
|
|
51
|
+
}
|
|
52
|
+
export type AuthorizeAnswer = {
|
|
53
|
+
approve: true; /** 32 bytes of 0x-hex. */
|
|
54
|
+
nonce: `0x${string}`; /** Unix seconds. */
|
|
55
|
+
validBefore: number;
|
|
56
|
+
} | {
|
|
57
|
+
approve: false;
|
|
58
|
+
message: string;
|
|
59
|
+
};
|
|
35
60
|
export interface CallOptions {
|
|
36
61
|
/** Same intentId + same request: returns the stored result, never signs again. Same intentId + different request: throws. */
|
|
37
62
|
intentId?: string;
|
package/dist/safe-fetch.js
CHANGED
|
@@ -28,6 +28,8 @@ import { buildResponseRecord, headersToRecord } from "./x402/http.js";
|
|
|
28
28
|
import { quoteFromResponse } from "./x402/quote.js";
|
|
29
29
|
import { decodeSettlementHeader } from "./x402/settlement.js";
|
|
30
30
|
import { HEADERS, PaymentRequirementsSchema, PaymentRequirementsV1Schema, ResourceInfoSchema, caip2Network, errMsg, normalizeV1, normalizeV2, } from "./x402/types.js";
|
|
31
|
+
/** A facilitator refuses an authorization about to lapse, so an approval with less than this left is not signed. */
|
|
32
|
+
const MIN_AUTH_SECONDS_LEFT = 10;
|
|
31
33
|
function toSigner(w) {
|
|
32
34
|
if (w && typeof w.address === "string" && typeof w.signTypedData === "function")
|
|
33
35
|
return w;
|
|
@@ -292,6 +294,8 @@ export function safeFetch(wallet, options) {
|
|
|
292
294
|
let quote;
|
|
293
295
|
let approved;
|
|
294
296
|
let refusal;
|
|
297
|
+
let auth;
|
|
298
|
+
let authSigned = false;
|
|
295
299
|
let failure;
|
|
296
300
|
let signingStarted = false;
|
|
297
301
|
let signedRecorded = false;
|
|
@@ -313,7 +317,21 @@ export function safeFetch(wallet, options) {
|
|
|
313
317
|
typeof q.asset === "string" &&
|
|
314
318
|
q.asset.toLowerCase() === usdc &&
|
|
315
319
|
(q.extra?.assetTransferMethod ?? "eip3009") === "eip3009");
|
|
316
|
-
|
|
320
|
+
// With `authorize` the approval decides the nonce and deadline; the SDK has no way to take them, so they are set
|
|
321
|
+
// here at signing and on the signed payload in onAfterPaymentCreation.
|
|
322
|
+
const schemeSigner = !options.authorize
|
|
323
|
+
? signer
|
|
324
|
+
: {
|
|
325
|
+
address: signer.address,
|
|
326
|
+
signTypedData: async (m) => {
|
|
327
|
+
if (!auth || m.primaryType !== "TransferWithAuthorization")
|
|
328
|
+
throw new Error("x402-safe-fetch: refusing to sign without an approval");
|
|
329
|
+
const signature = await signer.signTypedData({ ...m, message: { ...m.message, nonce: auth.nonce, validBefore: auth.validBefore } });
|
|
330
|
+
authSigned = true;
|
|
331
|
+
return signature;
|
|
332
|
+
},
|
|
333
|
+
};
|
|
334
|
+
registerExactEvmScheme(client, { signer: schemeSigner, networks: [network], policies: [policy] });
|
|
317
335
|
client.onBeforePaymentCreation(async ({ paymentRequired, selectedRequirements }) => {
|
|
318
336
|
signingStarted = true;
|
|
319
337
|
let norm;
|
|
@@ -398,6 +416,24 @@ export function safeFetch(wallet, options) {
|
|
|
398
416
|
};
|
|
399
417
|
return { abort: true, reason: refusal.message };
|
|
400
418
|
}
|
|
419
|
+
// 4. Last, so a payment refused above never takes up a reservation with whoever approves it.
|
|
420
|
+
if (options.authorize) {
|
|
421
|
+
let answer;
|
|
422
|
+
try {
|
|
423
|
+
answer = await options.authorize({ intentId: r.intent_id, url: req.url, payer: signer.address, payTo: norm.payTo, amountAtomic: amount.toString(), network: caip2Network(norm), asset: norm.asset, scheme: norm.scheme });
|
|
424
|
+
}
|
|
425
|
+
catch (e) {
|
|
426
|
+
answer = { approve: false, message: `could not get an approval: ${errMsg(e)}` };
|
|
427
|
+
}
|
|
428
|
+
if (answer?.approve === true && !(/^0x[0-9a-fA-F]{64}$/.test(answer.nonce) && Number.isSafeInteger(answer.validBefore) && answer.validBefore - Date.now() / 1000 >= MIN_AUTH_SECONDS_LEFT)) {
|
|
429
|
+
answer = { approve: false, message: "the approval was malformed or about to lapse" };
|
|
430
|
+
}
|
|
431
|
+
if (answer?.approve !== true) {
|
|
432
|
+
refusal = { code: "refused_authorize", message: `refused to pay ${usd} for ${req.url}: ${answer?.message ?? "no approval"}`, sellerUrl: i.seller_url };
|
|
433
|
+
return { abort: true, reason: refusal.message };
|
|
434
|
+
}
|
|
435
|
+
auth = { nonce: answer.nonce, validBefore: BigInt(answer.validBefore) };
|
|
436
|
+
}
|
|
401
437
|
approved = amount;
|
|
402
438
|
try {
|
|
403
439
|
await lease.update({ phase: "signing", amount_atomic: amount.toString(), pay_to: norm.payTo });
|
|
@@ -426,6 +462,14 @@ export function safeFetch(wallet, options) {
|
|
|
426
462
|
failure = { code: "sdk", message: `signed to ${to} does not match requirements.payTo ${quote?.payTo}` };
|
|
427
463
|
throw new Error(failure.message);
|
|
428
464
|
}
|
|
465
|
+
if (auth) {
|
|
466
|
+
if (!authSigned) {
|
|
467
|
+
failure = { code: "sdk", message: "the payment was not signed with the approval's nonce" };
|
|
468
|
+
throw new Error(failure.message);
|
|
469
|
+
}
|
|
470
|
+
a.nonce = auth.nonce;
|
|
471
|
+
a.validBefore = auth.validBefore.toString();
|
|
472
|
+
}
|
|
429
473
|
r.nonce = String(a.nonce);
|
|
430
474
|
r.payer = String(a.from).toLowerCase();
|
|
431
475
|
r.amount_usdc = atomicToUsdc(BigInt(value));
|
|
@@ -495,7 +539,9 @@ export function safeFetch(wallet, options) {
|
|
|
495
539
|
attachProof(r, undefined, {});
|
|
496
540
|
await lease.update({ phase: "refused" }).catch(() => undefined);
|
|
497
541
|
await persistReceipt(r);
|
|
498
|
-
|
|
542
|
+
// A buyer's own rule says nothing about the seller, so it is not reported to the index.
|
|
543
|
+
if (refusal.code !== "refused_authorize")
|
|
544
|
+
emitTelemetry(r);
|
|
499
545
|
throw new PaymentRefusedError(refusal.code, `x402-safe-fetch ${refusal.message}`, refusal.sellerUrl, r);
|
|
500
546
|
}
|
|
501
547
|
if (signedRecorded) {
|
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.4.0";
|
|
3
3
|
/** Sent on every request to the index so it can count calls per client. Carries only CLIENT_ID. */
|
|
4
4
|
export declare const CLIENT_HEADER = "X-Paidfor-Client";
|
|
5
5
|
export interface TelemetryPayload {
|
package/dist/telemetry.js
CHANGED
|
@@ -9,7 +9,7 @@ import { createHash } from "node:crypto";
|
|
|
9
9
|
import { appendFile, mkdir } from "node:fs/promises";
|
|
10
10
|
import { join } from "node:path";
|
|
11
11
|
import { REFUSED_OUTCOMES } from "./proof.js";
|
|
12
|
-
export const CLIENT_ID = "x402-safe-fetch/0.
|
|
12
|
+
export const CLIENT_ID = "x402-safe-fetch/0.4.0";
|
|
13
13
|
/** Sent on every request to the index so it can count calls per client. Carries only CLIENT_ID. */
|
|
14
14
|
export const CLIENT_HEADER = "X-Paidfor-Client";
|
|
15
15
|
/** sha256 hex of the URL path with any trailing slash removed. Query string and fragment never enter it. */
|
package/docs/telemetry.md
CHANGED
|
@@ -109,7 +109,7 @@ Outcomes (`outcome`), mapped like the harness classifier, first match wins:
|
|
|
109
109
|
| `wrong_goods` | A schema, entity or freshness validator failed. This client ships none of them, so it does not send this today. |
|
|
110
110
|
| `overcharge` | Paid more than 1.1x the reference (index listed price, else the last price paid). Only possible if `maxOverListedRatio` was raised. |
|
|
111
111
|
| `ok` | None of the above. |
|
|
112
|
-
| `refused_verdict`, `refused_ratio`, `refused_max_per_call`, `no_acceptable_quote` | Refused; nothing was signed. **No `proof`.** |
|
|
112
|
+
| `refused_verdict`, `refused_ratio`, `refused_max_per_call`, `no_acceptable_quote` | Refused; nothing was signed. **No `proof`.** A refusal by the `authorize` option (`refused_authorize` on the receipt) sends no row at all. |
|
|
113
113
|
| `paid_no_response`, `error` | Signed and sent with no response (with `proof`, `tx_hash` null), or failed before signing (no `proof`). |
|
|
114
114
|
|
|
115
115
|
### `path` (0.2.1): only for sellers the index has never measured
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@paidfor/x402-safe-fetch",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.4.0",
|
|
4
4
|
"description": "Drop-in wrapper around @x402/fetch that refuses overpriced quotes and bad sellers, never pays twice for one intent, and checks what it bought.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "MIT",
|