@fiderail/guard 0.0.0-stage → 2.3.2

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/index.js ADDED
@@ -0,0 +1,870 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { getAssetSpec, getPrimaryAsset, getPrimaryAssetContract, normalizeChainAddress, normalizeChainName, rawAmountToDecimal, toUsdAmount, } from "@fiderail/spec";
4
+ import { createSaltedDeliveryReceiptV2, sha256Hex, } from "@fiderail/zk-types";
5
+ import { clampPolicy, computeDeliveryReceipt, computePaymentFingerprint, computeQuoteDigest, isAssetAllowed, normalizeEndpointKey, scanOutboundSecrets, serializeBody, validateMandateChain, } from "@fiderail/core";
6
+ import { verifyEd25519MandateSignature } from "./mandate.js";
7
+ import { createSqliteSpendLedger } from "./sqlite-ledger.js";
8
+ export * from "./mandate.js";
9
+ export * from "./sqlite-ledger.js";
10
+ export * from "./adapters.js";
11
+ export { clampPolicy, computeDeliveryReceipt, computePaymentFingerprint, computeQuoteDigest, isAssetAllowed, normalizeEndpointKey, scanOutboundSecrets, };
12
+ export const CANONICAL_USDC_ASSETS = Object.freeze({
13
+ base: getPrimaryAssetContract("base").toLowerCase(),
14
+ solana: getPrimaryAssetContract("solana"),
15
+ arbitrum: getPrimaryAssetContract("arbitrum").toLowerCase(),
16
+ polygon: getPrimaryAssetContract("polygon").toLowerCase(),
17
+ });
18
+ function getUtcDayKey(nowDate = new Date()) {
19
+ return nowDate.toISOString().slice(0, 10);
20
+ }
21
+ /**
22
+ * Local UTC-day spend, two-phase atomic reservation, idempotency, recoverable proof cache,
23
+ * and HTTP 5xx circuit-breaker ledger. Keys and funds stay 100% local.
24
+ * Automatically upgrades to concurrent-safe SQLite WAL when `ledgerPath` ends with `.db` / `.sqlite` / `.sqlite3`.
25
+ */
26
+ export function createSpendLedger(ledgerPath = ":memory:") {
27
+ if (typeof ledgerPath === "string" &&
28
+ /\.(?:db|sqlite|sqlite3)$/i.test(ledgerPath.trim())) {
29
+ return createSqliteSpendLedger(ledgerPath.trim());
30
+ }
31
+ const isMemory = !ledgerPath || ledgerPath === ":memory:";
32
+ let state = {};
33
+ const pendingReservations = new Map();
34
+ const recoverableProofs = new Map();
35
+ let reservationSeq = 0;
36
+ if (!isMemory && fs.existsSync(ledgerPath)) {
37
+ try {
38
+ const parsed = JSON.parse(fs.readFileSync(ledgerPath, "utf8"));
39
+ if (parsed && typeof parsed === "object")
40
+ state = parsed;
41
+ }
42
+ catch {
43
+ state = {};
44
+ }
45
+ }
46
+ function ensureMaps() {
47
+ if (!state._recentPayments || typeof state._recentPayments !== "object") {
48
+ state._recentPayments = {};
49
+ }
50
+ if (!state._endpointHealth || typeof state._endpointHealth !== "object") {
51
+ state._endpointHealth = {};
52
+ }
53
+ }
54
+ function persist() {
55
+ if (isMemory)
56
+ return;
57
+ const abs = path.resolve(ledgerPath);
58
+ fs.mkdirSync(path.dirname(abs), { recursive: true });
59
+ const tmp = `${abs}.tmp`;
60
+ fs.writeFileSync(tmp, JSON.stringify(state, null, 2), "utf8");
61
+ fs.renameSync(tmp, abs);
62
+ }
63
+ function getSpentTodayUsdc(nowDate = new Date()) {
64
+ const day = getUtcDayKey(nowDate);
65
+ return Number((state[day]?.spentUsdc || 0).toFixed(6));
66
+ }
67
+ function getPendingReservedTodayUsdc(nowDate = new Date(), nowMs = Date.now()) {
68
+ const day = getUtcDayKey(nowDate);
69
+ let total = 0;
70
+ for (const [id, r] of pendingReservations.entries()) {
71
+ if (nowMs - r.createdAtMs > 120000) {
72
+ pendingReservations.delete(id);
73
+ continue;
74
+ }
75
+ if (r.day === day)
76
+ total += r.amountUsdc;
77
+ }
78
+ return Number(total.toFixed(6));
79
+ }
80
+ function getEffectiveSpentTodayUsdc(nowDate = new Date()) {
81
+ return Number((getSpentTodayUsdc(nowDate) + getPendingReservedTodayUsdc(nowDate)).toFixed(6));
82
+ }
83
+ function getTxCountToday(nowDate = new Date()) {
84
+ const day = getUtcDayKey(nowDate);
85
+ return Number(state[day]?.txCount || 0);
86
+ }
87
+ function recordSpend(amountUsdc, nowDate = new Date()) {
88
+ const amt = Number(amountUsdc);
89
+ if (!Number.isFinite(amt) || amt <= 0)
90
+ return getSpentTodayUsdc(nowDate);
91
+ const day = getUtcDayKey(nowDate);
92
+ const prev = state[day] || { spentUsdc: 0, txCount: 0 };
93
+ state[day] = {
94
+ spentUsdc: Number((prev.spentUsdc + amt).toFixed(6)),
95
+ txCount: prev.txCount + 1,
96
+ updatedAt: nowDate.toISOString(),
97
+ };
98
+ persist();
99
+ return state[day].spentUsdc;
100
+ }
101
+ function reserveBudget(amountUsdc, maxDailyUsdc, nowDate = new Date()) {
102
+ const amt = Number(amountUsdc);
103
+ if (!Number.isFinite(amt) || amt <= 0) {
104
+ return {
105
+ ok: false,
106
+ reservationId: null,
107
+ effectiveSpentUsdc: getEffectiveSpentTodayUsdc(nowDate),
108
+ };
109
+ }
110
+ const effective = getEffectiveSpentTodayUsdc(nowDate);
111
+ const cap = Number(maxDailyUsdc);
112
+ if (Number.isFinite(cap) && effective + amt > cap + 1e-9) {
113
+ return { ok: false, reservationId: null, effectiveSpentUsdc: effective };
114
+ }
115
+ reservationSeq += 1;
116
+ const reservationId = `res_${reservationSeq}_${Date.now()}`;
117
+ pendingReservations.set(reservationId, {
118
+ day: getUtcDayKey(nowDate),
119
+ amountUsdc: Number(amt.toFixed(6)),
120
+ createdAtMs: Date.now(),
121
+ });
122
+ return {
123
+ ok: true,
124
+ reservationId,
125
+ effectiveSpentUsdc: Number((effective + amt).toFixed(6)),
126
+ };
127
+ }
128
+ function commitReservation(reservationId, nowDate = new Date()) {
129
+ const rec = pendingReservations.get(reservationId);
130
+ if (!rec)
131
+ return getSpentTodayUsdc(nowDate);
132
+ pendingReservations.delete(reservationId);
133
+ return recordSpend(rec.amountUsdc, nowDate);
134
+ }
135
+ function releaseReservation(reservationId) {
136
+ if (!reservationId)
137
+ return false;
138
+ return pendingReservations.delete(reservationId);
139
+ }
140
+ function recordRecoverableProof(fingerprint, { proofValue, quoteDigest, ttlMs = 60000, nowMs = Date.now() }) {
141
+ if (!fingerprint || !proofValue)
142
+ return;
143
+ recoverableProofs.set(fingerprint, {
144
+ proofValue,
145
+ quoteDigest,
146
+ expiresAtMs: nowMs + Math.max(1000, Number(ttlMs) || 60000),
147
+ });
148
+ }
149
+ function getRecoverableProof(fingerprint, nowMs = Date.now()) {
150
+ const rec = recoverableProofs.get(fingerprint);
151
+ if (!rec)
152
+ return null;
153
+ if (rec.expiresAtMs <= nowMs) {
154
+ recoverableProofs.delete(fingerprint);
155
+ return null;
156
+ }
157
+ return rec;
158
+ }
159
+ function clearRecoverableProof(fingerprint) {
160
+ if (!fingerprint)
161
+ return;
162
+ recoverableProofs.delete(fingerprint);
163
+ }
164
+ function checkIdempotency(fingerprint, windowMs = 60000, nowMs = Date.now()) {
165
+ ensureMaps();
166
+ if (!fingerprint || windowMs <= 0) {
167
+ return { isDuplicate: false, secondsSinceLast: null };
168
+ }
169
+ for (const [fp, entry] of Object.entries(state._recentPayments)) {
170
+ if (!entry || nowMs - Number(entry.lastPaidAtMs || 0) > Math.max(windowMs * 2, 300000)) {
171
+ delete state._recentPayments[fp];
172
+ }
173
+ }
174
+ const existing = state._recentPayments[fingerprint];
175
+ if (!existing)
176
+ return { isDuplicate: false, secondsSinceLast: null };
177
+ const elapsedMs = nowMs - Number(existing.lastPaidAtMs || 0);
178
+ if (elapsedMs >= 0 && elapsedMs < windowMs) {
179
+ return {
180
+ isDuplicate: true,
181
+ secondsSinceLast: Number((elapsedMs / 1000).toFixed(2)),
182
+ };
183
+ }
184
+ return { isDuplicate: false, secondsSinceLast: null };
185
+ }
186
+ function recordPaymentFingerprint(fingerprint, nowMs = Date.now()) {
187
+ ensureMaps();
188
+ if (!fingerprint)
189
+ return;
190
+ const prev = state._recentPayments[fingerprint] || { count: 0 };
191
+ state._recentPayments[fingerprint] = {
192
+ lastPaidAtMs: nowMs,
193
+ count: prev.count + 1,
194
+ };
195
+ persist();
196
+ }
197
+ function checkCircuitBreaker(endpointKey, nowMs = Date.now()) {
198
+ ensureMaps();
199
+ const rec = state._endpointHealth[endpointKey];
200
+ if (!rec) {
201
+ return { open: false, retryAfterSec: 0, consecutiveFailures: 0, lastStatus: null };
202
+ }
203
+ const openUntil = Number(rec.circuitOpenUntilMs || 0);
204
+ if (openUntil > nowMs) {
205
+ return {
206
+ open: true,
207
+ retryAfterSec: Math.max(1, Math.ceil((openUntil - nowMs) / 1000)),
208
+ consecutiveFailures: Number(rec.consecutiveFailures || 0),
209
+ lastStatus: rec.lastStatus ?? null,
210
+ };
211
+ }
212
+ if (openUntil > 0 && openUntil <= nowMs) {
213
+ rec.circuitOpenUntilMs = 0;
214
+ rec.consecutiveFailures = 0;
215
+ persist();
216
+ }
217
+ return {
218
+ open: false,
219
+ retryAfterSec: 0,
220
+ consecutiveFailures: Number(rec.consecutiveFailures || 0),
221
+ lastStatus: rec.lastStatus ?? null,
222
+ };
223
+ }
224
+ function recordEndpointFailure(endpointKey, { status = null, maxConsecutiveFailures = 3, cooldownMs = 600000, nowMs = Date.now() } = {}) {
225
+ ensureMaps();
226
+ const prev = state._endpointHealth[endpointKey] || { consecutiveFailures: 0 };
227
+ const consecutiveFailures = Number(prev.consecutiveFailures || 0) + 1;
228
+ const threshold = Math.max(1, Number(maxConsecutiveFailures) || 3);
229
+ const opened = consecutiveFailures >= threshold;
230
+ const circuitOpenUntilMs = opened ? nowMs + Math.max(1000, Number(cooldownMs) || 600000) : 0;
231
+ state._endpointHealth[endpointKey] = {
232
+ consecutiveFailures,
233
+ lastFailureAtMs: nowMs,
234
+ lastStatus: status,
235
+ circuitOpenUntilMs,
236
+ };
237
+ persist();
238
+ return {
239
+ opened,
240
+ consecutiveFailures,
241
+ retryAfterSec: opened ? Math.ceil((circuitOpenUntilMs - nowMs) / 1000) : 0,
242
+ };
243
+ }
244
+ function recordEndpointSuccess(endpointKey) {
245
+ ensureMaps();
246
+ if (state._endpointHealth[endpointKey]) {
247
+ delete state._endpointHealth[endpointKey];
248
+ persist();
249
+ }
250
+ }
251
+ return {
252
+ getSpentTodayUsdc,
253
+ getPendingReservedTodayUsdc,
254
+ getEffectiveSpentTodayUsdc,
255
+ getTxCountToday,
256
+ recordSpend,
257
+ reserveBudget,
258
+ commitReservation,
259
+ releaseReservation,
260
+ recordRecoverableProof,
261
+ getRecoverableProof,
262
+ clearRecoverableProof,
263
+ checkIdempotency,
264
+ recordPaymentFingerprint,
265
+ checkCircuitBreaker,
266
+ recordEndpointFailure,
267
+ recordEndpointSuccess,
268
+ };
269
+ }
270
+ export function readHeaderCaseInsensitive(headers, name) {
271
+ if (!headers)
272
+ return null;
273
+ if (typeof headers.get === "function") {
274
+ return headers.get(name);
275
+ }
276
+ const target = name.toLowerCase();
277
+ for (const [k, v] of Object.entries(headers)) {
278
+ if (k.toLowerCase() === target)
279
+ return v ?? null;
280
+ }
281
+ return null;
282
+ }
283
+ export function parseX402ChallengeWithMeta(headers, bodyObj = null) {
284
+ let challenge = bodyObj && typeof bodyObj === "object" ? bodyObj : null;
285
+ const paymentRequiredHeader = readHeaderCaseInsensitive(headers, "payment-required");
286
+ const xPaymentRequiredHeader = readHeaderCaseInsensitive(headers, "x-payment-required");
287
+ const headerEncoded = xPaymentRequiredHeader || paymentRequiredHeader;
288
+ const headerBytes = typeof headerEncoded === "string" ? Buffer.byteLength(headerEncoded, "utf8") : null;
289
+ if (headerEncoded && typeof headerEncoded === "string") {
290
+ try {
291
+ const decoded = JSON.parse(Buffer.from(headerEncoded, "base64").toString("utf8"));
292
+ if (decoded && typeof decoded === "object")
293
+ challenge = decoded;
294
+ }
295
+ catch {
296
+ // fall back to bodyObj
297
+ }
298
+ }
299
+ const accepts = Array.isArray(challenge?.accepts) ? challenge.accepts : [];
300
+ const options = [];
301
+ for (const acc of accepts) {
302
+ if (!acc || typeof acc !== "object")
303
+ continue;
304
+ const chain = normalizeChainName(acc.network);
305
+ if (!chain)
306
+ continue;
307
+ const payTo = normalizeChainAddress(chain, acc.payTo);
308
+ if (!payTo)
309
+ continue;
310
+ const rawStr = String(acc.amount ?? acc.maxAmountRequired ?? "").trim();
311
+ const atomic = Number(rawStr);
312
+ if (!Number.isFinite(atomic) || atomic <= 0)
313
+ continue;
314
+ const primary = getPrimaryAsset(chain);
315
+ const assetSpec = getAssetSpec(chain, acc.asset) || primary;
316
+ const amountDecimal = rawAmountToDecimal(rawStr, assetSpec.decimals);
317
+ const amountUsd = toUsdAmount(amountDecimal, assetSpec.fiatPeg);
318
+ options.push({
319
+ chain,
320
+ network: String(acc.network),
321
+ scheme: String(acc.scheme || "exact"),
322
+ asset: acc.asset ? String(acc.asset) : null,
323
+ assetSymbol: assetSpec.symbol,
324
+ payTo,
325
+ amountRaw: rawStr,
326
+ amountDecimal,
327
+ amountUsdc: amountUsd,
328
+ raw: acc,
329
+ });
330
+ }
331
+ return {
332
+ options,
333
+ challenge,
334
+ headerBytes,
335
+ hasPaymentRequiredHeader: Boolean(headerEncoded),
336
+ };
337
+ }
338
+ export function parseX402Challenge(headers, bodyObj = null) {
339
+ return parseX402ChallengeWithMeta(headers, bodyObj).options;
340
+ }
341
+ export async function guardedX402Fetch({ url, method = "GET", headers = {}, body = undefined, preferredChain = "base", engine, ledger = createSpendLedger(":memory:"), policy = {}, hostPolicy = null, mandateChain, requireMandateSignatures, spentUnderMandateUsd, revokedMandateIds, autoRevokeMandateOnCompletion = false, telemetryOptOut = false, taskId = null, parentReceiptHash = null, fetchImpl = globalThis.fetch, signer = null, onApprovalRequired = null, onDeliveryTelemetry = null, }) {
342
+ if (!url || typeof url !== "string") {
343
+ throw new Error("A valid target URL is required.");
344
+ }
345
+ if (!engine || typeof engine.preflightPaymentGuard !== "function") {
346
+ throw new Error("A valid FideRail trust engine instance is required.");
347
+ }
348
+ const effectivePolicy = hostPolicy ? clampPolicy(hostPolicy, policy) : policy;
349
+ if (effectivePolicy.blockOutboundSecrets !== false) {
350
+ const scan = scanOutboundSecrets({
351
+ url,
352
+ headers,
353
+ body,
354
+ blockPii: Boolean(effectivePolicy.blockPii),
355
+ });
356
+ if (!scan.safe) {
357
+ return {
358
+ paid: false,
359
+ blocked: true,
360
+ readyToSign: false,
361
+ decision: "BLOCK",
362
+ reason: "OUTBOUND_SECRET_DETECTED",
363
+ detectedPatterns: scan.matches,
364
+ spentTodayUsdc: ledger.getSpentTodayUsdc(),
365
+ };
366
+ }
367
+ }
368
+ const endpointKey = normalizeEndpointKey(url);
369
+ const idempotencyWindowMs = Math.max(0, Number(effectivePolicy.idempotencyWindowSec ?? 60) * 1000);
370
+ const maxConsecutiveFailures = Math.max(1, Number(effectivePolicy.maxConsecutiveFailures ?? 3));
371
+ const cooldownMs = Math.max(1000, Number(effectivePolicy.circuitBreakerCooldownSec ?? 600) * 1000);
372
+ const breaker = ledger.checkCircuitBreaker(endpointKey);
373
+ if (breaker.open) {
374
+ return {
375
+ paid: false,
376
+ blocked: true,
377
+ readyToSign: false,
378
+ decision: "BLOCK",
379
+ reason: "CIRCUIT_BREAKER_OPEN",
380
+ retryAfterSec: breaker.retryAfterSec,
381
+ consecutiveFailures: breaker.consecutiveFailures,
382
+ lastStatus: breaker.lastStatus,
383
+ spentTodayUsdc: ledger.getSpentTodayUsdc(),
384
+ };
385
+ }
386
+ let probeRes;
387
+ try {
388
+ probeRes = await fetchImpl(url, {
389
+ method,
390
+ headers,
391
+ body: body,
392
+ signal: AbortSignal.timeout(15000),
393
+ });
394
+ }
395
+ catch (err) {
396
+ const failure = ledger.recordEndpointFailure(endpointKey, {
397
+ status: null,
398
+ maxConsecutiveFailures,
399
+ cooldownMs,
400
+ });
401
+ return {
402
+ paid: false,
403
+ blocked: failure.opened,
404
+ readyToSign: false,
405
+ decision: failure.opened ? "BLOCK" : "ERROR",
406
+ reason: failure.opened ? "CIRCUIT_BREAKER_OPEN" : "ENDPOINT_NETWORK_ERROR",
407
+ error: err.message,
408
+ consecutiveFailures: failure.consecutiveFailures,
409
+ retryAfterSec: failure.retryAfterSec,
410
+ spentTodayUsdc: ledger.getSpentTodayUsdc(),
411
+ };
412
+ }
413
+ if (probeRes.status >= 500) {
414
+ const failure = ledger.recordEndpointFailure(endpointKey, {
415
+ status: probeRes.status,
416
+ maxConsecutiveFailures,
417
+ cooldownMs,
418
+ });
419
+ return {
420
+ paid: false,
421
+ blocked: failure.opened,
422
+ readyToSign: false,
423
+ decision: failure.opened ? "BLOCK" : "ERROR",
424
+ reason: failure.opened ? "CIRCUIT_BREAKER_OPEN" : "ENDPOINT_SERVER_ERROR",
425
+ status: probeRes.status,
426
+ consecutiveFailures: failure.consecutiveFailures,
427
+ retryAfterSec: failure.retryAfterSec,
428
+ spentTodayUsdc: ledger.getSpentTodayUsdc(),
429
+ };
430
+ }
431
+ if (probeRes.status !== 402) {
432
+ if (probeRes.ok)
433
+ ledger.recordEndpointSuccess(endpointKey);
434
+ const bodyText = await probeRes.text();
435
+ return {
436
+ paid: false,
437
+ blocked: false,
438
+ readyToSign: false,
439
+ decision: "NO_PAYMENT_REQUIRED",
440
+ status: probeRes.status,
441
+ bodyText,
442
+ spentTodayUsdc: ledger.getSpentTodayUsdc(),
443
+ };
444
+ }
445
+ let bodyJson = null;
446
+ const rawBody = await probeRes.text();
447
+ try {
448
+ bodyJson = rawBody ? JSON.parse(rawBody) : null;
449
+ }
450
+ catch {
451
+ bodyJson = null;
452
+ }
453
+ const parsedMeta = parseX402ChallengeWithMeta(probeRes.headers, bodyJson);
454
+ const options = parsedMeta.options;
455
+ if (options.length === 0) {
456
+ throw new Error("HTTP 402 response contained no supported Base, Solana, Arbitrum, or Polygon payment options.");
457
+ }
458
+ const allowedAssets = effectivePolicy.allowedAssets ?? ["USDC"];
459
+ const strictAssetCheck = Boolean(effectivePolicy.strictAssetCheck);
460
+ const pref = normalizeChainName(preferredChain);
461
+ const permittedOptions = options.filter((o) => isAssetAllowed(o.chain, o.asset, allowedAssets, strictAssetCheck));
462
+ if (permittedOptions.length === 0) {
463
+ const rejectedSample = options.find((o) => o.chain === pref) || options[0];
464
+ return {
465
+ paid: false,
466
+ blocked: true,
467
+ readyToSign: false,
468
+ decision: "BLOCK",
469
+ reason: "DISALLOWED_PAYMENT_ASSET",
470
+ paymentOption: rejectedSample,
471
+ allowedAssets,
472
+ spentTodayUsdc: ledger.getSpentTodayUsdc(),
473
+ };
474
+ }
475
+ const chosen = permittedOptions.find((o) => o.chain === pref) || permittedOptions[0];
476
+ const spentTodayUsdc = ledger.getSpentTodayUsdc();
477
+ const effectiveSpentBeforeUsdc = ledger.getEffectiveSpentTodayUsdc();
478
+ const bodyHash = sha256Hex(serializeBody(body));
479
+ const quoteDigest = computeQuoteDigest({
480
+ method,
481
+ url,
482
+ bodyHash,
483
+ chain: chosen.chain,
484
+ payTo: chosen.payTo,
485
+ asset: chosen.asset,
486
+ amountUsdc: chosen.amountUsdc,
487
+ });
488
+ const frozenQuote = Object.freeze({ ...chosen, quoteDigest });
489
+ const fingerprint = computePaymentFingerprint({
490
+ method,
491
+ url,
492
+ body,
493
+ chain: chosen.chain,
494
+ payTo: chosen.payTo,
495
+ amountUsdc: chosen.amountUsdc,
496
+ });
497
+ const dup = ledger.checkIdempotency(fingerprint, idempotencyWindowMs);
498
+ if (dup.isDuplicate) {
499
+ return {
500
+ paid: false,
501
+ blocked: true,
502
+ readyToSign: false,
503
+ decision: "BLOCK",
504
+ reason: "DUPLICATE_PAYMENT_DETECTED",
505
+ secondsSinceLast: dup.secondsSinceLast,
506
+ quoteDigest,
507
+ paymentOption: frozenQuote,
508
+ spentTodayUsdc,
509
+ };
510
+ }
511
+ // Optional Attenuated Mandate Chain check (Control Plane capability gate)
512
+ const leafMandate = mandateChain && mandateChain.length > 0 ? mandateChain[mandateChain.length - 1] : null;
513
+ const mergedRevoked = new Set(revokedMandateIds || []);
514
+ if (typeof ledger.getRevokedMandateIds === "function") {
515
+ for (const id of ledger.getRevokedMandateIds())
516
+ mergedRevoked.add(id);
517
+ }
518
+ const effectiveMandateSpent = spentUnderMandateUsd ??
519
+ (leafMandate && typeof ledger.getMandateSpentUsd === "function"
520
+ ? ledger.getMandateSpentUsd(leafMandate.mandateId)
521
+ : 0);
522
+ if (mandateChain && mandateChain.length > 0) {
523
+ let domain = null;
524
+ try {
525
+ domain = new URL(url).hostname.toLowerCase();
526
+ }
527
+ catch {
528
+ domain = null;
529
+ }
530
+ const intent = {
531
+ intentId: quoteDigest,
532
+ taskId,
533
+ protocol: "x402",
534
+ chain: chosen.chain,
535
+ assetContract: chosen.asset || getPrimaryAssetContract(chosen.chain),
536
+ assetSymbol: chosen.assetSymbol,
537
+ amountRaw: chosen.amountRaw,
538
+ amountUsd: chosen.amountUsdc,
539
+ payee: chosen.payTo,
540
+ resourceUrl: url,
541
+ domain,
542
+ };
543
+ const hasSignedMandate = mandateChain.some((m) => Boolean(m.proof));
544
+ const checkSigs = requireMandateSignatures ?? hasSignedMandate;
545
+ const mandateCheck = validateMandateChain(mandateChain, intent, {
546
+ spentUnderMandateUsd: effectiveMandateSpent,
547
+ revokedMandateIds: mergedRevoked,
548
+ requireSignatures: checkSigs,
549
+ verifySignature: checkSigs ? verifyEd25519MandateSignature : undefined,
550
+ });
551
+ if (!mandateCheck.valid) {
552
+ return {
553
+ paid: false,
554
+ blocked: true,
555
+ readyToSign: false,
556
+ decision: "BLOCK",
557
+ reason: mandateCheck.reasons[0] || "MANDATE_VALIDATION_FAILED",
558
+ mandateCheck,
559
+ quoteDigest,
560
+ paymentOption: frozenQuote,
561
+ spentTodayUsdc,
562
+ };
563
+ }
564
+ }
565
+ const guard = await engine.preflightPaymentGuard({
566
+ chain: chosen.chain,
567
+ counterparty: chosen.payTo,
568
+ amountUsdc: chosen.amountUsdc,
569
+ assetSymbol: chosen.assetSymbol,
570
+ spentTodayUsdc: effectiveSpentBeforeUsdc,
571
+ policy: effectivePolicy,
572
+ });
573
+ if (guard.decision === "BLOCK") {
574
+ return {
575
+ paid: false,
576
+ blocked: true,
577
+ readyToSign: false,
578
+ decision: "BLOCK",
579
+ reason: guard.reasons[0] || "FIREWALL_BLOCKED",
580
+ quoteDigest,
581
+ paymentOption: frozenQuote,
582
+ guard,
583
+ spentTodayUsdc,
584
+ };
585
+ }
586
+ const hitlAboveUsdc = effectivePolicy.hitlAboveUsdc !== undefined && effectivePolicy.hitlAboveUsdc !== null
587
+ ? Number(effectivePolicy.hitlAboveUsdc)
588
+ : null;
589
+ const hitlRequired = hitlAboveUsdc !== null && Number.isFinite(hitlAboveUsdc) && chosen.amountUsdc > hitlAboveUsdc;
590
+ if (typeof signer !== "function") {
591
+ return {
592
+ paid: false,
593
+ blocked: false,
594
+ readyToSign: true,
595
+ decision: guard.decision,
596
+ hitlRequired,
597
+ quoteDigest,
598
+ paymentRequiredHeaderBytes: parsedMeta.headerBytes,
599
+ paymentOption: frozenQuote,
600
+ guard,
601
+ spentTodayUsdc,
602
+ message: "Pre-flight firewall passed; provide a local non-custodial signer callback to execute payment.",
603
+ };
604
+ }
605
+ const maxDailyCap = guard.policyApplied?.maxDailyUsdc ?? effectivePolicy.maxDailyUsdc ?? 10.0;
606
+ const reservation = ledger.reserveBudget(chosen.amountUsdc, maxDailyCap);
607
+ if (!reservation.ok) {
608
+ return {
609
+ paid: false,
610
+ blocked: true,
611
+ readyToSign: false,
612
+ decision: "BLOCK",
613
+ reason: "EXCEEDS_DAILY_BUDGET",
614
+ quoteDigest,
615
+ paymentOption: frozenQuote,
616
+ guard,
617
+ spentTodayUsdc: ledger.getSpentTodayUsdc(),
618
+ };
619
+ }
620
+ let activeReservationId = reservation.reservationId;
621
+ try {
622
+ const cachedProof = ledger.getRecoverableProof(fingerprint);
623
+ let proofValue = cachedProof && cachedProof.quoteDigest === quoteDigest ? cachedProof.proofValue : null;
624
+ const recoveredProof = Boolean(proofValue);
625
+ if (!proofValue) {
626
+ if (hitlRequired) {
627
+ if (typeof onApprovalRequired !== "function") {
628
+ return {
629
+ paid: false,
630
+ blocked: true,
631
+ readyToSign: false,
632
+ decision: "APPROVAL_REQUIRED",
633
+ reason: "HITL_APPROVAL_REQUIRED",
634
+ quoteDigest,
635
+ paymentOption: frozenQuote,
636
+ guard,
637
+ spentTodayUsdc: ledger.getSpentTodayUsdc(),
638
+ };
639
+ }
640
+ const approval = await onApprovalRequired({
641
+ quote: frozenQuote,
642
+ quoteDigest,
643
+ guard,
644
+ spentTodayUsdc: ledger.getSpentTodayUsdc(),
645
+ });
646
+ if (approval &&
647
+ typeof approval === "object" &&
648
+ approval.quoteDigest &&
649
+ approval.quoteDigest !== quoteDigest) {
650
+ return {
651
+ paid: false,
652
+ blocked: true,
653
+ readyToSign: false,
654
+ decision: "BLOCK",
655
+ reason: "QUOTE_TAMPERING_DETECTED",
656
+ quoteDigest,
657
+ paymentOption: frozenQuote,
658
+ guard,
659
+ spentTodayUsdc: ledger.getSpentTodayUsdc(),
660
+ };
661
+ }
662
+ const approved = approval === true || Boolean(typeof approval === "object" && approval?.approved);
663
+ if (!approved) {
664
+ return {
665
+ paid: false,
666
+ blocked: true,
667
+ readyToSign: false,
668
+ decision: "BLOCK",
669
+ reason: "HITL_APPROVAL_DENIED",
670
+ quoteDigest,
671
+ paymentOption: frozenQuote,
672
+ guard,
673
+ spentTodayUsdc: ledger.getSpentTodayUsdc(),
674
+ };
675
+ }
676
+ }
677
+ const signed = await signer({ ...frozenQuote }, guard);
678
+ if (signed &&
679
+ typeof signed === "object" &&
680
+ signed.quoteDigest &&
681
+ signed.quoteDigest !== quoteDigest) {
682
+ return {
683
+ paid: false,
684
+ blocked: true,
685
+ readyToSign: false,
686
+ decision: "BLOCK",
687
+ reason: "QUOTE_TAMPERING_DETECTED",
688
+ quoteDigest,
689
+ paymentOption: frozenQuote,
690
+ guard,
691
+ spentTodayUsdc: ledger.getSpentTodayUsdc(),
692
+ };
693
+ }
694
+ if (signed && typeof signed === "object" && signed.boundQuote) {
695
+ const bq = signed.boundQuote;
696
+ const mismatch = normalizeChainAddress(chosen.chain, bq.payTo || "") !== frozenQuote.payTo ||
697
+ Number(bq.amountUsdc) !== Number(frozenQuote.amountUsdc) ||
698
+ (bq.asset ?? null) !== (frozenQuote.asset ?? null) ||
699
+ (bq.quoteDigest && bq.quoteDigest !== quoteDigest);
700
+ if (mismatch) {
701
+ return {
702
+ paid: false,
703
+ blocked: true,
704
+ readyToSign: false,
705
+ decision: "BLOCK",
706
+ reason: "QUOTE_TAMPERING_DETECTED",
707
+ quoteDigest,
708
+ paymentOption: frozenQuote,
709
+ guard,
710
+ spentTodayUsdc: ledger.getSpentTodayUsdc(),
711
+ };
712
+ }
713
+ }
714
+ proofValue =
715
+ typeof signed === "string"
716
+ ? signed
717
+ : signed?.xPayment || signed?.headerValue || signed?.paymentHeader || null;
718
+ if (!proofValue) {
719
+ throw new Error("Local signer did not return a payment proof header value.");
720
+ }
721
+ }
722
+ const t0 = Date.now();
723
+ let paidRes;
724
+ try {
725
+ paidRes = await fetchImpl(url, {
726
+ method,
727
+ headers: {
728
+ ...headers,
729
+ "X-PAYMENT": proofValue,
730
+ "PAYMENT-SIGNATURE": proofValue,
731
+ },
732
+ body: body,
733
+ signal: AbortSignal.timeout(15000),
734
+ });
735
+ }
736
+ catch (err) {
737
+ ledger.recordRecoverableProof(fingerprint, {
738
+ proofValue,
739
+ quoteDigest,
740
+ ttlMs: Math.max(60000, idempotencyWindowMs || 60000),
741
+ });
742
+ const failure = ledger.recordEndpointFailure(endpointKey, {
743
+ status: null,
744
+ maxConsecutiveFailures,
745
+ cooldownMs,
746
+ });
747
+ return {
748
+ paid: false,
749
+ blocked: failure.opened,
750
+ readyToSign: false,
751
+ decision: failure.opened ? "BLOCK" : "ERROR",
752
+ reason: failure.opened ? "CIRCUIT_BREAKER_OPEN" : "PAID_REQUEST_NETWORK_ERROR",
753
+ error: err.message,
754
+ quoteDigest,
755
+ recoverableProofCached: true,
756
+ paymentOption: frozenQuote,
757
+ guard,
758
+ spentTodayUsdc: ledger.getSpentTodayUsdc(),
759
+ };
760
+ }
761
+ ledger.clearRecoverableProof(fingerprint);
762
+ const latencyMs = Date.now() - t0;
763
+ const paidBodyText = await paidRes.text();
764
+ const delivered = Boolean(paidRes.ok && paidBodyText.trim().length > 0);
765
+ if (paidRes.status !== 402 && activeReservationId) {
766
+ ledger.commitReservation(activeReservationId);
767
+ activeReservationId = null;
768
+ if (leafMandate && typeof ledger.recordMandateSpend === "function") {
769
+ ledger.recordMandateSpend(leafMandate.mandateId, chosen.amountUsdc);
770
+ }
771
+ }
772
+ let mandateRevokedOnCompletion = false;
773
+ if (delivered) {
774
+ ledger.recordPaymentFingerprint(fingerprint);
775
+ ledger.recordEndpointSuccess(endpointKey);
776
+ if (autoRevokeMandateOnCompletion &&
777
+ leafMandate &&
778
+ typeof ledger.revokeMandate === "function") {
779
+ ledger.revokeMandate(leafMandate.mandateId, "TASK_COMPLETED");
780
+ mandateRevokedOnCompletion = true;
781
+ }
782
+ }
783
+ else {
784
+ ledger.recordEndpointFailure(endpointKey, {
785
+ status: paidRes.status,
786
+ maxConsecutiveFailures,
787
+ cooldownMs,
788
+ });
789
+ }
790
+ const deliveryReceipt = computeDeliveryReceipt({
791
+ method,
792
+ url,
793
+ body,
794
+ quoteDigest,
795
+ chain: chosen.chain,
796
+ payTo: chosen.payTo,
797
+ amountUsdc: chosen.amountUsdc,
798
+ httpStatus: paidRes.status,
799
+ responseBody: paidBodyText,
800
+ delivered,
801
+ });
802
+ const deliveryReceiptV2 = createSaltedDeliveryReceiptV2({
803
+ method,
804
+ url,
805
+ body,
806
+ quoteDigest,
807
+ chain: chosen.chain,
808
+ assetSymbol: chosen.assetSymbol,
809
+ assetContract: chosen.asset || getPrimaryAssetContract(chosen.chain),
810
+ payTo: chosen.payTo,
811
+ amountRaw: chosen.amountRaw,
812
+ amountUsd: chosen.amountUsdc,
813
+ httpStatus: paidRes.status,
814
+ responseBody: paidBodyText,
815
+ delivered,
816
+ taskId,
817
+ parentReceiptHash,
818
+ });
819
+ const telemetryPayload = {
820
+ chain: chosen.chain,
821
+ address: chosen.payTo,
822
+ resourceUrl: url,
823
+ httpStatus: paidRes.status,
824
+ delivered,
825
+ latencyMs,
826
+ verificationTier: "L2_SIGNED_SAR_TELEMETRY",
827
+ receipt: deliveryReceiptV2,
828
+ };
829
+ if (typeof onDeliveryTelemetry === "function") {
830
+ try {
831
+ await onDeliveryTelemetry(telemetryPayload);
832
+ }
833
+ catch {
834
+ // Never fail buyer workflow if optional telemetry reporting fails
835
+ }
836
+ }
837
+ else if (!telemetryOptOut && typeof engine.recordDeliveryTelemetry === "function") {
838
+ try {
839
+ await engine.recordDeliveryTelemetry(telemetryPayload);
840
+ }
841
+ catch {
842
+ // Default anonymous L2 telemetry is best-effort and never blocks buyer execution
843
+ }
844
+ }
845
+ return {
846
+ paid: paidRes.ok,
847
+ delivered,
848
+ blocked: false,
849
+ readyToSign: false,
850
+ decision: guard.decision,
851
+ recoveredProof,
852
+ mandateRevokedOnCompletion,
853
+ quoteDigest,
854
+ deliveryReceipt,
855
+ deliveryReceiptV2,
856
+ paymentRequiredHeaderBytes: parsedMeta.headerBytes,
857
+ status: paidRes.status,
858
+ bodyText: paidBodyText,
859
+ paymentOption: frozenQuote,
860
+ guard,
861
+ spentTodayUsdc: ledger.getSpentTodayUsdc(),
862
+ };
863
+ }
864
+ finally {
865
+ if (activeReservationId) {
866
+ ledger.releaseReservation(activeReservationId);
867
+ }
868
+ }
869
+ }
870
+ //# sourceMappingURL=index.js.map