@paidfor/x402-safe-fetch 0.4.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,25 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.5.0
4
+
5
+ - **Team mode: `team: { key }`.** Budgets per wallet, human approvals and a ledger from a paidfor team account, with
6
+ one option. Every payment asks `{origin}/v1/team/authorize` (default origin `https://paidfor.dev`) before signing
7
+ and signs the minted nonce and deadline; anything but a clean approval throws `TeamRefusedError` (code
8
+ `refused_authorize`, with `decision`: `decline`, `needs_approval` with `approve_url` and `expires_at`,
9
+ `already_settled`, or `failed`) and signs nothing. Every approval's outcome is reported to `/v1/team/outcome`; a
10
+ report the server could not take is kept in `<receiptsDir>/team-outcomes` (in memory if the disk cannot take it)
11
+ and sent before the next payment. `receipt.team` carries the decision, the server's `warnings` and the report's
12
+ state. The key goes only to the team origin; a plain-http origin off this machine is refused.
13
+ - **`PAIDFOR_TEAM_KEY` turns team mode on** when `team` and `authorize` are both left out. If that variable is in
14
+ the environment of a program upgrading from 0.4.x, its payments now ask the team first; pass `team: false` to keep
15
+ the old behaviour. `team` and `authorize` together throw.
16
+ - Exported: `TeamRefusedError`, `TeamClient`, `outcomeFor`, `readDecision`, `isKeySafeOrigin`, `TEAM_ORIGIN` and the
17
+ types `TeamOptions`, `TeamDecision`, `TeamDecisionExtras`, `TeamWarning`, `TeamReceipt`, `TeamReportState`,
18
+ `TeamAuthorizeBody`, `TeamOutcomeBody`, `TeamClientOptions`.
19
+ `TeamClient` leaves bare queue entries (the `@paidfor/mcp` format, which names no key) untouched unless it is made
20
+ with `adoptBareEntries: true`; the `team` option never adopts them.
21
+ - `client` in telemetry rows and the `X-Paidfor-Client` header is `x402-safe-fetch/0.5.0`.
22
+
3
23
  ## 0.4.0
4
24
 
5
25
  - **`authorize`.** A new option: a callback asked after every local check and before anything is signed. An approval
package/README.md CHANGED
@@ -171,6 +171,41 @@ This is the whole message, for a paid call that got a 500:
171
171
  The first time a receipts directory is used with `"verified"`, the client prints a one-line notice pointing
172
172
  here.
173
173
 
174
+ ## With a team account
175
+
176
+ A free [paidfor team account](https://paidfor.dev/team) adds budgets per wallet, human approvals and a ledger. Add
177
+ the team key, nothing else:
178
+
179
+ ```ts
180
+ const fetchWithPay = safeFetch(account, {
181
+ maxPerCallUsd: 0.5,
182
+ team: { key: process.env.PAIDFOR_TEAM_KEY! },
183
+ });
184
+ ```
185
+
186
+ What you get:
187
+
188
+ - Before signing, every payment asks `https://paidfor.dev/v1/team/authorize` and signs only with the nonce and
189
+ deadline the team minted. Anything but a clean approval pays nothing and throws `TeamRefusedError` (code
190
+ `refused_authorize`): a decline (`decision.reason`, `decision.message`), a payment waiting for a person
191
+ (`decision.approve_url` and `decision.expires_at`: show the link, then call again with the same `intentId`), an
192
+ intent the team already saw paid (`already_settled`), or a team that could not be asked (timeout, 5xx, an answer
193
+ it could not read). Your local caps still apply: a payment must pass both.
194
+ - Every approval's outcome, paid or not, is reported to the team's ledger. A report the server could not take is
195
+ kept in `<receiptsDir>/team-outcomes` and sent before the next payment (in memory, until the process ends, if
196
+ the disk cannot take it).
197
+ - `receipt.team` says what the team decided, carries any `warnings` the server sent, and `outcome_report` (`sent`,
198
+ `queued` or `rejected`).
199
+
200
+ The wallet must be registered to the team: on [paidfor.dev/team](https://paidfor.dev/team), or with
201
+ `npx -y @paidfor/mcp@0.7.0 init --wallet --link` (add `--key-file <path>` for a key file of your own). The key goes
202
+ only to the team origin, never to a seller, and is never logged. `team` also takes `origin` (https only, or
203
+ http on localhost), `authorizeTimeoutMs` (default 10000) and `reportTimeoutMs` (default 5000).
204
+
205
+ 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
207
+ `authorize`, and with your own `authorize` the environment is not read.
208
+
174
209
  ## Ask before paying
175
210
 
176
211
  `authorize` asks a service of yours (a budget, a person) about each payment, after the local checks and before anything
@@ -222,6 +257,7 @@ own checks). Responses without a settlement (free calls, refusals) send nothing.
222
257
  | Error | `code` | Paid? |
223
258
  | --- | --- | --- |
224
259
  | `PaymentRefusedError` | `refused_verdict`, `refused_ratio`, `refused_max_per_call`, `refused_authorize` | No |
260
+ | `TeamRefusedError` (a `PaymentRefusedError`) | `refused_authorize`; `decision` says why | No |
225
261
  | `IntentConflictError` | `intent_conflict` | No |
226
262
  | `IntentIndeterminateError` | `intent_indeterminate` | Maybe, earlier; never again |
227
263
  | `SafeFetchError` | `paid_no_response` | Signed and possibly settled; `receipt.nonce` identifies it |
package/dist/errors.d.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import type { Receipt } from "./receipt.js";
2
+ import type { TeamDecision } from "./team.js";
2
3
  export type SafeFetchErrorCode = "refused_verdict" | "refused_ratio" | "refused_max_per_call" | "refused_authorize" | "no_acceptable_quote" | "intent_conflict" | "intent_indeterminate" | "intent_in_flight" | "paid_no_response" | "network" | "sdk";
3
4
  /** Every error this package throws. `receipt` is set whenever a call got far enough to write one. */
4
5
  export declare class SafeFetchError extends Error {
@@ -15,6 +16,18 @@ export declare class PaymentRefusedError extends SafeFetchError {
15
16
  name: string;
16
17
  constructor(code: "refused_verdict" | "refused_ratio" | "refused_max_per_call" | "refused_authorize", message: string, sellerUrl: string | null, receipt?: Receipt);
17
18
  }
19
+ /**
20
+ * The team (the `team` option) did not approve this payment, or could not be asked. Nothing was paid. `decision` says
21
+ * why: `needs_approval` carries the `approve_url` to show a person (then call again with the same intentId),
22
+ * `already_settled` means this intent was paid before, `decline` carries the server's `reason`, `failed` means the
23
+ * team could not be asked. An `approve` here was unusable (malformed, or about to lapse) and is reported as not paid.
24
+ * Always code `refused_authorize`.
25
+ */
26
+ export declare class TeamRefusedError extends PaymentRefusedError {
27
+ readonly decision: TeamDecision;
28
+ name: string;
29
+ constructor(decision: TeamDecision, message: string, sellerUrl: string | null, receipt?: Receipt);
30
+ }
18
31
  /** Same intentId, different request. Nothing was sent. */
19
32
  export declare class IntentConflictError extends SafeFetchError {
20
33
  name: string;
package/dist/errors.js CHANGED
@@ -18,6 +18,21 @@ export class PaymentRefusedError extends SafeFetchError {
18
18
  this.sellerUrl = sellerUrl;
19
19
  }
20
20
  }
21
+ /**
22
+ * The team (the `team` option) did not approve this payment, or could not be asked. Nothing was paid. `decision` says
23
+ * why: `needs_approval` carries the `approve_url` to show a person (then call again with the same intentId),
24
+ * `already_settled` means this intent was paid before, `decline` carries the server's `reason`, `failed` means the
25
+ * team could not be asked. An `approve` here was unusable (malformed, or about to lapse) and is reported as not paid.
26
+ * Always code `refused_authorize`.
27
+ */
28
+ export class TeamRefusedError extends PaymentRefusedError {
29
+ decision;
30
+ name = "TeamRefusedError";
31
+ constructor(decision, message, sellerUrl, receipt) {
32
+ super("refused_authorize", message, sellerUrl, receipt);
33
+ this.decision = decision;
34
+ }
35
+ }
21
36
  /** Same intentId, different request. Nothing was sent. */
22
37
  export class IntentConflictError extends SafeFetchError {
23
38
  name = "IntentConflictError";
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  export { safeFetch, hashRequest, type SafeFetch, type SafeFetchOptions, type SafeResponse, type CallOptions, type WalletLike, type SafeNetwork, type AuthorizeRequest, type AuthorizeAnswer } from "./safe-fetch.js";
2
- export { SafeFetchError, PaymentRefusedError, IntentConflictError, IntentIndeterminateError, type SafeFetchErrorCode } from "./errors.js";
2
+ export { SafeFetchError, PaymentRefusedError, IntentConflictError, IntentIndeterminateError, TeamRefusedError, type SafeFetchErrorCode } from "./errors.js";
3
3
  export type { Receipt, Outcome } from "./receipt.js";
4
4
  export type { Verdict, IndexCheck } from "./index-client.js";
5
5
  export type { ValidatorName } from "./taxonomy.js";
@@ -7,3 +7,4 @@ export type { ValidatorResult } from "./validators/types.js";
7
7
  export type { TelemetryPayload, TelemetryPayloadV2 } from "./telemetry.js";
8
8
  export type { TelemetryProof, TelemetryOutcome } from "./proof.js";
9
9
  export { reportOnly, withPaidforReporting, withPaidforReportingAxios, buildTxOnlyPayload, settlementTx, type ReportOnlyOptions, type ReportOutcome, type TxOnlyPayload, type AxiosLike } from "./report-only.js";
10
+ export { TeamClient, outcomeFor, readDecision, isKeySafeOrigin, TEAM_ORIGIN, type TeamOptions, type TeamDecision, type TeamDecisionExtras, type TeamWarning, type TeamReceipt, type TeamReportState, type TeamAuthorizeBody, type TeamOutcomeBody, type TeamClientOptions } from "./team.js";
package/dist/index.js CHANGED
@@ -1,3 +1,4 @@
1
1
  export { safeFetch, hashRequest } from "./safe-fetch.js";
2
- export { SafeFetchError, PaymentRefusedError, IntentConflictError, IntentIndeterminateError } from "./errors.js";
2
+ export { SafeFetchError, PaymentRefusedError, IntentConflictError, IntentIndeterminateError, TeamRefusedError } from "./errors.js";
3
3
  export { reportOnly, withPaidforReporting, withPaidforReportingAxios, buildTxOnlyPayload, settlementTx } from "./report-only.js";
4
+ export { TeamClient, outcomeFor, readDecision, isKeySafeOrigin, TEAM_ORIGIN } from "./team.js";
package/dist/receipt.d.ts CHANGED
@@ -2,6 +2,7 @@ import type { Verdict } from "./index-client.js";
2
2
  import type { ReferenceSource } from "./price.js";
3
3
  import type { TelemetryOutcome, TelemetryProof } from "./proof.js";
4
4
  import type { ValidatorName } from "./taxonomy.js";
5
+ import type { TeamReceipt } from "./team.js";
5
6
  import type { SettlementResponse } from "./x402/types.js";
6
7
  import type { ValidatorResult } from "./validators/types.js";
7
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";
@@ -85,6 +86,11 @@ export interface Receipt {
85
86
  code: string;
86
87
  message: string;
87
88
  } | null;
89
+ /**
90
+ * Team mode only (the `team` option): what the team decided, its `warnings`, and what became of the outcome report.
91
+ * `outcome_report` is filled in after the receipt file is written, so it is on the returned receipt only.
92
+ */
93
+ team?: TeamReceipt;
88
94
  }
89
95
  /** One JSON file per call: <receiptsDir>/<timestamp>-<random>.json. Returns the file name. */
90
96
  export declare function writeReceipt(dir: string, r: Receipt): Promise<string>;
@@ -1,6 +1,7 @@
1
1
  import type { ClientEvmSigner } from "@x402/evm";
2
2
  import { type Verdict } from "./index-client.js";
3
3
  import { type Receipt } from "./receipt.js";
4
+ import { type TeamOptions } from "./team.js";
4
5
  import { type ValidatorName } from "./taxonomy.js";
5
6
  export type SafeNetwork = "eip155:8453" | "eip155:84532";
6
7
  export interface SafeFetchOptions {
@@ -35,8 +36,19 @@ export interface SafeFetchOptions {
35
36
  * Asks someone else whether this payment may go ahead, after every local check has passed and before anything is
36
37
  * signed. An approval names the EIP-3009 nonce and `validBefore` to sign. Anything but a well-formed approval,
37
38
  * including a throw, is a `refused_authorize`: nothing is signed. Not asked for a free resource or a replay.
39
+ * The low-level hook behind `team`; passing both throws.
38
40
  */
39
41
  authorize?: (request: AuthorizeRequest) => Promise<AuthorizeAnswer>;
42
+ /**
43
+ * Team mode: a paidfor team account's budgets, approvals and ledger. Before signing, every payment asks
44
+ * `{origin}/v1/team/authorize` with the key and signs the nonce and deadline the team minted; anything but a clean
45
+ * 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.
47
+ *
48
+ * 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.
50
+ */
51
+ team?: TeamOptions | false;
40
52
  }
41
53
  /** The quote `authorize` is asked about. `network` is CAIP-2. */
42
54
  export interface AuthorizeRequest {
@@ -15,12 +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 } from "./errors.js";
18
+ import { 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
25
  import { ALL_VALIDATORS, MAX_BODY_BYTES } from "./taxonomy.js";
25
26
  import { CLIENT_ID, buildPayload, buildPayloadV2, sendTelemetry } from "./telemetry.js";
26
27
  import { runAllValidators, validatorsByName } from "./validators/index.js";
@@ -70,6 +71,57 @@ function wrapResponse(status, statusText, headers, body, url, receipt) {
70
71
  return res;
71
72
  }
72
73
  const TX_HASH_RE = /^0x[0-9a-fA-F]{64}$/;
74
+ let envNoticeShown = false;
75
+ /** `team`, or PAIDFOR_TEAM_KEY when neither `team` nor `authorize` is given. */
76
+ function resolveTeam(o) {
77
+ if (o.team === false)
78
+ return undefined;
79
+ if (o.team !== undefined) {
80
+ 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");
82
+ }
83
+ if (o.authorize)
84
+ throw new TypeError("safeFetch: pass team or authorize, not both (team supplies its own authorize)");
85
+ return { team: o.team, fromEnv: false };
86
+ }
87
+ if (o.authorize)
88
+ 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;
91
+ }
92
+ function teamReceipt(origin, d) {
93
+ return {
94
+ origin,
95
+ decision: d.kind,
96
+ auth_ref: d.kind === "approve" ? d.auth_ref : null,
97
+ reason: d.kind === "decline" ? d.reason : null,
98
+ message: d.kind === "approve" ? null : d.message || null,
99
+ approve_url: d.kind === "needs_approval" ? d.approve_url : null,
100
+ expires_at: d.kind === "needs_approval" ? d.expires_at : null,
101
+ ledger_id: d.ledger_id ?? null,
102
+ warnings: d.warnings,
103
+ usage: d.usage ?? null,
104
+ outcome_report: null,
105
+ };
106
+ }
107
+ /** An ISO time for Unix seconds, or the bare number; never throws. */
108
+ function unixTime(s) {
109
+ const d = new Date(s * 1000);
110
+ return Number.isFinite(d.getTime()) ? d.toISOString() : `Unix time ${String(s)}`;
111
+ }
112
+ /** The refusal text for a decision that is not an approval. */
113
+ function teamMessage(d, intentId) {
114
+ switch (d.kind) {
115
+ case "decline":
116
+ return `declined by your team's rules (${d.reason}): ${d.message}${d.retry_after !== undefined ? ` Ask again after ${unixTime(d.retry_after)}.` : ""}`;
117
+ case "needs_approval":
118
+ return `a person has to approve this payment first: ${d.approve_url} (the request waits until ${d.expires_at}). After they approve it, call again with intentId "${intentId}".${d.message ? ` ${d.message}` : ""}`;
119
+ case "already_settled":
120
+ return `this purchase was already paid (settlement ${d.settlement_ref}, outcome ${d.outcome}); nothing was paid again. For a new purchase use a new intentId.`;
121
+ case "failed":
122
+ return `the team's rules could not be checked: ${d.message} Calling again with intentId "${intentId}" is safe.`;
123
+ }
124
+ }
73
125
  /** Verified rows carry the payer and nonce, so they only go over https, or to this machine. */
74
126
  function isSecureOrLoopback(url) {
75
127
  try {
@@ -108,6 +160,7 @@ export function safeFetch(wallet, options) {
108
160
  const maxAtomic = usdToAtomic(options.maxPerCallUsd);
109
161
  const intents = new IntentStore(receiptsDir);
110
162
  const prices = new PriceBook(receiptsDir);
163
+ const teamConf = resolveTeam(options);
111
164
  const warn = (msg) => {
112
165
  try {
113
166
  logger.warn(`x402-safe-fetch: ${msg}`);
@@ -118,6 +171,21 @@ export function safeFetch(wallet, options) {
118
171
  };
119
172
  if (telemetry === "verified")
120
173
  void verifiedNotice();
174
+ const team = teamConf
175
+ ? new TeamClient({
176
+ origin: teamConf.team.origin ?? TEAM_ORIGIN,
177
+ key: teamConf.team.key,
178
+ queueDir: join(receiptsDir, "team-outcomes"),
179
+ fetch: baseFetch,
180
+ warn,
181
+ ...(teamConf.team.authorizeTimeoutMs !== undefined ? { authorizeTimeoutMs: teamConf.team.authorizeTimeoutMs } : {}),
182
+ ...(teamConf.team.reportTimeoutMs !== undefined ? { reportTimeoutMs: teamConf.team.reportTimeoutMs } : {}),
183
+ })
184
+ : undefined;
185
+ if (team && teamConf?.fromEnv && !envNoticeShown) {
186
+ envNoticeShown = true;
187
+ warn(`team mode is on from PAIDFOR_TEAM_KEY: every payment asks ${team.origin} first. Pass team: false to turn it off.`);
188
+ }
121
189
  /** Once per receipts directory: say what verified telemetry sends and where it is documented. */
122
190
  async function verifiedNotice() {
123
191
  const marker = join(receiptsDir, ".verified-telemetry-notice");
@@ -287,7 +355,7 @@ export function safeFetch(wallet, options) {
287
355
  const body = Buffer.from(stored.body_base64, "base64");
288
356
  return wrapResponse(stored.status, stored.statusText, stored.headers, body, stored.url || req.url, r);
289
357
  }
290
- async function live(lease, req, r, t0) {
358
+ async function live(lease, req, r, t0, authorize) {
291
359
  let quoteResult;
292
360
  let indexP;
293
361
  let idx;
@@ -319,7 +387,7 @@ export function safeFetch(wallet, options) {
319
387
  (q.extra?.assetTransferMethod ?? "eip3009") === "eip3009");
320
388
  // With `authorize` the approval decides the nonce and deadline; the SDK has no way to take them, so they are set
321
389
  // here at signing and on the signed payload in onAfterPaymentCreation.
322
- const schemeSigner = !options.authorize
390
+ const schemeSigner = !authorize
323
391
  ? signer
324
392
  : {
325
393
  address: signer.address,
@@ -417,10 +485,10 @@ export function safeFetch(wallet, options) {
417
485
  return { abort: true, reason: refusal.message };
418
486
  }
419
487
  // 4. Last, so a payment refused above never takes up a reservation with whoever approves it.
420
- if (options.authorize) {
488
+ if (authorize) {
421
489
  let answer;
422
490
  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 });
491
+ answer = await 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
492
  }
425
493
  catch (e) {
426
494
  answer = { approve: false, message: `could not get an approval: ${errMsg(e)}` };
@@ -647,13 +715,55 @@ export function safeFetch(wallet, options) {
647
715
  const req = await normalizeRequest(input, init);
648
716
  const requestHash = hashRequest(req);
649
717
  const intentId = call.intentId ?? randomUUID();
718
+ // Owed team reports go first: until the server has them it answers the same purchase with pending_settlement.
719
+ if (team)
720
+ await team.flush();
650
721
  const lease = await intents.acquire(intentId, requestHash);
651
722
  try {
652
723
  const r = baseReceipt(req, intentId, requestHash, t0);
653
- return lease.replay ? await replay(lease, req, r, t0) : await live(lease, req, r, t0);
724
+ if (lease.replay)
725
+ return await replay(lease, req, r, t0);
726
+ if (!team)
727
+ return await live(lease, req, r, t0, options.authorize);
728
+ return await teamLive(team, lease, req, r, t0);
654
729
  }
655
730
  finally {
656
731
  await lease.release();
657
732
  }
658
733
  };
734
+ /** live() with the team asked before signing, and every approval's outcome reported after. */
735
+ async function teamLive(team, lease, req, r, t0) {
736
+ let decision;
737
+ 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" });
739
+ decision = d;
740
+ r.team = teamReceipt(team.origin, d);
741
+ return d.kind === "approve" ? { approve: true, nonce: d.auth_ref, validBefore: d.valid_before } : { approve: false, message: teamMessage(d, q.intentId) };
742
+ };
743
+ /** Say what happened to an approved payment, paid or not. Nothing to say when nothing was approved. */
744
+ const settle = async (rec) => {
745
+ if (decision?.kind !== "approve")
746
+ return;
747
+ if (!rec) {
748
+ warn(`no receipt for approved intent ${r.intent_id}, so no team outcome was reported; the approval keeps counting against the budgets`);
749
+ return;
750
+ }
751
+ const state = await team.report(outcomeFor(rec, signer.address, decision.auth_ref));
752
+ if (rec.team)
753
+ rec.team.outcome_report = state;
754
+ };
755
+ let res;
756
+ try {
757
+ res = await live(lease, req, r, t0, authorize);
758
+ }
759
+ catch (e) {
760
+ await settle(e instanceof SafeFetchError ? e.receipt : undefined);
761
+ if (decision && e instanceof PaymentRefusedError && e.code === "refused_authorize") {
762
+ throw new TeamRefusedError(decision, e.message, e.sellerUrl, e.receipt);
763
+ }
764
+ throw e;
765
+ }
766
+ await settle(res.receipt);
767
+ return res;
768
+ }
659
769
  }
package/dist/team.d.ts ADDED
@@ -0,0 +1,153 @@
1
+ import type { Receipt } from "./receipt.js";
2
+ export declare const TEAM_ORIGIN = "https://paidfor.dev";
3
+ export declare const AUTHORIZE_TIMEOUT_MS = 10000;
4
+ export declare const REPORT_TIMEOUT_MS = 5000;
5
+ /** `team` in SafeFetchOptions. */
6
+ export interface TeamOptions {
7
+ /** The team key, `pft_...`. Sent only to `origin`, as `Authorization: Bearer`, never to a seller and never logged. */
8
+ key: string;
9
+ /** Where the team API lives. Default "https://paidfor.dev". https only, except localhost / 127.0.0.1 / [::1]. */
10
+ origin?: string;
11
+ /** How long to wait for a decision before refusing. Default 10000 ms. */
12
+ authorizeTimeoutMs?: number;
13
+ /** How long each outcome report may take. Default 5000 ms. */
14
+ reportTimeoutMs?: number;
15
+ }
16
+ /** A notice a newer server may attach to a decision, such as a budget nearly used up. */
17
+ export interface TeamWarning {
18
+ code: string;
19
+ message: string;
20
+ upgrade_url?: string;
21
+ }
22
+ /** Optional fields any decision may carry. Older servers send none. */
23
+ export interface TeamDecisionExtras {
24
+ /** Always an array; empty when the server sent none. */
25
+ warnings: TeamWarning[];
26
+ /** The server's spend summary, passed through as sent, when there is one. */
27
+ usage?: Record<string, unknown>;
28
+ /** The ledger row for this decision, when the server named one. */
29
+ ledger_id?: string;
30
+ }
31
+ /** The server's answer, read strictly. Only `approve` lets a payment be signed. */
32
+ export type TeamDecision = ({
33
+ kind: "approve";
34
+ auth_ref: string;
35
+ valid_before: number;
36
+ } | {
37
+ kind: "decline";
38
+ reason: string;
39
+ message: string;
40
+ retry_after?: number;
41
+ } | {
42
+ kind: "needs_approval";
43
+ approve_url: string;
44
+ expires_at: string;
45
+ message: string;
46
+ } | {
47
+ kind: "already_settled";
48
+ settlement_ref: string;
49
+ outcome: string;
50
+ message: string;
51
+ } | {
52
+ kind: "failed";
53
+ message: string;
54
+ }) & TeamDecisionExtras;
55
+ export type TeamAuthorizeBody = {
56
+ wallet: string;
57
+ intent_id: string;
58
+ resource_url: string;
59
+ pay_to: string;
60
+ amount_atomic: string;
61
+ network: string;
62
+ asset: string;
63
+ scheme: string;
64
+ protocol: "x402";
65
+ };
66
+ export type TeamOutcomeBody = {
67
+ wallet: string;
68
+ intent_id: string;
69
+ auth_ref: string;
70
+ paid: boolean;
71
+ settlement_ref?: string;
72
+ outcome?: string;
73
+ http_status?: number;
74
+ response_sha256?: string;
75
+ };
76
+ /**
77
+ * sent: the server has it. queued: kept (on disk, or in memory when the disk write failed) and sent again before the
78
+ * next payment. rejected: the server refused it for good (a 4xx other than 408 / 429).
79
+ */
80
+ export type TeamReportState = "sent" | "queued" | "rejected";
81
+ /** `receipt.team`: set on every call that asked the team. */
82
+ export interface TeamReceipt {
83
+ origin: string;
84
+ decision: TeamDecision["kind"];
85
+ /** The approval's reference (the signed EIP-3009 nonce), for `approve`. */
86
+ auth_ref: string | null;
87
+ reason: string | null;
88
+ message: string | null;
89
+ approve_url: string | null;
90
+ expires_at: string | null;
91
+ ledger_id: string | null;
92
+ warnings: TeamWarning[];
93
+ usage: Record<string, unknown> | null;
94
+ /** What happened to the outcome report. Null when nothing was approved, so there was nothing to report. */
95
+ outcome_report: TeamReportState | null;
96
+ }
97
+ /** What to report for a payment that was approved, from its receipt. */
98
+ export declare function outcomeFor(r: Receipt, wallet: string, authRef: string): TeamOutcomeBody;
99
+ /** A 200's body as a decision. Anything not exactly one of the contract's answers is "failed". Unknown fields are ignored. */
100
+ export declare function readDecision(b: unknown): TeamDecision;
101
+ /** The key travels in a header. Plain http is for a server on this machine only. */
102
+ export declare function isKeySafeOrigin(origin: string): boolean;
103
+ export interface TeamClientOptions {
104
+ /** Team API origin, e.g. "https://paidfor.dev". Must pass isKeySafeOrigin, or the constructor throws. */
105
+ origin: string;
106
+ key: string;
107
+ /** Where reports the server could not take are kept. Created on first use (mode 700, files 600). */
108
+ queueDir: string;
109
+ fetch?: typeof globalThis.fetch;
110
+ warn?: (m: string) => void;
111
+ authorizeTimeoutMs?: number;
112
+ reportTimeoutMs?: number;
113
+ /** Wait before the second try of a report. Default 250 ms. */
114
+ retryDelayMs?: number;
115
+ /**
116
+ * Also send bare queue entries (@paidfor/mcp's format, which names no origin or key) under this client's key, and
117
+ * delete them once the server has answered. Only for a directory whose bare entries are known to belong to this key,
118
+ * such as the MCP pointing at its own queue. Default false: bare entries are left untouched, because sent under another
119
+ * team's key they are refused for good and the report another team needs would be lost.
120
+ */
121
+ adoptBareEntries?: boolean;
122
+ }
123
+ /** The two team calls and the report queue. safeFetch's `team` option makes one; exported for callers wiring `authorize` themselves. */
124
+ export declare class TeamClient {
125
+ readonly origin: string;
126
+ private readonly key;
127
+ private readonly keyHash;
128
+ private readonly queueDir;
129
+ private readonly fetchFn;
130
+ private readonly warn;
131
+ private readonly authorizeTimeoutMs;
132
+ private readonly reportTimeoutMs;
133
+ private readonly retryDelayMs;
134
+ private readonly adoptBare;
135
+ /** Reports that could not be written to disk; sent again like the disk queue, lost if the process ends. */
136
+ private readonly memory;
137
+ private flushing;
138
+ constructor(o: TeamClientOptions);
139
+ private post;
140
+ /** Never throws: anything but a 200 with a readable decision is { kind: "failed" }. */
141
+ authorize(body: TeamAuthorizeBody): Promise<TeamDecision>;
142
+ /** One try. "retry" means the server could not take it now; a 4xx will never be taken, so it is not kept. */
143
+ private send;
144
+ private queueName;
145
+ /** Send the outcome of an approved payment, try once more, and keep it if the server still cannot take it. */
146
+ report(body: TeamOutcomeBody): Promise<TeamReportState>;
147
+ /** Reports still owed: on disk for this origin and key, plus those kept in memory. */
148
+ pending(): Promise<TeamOutcomeBody[]>;
149
+ private diskEntries;
150
+ /** Send what earlier reports left behind. Stops at the first one the server cannot take now. Never throws. */
151
+ flush(): Promise<void>;
152
+ private drain;
153
+ }
package/dist/team.js ADDED
@@ -0,0 +1,266 @@
1
+ /**
2
+ * Team mode: the two calls around a payment in paidfor's team API (https://paidfor.dev/docs/team-api.md, `/v1/team`).
3
+ * `authorize` asks before signing and turns anything but a clean decision into "failed", which pays nothing. `report`
4
+ * says what happened afterwards; a report the server could not take is kept and sent again before the next payment,
5
+ * because an approval nobody reports keeps counting against the budgets.
6
+ *
7
+ * Ported from @paidfor/mcp src/team.ts (the security-reviewed copy pay_x402 uses). Differences: the origin is checked
8
+ * when the client is made, the queue entry names the origin and a hash of the key it belongs to (so two clients sharing
9
+ * a directory never send each other's reports with the wrong key), a bare entry in @paidfor/mcp's format (which names no
10
+ * key) is left untouched unless the caller opts in with `adoptBareEntries`, a report that cannot be written to disk is
11
+ * kept in memory, `retry_after` is kept only when it is a plausible Unix time, and decisions carry the optional
12
+ * `warnings` and `usage` newer servers send.
13
+ */
14
+ import { createHash } from "node:crypto";
15
+ import { mkdir, readFile, readdir, rename, unlink, writeFile } from "node:fs/promises";
16
+ import { join } from "node:path";
17
+ export const TEAM_ORIGIN = "https://paidfor.dev";
18
+ export const AUTHORIZE_TIMEOUT_MS = 10_000;
19
+ export const REPORT_TIMEOUT_MS = 5_000;
20
+ /** The words the server takes for a paid outcome. */
21
+ const PAID_OUTCOMES = ["ok", "non_delivery", "wrong_goods", "overcharge", "duplicate", "paid_no_response"];
22
+ /** Shown when the team does not know the wallet. */
23
+ const MCP_INIT = "npx -y @paidfor/mcp@0.7.0 init --wallet --link";
24
+ /** What to report for a payment that was approved, from its receipt. */
25
+ export function outcomeFor(r, wallet, authRef) {
26
+ const base = { wallet, intent_id: r.intent_id, auth_ref: authRef };
27
+ // Nothing left this machine, or the seller says its settlement failed: the money did not move.
28
+ if (!r.paid || r.settlement.parsed?.success === false)
29
+ return { ...base, paid: false };
30
+ return {
31
+ ...base,
32
+ paid: true,
33
+ // With no transaction hash the signed nonce is what finds the settlement on chain.
34
+ settlement_ref: r.tx_hash ?? r.nonce ?? authRef,
35
+ outcome: r.reported_outcome && PAID_OUTCOMES.includes(r.reported_outcome) ? r.reported_outcome : "non_delivery",
36
+ ...(r.response ? { http_status: r.response.status } : {}),
37
+ ...(r.response?.sha256 ? { response_sha256: r.response.sha256 } : {}),
38
+ };
39
+ }
40
+ const str = (v) => typeof v === "string" && v.length > 0;
41
+ /** Latest `retry_after` accepted: year 9999. Anything outside (0, this] or not an integer is dropped. */
42
+ const MAX_RETRY_AFTER = 253_402_300_799;
43
+ /** `retry_after` is absolute Unix seconds (docs/team-api.md); a value that cannot be one is dropped, the decline kept. */
44
+ const retryAfter = (v) => (typeof v === "number" && Number.isSafeInteger(v) && v > 0 && v <= MAX_RETRY_AFTER ? v : undefined);
45
+ function extras(d) {
46
+ const warnings = Array.isArray(d.warnings)
47
+ ? d.warnings.flatMap((w) => {
48
+ if (!w || typeof w !== "object")
49
+ return [];
50
+ const o = w;
51
+ if (!str(o.code) || !str(o.message))
52
+ return [];
53
+ return [{ code: o.code.slice(0, 100), message: o.message.slice(0, 500), ...(str(o.upgrade_url) ? { upgrade_url: o.upgrade_url } : {}) }];
54
+ })
55
+ : [];
56
+ const usage = d.usage && typeof d.usage === "object" && !Array.isArray(d.usage) ? d.usage : undefined;
57
+ return { warnings, ...(usage ? { usage } : {}), ...(str(d.ledger_id) ? { ledger_id: d.ledger_id } : {}) };
58
+ }
59
+ function failedStatus(status, body, wallet, origin) {
60
+ const said = body && typeof body === "object" && str(body.error) ? ` ${body.error.slice(0, 300)}` : "";
61
+ const ex = { warnings: [] };
62
+ if (status === 401)
63
+ return { kind: "failed", message: `paidfor refused the team key; check team.key (or PAIDFOR_TEAM_KEY).${said}`, ...ex };
64
+ if (status === 404) {
65
+ return {
66
+ kind: "failed",
67
+ message: `wallet ${wallet} is not registered to this team. Register it on ${origin}/team, or run: ${MCP_INIT} (add --key-file <path> when the key is in a file of your own).${said}`,
68
+ ...ex,
69
+ };
70
+ }
71
+ return { kind: "failed", message: `paidfor answered HTTP ${status}.${said}`, ...ex };
72
+ }
73
+ /** A 200's body as a decision. Anything not exactly one of the contract's answers is "failed". Unknown fields are ignored. */
74
+ export function readDecision(b) {
75
+ const bad = { kind: "failed", message: "paidfor's answer could not be read.", warnings: [] };
76
+ if (!b || typeof b !== "object")
77
+ return bad;
78
+ const d = b;
79
+ const message = str(d.message) ? d.message : "";
80
+ const ex = extras(d);
81
+ switch (d.decision) {
82
+ case "approve":
83
+ return str(d.auth_ref) && typeof d.valid_before === "number" ? { kind: "approve", auth_ref: d.auth_ref, valid_before: d.valid_before, ...ex } : bad;
84
+ case "decline":
85
+ return str(d.reason) ? { kind: "decline", reason: d.reason, message: message || d.reason, ...(retryAfter(d.retry_after) !== undefined ? { retry_after: retryAfter(d.retry_after) } : {}), ...ex } : bad;
86
+ case "needs_approval":
87
+ return str(d.approve_url) && str(d.expires_at) ? { kind: "needs_approval", approve_url: d.approve_url, expires_at: d.expires_at, message, ...ex } : bad;
88
+ case "already_settled":
89
+ return { kind: "already_settled", settlement_ref: str(d.settlement_ref) ? d.settlement_ref : "unknown", outcome: str(d.outcome) ? d.outcome : "unknown", message, ...ex };
90
+ default:
91
+ return bad;
92
+ }
93
+ }
94
+ /** The key travels in a header. Plain http is for a server on this machine only. */
95
+ export function isKeySafeOrigin(origin) {
96
+ try {
97
+ const u = new URL(origin);
98
+ return u.protocol === "https:" || (u.protocol === "http:" && ["localhost", "127.0.0.1", "[::1]"].includes(u.hostname));
99
+ }
100
+ catch {
101
+ return false;
102
+ }
103
+ }
104
+ /** The two team calls and the report queue. safeFetch's `team` option makes one; exported for callers wiring `authorize` themselves. */
105
+ export class TeamClient {
106
+ origin;
107
+ key;
108
+ keyHash;
109
+ queueDir;
110
+ fetchFn;
111
+ warn;
112
+ authorizeTimeoutMs;
113
+ reportTimeoutMs;
114
+ retryDelayMs;
115
+ adoptBare;
116
+ /** Reports that could not be written to disk; sent again like the disk queue, lost if the process ends. */
117
+ memory = new Map();
118
+ flushing = null;
119
+ constructor(o) {
120
+ if (typeof o.key !== "string" || !o.key.trim() || /\s/.test(o.key.trim()))
121
+ throw new TypeError("team: key must be a non-empty team key with no spaces");
122
+ const origin = o.origin.replace(/\/+$/, "");
123
+ if (!isKeySafeOrigin(origin))
124
+ throw new TypeError(`team: refusing to send the team key to ${origin}; the origin must be https (or http on localhost)`);
125
+ this.origin = new URL(origin).origin;
126
+ this.key = o.key.trim();
127
+ this.keyHash = createHash("sha256").update(this.key).digest("hex").slice(0, 16);
128
+ this.queueDir = o.queueDir;
129
+ this.fetchFn = o.fetch ?? globalThis.fetch;
130
+ this.warn = o.warn ?? (() => undefined);
131
+ this.authorizeTimeoutMs = o.authorizeTimeoutMs ?? AUTHORIZE_TIMEOUT_MS;
132
+ this.reportTimeoutMs = o.reportTimeoutMs ?? REPORT_TIMEOUT_MS;
133
+ this.retryDelayMs = o.retryDelayMs ?? 250;
134
+ this.adoptBare = o.adoptBareEntries === true;
135
+ }
136
+ post(path, body, timeoutMs) {
137
+ return this.fetchFn(`${this.origin}${path}`, {
138
+ method: "POST",
139
+ headers: { "content-type": "application/json", authorization: `Bearer ${this.key}` },
140
+ body: JSON.stringify(body),
141
+ redirect: "error", // the key goes to the configured origin and nowhere else
142
+ signal: AbortSignal.timeout(timeoutMs),
143
+ });
144
+ }
145
+ /** Never throws: anything but a 200 with a readable decision is { kind: "failed" }. */
146
+ async authorize(body) {
147
+ let res;
148
+ try {
149
+ res = await this.post("/v1/team/authorize", body, this.authorizeTimeoutMs);
150
+ }
151
+ catch {
152
+ return { kind: "failed", message: "paidfor could not be reached.", warnings: [] };
153
+ }
154
+ let parsed = null;
155
+ try {
156
+ parsed = await res.json();
157
+ }
158
+ catch {
159
+ /* an unreadable body is handled below */
160
+ }
161
+ return res.status === 200 ? readDecision(parsed) : failedStatus(res.status, parsed, body.wallet, this.origin);
162
+ }
163
+ /** One try. "retry" means the server could not take it now; a 4xx will never be taken, so it is not kept. */
164
+ async send(body) {
165
+ try {
166
+ const res = await this.post("/v1/team/outcome", body, this.reportTimeoutMs);
167
+ void res.body?.cancel().catch(() => undefined);
168
+ if (res.ok)
169
+ return "sent";
170
+ if (res.status >= 400 && res.status < 500 && res.status !== 408 && res.status !== 429) {
171
+ this.warn(`team: the outcome for intent ${body.intent_id} was refused with HTTP ${res.status}`);
172
+ return "rejected";
173
+ }
174
+ return "retry";
175
+ }
176
+ catch {
177
+ return "retry";
178
+ }
179
+ }
180
+ queueName(body) {
181
+ // Scoped by origin and key, so two clients sharing a directory never overwrite each other's report. Files named the
182
+ // older way (intent and auth_ref only) are still read: every file is, and its origin and key_hash decide whose it is.
183
+ return `${createHash("sha256").update(`${this.origin}\n${this.keyHash}\n${body.intent_id}\n${body.auth_ref}`).digest("hex").slice(0, 40)}.json`;
184
+ }
185
+ /** Send the outcome of an approved payment, try once more, and keep it if the server still cannot take it. */
186
+ async report(body) {
187
+ let r = await this.send(body);
188
+ if (r === "retry") {
189
+ await new Promise((d) => setTimeout(d, this.retryDelayMs));
190
+ r = await this.send(body);
191
+ }
192
+ if (r !== "retry")
193
+ return r;
194
+ const name = this.queueName(body);
195
+ try {
196
+ await mkdir(this.queueDir, { recursive: true, mode: 0o700 });
197
+ const file = join(this.queueDir, name);
198
+ const entry = { v: 1, origin: this.origin, key_hash: this.keyHash, body };
199
+ await writeFile(`${file}.tmp`, JSON.stringify(entry), { mode: 0o600 });
200
+ await rename(`${file}.tmp`, file);
201
+ }
202
+ catch (e) {
203
+ this.memory.set(name, body);
204
+ this.warn(`team: could not write the outcome for intent ${body.intent_id} to disk (${e instanceof Error ? e.message : String(e)}); kept in memory until it is sent`);
205
+ }
206
+ return "queued";
207
+ }
208
+ /** Reports still owed: on disk for this origin and key, plus those kept in memory. */
209
+ async pending() {
210
+ const out = [...this.memory.values()];
211
+ for (const { body } of await this.diskEntries())
212
+ out.push(body);
213
+ return out;
214
+ }
215
+ async diskEntries() {
216
+ let names;
217
+ try {
218
+ names = (await readdir(this.queueDir)).filter((n) => n.endsWith(".json")).sort();
219
+ }
220
+ catch {
221
+ return []; // nothing queued yet
222
+ }
223
+ const out = [];
224
+ for (const name of names) {
225
+ const file = join(this.queueDir, name);
226
+ try {
227
+ const e = JSON.parse(await readFile(file, "utf8"));
228
+ if (e.v === 1 && e.body) {
229
+ if (e.origin === this.origin && e.key_hash === this.keyHash)
230
+ out.push({ file, body: e.body });
231
+ }
232
+ else if (this.adoptBare && str(e.intent_id) && str(e.auth_ref) && str(e.wallet)) {
233
+ // A bare outcome body, as @paidfor/mcp's queue keeps them. It names no key; the caller vouched that it is this one's.
234
+ out.push({ file, body: e });
235
+ }
236
+ }
237
+ catch (err) {
238
+ this.warn(`team: could not read the queued outcome ${name}: ${err instanceof Error ? err.message : String(err)}`);
239
+ }
240
+ }
241
+ return out;
242
+ }
243
+ /** Send what earlier reports left behind. Stops at the first one the server cannot take now. Never throws. */
244
+ flush() {
245
+ if (!this.flushing) {
246
+ this.flushing = this.drain().finally(() => {
247
+ this.flushing = null;
248
+ });
249
+ }
250
+ return this.flushing;
251
+ }
252
+ async drain() {
253
+ for (const [name, body] of [...this.memory]) {
254
+ const r = await this.send(body);
255
+ if (r === "retry")
256
+ return;
257
+ this.memory.delete(name);
258
+ }
259
+ for (const { file, body } of await this.diskEntries()) {
260
+ const r = await this.send(body);
261
+ if (r === "retry")
262
+ return;
263
+ await unlink(file).catch((e) => this.warn(`team: could not remove the sent outcome ${file}: ${e instanceof Error ? e.message : String(e)}`));
264
+ }
265
+ }
266
+ }
@@ -1,5 +1,5 @@
1
1
  import type { TelemetryOutcome, TelemetryProof } from "./proof.js";
2
- export declare const CLIENT_ID = "x402-safe-fetch/0.4.0";
2
+ export declare const CLIENT_ID = "x402-safe-fetch/0.5.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.4.0";
12
+ export const CLIENT_ID = "x402-safe-fetch/0.5.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@paidfor/x402-safe-fetch",
3
- "version": "0.4.0",
3
+ "version": "0.5.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",