@paidfor/x402-safe-fetch 0.5.0 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -16,8 +16,13 @@ export interface SafeFetchOptions {
16
16
  /** Validators to run on paid responses. Default: all four. */
17
17
  validators?: ValidatorName[];
18
18
  /**
19
- * Default "off". "anonymous" posts the outcome-only v1 payload in docs/telemetry.md. "verified" posts the v2
20
- * payload: the same fields plus a proof of payment (payer, nonce, pay-to, tx hash) the index checks on Base.
19
+ * Reporting each outcome to the index. On by default: the v2 payload in docs/telemetry.md, the outcome with a proof
20
+ * of payment (payer, nonce, pay-to, tx hash) the index checks on Base. paidfor is free because these reports feed it.
21
+ *
22
+ * The account decides, not this option: reporting stops only for a client in team mode whose account is on a paid
23
+ * plan and turned reporting off on its account page (the server says so in every authorize answer). "anonymous" and
24
+ * "off" ask for less than that; without such an account they are not honoured: verified rows are still sent and one
25
+ * line says so, once per process. Never a throw. `indexUrl: false` sends nothing (and checks no seller).
21
26
  */
22
27
  telemetry?: "anonymous" | "verified" | "off";
23
28
  /** Receipts, intents, price book and debug log. Default "./.x402-receipts" (resolved once, at creation). */
@@ -32,6 +37,12 @@ export interface SafeFetchOptions {
32
37
  logger?: {
33
38
  warn(msg: string): void;
34
39
  };
40
+ /**
41
+ * The one-time notice that says what reporting sends. Default true: it goes to `logger.warn` (stderr
42
+ * with the default console). `false` never shows it; a function receives the text instead of `logger`. Useful in
43
+ * an MCP server, whose client may show anything on stderr as an error.
44
+ */
45
+ telemetryNotice?: boolean | ((msg: string) => void);
35
46
  /**
36
47
  * Asks someone else whether this payment may go ahead, after every local check has passed and before anything is
37
48
  * signed. An approval names the EIP-3009 nonce and `validBefore` to sign. Anything but a well-formed approval,
@@ -43,10 +54,12 @@ export interface SafeFetchOptions {
43
54
  * Team mode: a paidfor team account's budgets, approvals and ledger. Before signing, every payment asks
44
55
  * `{origin}/v1/team/authorize` with the key and signs the nonce and deadline the team minted; anything but a clean
45
56
  * 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.
57
+ * report the server could not take is kept in `<receiptsDir>/team-outcomes` and sent before the next payment. A payment
58
+ * refused locally before the team is asked (verdict, ratio, per-call cap) is told to `/v1/team/refusals`,
59
+ * fire-and-forget. `project` tags every payment.
47
60
  *
48
61
  * 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.
62
+ * 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
63
  */
51
64
  team?: TeamOptions | false;
52
65
  }
@@ -70,7 +83,12 @@ export type AuthorizeAnswer = {
70
83
  message: string;
71
84
  };
72
85
  export interface CallOptions {
73
- /** Same intentId + same request: returns the stored result, never signs again. Same intentId + different request: throws. */
86
+ /**
87
+ * Same intentId + same request: returns the stored result, never signs again. Same intentId + different request: throws.
88
+ * After a `payment_rejected` the same intentId may be used again from the same wallet, network and asset; it signs
89
+ * the rejected authorization's nonce again, so at most one of the two can ever settle. Any other wallet, network or
90
+ * asset throws IntentConflictError.
91
+ */
74
92
  intentId?: string;
75
93
  }
76
94
  export type SafeResponse = Response & {
@@ -96,4 +114,8 @@ export declare function hashRequest(r: {
96
114
  url: string;
97
115
  body?: Uint8Array | undefined;
98
116
  }): string;
117
+ /** Tests only: show the once-per-process lines again. Not exported from the package. */
118
+ export declare function resetOnceNotices(): void;
119
+ /** Said when `telemetry: "anonymous"` or `"off"` is not honoured: no account, or an account whose plan does not allow it. */
120
+ export declare const TELEMETRY_NOT_HONOURED: (asked: string) => string;
99
121
  export declare function safeFetch(wallet: WalletLike, options: SafeFetchOptions): SafeFetch;
@@ -15,15 +15,15 @@ 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
- import { writeReceipt } from "./receipt.js";
24
- import { TEAM_ORIGIN, TeamClient, outcomeFor } from "./team.js";
23
+ import { receiptWarnings, writeReceipt } from "./receipt.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
- import { CLIENT_ID, buildPayload, buildPayloadV2, sendTelemetry } from "./telemetry.js";
26
+ import { CLIENT_ID, buildPayloadV2, sendTelemetry } from "./telemetry.js";
27
27
  import { runAllValidators, validatorsByName } from "./validators/index.js";
28
28
  import { buildResponseRecord, headersToRecord } from "./x402/http.js";
29
29
  import { quoteFromResponse } from "./x402/quote.js";
@@ -72,23 +72,51 @@ 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
- /** `team`, or PAIDFOR_TEAM_KEY when neither `team` nor `authorize` is given. */
75
+ /** The line that a request for less than verified reporting is not honoured, once per process. */
76
+ let lessNoticeShown = false;
77
+ /** The line that nothing is reported to a plain-http index, once per process. */
78
+ let insecureNoticeShown = false;
79
+ /** Tests only: show the once-per-process lines again. Not exported from the package. */
80
+ export function resetOnceNotices() {
81
+ envNoticeShown = lessNoticeShown = insecureNoticeShown = false;
82
+ }
83
+ /** Said when `telemetry: "anonymous"` or `"off"` is not honoured: no account, or an account whose plan does not allow it. */
84
+ export const TELEMETRY_NOT_HONOURED = (asked) => `telemetry: "${asked}" is not honoured: purchase outcomes are reported to the index with their proof of payment, because that is what keeps paidfor free. ` +
85
+ "Only a team account on a paid plan can turn reporting off, on its account page (https://paidfor.dev/team); plans: https://paidfor.dev/pricing. Shown once.";
86
+ /** A project tag as the server takes it, or a TypeError naming where the bad one came from. */
87
+ function projectTag(v, from) {
88
+ const p = cleanProject(v);
89
+ if (p === null)
90
+ throw new TypeError(`safeFetch: ${from} ${JSON.stringify(v)} is not a project tag: ${PROJECT_RULE}`);
91
+ return p;
92
+ }
93
+ /** `team`, or PAIDFOR_TEAM_KEY (and PAIDFOR_PROJECT) when neither `team` nor `authorize` is given. */
76
94
  function resolveTeam(o) {
77
95
  if (o.team === false)
78
96
  return undefined;
79
97
  if (o.team !== undefined) {
80
98
  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");
99
+ throw new TypeError("safeFetch: team must be { key: string, origin?: string, project?: string } or false");
82
100
  }
83
101
  if (o.authorize)
84
102
  throw new TypeError("safeFetch: pass team or authorize, not both (team supplies its own authorize)");
85
- return { team: o.team, fromEnv: false };
103
+ const project = o.team.project === undefined ? undefined : projectTag(o.team.project, "team.project");
104
+ return { team: o.team, fromEnv: false, project };
86
105
  }
87
106
  if (o.authorize)
88
107
  return undefined; // the caller asks someone itself; the environment is not consulted
89
- const key = typeof process !== "undefined" ? process.env?.PAIDFOR_TEAM_KEY?.trim() : undefined;
90
- return key ? { team: { key }, fromEnv: true } : undefined;
108
+ const env = typeof process !== "undefined" ? process.env : undefined;
109
+ const key = env?.PAIDFOR_TEAM_KEY?.trim();
110
+ if (!key)
111
+ return undefined;
112
+ // An empty PAIDFOR_PROJECT is the same as none; anything else must be a tag the server takes.
113
+ const rawProject = env?.PAIDFOR_PROJECT;
114
+ const project = rawProject === undefined || !rawProject.trim() ? undefined : projectTag(rawProject, "PAIDFOR_PROJECT");
115
+ return { team: { key }, fromEnv: true, project };
91
116
  }
117
+ /** Refusals the client makes by itself before the team is asked; the team is told about them (POST /v1/team/refusals). */
118
+ const LOCAL_REFUSALS = new Set(["refused_verdict", "refused_ratio", "refused_max_per_call"]);
119
+ const NONCE_RE = /^0x[0-9a-fA-F]{64}$/;
92
120
  function teamReceipt(origin, d) {
93
121
  return {
94
122
  origin,
@@ -149,10 +177,14 @@ export function safeFetch(wallet, options) {
149
177
  const indexUrl = options.indexUrl === false ? undefined : (options.indexUrl ?? "https://paidfor.dev/v1").replace(/\/$/, "");
150
178
  const refuseVerdicts = new Set(options.refuseVerdicts ?? ["avoid"]);
151
179
  const validators = validatorsByName(options.validators ?? [...ALL_VALIDATORS]);
152
- if (options.telemetry === "verified" && indexUrl !== undefined && !isSecureOrLoopback(indexUrl)) {
180
+ const secureIndex = indexUrl !== undefined && isSecureOrLoopback(indexUrl);
181
+ if (options.telemetry === "verified" && indexUrl !== undefined && !secureIndex) {
153
182
  throw new TypeError(`safeFetch: telemetry "verified" needs an https indexUrl (or a loopback one for local testing), got ${indexUrl}`);
154
183
  }
155
- const telemetry = indexUrl !== undefined && (options.telemetry === "anonymous" || options.telemetry === "verified") ? options.telemetry : "off";
184
+ /** Rows carry the payer and nonce, so they go only to an https index, or to this machine. */
185
+ const reporting = secureIndex;
186
+ /** A request for less than verified, which only the account can grant (issue 41). */
187
+ const askedLess = options.telemetry === "anonymous" || options.telemetry === "off" ? options.telemetry : null;
156
188
  const receiptsDir = resolve(options.receiptsDir ?? "./.x402-receipts");
157
189
  const baseFetch = options.fetch ?? globalThis.fetch;
158
190
  const indexTimeoutMs = options.indexTimeoutMs ?? 2000;
@@ -169,8 +201,13 @@ export function safeFetch(wallet, options) {
169
201
  /* ignore */
170
202
  }
171
203
  };
172
- if (telemetry === "verified")
204
+ const noticeOpt = options.telemetryNotice ?? true;
205
+ if (reporting && noticeOpt !== false)
173
206
  void verifiedNotice();
207
+ if (indexUrl !== undefined && !secureIndex && !insecureNoticeShown) {
208
+ insecureNoticeShown = true;
209
+ warn(`nothing is reported to ${indexUrl}: outcome reports carry the payer and nonce and go only to an https index (or a loopback one).`);
210
+ }
174
211
  const team = teamConf
175
212
  ? new TeamClient({
176
213
  origin: teamConf.team.origin ?? TEAM_ORIGIN,
@@ -196,10 +233,20 @@ export function safeFetch(wallet, options) {
196
233
  catch {
197
234
  /* first run */
198
235
  }
199
- warn('telemetry: "verified" sends each purchase outcome with its proof of payment (payer address, nonce, pay-to, tx hash) ' +
236
+ const text = "reporting is on: each purchase outcome is sent with its proof of payment (payer address, nonce, pay-to, tx hash) " +
200
237
  `to ${indexUrl}/telemetry so the index can check it on Base. No bodies, request parameters, IP or identity. ` +
201
- '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.');
238
+ "This is what keeps paidfor free; a team account on a paid plan can turn it off on its account page. " +
239
+ 'See "What verified telemetry sends and why": https://www.npmjs.com/package/@paidfor/x402-safe-fetch#what-verified-telemetry-sends-and-why. Shown once.';
240
+ if (typeof noticeOpt === "function") {
241
+ try {
242
+ noticeOpt(`x402-safe-fetch: ${text}`);
243
+ }
244
+ catch {
245
+ /* ignore */
246
+ }
247
+ }
248
+ else
249
+ warn(text);
203
250
  try {
204
251
  await mkdir(receiptsDir, { recursive: true });
205
252
  await writeFile(marker, `${new Date().toISOString()}\n`);
@@ -218,21 +265,58 @@ export function safeFetch(wallet, options) {
218
265
  return null;
219
266
  }
220
267
  }
268
+ /**
269
+ * Each payment's own authorize answer about reporting, kept with its receipt so that payments in flight at the same
270
+ * time never read each other's (a shared "last answer" would let one payment's answer decide another's row).
271
+ */
272
+ const askedTeam = new WeakMap();
273
+ /**
274
+ * Whether this outcome goes to the index. The account decides: only a team answer saying "off" stops it: this
275
+ * payment's own authorize answer, or, for a refusal made before this payment asked, the last answer the team gave.
276
+ * No answer means report.
277
+ */
278
+ function reportsNow(r) {
279
+ if (!reporting)
280
+ return false;
281
+ if (!team)
282
+ return true;
283
+ return (askedTeam.has(r) ? askedTeam.get(r) : team.telemetryReport()) !== "off";
284
+ }
285
+ /** Say once that a request for less than verified reporting was not honoured. Never silent, never a throw. */
286
+ function lessNotice() {
287
+ if (!askedLess || lessNoticeShown)
288
+ return;
289
+ lessNoticeShown = true;
290
+ const text = TELEMETRY_NOT_HONOURED(askedLess);
291
+ if (typeof noticeOpt === "function") {
292
+ try {
293
+ noticeOpt(`x402-safe-fetch: ${text}`);
294
+ }
295
+ catch {
296
+ /* ignore */
297
+ }
298
+ }
299
+ else
300
+ warn(text);
301
+ }
221
302
  function emitTelemetry(r) {
222
- if (telemetry === "off" || !indexUrl)
303
+ if (!indexUrl || !reportsNow(r))
304
+ return;
305
+ // Nothing was paid and the seller is not at fault for a wallet that cannot pay; the contract has no outcome for it.
306
+ if (r.outcome === "payment_rejected")
223
307
  return;
308
+ lessNotice();
224
309
  try {
225
- const payload = telemetry === "verified"
226
- ? buildPayloadV2({
227
- url: r.url,
228
- outcome: r.reported_outcome ?? "error",
229
- amountUsdc: r.amount_usdc,
230
- latencyMs: r.latency_ms,
231
- validatorFailures: failureLabels(r.validator_failures, r.response?.status),
232
- proof: r.proof,
233
- unknownSeller: r.index_note === UNKNOWN_SELLER_NOTE,
234
- })
235
- : buildPayload({ url: r.url, outcome: r.outcome, amountUsdc: r.amount_usdc, latencyMs: r.latency_ms, validatorFailures: r.validator_failures });
310
+ const payload = buildPayloadV2({
311
+ url: r.url,
312
+ outcome: r.reported_outcome ?? "error",
313
+ amountUsdc: r.amount_usdc,
314
+ latencyMs: r.latency_ms,
315
+ validatorFailures: failureLabels(r.validator_failures, r.response?.status),
316
+ warnings: (r.warnings ?? []).map((w) => w.code),
317
+ proof: r.proof,
318
+ unknownSeller: r.index_note === UNKNOWN_SELLER_NOTE,
319
+ });
236
320
  void sendTelemetry(indexUrl, payload, { receiptsDir, fetchImpl: baseFetch });
237
321
  }
238
322
  catch {
@@ -267,7 +351,7 @@ export function safeFetch(wallet, options) {
267
351
  responseSha256: r.response?.sha256 ?? null,
268
352
  declaredTimeoutS: r.quote.max_timeout_seconds,
269
353
  });
270
- if (r.proof && telemetry === "verified" && indexUrl) {
354
+ if (r.proof && indexUrl && reportsNow(r)) {
271
355
  r.verification_url = `${indexUrl}/telemetry/${r.proof.payer}/${r.proof.nonce}`;
272
356
  }
273
357
  }
@@ -302,10 +386,12 @@ export function safeFetch(wallet, options) {
302
386
  index_note: null,
303
387
  validators: {},
304
388
  validator_failures: [],
389
+ warnings: [],
305
390
  settlement: { header: null, version: null, parsed: null, parse_error: null },
306
391
  tx_hash: null,
307
392
  nonce: null,
308
393
  payer: null,
394
+ valid_before: null,
309
395
  proof: null,
310
396
  reported_outcome: null,
311
397
  verification_url: null,
@@ -341,9 +427,12 @@ export function safeFetch(wallet, options) {
341
427
  r.seller = original.seller;
342
428
  r.validators = original.validators;
343
429
  r.validator_failures = original.validator_failures;
430
+ if (original.warnings)
431
+ r.warnings = original.warnings;
344
432
  r.tx_hash = original.tx_hash;
345
433
  r.nonce = original.nonce;
346
434
  r.payer = original.payer ?? null;
435
+ r.valid_before = original.valid_before ?? null;
347
436
  r.proof = original.proof ?? null;
348
437
  r.reported_outcome = original.reported_outcome ?? null;
349
438
  r.verification_url = original.verification_url ?? null;
@@ -362,7 +451,10 @@ export function safeFetch(wallet, options) {
362
451
  let quote;
363
452
  let approved;
364
453
  let refusal;
454
+ // The nonce (and, from an approval, the deadline) to sign instead of the SDK's own.
365
455
  let auth;
456
+ // An earlier attempt of this intent was signed and rejected; that authorization may still be settled until its deadline.
457
+ const priorRejected = lease.record.rejected;
366
458
  let authSigned = false;
367
459
  let failure;
368
460
  let signingStarted = false;
@@ -385,16 +477,18 @@ export function safeFetch(wallet, options) {
385
477
  typeof q.asset === "string" &&
386
478
  q.asset.toLowerCase() === usdc &&
387
479
  (q.extra?.assetTransferMethod ?? "eip3009") === "eip3009");
388
- // With `authorize` the approval decides the nonce and deadline; the SDK has no way to take them, so they are set
389
- // here at signing and on the signed payload in onAfterPaymentCreation.
390
- const schemeSigner = !authorize
480
+ // With `authorize` the approval decides the nonce and deadline; after a rejected payment the old nonce is signed
481
+ // again. The SDK has no way to take either, so they are set here at signing and on the signed payload in
482
+ // onAfterPaymentCreation.
483
+ const schemeSigner = !authorize && !priorRejected
391
484
  ? signer
392
485
  : {
393
486
  address: signer.address,
394
487
  signTypedData: async (m) => {
395
488
  if (!auth || m.primaryType !== "TransferWithAuthorization")
396
489
  throw new Error("x402-safe-fetch: refusing to sign without an approval");
397
- const signature = await signer.signTypedData({ ...m, message: { ...m.message, nonce: auth.nonce, validBefore: auth.validBefore } });
490
+ const message = { ...m.message, nonce: auth.nonce, ...(auth.validBefore !== undefined ? { validBefore: auth.validBefore } : {}) };
491
+ const signature = await signer.signTypedData({ ...m, message });
398
492
  authSigned = true;
399
493
  return signature;
400
494
  },
@@ -484,7 +578,34 @@ export function safeFetch(wallet, options) {
484
578
  };
485
579
  return { abort: true, reason: refusal.message };
486
580
  }
487
- // 4. Last, so a payment refused above never takes up a reservation with whoever approves it.
581
+ // 4. A rejected authorization of this intent is reused only by the same payer, on the same network, for the same
582
+ // asset. EIP-3009 nonces are per payer and per token contract: the same nonce signed by another wallet, on another
583
+ // chain or for another token is a separate authorization, and both could settle. A changed pay-to or amount does
584
+ // not break this (one payer, one token, one nonce: only one of the two can ever be used), so it is allowed.
585
+ // Checked before the approval is asked for, so a refused retry holds no reservation.
586
+ if (priorRejected) {
587
+ const differs = [];
588
+ if (!priorRejected.payer)
589
+ differs.push("the payer was not recorded (an intent file from before 0.6.0)");
590
+ else {
591
+ if (priorRejected.payer.toLowerCase() !== signer.address.toLowerCase())
592
+ differs.push(`payer ${priorRejected.payer} vs this wallet ${signer.address.toLowerCase()}`);
593
+ if (priorRejected.network !== caip2Network(norm))
594
+ differs.push(`network ${priorRejected.network ?? "unknown"} vs ${caip2Network(norm)}`);
595
+ if ((priorRejected.asset ?? "").toLowerCase() !== norm.asset.toLowerCase())
596
+ differs.push(`asset ${priorRejected.asset ?? "unknown"} vs ${norm.asset.toLowerCase()}`);
597
+ }
598
+ if (differs.length) {
599
+ failure = {
600
+ code: "intent_conflict",
601
+ message: `intent ${r.intent_id} has a rejected authorization (nonce ${priorRejected.nonce}) that cannot be reused here: ${differs.join("; ")}. ` +
602
+ "Nothing was signed. Check on chain that the old authorization was not used (authorizationState(payer, nonce) on the USDC contract is false; " +
603
+ "true means used or cancelled, and only its AuthorizationUsed event and USDC Transfer show a payment), then use a new intentId.",
604
+ };
605
+ return { abort: true, reason: failure.message };
606
+ }
607
+ }
608
+ // 5. Last, so a payment refused above never takes up a reservation with whoever approves it.
488
609
  if (authorize) {
489
610
  let answer;
490
611
  try {
@@ -502,6 +623,28 @@ export function safeFetch(wallet, options) {
502
623
  }
503
624
  auth = { nonce: answer.nonce, validBefore: BigInt(answer.validBefore) };
504
625
  }
626
+ // 6. A rejected authorization of this intent can still be used until its deadline. Signing its nonce again (same
627
+ // payer, network and asset, checked above) means at most one of the two can ever move money. An approval with
628
+ // another nonce waits for that deadline; the deadline only stops later use of the old signature and does not show
629
+ // that it was never used. authorizationState(payer, nonce) false on chain shows that; true means used or cancelled,
630
+ // and only the AuthorizationUsed event with its USDC Transfer shows a payment (see the README).
631
+ if (priorRejected) {
632
+ if (!NONCE_RE.test(priorRejected.nonce)) {
633
+ 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.` };
634
+ return { abort: true, reason: failure.message };
635
+ }
636
+ if (!auth)
637
+ auth = { nonce: priorRejected.nonce };
638
+ else if (auth.nonce.toLowerCase() !== priorRejected.nonce.toLowerCase() && (priorRejected.valid_before === null || priorRejected.valid_before > Date.now() / 1000)) {
639
+ const until = priorRejected.valid_before === null ? "an unknown deadline" : unixTime(priorRejected.valid_before);
640
+ refusal = {
641
+ code: "refused_authorize",
642
+ 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.`,
643
+ sellerUrl: i.seller_url,
644
+ };
645
+ return { abort: true, reason: refusal.message };
646
+ }
647
+ }
505
648
  approved = amount;
506
649
  try {
507
650
  await lease.update({ phase: "signing", amount_atomic: amount.toString(), pay_to: norm.payTo });
@@ -536,9 +679,12 @@ export function safeFetch(wallet, options) {
536
679
  throw new Error(failure.message);
537
680
  }
538
681
  a.nonce = auth.nonce;
539
- a.validBefore = auth.validBefore.toString();
682
+ if (auth.validBefore !== undefined)
683
+ a.validBefore = auth.validBefore.toString();
540
684
  }
541
685
  r.nonce = String(a.nonce);
686
+ const vb = Number(a.validBefore);
687
+ r.valid_before = Number.isSafeInteger(vb) ? vb : null;
542
688
  r.payer = String(a.from).toLowerCase();
543
689
  r.amount_usdc = atomicToUsdc(BigInt(value));
544
690
  try {
@@ -647,6 +793,8 @@ export function safeFetch(wallet, options) {
647
793
  await persistReceipt(r);
648
794
  if (quoteResult)
649
795
  emitTelemetry(r);
796
+ if (code === "intent_conflict")
797
+ throw new IntentConflictError(code, `x402-safe-fetch: ${message}`, r, { cause: e });
650
798
  throw new SafeFetchError(code, `x402-safe-fetch: ${message}`, r, { cause: e });
651
799
  }
652
800
  // Response in hand. Read up to MAX_BODY_BYTES for the validators; the caller still gets the full body.
@@ -667,6 +815,7 @@ export function safeFetch(wallet, options) {
667
815
  }, validators);
668
816
  r.validators = results;
669
817
  r.validator_failures = Object.entries(results).filter(([, v]) => v.status === "fail").map(([k]) => k);
818
+ r.warnings = receiptWarnings(results);
670
819
  r.response = {
671
820
  status: res.status,
672
821
  content_type: res.headers.get("content-type"),
@@ -682,9 +831,44 @@ export function safeFetch(wallet, options) {
682
831
  await persistReceipt(r);
683
832
  return wrapResponse(res.status, res.statusText, res.headers, read.callerBody, res.url || req.url, r);
684
833
  }
685
- r.paid = true;
686
834
  const st = decodeSettlementHeader(record.headers);
687
835
  r.settlement = { header: st.raw ?? null, version: st.version ?? null, parsed: st.parsed ?? null, parse_error: st.parseError ?? null };
836
+ // The seller answered the paid request with another 402 and settled nothing (no settlement header, or one saying
837
+ // it failed): an empty wallet, an expired or refused authorization. Nothing was paid. An unreadable header is not
838
+ // taken as a rejection, since it may name a settlement.
839
+ if (res.status === 402 && (st.raw === undefined || st.parsed?.success === false)) {
840
+ finish(r, t0, "payment_rejected");
841
+ const why = st.parsed?.errorReason ? ` (${String(st.parsed.errorReason).slice(0, 200)})` : "";
842
+ // The same nonce signed again keeps the LATER of the two deadlines: the seller may still hold the earlier
843
+ // signature, and until it lapses no other nonce may be signed. Unknown (null) on either side never passes. A
844
+ // different amount or pay-to on the earlier signature does not matter: one payer, one token, one nonce, so only
845
+ // one of the signatures under it can ever settle; the deadline is the only thing that has to be carried over.
846
+ const sameNonce = priorRejected !== undefined && r.nonce !== null && priorRejected.nonce.toLowerCase() === r.nonce.toLowerCase();
847
+ const newVb = r.valid_before ?? null;
848
+ const keptVb = !sameNonce ? newVb : priorRejected.valid_before === null || newVb === null ? null : Math.max(priorRejected.valid_before, newVb);
849
+ const until = keptVb !== null ? unixTime(keptVb) : "an unknown deadline";
850
+ r.error = {
851
+ code: "payment_rejected",
852
+ message: `the seller answered the paid request for ${req.url} with HTTP 402${why} and settled nothing, so nothing was paid. ` +
853
+ `The signed authorization (payer ${r.payer}, nonce ${r.nonce}) can still be used until ${until}; that deadline only ` +
854
+ "stops later use. authorizationState(payer, nonce) on the USDC contract is false while the nonce was never used; " +
855
+ "true means used or cancelled, so look for its AuthorizationUsed event and USDC Transfer before counting it as paid. " +
856
+ `Calling again with intent ${r.intent_id} from the same wallet signs that same nonce, so at most one of the two can settle.`,
857
+ };
858
+ attachProof(r, undefined, st);
859
+ await persistReceipt(r);
860
+ try {
861
+ await lease.update({
862
+ phase: "rejected",
863
+ rejected: { nonce: r.nonce ?? "", valid_before: keptVb, payer: r.payer ?? "", network, asset: (r.quote?.asset ?? "").toLowerCase() },
864
+ });
865
+ }
866
+ catch (e) {
867
+ 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`);
868
+ }
869
+ return wrapResponse(res.status, res.statusText, res.headers, read.callerBody, res.url || req.url, r);
870
+ }
871
+ r.paid = true;
688
872
  const tx = st.parsed?.transaction;
689
873
  r.tx_hash = typeof tx === "string" && TX_HASH_RE.test(tx) ? tx : null;
690
874
  finish(r, t0, r.validator_failures.length ? "validator_failed" : "ok");
@@ -733,11 +917,13 @@ export function safeFetch(wallet, options) {
733
917
  };
734
918
  /** live() with the team asked before signing, and every approval's outcome reported after. */
735
919
  async function teamLive(team, lease, req, r, t0) {
920
+ const project = teamConf?.project;
736
921
  let decision;
737
922
  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" });
923
+ 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
924
  decision = d;
740
925
  r.team = teamReceipt(team.origin, d);
926
+ askedTeam.set(r, d.telemetry);
741
927
  return d.kind === "approve" ? { approve: true, nonce: d.auth_ref, validBefore: d.valid_before } : { approve: false, message: teamMessage(d, q.intentId) };
742
928
  };
743
929
  /** Say what happened to an approved payment, paid or not. Nothing to say when nothing was approved. */
@@ -757,6 +943,24 @@ export function safeFetch(wallet, options) {
757
943
  res = await live(lease, req, r, t0, authorize);
758
944
  }
759
945
  catch (e) {
946
+ if (e instanceof PaymentRefusedError && LOCAL_REFUSALS.has(e.code) && e.receipt?.quote) {
947
+ // Refused before the team was asked: tell it, so the ledger counts what was saved. Never awaited, never thrown.
948
+ const q = e.receipt.quote;
949
+ void team.reportRefusal({
950
+ wallet: signer.address,
951
+ intent_id: e.receipt.intent_id,
952
+ resource_url: e.receipt.url,
953
+ pay_to: q.pay_to,
954
+ amount_atomic: q.amount_atomic,
955
+ network,
956
+ asset: q.asset,
957
+ scheme: q.scheme,
958
+ protocol: "x402",
959
+ reason: e.code,
960
+ verdict: e.receipt.seller.verdict,
961
+ ...(project ? { project } : {}),
962
+ });
963
+ }
760
964
  await settle(e instanceof SafeFetchError ? e.receipt : undefined);
761
965
  if (decision && e instanceof PaymentRefusedError && e.code === "refused_authorize") {
762
966
  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 {
@@ -27,6 +38,11 @@ export interface TeamDecisionExtras {
27
38
  usage?: Record<string, unknown>;
28
39
  /** The ledger row for this decision, when the server named one. */
29
40
  ledger_id?: string;
41
+ /**
42
+ * Whether this payment's outcome goes to the index, as the account decides it (`telemetry.report`). "off" only when
43
+ * the team is on a plan that allows it and turned reporting off; absent (an older server, or anything else) means report.
44
+ */
45
+ telemetry?: "verified" | "off";
30
46
  }
31
47
  /** The server's answer, read strictly. Only `approve` lets a payment be signed. */
32
48
  export type TeamDecision = ({
@@ -62,6 +78,14 @@ export type TeamAuthorizeBody = {
62
78
  asset: string;
63
79
  scheme: string;
64
80
  protocol: "x402";
81
+ project?: string;
82
+ };
83
+ /** What the client refused by itself, before asking the team (`POST /v1/team/refusals`). */
84
+ export type TeamRefusalReason = "refused_verdict" | "refused_ratio" | "refused_max_per_call";
85
+ export type TeamRefusalBody = Omit<TeamAuthorizeBody, "project"> & {
86
+ reason: TeamRefusalReason;
87
+ verdict?: "avoid" | "caution" | "ok" | "unknown";
88
+ project?: string;
65
89
  };
66
90
  export type TeamOutcomeBody = {
67
91
  wallet: string;
@@ -135,10 +159,24 @@ export declare class TeamClient {
135
159
  /** Reports that could not be written to disk; sent again like the disk queue, lost if the process ends. */
136
160
  private readonly memory;
137
161
  private flushing;
162
+ /** What the last authorize answer said about reporting to the index; undefined until one says, and after any that does not. */
163
+ private lastTelemetry;
138
164
  constructor(o: TeamClientOptions);
139
165
  private post;
140
166
  /** Never throws: anything but a 200 with a readable decision is { kind: "failed" }. */
141
167
  authorize(body: TeamAuthorizeBody): Promise<TeamDecision>;
168
+ /**
169
+ * Whether outcomes go to the index, from the last authorize answer: "off" only when the account turned reporting off
170
+ * on a plan that allows it. Undefined before any answer said so, which means report.
171
+ */
172
+ telemetryReport(): "verified" | "off" | undefined;
173
+ private ask;
174
+ /**
175
+ * Tell the team about a payment this client refused before asking it, so the ledger and the bill can count what was
176
+ * saved. Fire-and-forget: one try, a 2 s timeout, every failure (a 404 from a server without the route included)
177
+ * swallowed and never logged. Never throws or rejects; the promise is returned only so tests can wait on it.
178
+ */
179
+ reportRefusal(body: TeamRefusalBody): Promise<void>;
142
180
  /** One try. "retry" means the server could not take it now; a 4xx will never be taken, so it is not kept. */
143
181
  private send;
144
182
  private queueName;