@fiderail/db 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.
@@ -0,0 +1,33 @@
1
+ import type { TrustStateRootCommitment } from "@fiderail/zk-types";
2
+ export declare const STATE_ROOT_SIGNING_FORMAT = "fiderail-state-root-v1:{epochId}:{merkleRoot}";
3
+ export interface StateRootPublicKeyInfo {
4
+ readonly keyId: string;
5
+ readonly algorithm: "Ed25519";
6
+ readonly use: "stateRoot";
7
+ readonly status: "ACTIVE";
8
+ readonly publicKeyPem: string;
9
+ readonly spkiBase64Url: string;
10
+ }
11
+ /**
12
+ * Deterministic canonical message signed by FideRail Ed25519 stateRoot keys.
13
+ */
14
+ export declare function createStateRootSigningPayload(merkleRoot: string, epochId: string): string;
15
+ /**
16
+ * Derives public verification key metadata (`keyId`, SPKI PEM, base64url DER) from
17
+ * `FIDERAIL_STATE_ROOT_PUBLIC_KEY_PEM` or `FIDERAIL_STATE_ROOT_PRIVATE_KEY_PEM`.
18
+ * Returns null if no Ed25519 signing/verification key is configured.
19
+ */
20
+ export declare function deriveStateRootPublicKey(options?: {
21
+ privateKeyPem?: string;
22
+ publicKeyPem?: string;
23
+ }): StateRootPublicKeyInfo | null;
24
+ /**
25
+ * Signs a Merkle trust stateRoot commitment with an Ed25519 PKCS#8 private key PEM.
26
+ * Falls back to `process.env.FIDERAIL_STATE_ROOT_PRIVATE_KEY_PEM` when omitted; returns null if unconfigured.
27
+ */
28
+ export declare function signStateRootEd25519(merkleRoot: string, epochId: string, privateKeyPem?: string): string | null;
29
+ /**
30
+ * Verifies an Ed25519 signature over a TrustStateRootCommitment against an SPKI public key PEM.
31
+ */
32
+ export declare function verifyStateRootEd25519(commitment: Pick<TrustStateRootCommitment, "merkleRoot" | "epochId" | "signature">, publicKeyPem: string): boolean;
33
+ //# sourceMappingURL=state-root-signer.d.ts.map
@@ -0,0 +1,81 @@
1
+ import crypto from "node:crypto";
2
+ export const STATE_ROOT_SIGNING_FORMAT = "fiderail-state-root-v1:{epochId}:{merkleRoot}";
3
+ function normalizePem(raw) {
4
+ if (!raw || typeof raw !== "string")
5
+ return "";
6
+ let s = raw.trim();
7
+ if ((s.startsWith('"') && s.endsWith('"')) || (s.startsWith("'") && s.endsWith("'"))) {
8
+ s = s.slice(1, -1);
9
+ }
10
+ return s.replace(/\\n/g, "\n").trim();
11
+ }
12
+ /**
13
+ * Deterministic canonical message signed by FideRail Ed25519 stateRoot keys.
14
+ */
15
+ export function createStateRootSigningPayload(merkleRoot, epochId) {
16
+ return `fiderail-state-root-v1:${epochId}:${merkleRoot}`;
17
+ }
18
+ /**
19
+ * Derives public verification key metadata (`keyId`, SPKI PEM, base64url DER) from
20
+ * `FIDERAIL_STATE_ROOT_PUBLIC_KEY_PEM` or `FIDERAIL_STATE_ROOT_PRIVATE_KEY_PEM`.
21
+ * Returns null if no Ed25519 signing/verification key is configured.
22
+ */
23
+ export function deriveStateRootPublicKey(options = {}) {
24
+ const pubPemInput = normalizePem(options.publicKeyPem ?? process.env.FIDERAIL_STATE_ROOT_PUBLIC_KEY_PEM);
25
+ const privPemInput = normalizePem(options.privateKeyPem ?? process.env.FIDERAIL_STATE_ROOT_PRIVATE_KEY_PEM);
26
+ try {
27
+ let pubKeyObj = null;
28
+ if (pubPemInput) {
29
+ pubKeyObj = crypto.createPublicKey(pubPemInput);
30
+ }
31
+ else if (privPemInput) {
32
+ const privKeyObj = crypto.createPrivateKey(privPemInput);
33
+ pubKeyObj = crypto.createPublicKey(privKeyObj);
34
+ }
35
+ if (!pubKeyObj || pubKeyObj.asymmetricKeyType !== "ed25519") {
36
+ return null;
37
+ }
38
+ const publicKeyPem = pubKeyObj.export({ type: "spki", format: "pem" }).toString().trim();
39
+ const spkiDer = pubKeyObj.export({ type: "spki", format: "der" });
40
+ const fingerprint = crypto.createHash("sha256").update(spkiDer).digest("hex").slice(0, 16);
41
+ return {
42
+ keyId: `ed25519:${fingerprint}`,
43
+ algorithm: "Ed25519",
44
+ use: "stateRoot",
45
+ status: "ACTIVE",
46
+ publicKeyPem,
47
+ spkiBase64Url: spkiDer.toString("base64url"),
48
+ };
49
+ }
50
+ catch {
51
+ return null;
52
+ }
53
+ }
54
+ /**
55
+ * Signs a Merkle trust stateRoot commitment with an Ed25519 PKCS#8 private key PEM.
56
+ * Falls back to `process.env.FIDERAIL_STATE_ROOT_PRIVATE_KEY_PEM` when omitted; returns null if unconfigured.
57
+ */
58
+ export function signStateRootEd25519(merkleRoot, epochId, privateKeyPem) {
59
+ const pem = normalizePem(privateKeyPem ?? process.env.FIDERAIL_STATE_ROOT_PRIVATE_KEY_PEM);
60
+ if (!pem)
61
+ return null;
62
+ const payload = createStateRootSigningPayload(merkleRoot, epochId);
63
+ const sig = crypto.sign(null, Buffer.from(payload, "utf8"), pem);
64
+ return sig.toString("base64");
65
+ }
66
+ /**
67
+ * Verifies an Ed25519 signature over a TrustStateRootCommitment against an SPKI public key PEM.
68
+ */
69
+ export function verifyStateRootEd25519(commitment, publicKeyPem) {
70
+ const pubPem = normalizePem(publicKeyPem);
71
+ if (!commitment?.signature || !pubPem)
72
+ return false;
73
+ try {
74
+ const payload = createStateRootSigningPayload(commitment.merkleRoot, commitment.epochId);
75
+ return crypto.verify(null, Buffer.from(payload, "utf8"), pubPem, Buffer.from(commitment.signature, "base64"));
76
+ }
77
+ catch {
78
+ return false;
79
+ }
80
+ }
81
+ //# sourceMappingURL=state-root-signer.js.map
package/package.json CHANGED
@@ -1,6 +1,58 @@
1
1
  {
2
2
  "name": "@fiderail/db",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "2.3.2",
4
+ "description": "FideRail storage abstraction: PostgreSQL 16 primary repository (monthly partitioned payments, NUMERIC(78,0), indexed queries), SQLite WAL repository, and lossless SQLite-to-PostgreSQL migrator.",
5
+ "type": "module",
6
+ "main": "./dist/index.js",
7
+ "types": "./dist/index.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "types": "./dist/index.d.ts",
11
+ "import": "./dist/index.js"
12
+ }
13
+ },
14
+ "files": [
15
+ "README.md",
16
+ "LICENSE",
17
+ "dist",
18
+ "sql",
19
+ "!dist/**/*.map",
20
+ "!dist/**/*.tsbuildinfo"
21
+ ],
22
+ "scripts": {
23
+ "prepublishOnly": "tsc -b"
24
+ },
25
+ "publishConfig": {
26
+ "access": "public"
27
+ },
28
+ "engines": {
29
+ "node": ">=22.13.0"
30
+ },
31
+ "homepage": "https://fiderail.com",
32
+ "repository": {
33
+ "type": "git",
34
+ "url": "git+https://gitlab.com/fiderail/fiderail.git",
35
+ "directory": "packages/db"
36
+ },
37
+ "bugs": {
38
+ "url": "https://gitlab.com/fiderail/fiderail/-/issues"
39
+ },
40
+ "keywords": [
41
+ "fiderail",
42
+ "ai-agent",
43
+ "postgresql",
44
+ "sqlite",
45
+ "storage",
46
+ "merkle",
47
+ "ed25519",
48
+ "payment-control-plane",
49
+ "x402"
50
+ ],
51
+ "dependencies": {
52
+ "@fiderail/core": "2.3.2",
53
+ "@fiderail/spec": "2.3.2",
54
+ "@fiderail/zk-types": "2.3.2",
55
+ "pg": "^8.14.1"
56
+ },
57
+ "license": "MIT"
58
+ }
@@ -0,0 +1,231 @@
1
+ -- FideRail — Canonical PostgreSQL 16 Schema
2
+ -- Locked to 4 chains x 2 fiat-pegged stablecoins (Base, Solana, Arbitrum, Polygon).
3
+ -- Zero custody: never stores private keys, session keys, or user balances.
4
+
5
+ CREATE TABLE IF NOT EXISTS payments (
6
+ chain_key TEXT NOT NULL,
7
+ tx_id TEXT NOT NULL,
8
+ event_index INTEGER NOT NULL DEFAULT 0,
9
+ asset_contract TEXT NOT NULL,
10
+ asset_symbol TEXT NOT NULL,
11
+ amount_raw NUMERIC(78, 0) NOT NULL,
12
+ amount_usd NUMERIC(24, 6) NOT NULL,
13
+ payer TEXT NOT NULL,
14
+ payee TEXT NOT NULL,
15
+ channel TEXT NOT NULL,
16
+ facilitator TEXT,
17
+ relayer TEXT,
18
+ block_number BIGINT,
19
+ block_time TIMESTAMPTZ NOT NULL,
20
+ confirmation_status TEXT NOT NULL DEFAULT 'CONFIRMED',
21
+ has_memo BOOLEAN NOT NULL DEFAULT FALSE,
22
+ inserted_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
23
+ PRIMARY KEY (chain_key, tx_id, event_index, block_time)
24
+ ) PARTITION BY RANGE (block_time);
25
+
26
+ -- Default partition catches any historical timestamps outside pre-created monthly partitions
27
+ CREATE TABLE IF NOT EXISTS payments_default PARTITION OF payments DEFAULT;
28
+
29
+ CREATE INDEX IF NOT EXISTS idx_payments_chain_payee_time
30
+ ON payments (chain_key, payee, block_time DESC);
31
+ CREATE INDEX IF NOT EXISTS idx_payments_chain_payer_time
32
+ ON payments (chain_key, payer, block_time DESC);
33
+ CREATE INDEX IF NOT EXISTS idx_payments_chain_block
34
+ ON payments (chain_key, block_number DESC);
35
+ CREATE INDEX IF NOT EXISTS idx_payments_chain_channel
36
+ ON payments (chain_key, channel);
37
+
38
+ -- Identity & Wallet Decoupling (never equate a single address with an entire AI Agent)
39
+ CREATE TABLE IF NOT EXISTS agent_identities (
40
+ identity_id TEXT PRIMARY KEY,
41
+ identity_type TEXT NOT NULL DEFAULT 'erc8004',
42
+ primary_chain TEXT NOT NULL,
43
+ metadata_hash TEXT,
44
+ erc8004_token_id BIGINT,
45
+ created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
46
+ updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
47
+ );
48
+
49
+ CREATE TABLE IF NOT EXISTS agent_wallets (
50
+ identity_id TEXT NOT NULL REFERENCES agent_identities(identity_id) ON DELETE CASCADE,
51
+ chain_key TEXT NOT NULL,
52
+ address TEXT NOT NULL,
53
+ relation_type TEXT NOT NULL DEFAULT 'PRIMARY',
54
+ proof_type TEXT NOT NULL DEFAULT 'eip712',
55
+ proof_payload JSONB,
56
+ status TEXT NOT NULL DEFAULT 'ACTIVE',
57
+ created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
58
+ PRIMARY KEY (identity_id, chain_key, address)
59
+ );
60
+
61
+ CREATE INDEX IF NOT EXISTS idx_agent_wallets_chain_addr
62
+ ON agent_wallets (chain_key, address);
63
+
64
+ -- Non-Custodial Parent->Child Associated Credit Endorsements (strictly isolated from credit_score)
65
+ CREATE TABLE IF NOT EXISTS associated_credit_endorsements (
66
+ endorsement_id TEXT PRIMARY KEY,
67
+ parent_chain TEXT NOT NULL,
68
+ parent_address TEXT NOT NULL,
69
+ child_chain TEXT NOT NULL,
70
+ child_address TEXT NOT NULL,
71
+ discount_factor NUMERIC(5, 4) NOT NULL DEFAULT 0.7000,
72
+ max_endorsed_score INTEGER NOT NULL DEFAULT 65,
73
+ max_endorsed_single_tx_usd NUMERIC(24, 6) NOT NULL DEFAULT 5.000000,
74
+ rule_version TEXT NOT NULL DEFAULT 'assoc-v1',
75
+ status TEXT NOT NULL DEFAULT 'ACTIVE',
76
+ issued_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
77
+ expires_at TIMESTAMPTZ NOT NULL,
78
+ proof_type TEXT NOT NULL DEFAULT 'ed25519',
79
+ proof_payload JSONB,
80
+ updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
81
+ );
82
+
83
+ CREATE INDEX IF NOT EXISTS idx_assoc_credit_child
84
+ ON associated_credit_endorsements (child_chain, child_address, status);
85
+
86
+ CREATE TABLE IF NOT EXISTS erc8004_identities (
87
+ chain_key TEXT NOT NULL,
88
+ owner_address TEXT NOT NULL,
89
+ token_id BIGINT,
90
+ block_number BIGINT,
91
+ block_time BIGINT,
92
+ PRIMARY KEY (chain_key, owner_address)
93
+ );
94
+
95
+ -- Materialized Trust Profiles (SQL-pushed filtering & pagination)
96
+ CREATE TABLE IF NOT EXISTS agent_profiles (
97
+ chain_key TEXT NOT NULL,
98
+ address TEXT NOT NULL,
99
+ credit_score INTEGER NOT NULL,
100
+ tier TEXT NOT NULL,
101
+ confidence NUMERIC(5, 4),
102
+ confidence_level TEXT,
103
+ risk_level TEXT,
104
+ model_version TEXT NOT NULL DEFAULT 'trust-v2',
105
+ model_hash TEXT,
106
+ tx_count INTEGER NOT NULL,
107
+ total_usdc NUMERIC(24, 6) NOT NULL,
108
+ unique_payers INTEGER NOT NULL,
109
+ median_ticket_usdc NUMERIC(24, 6) NOT NULL,
110
+ hhi NUMERIC(8, 4) NOT NULL,
111
+ top1_payer_share NUMERIC(8, 4) NOT NULL,
112
+ active_span_hours NUMERIC(12, 2) NOT NULL DEFAULT 0,
113
+ active_utc_days INTEGER NOT NULL DEFAULT 1,
114
+ metrics_json JSONB,
115
+ data_coverage_json JSONB,
116
+ channels_json JSONB NOT NULL DEFAULT '[]'::jsonb,
117
+ risk_flags_json JSONB NOT NULL DEFAULT '[]'::jsonb,
118
+ has_verified_x402 BOOLEAN NOT NULL DEFAULT FALSE,
119
+ erc8004_registered BOOLEAN NOT NULL DEFAULT FALSE,
120
+ first_seen_at TIMESTAMPTZ,
121
+ last_seen_at TIMESTAMPTZ,
122
+ updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
123
+ source TEXT NOT NULL DEFAULT 'postgres_live',
124
+ PRIMARY KEY (chain_key, address)
125
+ );
126
+
127
+ CREATE INDEX IF NOT EXISTS idx_profiles_rank
128
+ ON agent_profiles (chain_key, credit_score DESC, total_usdc DESC);
129
+ CREATE INDEX IF NOT EXISTS idx_profiles_tier_score
130
+ ON agent_profiles (tier, credit_score DESC);
131
+ CREATE INDEX IF NOT EXISTS idx_profiles_x402
132
+ ON agent_profiles (has_verified_x402, credit_score DESC);
133
+
134
+ -- Delta Reputation History
135
+ CREATE TABLE IF NOT EXISTS trust_score_history (
136
+ id BIGSERIAL PRIMARY KEY,
137
+ chain_key TEXT NOT NULL,
138
+ address TEXT NOT NULL,
139
+ model_version TEXT NOT NULL,
140
+ previous_score INTEGER,
141
+ current_score INTEGER NOT NULL,
142
+ reason_codes JSONB NOT NULL DEFAULT '[]'::jsonb,
143
+ recorded_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
144
+ );
145
+
146
+ CREATE INDEX IF NOT EXISTS idx_trust_history_addr_time
147
+ ON trust_score_history (chain_key, address, recorded_at DESC);
148
+
149
+ -- Signed Merkle State Root Commitments
150
+ CREATE TABLE IF NOT EXISTS trust_state_roots (
151
+ epoch_id TEXT PRIMARY KEY,
152
+ chain_key TEXT NOT NULL,
153
+ model_version TEXT NOT NULL,
154
+ model_hash TEXT NOT NULL,
155
+ merkle_root TEXT NOT NULL,
156
+ leaf_count INTEGER NOT NULL,
157
+ proof_type TEXT NOT NULL DEFAULT 'ed25519',
158
+ signature TEXT,
159
+ created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
160
+ );
161
+
162
+ CREATE INDEX IF NOT EXISTS idx_state_roots_chain_time
163
+ ON trust_state_roots (chain_key, created_at DESC);
164
+
165
+ -- Indexer Checkpoints & Operational State
166
+ CREATE TABLE IF NOT EXISTS indexer_state (
167
+ key TEXT PRIMARY KEY,
168
+ value TEXT NOT NULL,
169
+ updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
170
+ );
171
+
172
+ -- Service Capabilities (CDP Bazaar, PayAI Discovery, Open Bazaar)
173
+ CREATE TABLE IF NOT EXISTS service_capabilities (
174
+ chain_key TEXT NOT NULL,
175
+ address TEXT NOT NULL,
176
+ resource_url TEXT NOT NULL,
177
+ service_name TEXT,
178
+ description TEXT,
179
+ method TEXT,
180
+ price_usdc NUMERIC(24, 6),
181
+ tags_json JSONB NOT NULL DEFAULT '[]'::jsonb,
182
+ source TEXT NOT NULL,
183
+ last_updated TEXT,
184
+ synced_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
185
+ PRIMARY KEY (chain_key, address, resource_url)
186
+ );
187
+
188
+ CREATE INDEX IF NOT EXISTS idx_caps_chain_addr
189
+ ON service_capabilities (chain_key, address);
190
+
191
+ -- L1 Liveness Probes & L2 Delivery Telemetry Aggregates
192
+ CREATE TABLE IF NOT EXISTS service_liveness (
193
+ chain_key TEXT NOT NULL,
194
+ address TEXT NOT NULL,
195
+ resource_url TEXT NOT NULL,
196
+ liveness_status TEXT NOT NULL,
197
+ last_http_status INTEGER,
198
+ last_latency_ms INTEGER,
199
+ probe_total INTEGER NOT NULL DEFAULT 0,
200
+ probe_healthy INTEGER NOT NULL DEFAULT 0,
201
+ delivery_reports_total INTEGER NOT NULL DEFAULT 0,
202
+ delivery_reports_ok INTEGER NOT NULL DEFAULT 0,
203
+ header_bytes INTEGER,
204
+ observed_price_usdc NUMERIC(24, 6),
205
+ diagnostic_flags_json JSONB NOT NULL DEFAULT '[]'::jsonb,
206
+ last_error TEXT,
207
+ last_probed_at TIMESTAMPTZ,
208
+ updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
209
+ PRIMARY KEY (chain_key, address, resource_url)
210
+ );
211
+
212
+ CREATE INDEX IF NOT EXISTS idx_liveness_chain_addr
213
+ ON service_liveness (chain_key, address);
214
+
215
+ -- L2 Verifiable Delivery Attestations (fiderail-sar-v2 envelopes)
216
+ CREATE TABLE IF NOT EXISTS delivery_attestations (
217
+ id BIGSERIAL PRIMARY KEY,
218
+ chain_key TEXT NOT NULL,
219
+ address TEXT NOT NULL,
220
+ resource_url TEXT NOT NULL,
221
+ receipt_hash TEXT UNIQUE,
222
+ verification_tier TEXT NOT NULL DEFAULT 'L2_SIGNED_SAR_TELEMETRY',
223
+ delivered BOOLEAN NOT NULL,
224
+ http_status INTEGER,
225
+ latency_ms INTEGER,
226
+ receipt_payload JSONB,
227
+ recorded_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
228
+ );
229
+
230
+ CREATE INDEX IF NOT EXISTS idx_attestations_chain_addr
231
+ ON delivery_attestations (chain_key, address, recorded_at DESC);