@fiderail/guard 0.0.0-stage → 2.3.1

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 FideRail Contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,50 @@
1
- # Temporary Holding Version
1
+ # @fiderail/guard
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Non-custodial buyer-side Guard-and-Pay adapter for [FideRail](https://fiderail.com) supporting `x402`, `mcp-pay`, `a2a`, and `session-key` rails. Enforces two-phase atomic budget holds, concurrent SQLite WAL edge spend ledgers, outbound secret scrubbing, quote-digest binding, HTTP 5xx circuit breakers, offline Ed25519 Attenuated Capability Mandates, and salted `fiderail-sar-v2` delivery receipts.
4
+
5
+ ## Install
6
+
7
+ ```bash
8
+ npm install @fiderail/guard
9
+ ```
10
+
11
+ ## Quick Usage
12
+
13
+ ```ts
14
+ import { createRemoteTrustClient } from "@fiderail/core";
15
+ import { createSpendLedger, guardedX402Fetch } from "@fiderail/guard";
16
+
17
+ const engine = createRemoteTrustClient({ apiBaseUrl: "https://api.fiderail.com" });
18
+ const ledger = createSpendLedger("./edge-ledger.db");
19
+
20
+ const result = await guardedX402Fetch({
21
+ url: "https://api.example.com/paid-resource",
22
+ engine,
23
+ ledger,
24
+ policy: { maxSingleTxUsdc: 0.5, maxDailyUsdc: 5.0, minTrustScore: 40 },
25
+ });
26
+
27
+ console.log(result.decision, result.readyToSign);
28
+ ```
29
+
30
+ ## Key Exports
31
+
32
+ - **Guard-and-Pay & Protocol Adapters**: `guardedX402Fetch`, `parseX402Challenge`, `parseX402ChallengeWithMeta`, `guardPaymentIntent`, `guardMcpToolPayment`, `guardA2aTaskPayment`, `guardSessionKeyIntent`
33
+ - **Edge Spend Ledgers**: `createSpendLedger`, `createSqliteSpendLedger` (`SpendLedger`, `EdgeSpendLedger`)
34
+ - **Ed25519 Capability Mandates**: `generateMandateKeypair`, `issueRootMandate`, `delegateChildMandate`, `verifyEd25519MandateSignature`, `verifySignedMandateChain`, `encodeEd25519Identity`, `decodeEd25519Identity`
35
+ - **Policy & Digest Helpers**: `CANONICAL_USDC_ASSETS`, `clampPolicy`, `scanOutboundSecrets`, `computeQuoteDigest`, `computePaymentFingerprint`, `computeDeliveryReceipt`, `isAssetAllowed`
36
+
37
+ ## Runtime Requirements
38
+
39
+ Requires **Node.js `>= 22.13.0`** (uses built-in `node:sqlite` and `node:crypto`). Keys and funds remain 100% local on the buyer's machine.
40
+
41
+ ## Links
42
+
43
+ - Portal: [https://fiderail.com](https://fiderail.com)
44
+ - Documentation: [https://fiderail.com/docs](https://fiderail.com/docs)
45
+ - Source (GitLab): [https://gitlab.com/fiderail/fiderail](https://gitlab.com/fiderail/fiderail)
46
+ - Mirror (GitHub): [https://github.com/fiderail/fiderail](https://github.com/fiderail/fiderail)
47
+
48
+ ## License
49
+
50
+ [MIT](./LICENSE)
@@ -0,0 +1,82 @@
1
+ import { type AssetSymbol } from "@fiderail/spec";
2
+ import { type SettlementAttestationReceiptV2 } from "@fiderail/zk-types";
3
+ import { type AttenuatedMandate, type ControlPlaneVerdict, type FirewallPolicy, type PaymentIntent, type TrustEngine } from "@fiderail/core";
4
+ import { type EdgeSpendLedger } from "./sqlite-ledger.js";
5
+ export interface GuardPaymentIntentOptions<TExecutionResult = unknown> {
6
+ intent: PaymentIntent;
7
+ engine: TrustEngine;
8
+ ledger?: Partial<EdgeSpendLedger> & Pick<EdgeSpendLedger, "getSpentTodayUsdc" | "getEffectiveSpentTodayUsdc" | "reserveBudget" | "commitReservation" | "releaseReservation">;
9
+ policy?: FirewallPolicy;
10
+ hostPolicy?: FirewallPolicy | null;
11
+ mandateChain?: readonly AttenuatedMandate[];
12
+ requireMandateSignatures?: boolean;
13
+ spentUnderMandateUsd?: number;
14
+ revokedMandateIds?: ReadonlySet<string>;
15
+ autoRevokeMandateOnCompletion?: boolean;
16
+ parentReceiptHash?: string | null;
17
+ outboundPayload?: unknown;
18
+ outboundHeaders?: Record<string, unknown>;
19
+ telemetryOptOut?: boolean;
20
+ executor?: (intent: PaymentIntent, verdict: ControlPlaneVerdict) => Promise<{
21
+ ok: boolean;
22
+ httpStatus?: number | null;
23
+ responseBody?: string;
24
+ result?: TExecutionResult;
25
+ }>;
26
+ }
27
+ export interface GuardPaymentIntentResult<TExecutionResult = unknown> {
28
+ allowed: boolean;
29
+ executed: boolean;
30
+ delivered: boolean;
31
+ decision: "ALLOW" | "WARN" | "BLOCK";
32
+ reasons: string[];
33
+ verdict?: ControlPlaneVerdict;
34
+ mandateRevokedOnCompletion?: boolean;
35
+ deliveryReceiptV2?: SettlementAttestationReceiptV2;
36
+ executionResult?: TExecutionResult;
37
+ spentTodayUsdc: number;
38
+ }
39
+ /**
40
+ * Protocol-agnostic non-custodial Control Plane execution guard.
41
+ * Shared foundation for `mcp-pay`, `a2a`, `session-key`, and custom agent payment rails.
42
+ */
43
+ export declare function guardPaymentIntent<TExecutionResult = unknown>(options: GuardPaymentIntentOptions<TExecutionResult>): Promise<GuardPaymentIntentResult<TExecutionResult>>;
44
+ /**
45
+ * Paid MCP Tool Execution Adapter (`mcp-pay`).
46
+ */
47
+ export declare function guardMcpToolPayment<TResult = unknown>(params: Omit<GuardPaymentIntentOptions<TResult>, "intent"> & {
48
+ toolName: string;
49
+ serverUrl?: string;
50
+ chain: string;
51
+ payee: string;
52
+ amountUsd: number;
53
+ assetSymbol?: AssetSymbol;
54
+ taskId?: string | null;
55
+ serviceTags?: string[];
56
+ }): Promise<GuardPaymentIntentResult<TResult>>;
57
+ /**
58
+ * Agent-to-Agent Task Payment Adapter (`a2a`).
59
+ */
60
+ export declare function guardA2aTaskPayment<TResult = unknown>(params: Omit<GuardPaymentIntentOptions<TResult>, "intent"> & {
61
+ agentUrl: string;
62
+ taskId: string;
63
+ chain: string;
64
+ payee: string;
65
+ amountUsd: number;
66
+ assetSymbol?: AssetSymbol;
67
+ serviceTags?: string[];
68
+ }): Promise<GuardPaymentIntentResult<TResult>>;
69
+ /**
70
+ * Smart-Account / ERC-7715 / Solana Delegated Session-Key Adapter (`session-key`).
71
+ */
72
+ export declare function guardSessionKeyIntent<TResult = unknown>(params: Omit<GuardPaymentIntentOptions<TResult>, "intent"> & {
73
+ chain: string;
74
+ payee: string;
75
+ amountUsd: number;
76
+ assetSymbol?: AssetSymbol;
77
+ domain?: string | null;
78
+ resourceUrl?: string | null;
79
+ taskId?: string | null;
80
+ serviceTags?: string[];
81
+ }): Promise<GuardPaymentIntentResult<TResult>>;
82
+ //# sourceMappingURL=adapters.d.ts.map
@@ -0,0 +1,263 @@
1
+ import { decimalToRawAmount, getAssetSpec, getPrimaryAsset, normalizeChainAddress, normalizeChainName, } from "@fiderail/spec";
2
+ import { createSaltedDeliveryReceiptV2, sha256Hex, } from "@fiderail/zk-types";
3
+ import { clampPolicy, scanOutboundSecrets, validateMandateChain, } from "@fiderail/core";
4
+ import { verifyEd25519MandateSignature } from "./mandate.js";
5
+ import { createSqliteSpendLedger } from "./sqlite-ledger.js";
6
+ /**
7
+ * Protocol-agnostic non-custodial Control Plane execution guard.
8
+ * Shared foundation for `mcp-pay`, `a2a`, `session-key`, and custom agent payment rails.
9
+ */
10
+ export async function guardPaymentIntent(options) {
11
+ const { intent, engine, ledger = createSqliteSpendLedger(":memory:"), policy = {}, hostPolicy = null, mandateChain, requireMandateSignatures, revokedMandateIds, autoRevokeMandateOnCompletion = false, parentReceiptHash = null, outboundPayload, outboundHeaders, telemetryOptOut = false, executor, } = options;
12
+ const effectivePolicy = hostPolicy ? clampPolicy(hostPolicy, policy) : policy;
13
+ // 1. Outbound Secret & PII Scrubber ("Agents Have a Mouth")
14
+ if (effectivePolicy.blockOutboundSecrets !== false) {
15
+ const scan = scanOutboundSecrets({
16
+ url: intent.resourceUrl || "",
17
+ headers: outboundHeaders,
18
+ body: outboundPayload,
19
+ blockPii: Boolean(effectivePolicy.blockPii),
20
+ });
21
+ if (!scan.safe) {
22
+ return {
23
+ allowed: false,
24
+ executed: false,
25
+ delivered: false,
26
+ decision: "BLOCK",
27
+ reasons: [`OUTBOUND_SECRET_DETECTED:${scan.matches.join(",")}`],
28
+ spentTodayUsdc: ledger.getSpentTodayUsdc(),
29
+ };
30
+ }
31
+ }
32
+ // 2. Cryptographic Attenuated Capability Mandate chain verification
33
+ const leafMandate = mandateChain && mandateChain.length > 0 ? mandateChain[mandateChain.length - 1] : null;
34
+ const mergedRevoked = new Set(revokedMandateIds || []);
35
+ if (typeof ledger.getRevokedMandateIds === "function") {
36
+ for (const id of ledger.getRevokedMandateIds())
37
+ mergedRevoked.add(id);
38
+ }
39
+ const trackedMandateSpend = options.spentUnderMandateUsd ??
40
+ (leafMandate && typeof ledger.getMandateSpentUsd === "function"
41
+ ? ledger.getMandateSpentUsd(leafMandate.mandateId)
42
+ : 0);
43
+ if (mandateChain && mandateChain.length > 0) {
44
+ const hasSignedMandate = mandateChain.some((m) => Boolean(m.proof));
45
+ const checkSigs = requireMandateSignatures ?? hasSignedMandate;
46
+ const sigCheck = validateMandateChain(mandateChain, intent, {
47
+ spentUnderMandateUsd: trackedMandateSpend,
48
+ revokedMandateIds: mergedRevoked,
49
+ requireSignatures: checkSigs,
50
+ verifySignature: checkSigs ? verifyEd25519MandateSignature : undefined,
51
+ });
52
+ if (!sigCheck.valid) {
53
+ return {
54
+ allowed: false,
55
+ executed: false,
56
+ delivered: false,
57
+ decision: "BLOCK",
58
+ reasons: sigCheck.reasons,
59
+ spentTodayUsdc: ledger.getSpentTodayUsdc(),
60
+ };
61
+ }
62
+ }
63
+ // 3. Control Plane evaluation (Mandate + Risk Intelligence + Policy Firewall)
64
+ const effectiveSpentBefore = ledger.getEffectiveSpentTodayUsdc();
65
+ const verdict = await engine.evaluatePaymentIntent({
66
+ intent,
67
+ mandateChain,
68
+ spentTodayUsd: effectiveSpentBefore,
69
+ spentUnderMandateUsd: trackedMandateSpend,
70
+ revokedMandateIds: mergedRevoked,
71
+ policy: effectivePolicy,
72
+ });
73
+ if (verdict.decision === "BLOCK") {
74
+ return {
75
+ allowed: false,
76
+ executed: false,
77
+ delivered: false,
78
+ decision: "BLOCK",
79
+ reasons: verdict.reasons,
80
+ verdict,
81
+ spentTodayUsdc: ledger.getSpentTodayUsdc(),
82
+ };
83
+ }
84
+ if (typeof executor !== "function") {
85
+ return {
86
+ allowed: true,
87
+ executed: false,
88
+ delivered: false,
89
+ decision: verdict.decision,
90
+ reasons: verdict.reasons,
91
+ verdict,
92
+ spentTodayUsdc: ledger.getSpentTodayUsdc(),
93
+ };
94
+ }
95
+ // 4. Atomic two-phase budget reservation before local wallet/session execution
96
+ const maxDailyCap = verdict.firewallCheck.policyApplied.maxDailyUsdc ?? effectivePolicy.maxDailyUsdc ?? 10;
97
+ const reservation = ledger.reserveBudget(intent.amountUsd, maxDailyCap);
98
+ if (!reservation.ok) {
99
+ return {
100
+ allowed: false,
101
+ executed: false,
102
+ delivered: false,
103
+ decision: "BLOCK",
104
+ reasons: ["EXCEEDS_DAILY_BUDGET"],
105
+ verdict,
106
+ spentTodayUsdc: ledger.getSpentTodayUsdc(),
107
+ };
108
+ }
109
+ let activeResId = reservation.reservationId;
110
+ try {
111
+ const t0 = Date.now();
112
+ const execOut = await executor(intent, verdict);
113
+ const latencyMs = Date.now() - t0;
114
+ const delivered = Boolean(execOut.ok);
115
+ if (activeResId) {
116
+ ledger.commitReservation(activeResId);
117
+ activeResId = null;
118
+ }
119
+ if (leafMandate && typeof ledger.recordMandateSpend === "function") {
120
+ ledger.recordMandateSpend(leafMandate.mandateId, intent.amountUsd);
121
+ }
122
+ let mandateRevokedOnCompletion = false;
123
+ if (delivered &&
124
+ autoRevokeMandateOnCompletion &&
125
+ leafMandate &&
126
+ typeof ledger.revokeMandate === "function") {
127
+ ledger.revokeMandate(leafMandate.mandateId, "TASK_COMPLETED");
128
+ mandateRevokedOnCompletion = true;
129
+ }
130
+ const deliveryReceiptV2 = createSaltedDeliveryReceiptV2({
131
+ method: intent.protocol.toUpperCase(),
132
+ url: intent.resourceUrl || `protocol://${intent.protocol}/${intent.intentId}`,
133
+ body: outboundPayload ?? "",
134
+ quoteDigest: intent.metadataHash || sha256Hex(intent.intentId),
135
+ chain: intent.chain,
136
+ assetSymbol: intent.assetSymbol,
137
+ assetContract: intent.assetContract,
138
+ payTo: intent.payee,
139
+ amountRaw: intent.amountRaw,
140
+ amountUsd: intent.amountUsd,
141
+ httpStatus: execOut.httpStatus ?? (delivered ? 200 : 500),
142
+ responseBody: execOut.responseBody ?? "",
143
+ delivered,
144
+ taskId: intent.taskId ?? null,
145
+ parentReceiptHash,
146
+ });
147
+ if (!telemetryOptOut && intent.resourceUrl && typeof engine.recordDeliveryTelemetry === "function") {
148
+ try {
149
+ await engine.recordDeliveryTelemetry({
150
+ chain: intent.chain,
151
+ address: intent.payee,
152
+ resourceUrl: intent.resourceUrl,
153
+ httpStatus: execOut.httpStatus ?? (delivered ? 200 : 500),
154
+ delivered,
155
+ latencyMs,
156
+ verificationTier: "L2_SIGNED_SAR_TELEMETRY",
157
+ receipt: deliveryReceiptV2,
158
+ });
159
+ }
160
+ catch {
161
+ // Never disrupt edge execution on optional telemetry errors
162
+ }
163
+ }
164
+ return {
165
+ allowed: true,
166
+ executed: true,
167
+ delivered,
168
+ decision: verdict.decision,
169
+ reasons: verdict.reasons,
170
+ verdict,
171
+ mandateRevokedOnCompletion,
172
+ deliveryReceiptV2,
173
+ executionResult: execOut.result,
174
+ spentTodayUsdc: ledger.getSpentTodayUsdc(),
175
+ };
176
+ }
177
+ finally {
178
+ if (activeResId) {
179
+ ledger.releaseReservation(activeResId);
180
+ }
181
+ }
182
+ }
183
+ function buildAdapterIntent(params) {
184
+ const chain = normalizeChainName(params.chain);
185
+ if (!chain) {
186
+ throw new Error(`Unsupported chain "${params.chain}". Expected base, solana, arbitrum, or polygon.`);
187
+ }
188
+ const assetSpec = getAssetSpec(chain, params.assetSymbol) || getPrimaryAsset(chain);
189
+ const payee = normalizeChainAddress(chain, params.payee);
190
+ let domain = params.domain ?? null;
191
+ if (!domain && params.resourceUrl) {
192
+ try {
193
+ domain = new URL(params.resourceUrl).hostname.toLowerCase();
194
+ }
195
+ catch {
196
+ domain = null;
197
+ }
198
+ }
199
+ return {
200
+ intentId: params.intentId || `${params.protocol}_${Date.now()}_${Math.random().toString(16).slice(2, 10)}`,
201
+ taskId: params.taskId ?? null,
202
+ protocol: params.protocol,
203
+ chain: chain,
204
+ assetContract: assetSpec.contract,
205
+ assetSymbol: assetSpec.symbol,
206
+ amountRaw: decimalToRawAmount(params.amountUsd, assetSpec.decimals),
207
+ amountUsd: Number(params.amountUsd),
208
+ payee,
209
+ resourceUrl: params.resourceUrl ?? null,
210
+ domain,
211
+ serviceTags: params.serviceTags,
212
+ };
213
+ }
214
+ /**
215
+ * Paid MCP Tool Execution Adapter (`mcp-pay`).
216
+ */
217
+ export async function guardMcpToolPayment(params) {
218
+ const intent = buildAdapterIntent({
219
+ protocol: "mcp-pay",
220
+ chain: params.chain,
221
+ payee: params.payee,
222
+ amountUsd: params.amountUsd,
223
+ assetSymbol: params.assetSymbol,
224
+ resourceUrl: params.serverUrl || `https://mcp.local/tools/${encodeURIComponent(params.toolName)}`,
225
+ taskId: params.taskId,
226
+ serviceTags: params.serviceTags ?? ["mcp-tool", params.toolName],
227
+ });
228
+ return guardPaymentIntent({ ...params, intent });
229
+ }
230
+ /**
231
+ * Agent-to-Agent Task Payment Adapter (`a2a`).
232
+ */
233
+ export async function guardA2aTaskPayment(params) {
234
+ const intent = buildAdapterIntent({
235
+ protocol: "a2a",
236
+ chain: params.chain,
237
+ payee: params.payee,
238
+ amountUsd: params.amountUsd,
239
+ assetSymbol: params.assetSymbol,
240
+ resourceUrl: params.agentUrl,
241
+ taskId: params.taskId,
242
+ serviceTags: params.serviceTags ?? ["a2a"],
243
+ });
244
+ return guardPaymentIntent({ ...params, intent });
245
+ }
246
+ /**
247
+ * Smart-Account / ERC-7715 / Solana Delegated Session-Key Adapter (`session-key`).
248
+ */
249
+ export async function guardSessionKeyIntent(params) {
250
+ const intent = buildAdapterIntent({
251
+ protocol: "session-key",
252
+ chain: params.chain,
253
+ payee: params.payee,
254
+ amountUsd: params.amountUsd,
255
+ assetSymbol: params.assetSymbol,
256
+ resourceUrl: params.resourceUrl,
257
+ domain: params.domain,
258
+ taskId: params.taskId,
259
+ serviceTags: params.serviceTags ?? ["session-key"],
260
+ });
261
+ return guardPaymentIntent({ ...params, intent });
262
+ }
263
+ //# sourceMappingURL=adapters.js.map
@@ -0,0 +1,126 @@
1
+ import { type AssetSymbol, type ChainKey } from "@fiderail/spec";
2
+ import { clampPolicy, computeDeliveryReceipt, computePaymentFingerprint, computeQuoteDigest, isAssetAllowed, normalizeEndpointKey, scanOutboundSecrets, type AttenuatedMandate, type FirewallPolicy, type TrustEngine } from "@fiderail/core";
3
+ export * from "./mandate.js";
4
+ export * from "./sqlite-ledger.js";
5
+ export * from "./adapters.js";
6
+ export { clampPolicy, computeDeliveryReceipt, computePaymentFingerprint, computeQuoteDigest, isAssetAllowed, normalizeEndpointKey, scanOutboundSecrets, };
7
+ export declare const CANONICAL_USDC_ASSETS: Readonly<{
8
+ base: string;
9
+ solana: string;
10
+ arbitrum: string;
11
+ polygon: string;
12
+ }>;
13
+ export interface SpendLedger {
14
+ getSpentTodayUsdc(nowDate?: Date): number;
15
+ getPendingReservedTodayUsdc(nowDate?: Date, nowMs?: number): number;
16
+ getEffectiveSpentTodayUsdc(nowDate?: Date): number;
17
+ getTxCountToday(nowDate?: Date): number;
18
+ recordSpend(amountUsdc: number, nowDate?: Date): number;
19
+ reserveBudget(amountUsdc: number, maxDailyUsdc: number, nowDate?: Date): {
20
+ ok: boolean;
21
+ reservationId: string | null;
22
+ effectiveSpentUsdc: number;
23
+ };
24
+ commitReservation(reservationId: string, nowDate?: Date): number;
25
+ releaseReservation(reservationId: string | null): boolean;
26
+ recordRecoverableProof(fingerprint: string, opts: {
27
+ proofValue: string;
28
+ quoteDigest: string;
29
+ ttlMs?: number;
30
+ nowMs?: number;
31
+ }): void;
32
+ getRecoverableProof(fingerprint: string, nowMs?: number): {
33
+ proofValue: string;
34
+ quoteDigest: string;
35
+ expiresAtMs: number;
36
+ } | null;
37
+ clearRecoverableProof(fingerprint: string): void;
38
+ checkIdempotency(fingerprint: string, windowMs?: number, nowMs?: number): {
39
+ isDuplicate: boolean;
40
+ secondsSinceLast: number | null;
41
+ };
42
+ recordPaymentFingerprint(fingerprint: string, nowMs?: number): void;
43
+ checkCircuitBreaker(endpointKey: string, nowMs?: number): {
44
+ open: boolean;
45
+ retryAfterSec: number;
46
+ consecutiveFailures: number;
47
+ lastStatus: number | null;
48
+ };
49
+ recordEndpointFailure(endpointKey: string, opts?: {
50
+ status?: number | null;
51
+ maxConsecutiveFailures?: number;
52
+ cooldownMs?: number;
53
+ nowMs?: number;
54
+ }): {
55
+ opened: boolean;
56
+ consecutiveFailures: number;
57
+ retryAfterSec: number;
58
+ };
59
+ recordEndpointSuccess(endpointKey: string): void;
60
+ getMandateSpentUsd?(mandateId: string): number;
61
+ recordMandateSpend?(mandateId: string, amountUsd: number): number;
62
+ revokeMandate?(mandateId: string, reason?: string): void;
63
+ isMandateRevoked?(mandateId: string): boolean;
64
+ getRevokedMandateIds?(): Set<string>;
65
+ close?(): void;
66
+ }
67
+ /**
68
+ * Local UTC-day spend, two-phase atomic reservation, idempotency, recoverable proof cache,
69
+ * and HTTP 5xx circuit-breaker ledger. Keys and funds stay 100% local.
70
+ * Automatically upgrades to concurrent-safe SQLite WAL when `ledgerPath` ends with `.db` / `.sqlite` / `.sqlite3`.
71
+ */
72
+ export declare function createSpendLedger(ledgerPath?: string): SpendLedger;
73
+ export declare function readHeaderCaseInsensitive(headers: Headers | Record<string, string | undefined> | null | undefined, name: string): string | null;
74
+ export interface ParsedX402PaymentOption {
75
+ chain: ChainKey;
76
+ network: string;
77
+ scheme: string;
78
+ asset: string | null;
79
+ assetSymbol: AssetSymbol;
80
+ payTo: string;
81
+ amountRaw: string;
82
+ amountDecimal: number;
83
+ amountUsdc: number;
84
+ raw: Record<string, any>;
85
+ }
86
+ export declare function parseX402ChallengeWithMeta(headers: Headers | Record<string, string | undefined> | null | undefined, bodyObj?: Record<string, any> | null): {
87
+ options: ParsedX402PaymentOption[];
88
+ challenge: Record<string, any> | null;
89
+ headerBytes: number | null;
90
+ hasPaymentRequiredHeader: boolean;
91
+ };
92
+ export declare function parseX402Challenge(headers: Headers | Record<string, string | undefined> | null | undefined, bodyObj?: Record<string, any> | null): ParsedX402PaymentOption[];
93
+ export interface GuardedX402FetchOptions {
94
+ url: string;
95
+ method?: string;
96
+ headers?: Record<string, string>;
97
+ body?: unknown;
98
+ preferredChain?: string;
99
+ engine: TrustEngine;
100
+ ledger?: SpendLedger;
101
+ policy?: FirewallPolicy;
102
+ hostPolicy?: FirewallPolicy | null;
103
+ mandateChain?: readonly AttenuatedMandate[];
104
+ requireMandateSignatures?: boolean;
105
+ spentUnderMandateUsd?: number;
106
+ revokedMandateIds?: ReadonlySet<string>;
107
+ autoRevokeMandateOnCompletion?: boolean;
108
+ telemetryOptOut?: boolean;
109
+ taskId?: string | null;
110
+ parentReceiptHash?: string | null;
111
+ fetchImpl?: typeof globalThis.fetch;
112
+ signer?: ((quote: ParsedX402PaymentOption & {
113
+ quoteDigest: string;
114
+ }, guard: any) => Promise<string | {
115
+ xPayment?: string;
116
+ headerValue?: string;
117
+ boundQuote?: any;
118
+ }>) | null;
119
+ onApprovalRequired?: ((ctx: any) => Promise<boolean | {
120
+ approved: boolean;
121
+ quoteDigest?: string;
122
+ }>) | null;
123
+ onDeliveryTelemetry?: ((payload: any) => Promise<void> | void) | null;
124
+ }
125
+ export declare function guardedX402Fetch({ url, method, headers, body, preferredChain, engine, ledger, policy, hostPolicy, mandateChain, requireMandateSignatures, spentUnderMandateUsd, revokedMandateIds, autoRevokeMandateOnCompletion, telemetryOptOut, taskId, parentReceiptHash, fetchImpl, signer, onApprovalRequired, onDeliveryTelemetry, }: GuardedX402FetchOptions): Promise<Record<string, any>>;
126
+ //# sourceMappingURL=index.d.ts.map