@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/CHANGELOG.md +59 -0
- package/README.md +108 -10
- package/dist/errors.d.ts +13 -0
- package/dist/errors.js +15 -0
- package/dist/index.d.ts +2 -1
- package/dist/index.js +2 -1
- package/dist/intents.d.ts +19 -1
- package/dist/intents.js +7 -0
- package/dist/proof.js +2 -1
- package/dist/receipt.d.ts +16 -2
- package/dist/safe-fetch.d.ts +26 -1
- package/dist/safe-fetch.js +271 -15
- package/dist/team.d.ts +178 -0
- package/dist/team.js +294 -0
- package/dist/telemetry.d.ts +1 -1
- package/dist/telemetry.js +1 -1
- package/docs/telemetry.md +10 -8
- package/package.json +1 -1
package/dist/safe-fetch.js
CHANGED
|
@@ -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 { IntentConflictError, IntentIndeterminateError, PaymentRefusedError, SafeFetchError, TeamRefusedError } from "./errors.js";
|
|
19
19
|
import { UNKNOWN_SELLER_NOTE, checkIndex } from "./index-client.js";
|
|
20
20
|
import { IntentStore } from "./intents.js";
|
|
21
21
|
import { PriceBook, USDC_BY_NETWORK, atomicToUsdc, exceedsRatio, quoteRatio, resourceKey, usdToAtomic, usdcStringToAtomic } from "./price.js";
|
|
22
22
|
import { DEFAULT_MAX_RATIO, REFUSED_OUTCOMES, buildProof, failureLabels, harnessOutcome } from "./proof.js";
|
|
23
23
|
import { writeReceipt } from "./receipt.js";
|
|
24
|
+
import { PROJECT_RULE, TEAM_ORIGIN, TeamClient, cleanProject, 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,74 @@ 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
|
+
/** A project tag as the server takes it, or a TypeError naming where the bad one came from. */
|
|
76
|
+
function projectTag(v, from) {
|
|
77
|
+
const p = cleanProject(v);
|
|
78
|
+
if (p === null)
|
|
79
|
+
throw new TypeError(`safeFetch: ${from} ${JSON.stringify(v)} is not a project tag: ${PROJECT_RULE}`);
|
|
80
|
+
return p;
|
|
81
|
+
}
|
|
82
|
+
/** `team`, or PAIDFOR_TEAM_KEY (and PAIDFOR_PROJECT) when neither `team` nor `authorize` is given. */
|
|
83
|
+
function resolveTeam(o) {
|
|
84
|
+
if (o.team === false)
|
|
85
|
+
return undefined;
|
|
86
|
+
if (o.team !== undefined) {
|
|
87
|
+
if (!o.team || typeof o.team !== "object" || typeof o.team.key !== "string" || !o.team.key.trim()) {
|
|
88
|
+
throw new TypeError("safeFetch: team must be { key: string, origin?: string, project?: string } or false");
|
|
89
|
+
}
|
|
90
|
+
if (o.authorize)
|
|
91
|
+
throw new TypeError("safeFetch: pass team or authorize, not both (team supplies its own authorize)");
|
|
92
|
+
const project = o.team.project === undefined ? undefined : projectTag(o.team.project, "team.project");
|
|
93
|
+
return { team: o.team, fromEnv: false, project };
|
|
94
|
+
}
|
|
95
|
+
if (o.authorize)
|
|
96
|
+
return undefined; // the caller asks someone itself; the environment is not consulted
|
|
97
|
+
const env = typeof process !== "undefined" ? process.env : undefined;
|
|
98
|
+
const key = env?.PAIDFOR_TEAM_KEY?.trim();
|
|
99
|
+
if (!key)
|
|
100
|
+
return undefined;
|
|
101
|
+
// An empty PAIDFOR_PROJECT is the same as none; anything else must be a tag the server takes.
|
|
102
|
+
const rawProject = env?.PAIDFOR_PROJECT;
|
|
103
|
+
const project = rawProject === undefined || !rawProject.trim() ? undefined : projectTag(rawProject, "PAIDFOR_PROJECT");
|
|
104
|
+
return { team: { key }, fromEnv: true, project };
|
|
105
|
+
}
|
|
106
|
+
/** Refusals the client makes by itself before the team is asked; the team is told about them (POST /v1/team/refusals). */
|
|
107
|
+
const LOCAL_REFUSALS = new Set(["refused_verdict", "refused_ratio", "refused_max_per_call"]);
|
|
108
|
+
const NONCE_RE = /^0x[0-9a-fA-F]{64}$/;
|
|
109
|
+
function teamReceipt(origin, d) {
|
|
110
|
+
return {
|
|
111
|
+
origin,
|
|
112
|
+
decision: d.kind,
|
|
113
|
+
auth_ref: d.kind === "approve" ? d.auth_ref : null,
|
|
114
|
+
reason: d.kind === "decline" ? d.reason : null,
|
|
115
|
+
message: d.kind === "approve" ? null : d.message || null,
|
|
116
|
+
approve_url: d.kind === "needs_approval" ? d.approve_url : null,
|
|
117
|
+
expires_at: d.kind === "needs_approval" ? d.expires_at : null,
|
|
118
|
+
ledger_id: d.ledger_id ?? null,
|
|
119
|
+
warnings: d.warnings,
|
|
120
|
+
usage: d.usage ?? null,
|
|
121
|
+
outcome_report: null,
|
|
122
|
+
};
|
|
123
|
+
}
|
|
124
|
+
/** An ISO time for Unix seconds, or the bare number; never throws. */
|
|
125
|
+
function unixTime(s) {
|
|
126
|
+
const d = new Date(s * 1000);
|
|
127
|
+
return Number.isFinite(d.getTime()) ? d.toISOString() : `Unix time ${String(s)}`;
|
|
128
|
+
}
|
|
129
|
+
/** The refusal text for a decision that is not an approval. */
|
|
130
|
+
function teamMessage(d, intentId) {
|
|
131
|
+
switch (d.kind) {
|
|
132
|
+
case "decline":
|
|
133
|
+
return `declined by your team's rules (${d.reason}): ${d.message}${d.retry_after !== undefined ? ` Ask again after ${unixTime(d.retry_after)}.` : ""}`;
|
|
134
|
+
case "needs_approval":
|
|
135
|
+
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}` : ""}`;
|
|
136
|
+
case "already_settled":
|
|
137
|
+
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.`;
|
|
138
|
+
case "failed":
|
|
139
|
+
return `the team's rules could not be checked: ${d.message} Calling again with intentId "${intentId}" is safe.`;
|
|
140
|
+
}
|
|
141
|
+
}
|
|
73
142
|
/** Verified rows carry the payer and nonce, so they only go over https, or to this machine. */
|
|
74
143
|
function isSecureOrLoopback(url) {
|
|
75
144
|
try {
|
|
@@ -108,6 +177,7 @@ export function safeFetch(wallet, options) {
|
|
|
108
177
|
const maxAtomic = usdToAtomic(options.maxPerCallUsd);
|
|
109
178
|
const intents = new IntentStore(receiptsDir);
|
|
110
179
|
const prices = new PriceBook(receiptsDir);
|
|
180
|
+
const teamConf = resolveTeam(options);
|
|
111
181
|
const warn = (msg) => {
|
|
112
182
|
try {
|
|
113
183
|
logger.warn(`x402-safe-fetch: ${msg}`);
|
|
@@ -116,8 +186,24 @@ export function safeFetch(wallet, options) {
|
|
|
116
186
|
/* ignore */
|
|
117
187
|
}
|
|
118
188
|
};
|
|
119
|
-
|
|
189
|
+
const noticeOpt = options.telemetryNotice ?? true;
|
|
190
|
+
if (telemetry === "verified" && noticeOpt !== false)
|
|
120
191
|
void verifiedNotice();
|
|
192
|
+
const team = teamConf
|
|
193
|
+
? new TeamClient({
|
|
194
|
+
origin: teamConf.team.origin ?? TEAM_ORIGIN,
|
|
195
|
+
key: teamConf.team.key,
|
|
196
|
+
queueDir: join(receiptsDir, "team-outcomes"),
|
|
197
|
+
fetch: baseFetch,
|
|
198
|
+
warn,
|
|
199
|
+
...(teamConf.team.authorizeTimeoutMs !== undefined ? { authorizeTimeoutMs: teamConf.team.authorizeTimeoutMs } : {}),
|
|
200
|
+
...(teamConf.team.reportTimeoutMs !== undefined ? { reportTimeoutMs: teamConf.team.reportTimeoutMs } : {}),
|
|
201
|
+
})
|
|
202
|
+
: undefined;
|
|
203
|
+
if (team && teamConf?.fromEnv && !envNoticeShown) {
|
|
204
|
+
envNoticeShown = true;
|
|
205
|
+
warn(`team mode is on from PAIDFOR_TEAM_KEY: every payment asks ${team.origin} first. Pass team: false to turn it off.`);
|
|
206
|
+
}
|
|
121
207
|
/** Once per receipts directory: say what verified telemetry sends and where it is documented. */
|
|
122
208
|
async function verifiedNotice() {
|
|
123
209
|
const marker = join(receiptsDir, ".verified-telemetry-notice");
|
|
@@ -128,10 +214,20 @@ export function safeFetch(wallet, options) {
|
|
|
128
214
|
catch {
|
|
129
215
|
/* first run */
|
|
130
216
|
}
|
|
131
|
-
|
|
217
|
+
const text = 'telemetry: "verified" sends each purchase outcome with its proof of payment (payer address, nonce, pay-to, tx hash) ' +
|
|
132
218
|
`to ${indexUrl}/telemetry so the index can check it on Base. No bodies, request parameters, IP or identity. ` +
|
|
133
219
|
'See "What verified telemetry sends and why": https://www.npmjs.com/package/@paidfor/x402-safe-fetch#what-verified-telemetry-sends-and-why ' +
|
|
134
|
-
'(set telemetry: "anonymous" or "off" to change it). Shown once.'
|
|
220
|
+
'(set telemetry: "anonymous" or "off" to change it). Shown once.';
|
|
221
|
+
if (typeof noticeOpt === "function") {
|
|
222
|
+
try {
|
|
223
|
+
noticeOpt(`x402-safe-fetch: ${text}`);
|
|
224
|
+
}
|
|
225
|
+
catch {
|
|
226
|
+
/* ignore */
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
else
|
|
230
|
+
warn(text);
|
|
135
231
|
try {
|
|
136
232
|
await mkdir(receiptsDir, { recursive: true });
|
|
137
233
|
await writeFile(marker, `${new Date().toISOString()}\n`);
|
|
@@ -153,6 +249,9 @@ export function safeFetch(wallet, options) {
|
|
|
153
249
|
function emitTelemetry(r) {
|
|
154
250
|
if (telemetry === "off" || !indexUrl)
|
|
155
251
|
return;
|
|
252
|
+
// Nothing was paid and the seller is not at fault for a wallet that cannot pay; the contract has no outcome for it.
|
|
253
|
+
if (r.outcome === "payment_rejected")
|
|
254
|
+
return;
|
|
156
255
|
try {
|
|
157
256
|
const payload = telemetry === "verified"
|
|
158
257
|
? buildPayloadV2({
|
|
@@ -238,6 +337,7 @@ export function safeFetch(wallet, options) {
|
|
|
238
337
|
tx_hash: null,
|
|
239
338
|
nonce: null,
|
|
240
339
|
payer: null,
|
|
340
|
+
valid_before: null,
|
|
241
341
|
proof: null,
|
|
242
342
|
reported_outcome: null,
|
|
243
343
|
verification_url: null,
|
|
@@ -276,6 +376,7 @@ export function safeFetch(wallet, options) {
|
|
|
276
376
|
r.tx_hash = original.tx_hash;
|
|
277
377
|
r.nonce = original.nonce;
|
|
278
378
|
r.payer = original.payer ?? null;
|
|
379
|
+
r.valid_before = original.valid_before ?? null;
|
|
279
380
|
r.proof = original.proof ?? null;
|
|
280
381
|
r.reported_outcome = original.reported_outcome ?? null;
|
|
281
382
|
r.verification_url = original.verification_url ?? null;
|
|
@@ -287,14 +388,17 @@ export function safeFetch(wallet, options) {
|
|
|
287
388
|
const body = Buffer.from(stored.body_base64, "base64");
|
|
288
389
|
return wrapResponse(stored.status, stored.statusText, stored.headers, body, stored.url || req.url, r);
|
|
289
390
|
}
|
|
290
|
-
async function live(lease, req, r, t0) {
|
|
391
|
+
async function live(lease, req, r, t0, authorize) {
|
|
291
392
|
let quoteResult;
|
|
292
393
|
let indexP;
|
|
293
394
|
let idx;
|
|
294
395
|
let quote;
|
|
295
396
|
let approved;
|
|
296
397
|
let refusal;
|
|
398
|
+
// The nonce (and, from an approval, the deadline) to sign instead of the SDK's own.
|
|
297
399
|
let auth;
|
|
400
|
+
// An earlier attempt of this intent was signed and rejected; that authorization may still be settled until its deadline.
|
|
401
|
+
const priorRejected = lease.record.rejected;
|
|
298
402
|
let authSigned = false;
|
|
299
403
|
let failure;
|
|
300
404
|
let signingStarted = false;
|
|
@@ -317,16 +421,18 @@ export function safeFetch(wallet, options) {
|
|
|
317
421
|
typeof q.asset === "string" &&
|
|
318
422
|
q.asset.toLowerCase() === usdc &&
|
|
319
423
|
(q.extra?.assetTransferMethod ?? "eip3009") === "eip3009");
|
|
320
|
-
// With `authorize` the approval decides the nonce and deadline;
|
|
321
|
-
// here at signing and on the signed payload in
|
|
322
|
-
|
|
424
|
+
// With `authorize` the approval decides the nonce and deadline; after a rejected payment the old nonce is signed
|
|
425
|
+
// again. The SDK has no way to take either, so they are set here at signing and on the signed payload in
|
|
426
|
+
// onAfterPaymentCreation.
|
|
427
|
+
const schemeSigner = !authorize && !priorRejected
|
|
323
428
|
? signer
|
|
324
429
|
: {
|
|
325
430
|
address: signer.address,
|
|
326
431
|
signTypedData: async (m) => {
|
|
327
432
|
if (!auth || m.primaryType !== "TransferWithAuthorization")
|
|
328
433
|
throw new Error("x402-safe-fetch: refusing to sign without an approval");
|
|
329
|
-
const
|
|
434
|
+
const message = { ...m.message, nonce: auth.nonce, ...(auth.validBefore !== undefined ? { validBefore: auth.validBefore } : {}) };
|
|
435
|
+
const signature = await signer.signTypedData({ ...m, message });
|
|
330
436
|
authSigned = true;
|
|
331
437
|
return signature;
|
|
332
438
|
},
|
|
@@ -416,11 +522,38 @@ export function safeFetch(wallet, options) {
|
|
|
416
522
|
};
|
|
417
523
|
return { abort: true, reason: refusal.message };
|
|
418
524
|
}
|
|
419
|
-
// 4.
|
|
420
|
-
|
|
525
|
+
// 4. A rejected authorization of this intent is reused only by the same payer, on the same network, for the same
|
|
526
|
+
// asset. EIP-3009 nonces are per payer and per token contract: the same nonce signed by another wallet, on another
|
|
527
|
+
// chain or for another token is a separate authorization, and both could settle. A changed pay-to or amount does
|
|
528
|
+
// not break this (one payer, one token, one nonce: only one of the two can ever be used), so it is allowed.
|
|
529
|
+
// Checked before the approval is asked for, so a refused retry holds no reservation.
|
|
530
|
+
if (priorRejected) {
|
|
531
|
+
const differs = [];
|
|
532
|
+
if (!priorRejected.payer)
|
|
533
|
+
differs.push("the payer was not recorded (an intent file from before 0.6.0)");
|
|
534
|
+
else {
|
|
535
|
+
if (priorRejected.payer.toLowerCase() !== signer.address.toLowerCase())
|
|
536
|
+
differs.push(`payer ${priorRejected.payer} vs this wallet ${signer.address.toLowerCase()}`);
|
|
537
|
+
if (priorRejected.network !== caip2Network(norm))
|
|
538
|
+
differs.push(`network ${priorRejected.network ?? "unknown"} vs ${caip2Network(norm)}`);
|
|
539
|
+
if ((priorRejected.asset ?? "").toLowerCase() !== norm.asset.toLowerCase())
|
|
540
|
+
differs.push(`asset ${priorRejected.asset ?? "unknown"} vs ${norm.asset.toLowerCase()}`);
|
|
541
|
+
}
|
|
542
|
+
if (differs.length) {
|
|
543
|
+
failure = {
|
|
544
|
+
code: "intent_conflict",
|
|
545
|
+
message: `intent ${r.intent_id} has a rejected authorization (nonce ${priorRejected.nonce}) that cannot be reused here: ${differs.join("; ")}. ` +
|
|
546
|
+
"Nothing was signed. Check on chain that the old authorization was not used (authorizationState(payer, nonce) on the USDC contract is false; " +
|
|
547
|
+
"true means used or cancelled, and only its AuthorizationUsed event and USDC Transfer show a payment), then use a new intentId.",
|
|
548
|
+
};
|
|
549
|
+
return { abort: true, reason: failure.message };
|
|
550
|
+
}
|
|
551
|
+
}
|
|
552
|
+
// 5. Last, so a payment refused above never takes up a reservation with whoever approves it.
|
|
553
|
+
if (authorize) {
|
|
421
554
|
let answer;
|
|
422
555
|
try {
|
|
423
|
-
answer = await
|
|
556
|
+
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
557
|
}
|
|
425
558
|
catch (e) {
|
|
426
559
|
answer = { approve: false, message: `could not get an approval: ${errMsg(e)}` };
|
|
@@ -434,6 +567,28 @@ export function safeFetch(wallet, options) {
|
|
|
434
567
|
}
|
|
435
568
|
auth = { nonce: answer.nonce, validBefore: BigInt(answer.validBefore) };
|
|
436
569
|
}
|
|
570
|
+
// 6. A rejected authorization of this intent can still be used until its deadline. Signing its nonce again (same
|
|
571
|
+
// payer, network and asset, checked above) means at most one of the two can ever move money. An approval with
|
|
572
|
+
// another nonce waits for that deadline; the deadline only stops later use of the old signature and does not show
|
|
573
|
+
// that it was never used. authorizationState(payer, nonce) false on chain shows that; true means used or cancelled,
|
|
574
|
+
// and only the AuthorizationUsed event with its USDC Transfer shows a payment (see the README).
|
|
575
|
+
if (priorRejected) {
|
|
576
|
+
if (!NONCE_RE.test(priorRejected.nonce)) {
|
|
577
|
+
failure = { code: "sdk", message: `intent ${r.intent_id} has a rejected authorization with an unreadable nonce; not signing again. Use a new intentId after checking the chain.` };
|
|
578
|
+
return { abort: true, reason: failure.message };
|
|
579
|
+
}
|
|
580
|
+
if (!auth)
|
|
581
|
+
auth = { nonce: priorRejected.nonce };
|
|
582
|
+
else if (auth.nonce.toLowerCase() !== priorRejected.nonce.toLowerCase() && (priorRejected.valid_before === null || priorRejected.valid_before > Date.now() / 1000)) {
|
|
583
|
+
const until = priorRejected.valid_before === null ? "an unknown deadline" : unixTime(priorRejected.valid_before);
|
|
584
|
+
refusal = {
|
|
585
|
+
code: "refused_authorize",
|
|
586
|
+
message: `refused to pay ${usd} for ${req.url}: an earlier payment for intent ${r.intent_id} (nonce ${priorRejected.nonce}) was rejected by the seller but can still be settled until ${until}, and the approval names a different nonce. Call again after that time, once authorizationState(payer, nonce) on the USDC contract is false (never used): the deadline alone does not show that.`,
|
|
587
|
+
sellerUrl: i.seller_url,
|
|
588
|
+
};
|
|
589
|
+
return { abort: true, reason: refusal.message };
|
|
590
|
+
}
|
|
591
|
+
}
|
|
437
592
|
approved = amount;
|
|
438
593
|
try {
|
|
439
594
|
await lease.update({ phase: "signing", amount_atomic: amount.toString(), pay_to: norm.payTo });
|
|
@@ -468,9 +623,12 @@ export function safeFetch(wallet, options) {
|
|
|
468
623
|
throw new Error(failure.message);
|
|
469
624
|
}
|
|
470
625
|
a.nonce = auth.nonce;
|
|
471
|
-
|
|
626
|
+
if (auth.validBefore !== undefined)
|
|
627
|
+
a.validBefore = auth.validBefore.toString();
|
|
472
628
|
}
|
|
473
629
|
r.nonce = String(a.nonce);
|
|
630
|
+
const vb = Number(a.validBefore);
|
|
631
|
+
r.valid_before = Number.isSafeInteger(vb) ? vb : null;
|
|
474
632
|
r.payer = String(a.from).toLowerCase();
|
|
475
633
|
r.amount_usdc = atomicToUsdc(BigInt(value));
|
|
476
634
|
try {
|
|
@@ -579,6 +737,8 @@ export function safeFetch(wallet, options) {
|
|
|
579
737
|
await persistReceipt(r);
|
|
580
738
|
if (quoteResult)
|
|
581
739
|
emitTelemetry(r);
|
|
740
|
+
if (code === "intent_conflict")
|
|
741
|
+
throw new IntentConflictError(code, `x402-safe-fetch: ${message}`, r, { cause: e });
|
|
582
742
|
throw new SafeFetchError(code, `x402-safe-fetch: ${message}`, r, { cause: e });
|
|
583
743
|
}
|
|
584
744
|
// Response in hand. Read up to MAX_BODY_BYTES for the validators; the caller still gets the full body.
|
|
@@ -614,9 +774,44 @@ export function safeFetch(wallet, options) {
|
|
|
614
774
|
await persistReceipt(r);
|
|
615
775
|
return wrapResponse(res.status, res.statusText, res.headers, read.callerBody, res.url || req.url, r);
|
|
616
776
|
}
|
|
617
|
-
r.paid = true;
|
|
618
777
|
const st = decodeSettlementHeader(record.headers);
|
|
619
778
|
r.settlement = { header: st.raw ?? null, version: st.version ?? null, parsed: st.parsed ?? null, parse_error: st.parseError ?? null };
|
|
779
|
+
// The seller answered the paid request with another 402 and settled nothing (no settlement header, or one saying
|
|
780
|
+
// it failed): an empty wallet, an expired or refused authorization. Nothing was paid. An unreadable header is not
|
|
781
|
+
// taken as a rejection, since it may name a settlement.
|
|
782
|
+
if (res.status === 402 && (st.raw === undefined || st.parsed?.success === false)) {
|
|
783
|
+
finish(r, t0, "payment_rejected");
|
|
784
|
+
const why = st.parsed?.errorReason ? ` (${String(st.parsed.errorReason).slice(0, 200)})` : "";
|
|
785
|
+
// The same nonce signed again keeps the LATER of the two deadlines: the seller may still hold the earlier
|
|
786
|
+
// signature, and until it lapses no other nonce may be signed. Unknown (null) on either side never passes. A
|
|
787
|
+
// different amount or pay-to on the earlier signature does not matter: one payer, one token, one nonce, so only
|
|
788
|
+
// one of the signatures under it can ever settle; the deadline is the only thing that has to be carried over.
|
|
789
|
+
const sameNonce = priorRejected !== undefined && r.nonce !== null && priorRejected.nonce.toLowerCase() === r.nonce.toLowerCase();
|
|
790
|
+
const newVb = r.valid_before ?? null;
|
|
791
|
+
const keptVb = !sameNonce ? newVb : priorRejected.valid_before === null || newVb === null ? null : Math.max(priorRejected.valid_before, newVb);
|
|
792
|
+
const until = keptVb !== null ? unixTime(keptVb) : "an unknown deadline";
|
|
793
|
+
r.error = {
|
|
794
|
+
code: "payment_rejected",
|
|
795
|
+
message: `the seller answered the paid request for ${req.url} with HTTP 402${why} and settled nothing, so nothing was paid. ` +
|
|
796
|
+
`The signed authorization (payer ${r.payer}, nonce ${r.nonce}) can still be used until ${until}; that deadline only ` +
|
|
797
|
+
"stops later use. authorizationState(payer, nonce) on the USDC contract is false while the nonce was never used; " +
|
|
798
|
+
"true means used or cancelled, so look for its AuthorizationUsed event and USDC Transfer before counting it as paid. " +
|
|
799
|
+
`Calling again with intent ${r.intent_id} from the same wallet signs that same nonce, so at most one of the two can settle.`,
|
|
800
|
+
};
|
|
801
|
+
attachProof(r, undefined, st);
|
|
802
|
+
await persistReceipt(r);
|
|
803
|
+
try {
|
|
804
|
+
await lease.update({
|
|
805
|
+
phase: "rejected",
|
|
806
|
+
rejected: { nonce: r.nonce ?? "", valid_before: keptVb, payer: r.payer ?? "", network, asset: (r.quote?.asset ?? "").toLowerCase() },
|
|
807
|
+
});
|
|
808
|
+
}
|
|
809
|
+
catch (e) {
|
|
810
|
+
warn(`rejected payment for intent ${r.intent_id} could not be recorded (${errMsg(e)}); a retry with this intentId will refuse rather than sign again`);
|
|
811
|
+
}
|
|
812
|
+
return wrapResponse(res.status, res.statusText, res.headers, read.callerBody, res.url || req.url, r);
|
|
813
|
+
}
|
|
814
|
+
r.paid = true;
|
|
620
815
|
const tx = st.parsed?.transaction;
|
|
621
816
|
r.tx_hash = typeof tx === "string" && TX_HASH_RE.test(tx) ? tx : null;
|
|
622
817
|
finish(r, t0, r.validator_failures.length ? "validator_failed" : "ok");
|
|
@@ -647,13 +842,74 @@ export function safeFetch(wallet, options) {
|
|
|
647
842
|
const req = await normalizeRequest(input, init);
|
|
648
843
|
const requestHash = hashRequest(req);
|
|
649
844
|
const intentId = call.intentId ?? randomUUID();
|
|
845
|
+
// Owed team reports go first: until the server has them it answers the same purchase with pending_settlement.
|
|
846
|
+
if (team)
|
|
847
|
+
await team.flush();
|
|
650
848
|
const lease = await intents.acquire(intentId, requestHash);
|
|
651
849
|
try {
|
|
652
850
|
const r = baseReceipt(req, intentId, requestHash, t0);
|
|
653
|
-
|
|
851
|
+
if (lease.replay)
|
|
852
|
+
return await replay(lease, req, r, t0);
|
|
853
|
+
if (!team)
|
|
854
|
+
return await live(lease, req, r, t0, options.authorize);
|
|
855
|
+
return await teamLive(team, lease, req, r, t0);
|
|
654
856
|
}
|
|
655
857
|
finally {
|
|
656
858
|
await lease.release();
|
|
657
859
|
}
|
|
658
860
|
};
|
|
861
|
+
/** live() with the team asked before signing, and every approval's outcome reported after. */
|
|
862
|
+
async function teamLive(team, lease, req, r, t0) {
|
|
863
|
+
const project = teamConf?.project;
|
|
864
|
+
let decision;
|
|
865
|
+
const authorize = async (q) => {
|
|
866
|
+
const d = await team.authorize({ wallet: q.payer, intent_id: q.intentId, resource_url: q.url, pay_to: q.payTo, amount_atomic: q.amountAtomic, network: q.network, asset: q.asset, scheme: q.scheme, protocol: "x402", ...(project ? { project } : {}) });
|
|
867
|
+
decision = d;
|
|
868
|
+
r.team = teamReceipt(team.origin, d);
|
|
869
|
+
return d.kind === "approve" ? { approve: true, nonce: d.auth_ref, validBefore: d.valid_before } : { approve: false, message: teamMessage(d, q.intentId) };
|
|
870
|
+
};
|
|
871
|
+
/** Say what happened to an approved payment, paid or not. Nothing to say when nothing was approved. */
|
|
872
|
+
const settle = async (rec) => {
|
|
873
|
+
if (decision?.kind !== "approve")
|
|
874
|
+
return;
|
|
875
|
+
if (!rec) {
|
|
876
|
+
warn(`no receipt for approved intent ${r.intent_id}, so no team outcome was reported; the approval keeps counting against the budgets`);
|
|
877
|
+
return;
|
|
878
|
+
}
|
|
879
|
+
const state = await team.report(outcomeFor(rec, signer.address, decision.auth_ref));
|
|
880
|
+
if (rec.team)
|
|
881
|
+
rec.team.outcome_report = state;
|
|
882
|
+
};
|
|
883
|
+
let res;
|
|
884
|
+
try {
|
|
885
|
+
res = await live(lease, req, r, t0, authorize);
|
|
886
|
+
}
|
|
887
|
+
catch (e) {
|
|
888
|
+
if (e instanceof PaymentRefusedError && LOCAL_REFUSALS.has(e.code) && e.receipt?.quote) {
|
|
889
|
+
// Refused before the team was asked: tell it, so the ledger counts what was saved. Never awaited, never thrown.
|
|
890
|
+
const q = e.receipt.quote;
|
|
891
|
+
void team.reportRefusal({
|
|
892
|
+
wallet: signer.address,
|
|
893
|
+
intent_id: e.receipt.intent_id,
|
|
894
|
+
resource_url: e.receipt.url,
|
|
895
|
+
pay_to: q.pay_to,
|
|
896
|
+
amount_atomic: q.amount_atomic,
|
|
897
|
+
network,
|
|
898
|
+
asset: q.asset,
|
|
899
|
+
scheme: q.scheme,
|
|
900
|
+
protocol: "x402",
|
|
901
|
+
reason: e.code,
|
|
902
|
+
verdict: e.receipt.seller.verdict,
|
|
903
|
+
...(project ? { project } : {}),
|
|
904
|
+
});
|
|
905
|
+
}
|
|
906
|
+
await settle(e instanceof SafeFetchError ? e.receipt : undefined);
|
|
907
|
+
if (decision && e instanceof PaymentRefusedError && e.code === "refused_authorize") {
|
|
908
|
+
throw new TeamRefusedError(decision, e.message, e.sellerUrl, e.receipt);
|
|
909
|
+
}
|
|
910
|
+
throw e;
|
|
911
|
+
}
|
|
912
|
+
await settle(res.receipt);
|
|
913
|
+
return res;
|
|
914
|
+
}
|
|
659
915
|
}
|
package/dist/team.d.ts
ADDED
|
@@ -0,0 +1,178 @@
|
|
|
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
|
+
/** 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;
|
|
10
|
+
/** `team` in SafeFetchOptions. */
|
|
11
|
+
export interface TeamOptions {
|
|
12
|
+
/** The team key, `pft_...`. Sent only to `origin`, as `Authorization: Bearer`, never to a seller and never logged. */
|
|
13
|
+
key: string;
|
|
14
|
+
/** Where the team API lives. Default "https://paidfor.dev". https only, except localhost / 127.0.0.1 / [::1]. */
|
|
15
|
+
origin?: string;
|
|
16
|
+
/** How long to wait for a decision before refusing. Default 10000 ms. */
|
|
17
|
+
authorizeTimeoutMs?: number;
|
|
18
|
+
/** How long each outcome report may take. Default 5000 ms. */
|
|
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;
|
|
26
|
+
}
|
|
27
|
+
/** A notice a newer server may attach to a decision, such as a budget nearly used up. */
|
|
28
|
+
export interface TeamWarning {
|
|
29
|
+
code: string;
|
|
30
|
+
message: string;
|
|
31
|
+
upgrade_url?: string;
|
|
32
|
+
}
|
|
33
|
+
/** Optional fields any decision may carry. Older servers send none. */
|
|
34
|
+
export interface TeamDecisionExtras {
|
|
35
|
+
/** Always an array; empty when the server sent none. */
|
|
36
|
+
warnings: TeamWarning[];
|
|
37
|
+
/** The server's spend summary, passed through as sent, when there is one. */
|
|
38
|
+
usage?: Record<string, unknown>;
|
|
39
|
+
/** The ledger row for this decision, when the server named one. */
|
|
40
|
+
ledger_id?: string;
|
|
41
|
+
}
|
|
42
|
+
/** The server's answer, read strictly. Only `approve` lets a payment be signed. */
|
|
43
|
+
export type TeamDecision = ({
|
|
44
|
+
kind: "approve";
|
|
45
|
+
auth_ref: string;
|
|
46
|
+
valid_before: number;
|
|
47
|
+
} | {
|
|
48
|
+
kind: "decline";
|
|
49
|
+
reason: string;
|
|
50
|
+
message: string;
|
|
51
|
+
retry_after?: number;
|
|
52
|
+
} | {
|
|
53
|
+
kind: "needs_approval";
|
|
54
|
+
approve_url: string;
|
|
55
|
+
expires_at: string;
|
|
56
|
+
message: string;
|
|
57
|
+
} | {
|
|
58
|
+
kind: "already_settled";
|
|
59
|
+
settlement_ref: string;
|
|
60
|
+
outcome: string;
|
|
61
|
+
message: string;
|
|
62
|
+
} | {
|
|
63
|
+
kind: "failed";
|
|
64
|
+
message: string;
|
|
65
|
+
}) & TeamDecisionExtras;
|
|
66
|
+
export type TeamAuthorizeBody = {
|
|
67
|
+
wallet: string;
|
|
68
|
+
intent_id: string;
|
|
69
|
+
resource_url: string;
|
|
70
|
+
pay_to: string;
|
|
71
|
+
amount_atomic: string;
|
|
72
|
+
network: string;
|
|
73
|
+
asset: string;
|
|
74
|
+
scheme: string;
|
|
75
|
+
protocol: "x402";
|
|
76
|
+
project?: string;
|
|
77
|
+
};
|
|
78
|
+
/** What the client refused by itself, before asking the team (`POST /v1/team/refusals`). */
|
|
79
|
+
export type TeamRefusalReason = "refused_verdict" | "refused_ratio" | "refused_max_per_call";
|
|
80
|
+
export type TeamRefusalBody = Omit<TeamAuthorizeBody, "project"> & {
|
|
81
|
+
reason: TeamRefusalReason;
|
|
82
|
+
verdict?: "avoid" | "caution" | "ok" | "unknown";
|
|
83
|
+
project?: string;
|
|
84
|
+
};
|
|
85
|
+
export type TeamOutcomeBody = {
|
|
86
|
+
wallet: string;
|
|
87
|
+
intent_id: string;
|
|
88
|
+
auth_ref: string;
|
|
89
|
+
paid: boolean;
|
|
90
|
+
settlement_ref?: string;
|
|
91
|
+
outcome?: string;
|
|
92
|
+
http_status?: number;
|
|
93
|
+
response_sha256?: string;
|
|
94
|
+
};
|
|
95
|
+
/**
|
|
96
|
+
* sent: the server has it. queued: kept (on disk, or in memory when the disk write failed) and sent again before the
|
|
97
|
+
* next payment. rejected: the server refused it for good (a 4xx other than 408 / 429).
|
|
98
|
+
*/
|
|
99
|
+
export type TeamReportState = "sent" | "queued" | "rejected";
|
|
100
|
+
/** `receipt.team`: set on every call that asked the team. */
|
|
101
|
+
export interface TeamReceipt {
|
|
102
|
+
origin: string;
|
|
103
|
+
decision: TeamDecision["kind"];
|
|
104
|
+
/** The approval's reference (the signed EIP-3009 nonce), for `approve`. */
|
|
105
|
+
auth_ref: string | null;
|
|
106
|
+
reason: string | null;
|
|
107
|
+
message: string | null;
|
|
108
|
+
approve_url: string | null;
|
|
109
|
+
expires_at: string | null;
|
|
110
|
+
ledger_id: string | null;
|
|
111
|
+
warnings: TeamWarning[];
|
|
112
|
+
usage: Record<string, unknown> | null;
|
|
113
|
+
/** What happened to the outcome report. Null when nothing was approved, so there was nothing to report. */
|
|
114
|
+
outcome_report: TeamReportState | null;
|
|
115
|
+
}
|
|
116
|
+
/** What to report for a payment that was approved, from its receipt. */
|
|
117
|
+
export declare function outcomeFor(r: Receipt, wallet: string, authRef: string): TeamOutcomeBody;
|
|
118
|
+
/** A 200's body as a decision. Anything not exactly one of the contract's answers is "failed". Unknown fields are ignored. */
|
|
119
|
+
export declare function readDecision(b: unknown): TeamDecision;
|
|
120
|
+
/** The key travels in a header. Plain http is for a server on this machine only. */
|
|
121
|
+
export declare function isKeySafeOrigin(origin: string): boolean;
|
|
122
|
+
export interface TeamClientOptions {
|
|
123
|
+
/** Team API origin, e.g. "https://paidfor.dev". Must pass isKeySafeOrigin, or the constructor throws. */
|
|
124
|
+
origin: string;
|
|
125
|
+
key: string;
|
|
126
|
+
/** Where reports the server could not take are kept. Created on first use (mode 700, files 600). */
|
|
127
|
+
queueDir: string;
|
|
128
|
+
fetch?: typeof globalThis.fetch;
|
|
129
|
+
warn?: (m: string) => void;
|
|
130
|
+
authorizeTimeoutMs?: number;
|
|
131
|
+
reportTimeoutMs?: number;
|
|
132
|
+
/** Wait before the second try of a report. Default 250 ms. */
|
|
133
|
+
retryDelayMs?: number;
|
|
134
|
+
/**
|
|
135
|
+
* Also send bare queue entries (@paidfor/mcp's format, which names no origin or key) under this client's key, and
|
|
136
|
+
* delete them once the server has answered. Only for a directory whose bare entries are known to belong to this key,
|
|
137
|
+
* such as the MCP pointing at its own queue. Default false: bare entries are left untouched, because sent under another
|
|
138
|
+
* team's key they are refused for good and the report another team needs would be lost.
|
|
139
|
+
*/
|
|
140
|
+
adoptBareEntries?: boolean;
|
|
141
|
+
}
|
|
142
|
+
/** The two team calls and the report queue. safeFetch's `team` option makes one; exported for callers wiring `authorize` themselves. */
|
|
143
|
+
export declare class TeamClient {
|
|
144
|
+
readonly origin: string;
|
|
145
|
+
private readonly key;
|
|
146
|
+
private readonly keyHash;
|
|
147
|
+
private readonly queueDir;
|
|
148
|
+
private readonly fetchFn;
|
|
149
|
+
private readonly warn;
|
|
150
|
+
private readonly authorizeTimeoutMs;
|
|
151
|
+
private readonly reportTimeoutMs;
|
|
152
|
+
private readonly retryDelayMs;
|
|
153
|
+
private readonly adoptBare;
|
|
154
|
+
/** Reports that could not be written to disk; sent again like the disk queue, lost if the process ends. */
|
|
155
|
+
private readonly memory;
|
|
156
|
+
private flushing;
|
|
157
|
+
constructor(o: TeamClientOptions);
|
|
158
|
+
private post;
|
|
159
|
+
/** Never throws: anything but a 200 with a readable decision is { kind: "failed" }. */
|
|
160
|
+
authorize(body: TeamAuthorizeBody): Promise<TeamDecision>;
|
|
161
|
+
/**
|
|
162
|
+
* Tell the team about a payment this client refused before asking it, so the ledger and the bill can count what was
|
|
163
|
+
* saved. Fire-and-forget: one try, a 2 s timeout, every failure (a 404 from a server without the route included)
|
|
164
|
+
* swallowed and never logged. Never throws or rejects; the promise is returned only so tests can wait on it.
|
|
165
|
+
*/
|
|
166
|
+
reportRefusal(body: TeamRefusalBody): Promise<void>;
|
|
167
|
+
/** One try. "retry" means the server could not take it now; a 4xx will never be taken, so it is not kept. */
|
|
168
|
+
private send;
|
|
169
|
+
private queueName;
|
|
170
|
+
/** Send the outcome of an approved payment, try once more, and keep it if the server still cannot take it. */
|
|
171
|
+
report(body: TeamOutcomeBody): Promise<TeamReportState>;
|
|
172
|
+
/** Reports still owed: on disk for this origin and key, plus those kept in memory. */
|
|
173
|
+
pending(): Promise<TeamOutcomeBody[]>;
|
|
174
|
+
private diskEntries;
|
|
175
|
+
/** Send what earlier reports left behind. Stops at the first one the server cannot take now. Never throws. */
|
|
176
|
+
flush(): Promise<void>;
|
|
177
|
+
private drain;
|
|
178
|
+
}
|