@paidfor/x402-safe-fetch 0.4.0 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/team.js ADDED
@@ -0,0 +1,294 @@
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
+ /** How long a refusal notice may take. Never awaited by a payment. */
21
+ export const REFUSAL_TIMEOUT_MS = 2_000;
22
+ /** The words the server takes for a paid outcome. */
23
+ const PAID_OUTCOMES = ["ok", "non_delivery", "wrong_goods", "overcharge", "duplicate", "paid_no_response"];
24
+ /** Shown when the team does not know the wallet. */
25
+ const MCP_INIT = "npx -y @paidfor/mcp@latest init --wallet --link";
26
+ /**
27
+ * The server's rule for a project tag (paidfor lib/team/project.ts): trimmed, then 1 to 64 letters, digits, spaces or
28
+ * . _ -. A tag the server would refuse is refused here, when the client is made, instead of on every payment.
29
+ */
30
+ const PROJECT_RE = /^[A-Za-z0-9._ -]{1,64}$/;
31
+ export const PROJECT_RULE = 'a project tag is 1 to 64 letters, digits, spaces or . _ - (for example "research-q4")';
32
+ /** The tag made canonical (trimmed), or null when the server would refuse it. */
33
+ export function cleanProject(v) {
34
+ if (typeof v !== "string")
35
+ return null;
36
+ const t = v.trim();
37
+ return PROJECT_RE.test(t) ? t : null;
38
+ }
39
+ /** What to report for a payment that was approved, from its receipt. */
40
+ export function outcomeFor(r, wallet, authRef) {
41
+ const base = { wallet, intent_id: r.intent_id, auth_ref: authRef };
42
+ // Nothing left this machine, or the seller says its settlement failed: the money did not move.
43
+ if (!r.paid || r.settlement.parsed?.success === false)
44
+ return { ...base, paid: false };
45
+ return {
46
+ ...base,
47
+ paid: true,
48
+ // With no transaction hash the signed nonce is what finds the settlement on chain.
49
+ settlement_ref: r.tx_hash ?? r.nonce ?? authRef,
50
+ outcome: r.reported_outcome && PAID_OUTCOMES.includes(r.reported_outcome) ? r.reported_outcome : "non_delivery",
51
+ ...(r.response ? { http_status: r.response.status } : {}),
52
+ ...(r.response?.sha256 ? { response_sha256: r.response.sha256 } : {}),
53
+ };
54
+ }
55
+ const str = (v) => typeof v === "string" && v.length > 0;
56
+ /** Latest `retry_after` accepted: year 9999. Anything outside (0, this] or not an integer is dropped. */
57
+ const MAX_RETRY_AFTER = 253_402_300_799;
58
+ /** `retry_after` is absolute Unix seconds (docs/team-api.md); a value that cannot be one is dropped, the decline kept. */
59
+ const retryAfter = (v) => (typeof v === "number" && Number.isSafeInteger(v) && v > 0 && v <= MAX_RETRY_AFTER ? v : undefined);
60
+ function extras(d) {
61
+ const warnings = Array.isArray(d.warnings)
62
+ ? d.warnings.flatMap((w) => {
63
+ if (!w || typeof w !== "object")
64
+ return [];
65
+ const o = w;
66
+ if (!str(o.code) || !str(o.message))
67
+ return [];
68
+ return [{ code: o.code.slice(0, 100), message: o.message.slice(0, 500), ...(str(o.upgrade_url) ? { upgrade_url: o.upgrade_url } : {}) }];
69
+ })
70
+ : [];
71
+ const usage = d.usage && typeof d.usage === "object" && !Array.isArray(d.usage) ? d.usage : undefined;
72
+ return { warnings, ...(usage ? { usage } : {}), ...(str(d.ledger_id) ? { ledger_id: d.ledger_id } : {}) };
73
+ }
74
+ function failedStatus(status, body, wallet, origin) {
75
+ const said = body && typeof body === "object" && str(body.error) ? ` ${body.error.slice(0, 300)}` : "";
76
+ const ex = { warnings: [] };
77
+ if (status === 401)
78
+ return { kind: "failed", message: `paidfor refused the team key; check team.key (or PAIDFOR_TEAM_KEY).${said}`, ...ex };
79
+ if (status === 404) {
80
+ return {
81
+ kind: "failed",
82
+ 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}`,
83
+ ...ex,
84
+ };
85
+ }
86
+ return { kind: "failed", message: `paidfor answered HTTP ${status}.${said}`, ...ex };
87
+ }
88
+ /** A 200's body as a decision. Anything not exactly one of the contract's answers is "failed". Unknown fields are ignored. */
89
+ export function readDecision(b) {
90
+ const bad = { kind: "failed", message: "paidfor's answer could not be read.", warnings: [] };
91
+ if (!b || typeof b !== "object")
92
+ return bad;
93
+ const d = b;
94
+ const message = str(d.message) ? d.message : "";
95
+ const ex = extras(d);
96
+ switch (d.decision) {
97
+ case "approve":
98
+ return str(d.auth_ref) && typeof d.valid_before === "number" ? { kind: "approve", auth_ref: d.auth_ref, valid_before: d.valid_before, ...ex } : bad;
99
+ case "decline":
100
+ 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;
101
+ case "needs_approval":
102
+ 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;
103
+ case "already_settled":
104
+ return { kind: "already_settled", settlement_ref: str(d.settlement_ref) ? d.settlement_ref : "unknown", outcome: str(d.outcome) ? d.outcome : "unknown", message, ...ex };
105
+ default:
106
+ return bad;
107
+ }
108
+ }
109
+ /** The key travels in a header. Plain http is for a server on this machine only. */
110
+ export function isKeySafeOrigin(origin) {
111
+ try {
112
+ const u = new URL(origin);
113
+ return u.protocol === "https:" || (u.protocol === "http:" && ["localhost", "127.0.0.1", "[::1]"].includes(u.hostname));
114
+ }
115
+ catch {
116
+ return false;
117
+ }
118
+ }
119
+ /** The two team calls and the report queue. safeFetch's `team` option makes one; exported for callers wiring `authorize` themselves. */
120
+ export class TeamClient {
121
+ origin;
122
+ key;
123
+ keyHash;
124
+ queueDir;
125
+ fetchFn;
126
+ warn;
127
+ authorizeTimeoutMs;
128
+ reportTimeoutMs;
129
+ retryDelayMs;
130
+ adoptBare;
131
+ /** Reports that could not be written to disk; sent again like the disk queue, lost if the process ends. */
132
+ memory = new Map();
133
+ flushing = null;
134
+ constructor(o) {
135
+ if (typeof o.key !== "string" || !o.key.trim() || /\s/.test(o.key.trim()))
136
+ throw new TypeError("team: key must be a non-empty team key with no spaces");
137
+ const origin = o.origin.replace(/\/+$/, "");
138
+ if (!isKeySafeOrigin(origin))
139
+ throw new TypeError(`team: refusing to send the team key to ${origin}; the origin must be https (or http on localhost)`);
140
+ this.origin = new URL(origin).origin;
141
+ this.key = o.key.trim();
142
+ this.keyHash = createHash("sha256").update(this.key).digest("hex").slice(0, 16);
143
+ this.queueDir = o.queueDir;
144
+ this.fetchFn = o.fetch ?? globalThis.fetch;
145
+ this.warn = o.warn ?? (() => undefined);
146
+ this.authorizeTimeoutMs = o.authorizeTimeoutMs ?? AUTHORIZE_TIMEOUT_MS;
147
+ this.reportTimeoutMs = o.reportTimeoutMs ?? REPORT_TIMEOUT_MS;
148
+ this.retryDelayMs = o.retryDelayMs ?? 250;
149
+ this.adoptBare = o.adoptBareEntries === true;
150
+ }
151
+ post(path, body, timeoutMs) {
152
+ return this.fetchFn(`${this.origin}${path}`, {
153
+ method: "POST",
154
+ headers: { "content-type": "application/json", authorization: `Bearer ${this.key}` },
155
+ body: JSON.stringify(body),
156
+ redirect: "error", // the key goes to the configured origin and nowhere else
157
+ signal: AbortSignal.timeout(timeoutMs),
158
+ });
159
+ }
160
+ /** Never throws: anything but a 200 with a readable decision is { kind: "failed" }. */
161
+ async authorize(body) {
162
+ let res;
163
+ try {
164
+ res = await this.post("/v1/team/authorize", body, this.authorizeTimeoutMs);
165
+ }
166
+ catch {
167
+ return { kind: "failed", message: "paidfor could not be reached.", warnings: [] };
168
+ }
169
+ let parsed = null;
170
+ try {
171
+ parsed = await res.json();
172
+ }
173
+ catch {
174
+ /* an unreadable body is handled below */
175
+ }
176
+ return res.status === 200 ? readDecision(parsed) : failedStatus(res.status, parsed, body.wallet, this.origin);
177
+ }
178
+ /**
179
+ * Tell the team about a payment this client refused before asking it, so the ledger and the bill can count what was
180
+ * saved. Fire-and-forget: one try, a 2 s timeout, every failure (a 404 from a server without the route included)
181
+ * swallowed and never logged. Never throws or rejects; the promise is returned only so tests can wait on it.
182
+ */
183
+ reportRefusal(body) {
184
+ try {
185
+ return this.post("/v1/team/refusals", body, REFUSAL_TIMEOUT_MS).then((res) => void res.body?.cancel().catch(() => undefined), () => undefined).catch(() => undefined);
186
+ }
187
+ catch {
188
+ return Promise.resolve();
189
+ }
190
+ }
191
+ /** One try. "retry" means the server could not take it now; a 4xx will never be taken, so it is not kept. */
192
+ async send(body) {
193
+ try {
194
+ const res = await this.post("/v1/team/outcome", body, this.reportTimeoutMs);
195
+ void res.body?.cancel().catch(() => undefined);
196
+ if (res.ok)
197
+ return "sent";
198
+ if (res.status >= 400 && res.status < 500 && res.status !== 408 && res.status !== 429) {
199
+ this.warn(`team: the outcome for intent ${body.intent_id} was refused with HTTP ${res.status}`);
200
+ return "rejected";
201
+ }
202
+ return "retry";
203
+ }
204
+ catch {
205
+ return "retry";
206
+ }
207
+ }
208
+ queueName(body) {
209
+ // Scoped by origin and key, so two clients sharing a directory never overwrite each other's report. Files named the
210
+ // older way (intent and auth_ref only) are still read: every file is, and its origin and key_hash decide whose it is.
211
+ return `${createHash("sha256").update(`${this.origin}\n${this.keyHash}\n${body.intent_id}\n${body.auth_ref}`).digest("hex").slice(0, 40)}.json`;
212
+ }
213
+ /** Send the outcome of an approved payment, try once more, and keep it if the server still cannot take it. */
214
+ async report(body) {
215
+ let r = await this.send(body);
216
+ if (r === "retry") {
217
+ await new Promise((d) => setTimeout(d, this.retryDelayMs));
218
+ r = await this.send(body);
219
+ }
220
+ if (r !== "retry")
221
+ return r;
222
+ const name = this.queueName(body);
223
+ try {
224
+ await mkdir(this.queueDir, { recursive: true, mode: 0o700 });
225
+ const file = join(this.queueDir, name);
226
+ const entry = { v: 1, origin: this.origin, key_hash: this.keyHash, body };
227
+ await writeFile(`${file}.tmp`, JSON.stringify(entry), { mode: 0o600 });
228
+ await rename(`${file}.tmp`, file);
229
+ }
230
+ catch (e) {
231
+ this.memory.set(name, body);
232
+ 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`);
233
+ }
234
+ return "queued";
235
+ }
236
+ /** Reports still owed: on disk for this origin and key, plus those kept in memory. */
237
+ async pending() {
238
+ const out = [...this.memory.values()];
239
+ for (const { body } of await this.diskEntries())
240
+ out.push(body);
241
+ return out;
242
+ }
243
+ async diskEntries() {
244
+ let names;
245
+ try {
246
+ names = (await readdir(this.queueDir)).filter((n) => n.endsWith(".json")).sort();
247
+ }
248
+ catch {
249
+ return []; // nothing queued yet
250
+ }
251
+ const out = [];
252
+ for (const name of names) {
253
+ const file = join(this.queueDir, name);
254
+ try {
255
+ const e = JSON.parse(await readFile(file, "utf8"));
256
+ if (e.v === 1 && e.body) {
257
+ if (e.origin === this.origin && e.key_hash === this.keyHash)
258
+ out.push({ file, body: e.body });
259
+ }
260
+ else if (this.adoptBare && str(e.intent_id) && str(e.auth_ref) && str(e.wallet)) {
261
+ // A bare outcome body, as @paidfor/mcp's queue keeps them. It names no key; the caller vouched that it is this one's.
262
+ out.push({ file, body: e });
263
+ }
264
+ }
265
+ catch (err) {
266
+ this.warn(`team: could not read the queued outcome ${name}: ${err instanceof Error ? err.message : String(err)}`);
267
+ }
268
+ }
269
+ return out;
270
+ }
271
+ /** Send what earlier reports left behind. Stops at the first one the server cannot take now. Never throws. */
272
+ flush() {
273
+ if (!this.flushing) {
274
+ this.flushing = this.drain().finally(() => {
275
+ this.flushing = null;
276
+ });
277
+ }
278
+ return this.flushing;
279
+ }
280
+ async drain() {
281
+ for (const [name, body] of [...this.memory]) {
282
+ const r = await this.send(body);
283
+ if (r === "retry")
284
+ return;
285
+ this.memory.delete(name);
286
+ }
287
+ for (const { file, body } of await this.diskEntries()) {
288
+ const r = await this.send(body);
289
+ if (r === "retry")
290
+ return;
291
+ await unlink(file).catch((e) => this.warn(`team: could not remove the sent outcome ${file}: ${e instanceof Error ? e.message : String(e)}`));
292
+ }
293
+ }
294
+ }
@@ -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.6.0";
3
3
  /** Sent on every request to the index so it can count calls per client. Carries only CLIENT_ID. */
4
4
  export declare const CLIENT_HEADER = "X-Paidfor-Client";
5
5
  export interface TelemetryPayload {
package/dist/telemetry.js CHANGED
@@ -9,7 +9,7 @@ import { createHash } from "node:crypto";
9
9
  import { appendFile, mkdir } from "node:fs/promises";
10
10
  import { join } from "node:path";
11
11
  import { REFUSED_OUTCOMES } from "./proof.js";
12
- export const CLIENT_ID = "x402-safe-fetch/0.4.0";
12
+ export const CLIENT_ID = "x402-safe-fetch/0.6.0";
13
13
  /** Sent on every request to the index so it can count calls per client. Carries only CLIENT_ID. */
14
14
  export const CLIENT_HEADER = "X-Paidfor-Client";
15
15
  /** sha256 hex of the URL path with any trailing slash removed. Query string and fragment never enter it. */
package/docs/telemetry.md CHANGED
@@ -19,7 +19,7 @@ No account and no key are needed to send it.
19
19
  "amount_usdc": "0.010000",
20
20
  "latency_ms": 412,
21
21
  "validator_failures": [],
22
- "client": "x402-safe-fetch/0.3.0"
22
+ "client": "x402-safe-fetch/<version>"
23
23
  }
24
24
  ```
25
25
 
@@ -32,7 +32,7 @@ No account and no key are needed to send it.
32
32
  | `amount_usdc` | Amount of the signed authorization as a 6-decimal string. `"0.000000"` when nothing was signed. |
33
33
  | `latency_ms` | Wall time of the call in milliseconds, rounded. |
34
34
  | `validator_failures` | Names of the validators that failed, for example `["http_status"]`. Names only, no evidence. |
35
- | `client` | `x402-safe-fetch/<version>`, `x402-safe-fetch/0.3.0` for this version. |
35
+ | `client` | `x402-safe-fetch/<version>`, for example `x402-safe-fetch/0.6.0`. |
36
36
 
37
37
  ## What is never sent (v1)
38
38
 
@@ -42,7 +42,9 @@ No account and no key are needed to send it.
42
42
  - The `intentId`, the request hash, or anything that links two calls together.
43
43
  - Validator evidence, error messages, or seller response text.
44
44
 
45
- Calls to free resources (no 402) and replays of a stored intent send nothing.
45
+ Calls to free resources (no 402) and replays of a stored intent send nothing. Nor does a payment the seller
46
+ rejected (receipt outcome `payment_rejected`, from 0.6.0: the paid request answered 402 again and nothing settled),
47
+ in either version: nothing was paid, and the row would otherwise read as a failure of the seller.
46
48
 
47
49
  ## How it is sent
48
50
 
@@ -74,7 +76,7 @@ Additive over v1. `v` is `2`, `outcome` uses the harness names, `validator_failu
74
76
  "amount_usdc": "0.002000",
75
77
  "latency_ms": 1840,
76
78
  "validator_failures": ["http_status:500"],
77
- "client": "x402-safe-fetch/0.3.0",
79
+ "client": "x402-safe-fetch/<version>",
78
80
  "proof": {
79
81
  "network": "eip155:8453",
80
82
  "scheme": "exact",
@@ -104,7 +106,7 @@ Outcomes (`outcome`), mapped like the harness classifier, first match wins:
104
106
  | v2 outcome | When |
105
107
  | --- | --- |
106
108
  | `duplicate` | More than one settlement observed for one intent. The client sends one paid request per intent, so in practice it never sees this. |
107
- | `error` | The settlement header says `success: false` and the answer was not 2xx: the seller rejected the payment (the harness's `not_paid`). Proof is still sent, so the index can confirm nothing moved. |
109
+ | `error` | The settlement header says `success: false` and the answer was neither 2xx nor 402: the seller rejected the payment (the harness's `not_paid`). Proof is still sent, so the index can confirm nothing moved. A 402 with no settlement, or with `success: false`, is `payment_rejected` on the receipt and sends no row (0.6.0). |
108
110
  | `non_delivery` | A non-2xx answer after the payment (even with `http_status` turned off), or `non_empty`, `content_type` or `not_truncated` failed. |
109
111
  | `wrong_goods` | A schema, entity or freshness validator failed. This client ships none of them, so it does not send this today. |
110
112
  | `overcharge` | Paid more than 1.1x the reference (index listed price, else the last price paid). Only possible if `maxOverListedRatio` was raised. |
@@ -133,7 +135,7 @@ settled payment; the v2 row adds the link from that payment to the seller host,
133
135
  failures and response hash. Bodies, request parameters, headers, the intent id and validator evidence are never
134
136
  sent in either version. `"verified"` requires an https `indexUrl` (loopback excepted), and no telemetry request
135
137
  follows a redirect. Each receipt stores the same `proof` and, in `"verified"` mode,
136
- `verification_url` = `{indexUrl}/telemetry/<payer>/<nonce>` (404 until the index serves that route).
138
+ `verification_url` = `{indexUrl}/telemetry/<payer>/<nonce>`, which shows whether the index verified the row.
137
139
 
138
140
  ## tx_only (report-only)
139
141
 
@@ -151,7 +153,7 @@ Base settlement header, one object goes to `POST {indexUrl}/telemetry` (default
151
153
  "outcome": "ok",
152
154
  "latency_ms": 412,
153
155
  "validator_failures": [],
154
- "client": "x402-safe-fetch/0.3.0",
156
+ "client": "x402-safe-fetch/<version>",
155
157
  "proof": { "network": "eip155:8453", "tx_hash": "0x<settlement transaction hash>" }
156
158
  }
157
159
  ```
@@ -168,7 +170,7 @@ Base settlement header, one object goes to `POST {indexUrl}/telemetry` (default
168
170
  No payer, pay-to, nonce, amount or signature is sent: the index reads the payer, the recipient and the amount from the
169
171
  transaction on Base, and the report counts only once that transaction is a USDC transfer to the seller. The index
170
172
  answers `verified`, `pending` or a 422 with the reason; one transaction is one row across every channel. The request
171
- carries `X-Paidfor-Client: x402-safe-fetch/0.3.0`, waits up to 10 seconds (the index checks the chain before
173
+ carries `X-Paidfor-Client: x402-safe-fetch/<version>`, waits up to 10 seconds (the index checks the chain before
172
174
  answering), never follows a redirect, and needs an https `indexUrl` (loopback excepted). Failures are counted in
173
175
  `<receiptsDir>/debug.log` when you pass a `receiptsDir`, otherwise nowhere. The same row is what the paidfor MCP tool
174
176
  `report_x402_payment` and the paidfor skill send.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@paidfor/x402-safe-fetch",
3
- "version": "0.4.0",
3
+ "version": "0.6.0",
4
4
  "description": "Drop-in wrapper around @x402/fetch that refuses overpriced quotes and bad sellers, never pays twice for one intent, and checks what it bought.",
5
5
  "type": "module",
6
6
  "license": "MIT",