@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.
@@ -0,0 +1,63 @@
1
+ import crypto from "node:crypto";
2
+ import { type AttenuatedMandate, type MandateConstraints, type MandateMode, type MandateValidationResult, type PaymentIntent } from "@fiderail/core";
3
+ export interface MandateKeypair {
4
+ identity: string;
5
+ publicKeyPem: string;
6
+ privateKeyPem: string;
7
+ }
8
+ /**
9
+ * Encodes an Ed25519 SPKI public key into a self-contained offline-verifiable identity string.
10
+ * Format: `ed25519:<base64url-spki-der>`
11
+ */
12
+ export declare function encodeEd25519Identity(publicKeyPem: string): string;
13
+ /**
14
+ * Decodes an `ed25519:<base64url-spki-der>` identity (or raw SPKI PEM) back into a crypto.KeyObject.
15
+ */
16
+ export declare function decodeEd25519Identity(identity: string): crypto.KeyObject | null;
17
+ /**
18
+ * Generates an Ed25519 keypair for a root human authority, orchestrator agent, or sub-agent.
19
+ * Private keys stay 100% local on the user's or agent's machine (Zero Custody).
20
+ */
21
+ export declare function generateMandateKeypair(): MandateKeypair;
22
+ /**
23
+ * Issues and Ed25519-signs a root Attenuated Capability Mandate (`SPECIFIED` or `BOUNDED`).
24
+ */
25
+ export declare function issueRootMandate(params: {
26
+ issuerPrivateKeyPem: string;
27
+ subjectIdentity: string;
28
+ mode: MandateMode;
29
+ constraints: MandateConstraints;
30
+ ttlSec?: number;
31
+ expiresAt?: string;
32
+ issuedAt?: string;
33
+ mandateId?: string;
34
+ }): AttenuatedMandate;
35
+ /**
36
+ * Offline monotonic sub-agent delegation (UCAN/Biscuit style).
37
+ * An orchestrator agent signs a strictly narrower child mandate using its own private key
38
+ * (which MUST correspond to `parentMandate.subject`), with zero central server approval.
39
+ */
40
+ export declare function delegateChildMandate(params: {
41
+ parentMandate: AttenuatedMandate;
42
+ parentPrivateKeyPem: string;
43
+ childSubjectIdentity: string;
44
+ mode?: MandateMode;
45
+ constraints: Partial<MandateConstraints>;
46
+ ttlSec?: number;
47
+ expiresAt?: string;
48
+ issuedAt?: string;
49
+ mandateId?: string;
50
+ }): AttenuatedMandate;
51
+ /**
52
+ * Verifies an Ed25519 signature over a mandate's canonical JCS payload against `expectedSigner`.
53
+ */
54
+ export declare function verifyEd25519MandateSignature(mandate: AttenuatedMandate, signingPayload: string, expectedSigner: string): boolean;
55
+ /**
56
+ * Offline cryptographic verification of a complete Attenuated Capability Mandate chain.
57
+ */
58
+ export declare function verifySignedMandateChain(chain: readonly AttenuatedMandate[], intent: PaymentIntent, options?: {
59
+ nowMs?: number;
60
+ spentUnderMandateUsd?: number;
61
+ revokedMandateIds?: ReadonlySet<string>;
62
+ }): MandateValidationResult;
63
+ //# sourceMappingURL=mandate.d.ts.map
@@ -0,0 +1,214 @@
1
+ import crypto from "node:crypto";
2
+ import { createMandateSigningPayload, validateMandateChain, } from "@fiderail/core";
3
+ const ED25519_ID_PREFIX = "ed25519:";
4
+ /**
5
+ * Encodes an Ed25519 SPKI public key into a self-contained offline-verifiable identity string.
6
+ * Format: `ed25519:<base64url-spki-der>`
7
+ */
8
+ export function encodeEd25519Identity(publicKeyPem) {
9
+ const keyObj = crypto.createPublicKey(publicKeyPem);
10
+ const spkiDer = keyObj.export({ type: "spki", format: "der" });
11
+ return `${ED25519_ID_PREFIX}${spkiDer.toString("base64url")}`;
12
+ }
13
+ /**
14
+ * Decodes an `ed25519:<base64url-spki-der>` identity (or raw SPKI PEM) back into a crypto.KeyObject.
15
+ */
16
+ export function decodeEd25519Identity(identity) {
17
+ if (!identity || typeof identity !== "string")
18
+ return null;
19
+ try {
20
+ if (identity.startsWith(ED25519_ID_PREFIX)) {
21
+ const der = Buffer.from(identity.slice(ED25519_ID_PREFIX.length), "base64url");
22
+ return crypto.createPublicKey({ key: der, format: "der", type: "spki" });
23
+ }
24
+ if (identity.includes("BEGIN PUBLIC KEY")) {
25
+ return crypto.createPublicKey(identity);
26
+ }
27
+ return null;
28
+ }
29
+ catch {
30
+ return null;
31
+ }
32
+ }
33
+ /**
34
+ * Generates an Ed25519 keypair for a root human authority, orchestrator agent, or sub-agent.
35
+ * Private keys stay 100% local on the user's or agent's machine (Zero Custody).
36
+ */
37
+ export function generateMandateKeypair() {
38
+ const { publicKey, privateKey } = crypto.generateKeyPairSync("ed25519");
39
+ const publicKeyPem = publicKey.export({ type: "spki", format: "pem" }).toString();
40
+ const privateKeyPem = privateKey.export({ type: "pkcs8", format: "pem" }).toString();
41
+ return {
42
+ identity: encodeEd25519Identity(publicKeyPem),
43
+ publicKeyPem,
44
+ privateKeyPem,
45
+ };
46
+ }
47
+ function deriveIdentityFromPrivateKey(privateKeyPem) {
48
+ const privKey = crypto.createPrivateKey(privateKeyPem);
49
+ const pubKey = crypto.createPublicKey(privKey);
50
+ const spkiDer = pubKey.export({ type: "spki", format: "der" });
51
+ return `${ED25519_ID_PREFIX}${spkiDer.toString("base64url")}`;
52
+ }
53
+ function isSubsetCI(child, parent) {
54
+ const set = new Set(parent.map((v) => v.toLowerCase()));
55
+ return child.every((v) => set.has(v.toLowerCase()));
56
+ }
57
+ /**
58
+ * Issues and Ed25519-signs a root Attenuated Capability Mandate (`SPECIFIED` or `BOUNDED`).
59
+ */
60
+ export function issueRootMandate(params) {
61
+ const rootIssuer = deriveIdentityFromPrivateKey(params.issuerPrivateKeyPem);
62
+ const nowMs = params.issuedAt ? Date.parse(params.issuedAt) : Date.now();
63
+ const issuedAt = new Date(nowMs).toISOString();
64
+ const expiresAt = params.expiresAt ||
65
+ new Date(nowMs + Math.max(10, Number(params.ttlSec ?? 3600)) * 1000).toISOString();
66
+ const unsigned = {
67
+ mandateId: params.mandateId || `mnd_root_${crypto.randomBytes(8).toString("hex")}`,
68
+ parentMandateId: null,
69
+ rootIssuer,
70
+ subject: params.subjectIdentity,
71
+ mode: params.mode,
72
+ status: "ACTIVE",
73
+ constraints: params.constraints,
74
+ issuedAt,
75
+ expiresAt,
76
+ proofType: "ed25519",
77
+ };
78
+ const payload = createMandateSigningPayload(unsigned);
79
+ const proof = crypto
80
+ .sign(null, Buffer.from(payload, "utf8"), params.issuerPrivateKeyPem)
81
+ .toString("base64");
82
+ return { ...unsigned, proof };
83
+ }
84
+ /**
85
+ * Offline monotonic sub-agent delegation (UCAN/Biscuit style).
86
+ * An orchestrator agent signs a strictly narrower child mandate using its own private key
87
+ * (which MUST correspond to `parentMandate.subject`), with zero central server approval.
88
+ */
89
+ export function delegateChildMandate(params) {
90
+ const parent = params.parentMandate;
91
+ const signerIdentity = deriveIdentityFromPrivateKey(params.parentPrivateKeyPem);
92
+ if (signerIdentity !== parent.subject) {
93
+ throw new Error("Attenuation signer mismatch: parentPrivateKeyPem does not match parentMandate.subject.");
94
+ }
95
+ if (parent.status !== "ACTIVE") {
96
+ throw new Error(`Cannot delegate from non-ACTIVE parent mandate (${parent.status}).`);
97
+ }
98
+ const nowMs = params.issuedAt ? Date.parse(params.issuedAt) : Date.now();
99
+ const issuedAt = new Date(nowMs).toISOString();
100
+ const parentExpMs = Date.parse(parent.expiresAt);
101
+ const requestedExpMs = params.expiresAt
102
+ ? Date.parse(params.expiresAt)
103
+ : params.ttlSec !== undefined
104
+ ? nowMs + Math.max(1, Number(params.ttlSec)) * 1000
105
+ : parentExpMs;
106
+ if (requestedExpMs > parentExpMs) {
107
+ throw new Error("Monotonic attenuation violation: child expiresAt exceeds parent expiresAt.");
108
+ }
109
+ const nextMode = params.mode ?? parent.mode;
110
+ if (parent.mode === "SPECIFIED" && nextMode !== "SPECIFIED") {
111
+ throw new Error("Monotonic attenuation violation: cannot widen SPECIFIED mode to BOUNDED.");
112
+ }
113
+ const p = parent.constraints;
114
+ const req = params.constraints || {};
115
+ const maxSingleTxUsd = req.maxSingleTxUsd ?? p.maxSingleTxUsd;
116
+ const maxTotalUsd = req.maxTotalUsd ?? p.maxTotalUsd;
117
+ const minTrustScore = req.minTrustScore ?? p.minTrustScore;
118
+ const blockLoops = req.blockLoops ?? p.blockLoops;
119
+ const allowedChains = req.allowedChains ?? [...p.allowedChains];
120
+ const allowedAssets = req.allowedAssets ?? [...p.allowedAssets];
121
+ const allowedDomains = req.allowedDomains ?? (p.allowedDomains ? [...p.allowedDomains] : undefined);
122
+ const allowedPayees = req.allowedPayees ?? (p.allowedPayees ? [...p.allowedPayees] : undefined);
123
+ const allowedServiceTags = req.allowedServiceTags ?? (p.allowedServiceTags ? [...p.allowedServiceTags] : undefined);
124
+ if (maxSingleTxUsd > p.maxSingleTxUsd) {
125
+ throw new Error("Monotonic attenuation violation: child maxSingleTxUsd exceeds parent.");
126
+ }
127
+ if (maxTotalUsd > p.maxTotalUsd) {
128
+ throw new Error("Monotonic attenuation violation: child maxTotalUsd exceeds parent.");
129
+ }
130
+ if (minTrustScore < p.minTrustScore) {
131
+ throw new Error("Monotonic attenuation violation: child minTrustScore is lower than parent.");
132
+ }
133
+ if (p.blockLoops && !blockLoops) {
134
+ throw new Error("Monotonic attenuation violation: child cannot disable parent blockLoops.");
135
+ }
136
+ if (!isSubsetCI(allowedChains, p.allowedChains)) {
137
+ throw new Error("Monotonic attenuation violation: child allowedChains widens parent.");
138
+ }
139
+ if (!isSubsetCI(allowedAssets, p.allowedAssets)) {
140
+ throw new Error("Monotonic attenuation violation: child allowedAssets widens parent.");
141
+ }
142
+ if (p.allowedDomains && p.allowedDomains.length > 0) {
143
+ if (!allowedDomains || allowedDomains.length === 0 || !isSubsetCI(allowedDomains, p.allowedDomains)) {
144
+ throw new Error("Monotonic attenuation violation: child allowedDomains widens parent.");
145
+ }
146
+ }
147
+ if (p.allowedPayees && p.allowedPayees.length > 0) {
148
+ if (!allowedPayees || allowedPayees.length === 0 || !isSubsetCI(allowedPayees, p.allowedPayees)) {
149
+ throw new Error("Monotonic attenuation violation: child allowedPayees widens parent.");
150
+ }
151
+ }
152
+ if (p.allowedServiceTags && p.allowedServiceTags.length > 0) {
153
+ if (!allowedServiceTags ||
154
+ allowedServiceTags.length === 0 ||
155
+ !isSubsetCI(allowedServiceTags, p.allowedServiceTags)) {
156
+ throw new Error("Monotonic attenuation violation: child allowedServiceTags widens parent.");
157
+ }
158
+ }
159
+ const childConstraints = {
160
+ maxSingleTxUsd,
161
+ maxTotalUsd,
162
+ allowedChains,
163
+ allowedAssets,
164
+ ...(allowedPayees ? { allowedPayees } : {}),
165
+ ...(allowedDomains ? { allowedDomains } : {}),
166
+ ...(allowedServiceTags ? { allowedServiceTags } : {}),
167
+ minTrustScore,
168
+ blockLoops,
169
+ };
170
+ const unsigned = {
171
+ mandateId: params.mandateId || `mnd_sub_${crypto.randomBytes(8).toString("hex")}`,
172
+ parentMandateId: parent.mandateId,
173
+ rootIssuer: parent.rootIssuer,
174
+ subject: params.childSubjectIdentity,
175
+ mode: nextMode,
176
+ status: "ACTIVE",
177
+ constraints: childConstraints,
178
+ issuedAt,
179
+ expiresAt: new Date(requestedExpMs).toISOString(),
180
+ proofType: "ed25519",
181
+ };
182
+ const payload = createMandateSigningPayload(unsigned);
183
+ const proof = crypto
184
+ .sign(null, Buffer.from(payload, "utf8"), params.parentPrivateKeyPem)
185
+ .toString("base64");
186
+ return { ...unsigned, proof };
187
+ }
188
+ /**
189
+ * Verifies an Ed25519 signature over a mandate's canonical JCS payload against `expectedSigner`.
190
+ */
191
+ export function verifyEd25519MandateSignature(mandate, signingPayload, expectedSigner) {
192
+ if (!mandate.proof || mandate.proofType !== "ed25519")
193
+ return false;
194
+ const pubKey = decodeEd25519Identity(expectedSigner);
195
+ if (!pubKey)
196
+ return false;
197
+ try {
198
+ return crypto.verify(null, Buffer.from(signingPayload, "utf8"), pubKey, Buffer.from(mandate.proof, "base64"));
199
+ }
200
+ catch {
201
+ return false;
202
+ }
203
+ }
204
+ /**
205
+ * Offline cryptographic verification of a complete Attenuated Capability Mandate chain.
206
+ */
207
+ export function verifySignedMandateChain(chain, intent, options = {}) {
208
+ return validateMandateChain(chain, intent, {
209
+ ...options,
210
+ requireSignatures: true,
211
+ verifySignature: verifyEd25519MandateSignature,
212
+ });
213
+ }
214
+ //# sourceMappingURL=mandate.js.map
@@ -0,0 +1,65 @@
1
+ import type { AgentTrustLookupResult } from "@fiderail/core";
2
+ export interface EdgeSpendLedger {
3
+ getSpentTodayUsdc(nowDate?: Date): number;
4
+ getPendingReservedTodayUsdc(nowDate?: Date, nowMs?: number): number;
5
+ getEffectiveSpentTodayUsdc(nowDate?: Date): number;
6
+ getTxCountToday(nowDate?: Date): number;
7
+ recordSpend(amountUsdc: number, nowDate?: Date): number;
8
+ reserveBudget(amountUsdc: number, maxDailyUsdc: number, nowDate?: Date): {
9
+ ok: boolean;
10
+ reservationId: string | null;
11
+ effectiveSpentUsdc: number;
12
+ };
13
+ commitReservation(reservationId: string, nowDate?: Date): number;
14
+ releaseReservation(reservationId: string | null): boolean;
15
+ recordRecoverableProof(fingerprint: string, opts: {
16
+ proofValue: string;
17
+ quoteDigest: string;
18
+ ttlMs?: number;
19
+ nowMs?: number;
20
+ }): void;
21
+ getRecoverableProof(fingerprint: string, nowMs?: number): {
22
+ proofValue: string;
23
+ quoteDigest: string;
24
+ expiresAtMs: number;
25
+ } | null;
26
+ clearRecoverableProof(fingerprint: string): void;
27
+ checkIdempotency(fingerprint: string, windowMs?: number, nowMs?: number): {
28
+ isDuplicate: boolean;
29
+ secondsSinceLast: number | null;
30
+ };
31
+ recordPaymentFingerprint(fingerprint: string, nowMs?: number): void;
32
+ checkCircuitBreaker(endpointKey: string, nowMs?: number): {
33
+ open: boolean;
34
+ retryAfterSec: number;
35
+ consecutiveFailures: number;
36
+ lastStatus: number | null;
37
+ };
38
+ recordEndpointFailure(endpointKey: string, opts?: {
39
+ status?: number | null;
40
+ maxConsecutiveFailures?: number;
41
+ cooldownMs?: number;
42
+ nowMs?: number;
43
+ }): {
44
+ opened: boolean;
45
+ consecutiveFailures: number;
46
+ retryAfterSec: number;
47
+ };
48
+ recordEndpointSuccess(endpointKey: string): void;
49
+ getMandateSpentUsd(mandateId: string): number;
50
+ recordMandateSpend(mandateId: string, amountUsd: number): number;
51
+ revokeMandate(mandateId: string, reason?: string): void;
52
+ isMandateRevoked(mandateId: string): boolean;
53
+ getRevokedMandateIds(): Set<string>;
54
+ getCachedTrust(chain: string, address: string, nowMs?: number): AgentTrustLookupResult | null;
55
+ setCachedTrust(chain: string, address: string, profile: AgentTrustLookupResult, ttlMs?: number, nowMs?: number): void;
56
+ clearTrustCache(): void;
57
+ close(): void;
58
+ }
59
+ /**
60
+ * Concurrent-safe embedded SQLite WAL edge ledger (zero npm deps; uses Node 22+ `node:sqlite`).
61
+ * Uses `BEGIN IMMEDIATE` write locks so concurrent Promise.all bursts AND multiple separate
62
+ * agent processes sharing the same `.db` file cannot overspend `maxDailyUsdc`.
63
+ */
64
+ export declare function createSqliteSpendLedger(dbPath?: string): EdgeSpendLedger;
65
+ //# sourceMappingURL=sqlite-ledger.d.ts.map