apodictic-sdk 0.0.0-stage → 3.9.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/README.md +58 -2
- package/package.json +29 -4
- package/src/enclave_worker.py +717 -0
- package/src/index.d.ts +157 -0
- package/src/index.mjs +622 -0
- package/src/odoo20_guard.mjs +321 -0
- package/src/pglite_shadow.d.mts +36 -0
- package/src/pglite_shadow.mjs +286 -0
- package/src/standalone_z3_enclave.py +2094 -0
- package/src/z3_wasm_verifier.mjs +1314 -0
package/src/index.mjs
ADDED
|
@@ -0,0 +1,622 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @apodictic/sdk — Standalone & Remote SymbolicGateway
|
|
3
|
+
* Persistent local Z3 5.4.1 / PostgreSQL AST / WORM / Rollback / Bi-Temporal /
|
|
4
|
+
* 3-Way Match / Indirect Tax enclave client with full remote HTTP gateway parity
|
|
5
|
+
* and Zero-PII local redaction before any cloud egress.
|
|
6
|
+
*/
|
|
7
|
+
import { spawn } from 'node:child_process';
|
|
8
|
+
import fs from 'node:fs';
|
|
9
|
+
import path from 'node:path';
|
|
10
|
+
import readline from 'node:readline';
|
|
11
|
+
import { fileURLToPath } from 'node:url';
|
|
12
|
+
import { evaluateOdoo20Call, extractOdoo20Call } from './odoo20_guard.mjs';
|
|
13
|
+
import { PGlite, ShadowPostgresVerifier } from './pglite_shadow.mjs';
|
|
14
|
+
import { terminateZ3WasmThreads, Z3WasmEnclaveSession } from './z3_wasm_verifier.mjs';
|
|
15
|
+
|
|
16
|
+
const ZERO_WIDTH_RE = /[\u200B-\u200D\uFEFF\u00AD]/g;
|
|
17
|
+
|
|
18
|
+
export function validateIbanMod97(candidate) {
|
|
19
|
+
const cleaned = String(candidate || '').replace(/[\s-]+/g, '').toUpperCase();
|
|
20
|
+
if (cleaned.length < 15 || cleaned.length > 34) return false;
|
|
21
|
+
if (!/^[A-Z]{2}\d{2}[A-Z0-9]+$/.test(cleaned)) return false;
|
|
22
|
+
const rearranged = cleaned.slice(4) + cleaned.slice(0, 2) + '00';
|
|
23
|
+
let mod = 0;
|
|
24
|
+
for (const ch of rearranged) {
|
|
25
|
+
const val = ch >= 'A' && ch <= 'Z' ? String(ch.charCodeAt(0) - 55) : ch;
|
|
26
|
+
for (const d of val) {
|
|
27
|
+
mod = (mod * 10 + Number(d)) % 97;
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
return String(98 - mod).padStart(2, '0') === cleaned.slice(2, 4);
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export function validateLuhnPan(candidate) {
|
|
34
|
+
const digits = String(candidate || '').replace(/[\s-]+/g, '');
|
|
35
|
+
if (!/^\d{13,19}$/.test(digits)) return false;
|
|
36
|
+
let sum = 0;
|
|
37
|
+
let alt = false;
|
|
38
|
+
for (let i = digits.length - 1; i >= 0; i--) {
|
|
39
|
+
let n = Number(digits[i]);
|
|
40
|
+
if (alt) {
|
|
41
|
+
n *= 2;
|
|
42
|
+
if (n > 9) n -= 9;
|
|
43
|
+
}
|
|
44
|
+
sum += n;
|
|
45
|
+
alt = !alt;
|
|
46
|
+
}
|
|
47
|
+
return sum > 0 && sum % 10 === 0;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
const PATTERNS = [
|
|
51
|
+
{ key: 'SECRET', re: /-----BEGIN [A-Z0-9 ]*PRIVATE KEY-----[\s\S]*?-----END [A-Z0-9 ]*PRIVATE KEY-----/g },
|
|
52
|
+
{ key: 'SECRET', re: /\b(?:sk_live|sk_test|pk_live|pk_test|rk_live|rk_test|ghp|gho|glpat|xoxb|xoxp|odoo_rpc_live)_[A-Za-z0-9_-]{6,}\b/g },
|
|
53
|
+
{ key: 'SECRET', re: /\bAIzaSy[A-Za-z0-9_-]{20,40}\b/g },
|
|
54
|
+
{ key: 'SECRET', re: /\bAKIA[0-9A-Z]{16}\b/g },
|
|
55
|
+
{ key: 'SECRET', re: /\beyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\b/g },
|
|
56
|
+
{ key: 'DB_URL', re: /\bpostgres(?:ql)?:\/\/[^\s'"]+@[^\s'"]+\b/gi },
|
|
57
|
+
{ key: 'IBAN', re: /\b[A-Za-z]{2}\d{2}(?:[A-Za-z0-9]{10,30}|(?:[\s-][A-Za-z0-9]{4}){2,7}(?:[\s-][A-Za-z0-9]{1,4})?)\b/g },
|
|
58
|
+
{ key: 'CARD', re: /\b(?:\d{4}[-\s]?\d{6}[-\s]?\d{5}|\d{4}[-\s]?\d{4}[-\s]?\d{4}[-\s]?\d{1,7}|\d{13,19})\b/g },
|
|
59
|
+
{ key: 'EMAIL', re: /\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b/g },
|
|
60
|
+
{ key: 'TAX', re: /\b(?:ETA-\d{6,12}|TIN\s*\d{2}-\d{7}|\d{3}-\d{3}-\d{3})\b/g },
|
|
61
|
+
{ key: 'QUOTED_LIT', re: /'((?:''|[^']){4,})'/g },
|
|
62
|
+
];
|
|
63
|
+
|
|
64
|
+
const SRC_DIR = path.dirname(fileURLToPath(import.meta.url));
|
|
65
|
+
const WORKER_SCRIPT = path.join(SRC_DIR, 'enclave_worker.py');
|
|
66
|
+
const DEFAULT_REPO_ROOT = path.resolve(SRC_DIR, '..', '..', '..');
|
|
67
|
+
|
|
68
|
+
export class SymbolicGateway {
|
|
69
|
+
constructor(options = {}) {
|
|
70
|
+
this.posture = options.posture || (options.airgap ? 'MODE_A_AIRGAP' : 'MODE_B_HYBRID');
|
|
71
|
+
this.airgap = Boolean(options.airgap) || this.posture === 'MODE_A_AIRGAP';
|
|
72
|
+
this.vaultPath = options.vaultPath || 'sqlite:///var/run/apodictic/sym_vault.db';
|
|
73
|
+
this.forbidRawLiterals = options.forbidRawLiterals !== false;
|
|
74
|
+
this.endpoint = this.airgap ? '' : (options.endpoint || process.env.APODICTIC_ENDPOINT || '');
|
|
75
|
+
this.apiKey = options.apiKey || process.env.APODICTIC_API_KEY || '';
|
|
76
|
+
this.repoRoot = options.repoRoot || process.env.APODICTIC_REPO_ROOT || DEFAULT_REPO_ROOT;
|
|
77
|
+
this.pythonBin = options.pythonBin || process.env.APODICTIC_PYTHON || 'python3';
|
|
78
|
+
this.engine = options.engine || 'auto'; // 'auto' | 'python' | 'wasm' | 'rust'
|
|
79
|
+
this.rustKernelPath = options.rustKernelPath || process.env.APODICTIC_RUST_KERNEL || '';
|
|
80
|
+
this.stateDbPath = options.stateDbPath || process.env.APODICTIC_STATE_DB || '';
|
|
81
|
+
this.timeoutMs = options.timeoutMs ?? 15000;
|
|
82
|
+
|
|
83
|
+
this.forward = new Map();
|
|
84
|
+
this.sensitiveSecrets = new Map();
|
|
85
|
+
this.quotedLiterals = new Map();
|
|
86
|
+
this.reverse = new Map();
|
|
87
|
+
this.counters = {};
|
|
88
|
+
|
|
89
|
+
this._worker = null;
|
|
90
|
+
this._pending = new Map();
|
|
91
|
+
this._nextReqId = 1;
|
|
92
|
+
this._pythonUnavailable = process.env.APODICTIC_DISABLE_PYTHON === '1';
|
|
93
|
+
|
|
94
|
+
this._wasmSession = null;
|
|
95
|
+
|
|
96
|
+
this._rustWorker = null;
|
|
97
|
+
this._rustPending = new Map();
|
|
98
|
+
this._nextRustReqId = 1;
|
|
99
|
+
|
|
100
|
+
this._shadowVerifier = null;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
_mint(prefix, raw) {
|
|
104
|
+
if (this.forward.has(raw)) return this.forward.get(raw);
|
|
105
|
+
const n = (this.counters[prefix] = (this.counters[prefix] || 0) + 1);
|
|
106
|
+
const sym = `<SYM_${prefix}_${String(n).padStart(2, '0')}>`;
|
|
107
|
+
this.forward.set(raw, sym);
|
|
108
|
+
if (prefix === 'LIT') {
|
|
109
|
+
this.quotedLiterals.set(raw, sym);
|
|
110
|
+
} else {
|
|
111
|
+
this.sensitiveSecrets.set(raw, sym);
|
|
112
|
+
}
|
|
113
|
+
this.reverse.set(sym, raw);
|
|
114
|
+
return sym;
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
scrubSqlAst(input, opts = {}) {
|
|
118
|
+
const scrubQuotedLiterals = opts?.scrubQuotedLiterals !== false;
|
|
119
|
+
let text = String(input ?? '').replace(ZERO_WIDTH_RE, '');
|
|
120
|
+
let redacted = 0;
|
|
121
|
+
let ibanMod97ValidCount = 0;
|
|
122
|
+
let luhnPanValidCount = 0;
|
|
123
|
+
for (const { key, re } of PATTERNS) {
|
|
124
|
+
if (key === 'QUOTED_LIT' && !scrubQuotedLiterals) continue;
|
|
125
|
+
text = text.replace(re, (match, group1) => {
|
|
126
|
+
if (key === 'CARD') {
|
|
127
|
+
if (!validateLuhnPan(match)) return match;
|
|
128
|
+
luhnPanValidCount++;
|
|
129
|
+
}
|
|
130
|
+
if (key === 'IBAN') {
|
|
131
|
+
if (!validateIbanMod97(match)) return match;
|
|
132
|
+
ibanMod97ValidCount++;
|
|
133
|
+
}
|
|
134
|
+
if (key === 'QUOTED_LIT') {
|
|
135
|
+
if (group1.startsWith('<SYM_') && group1.endsWith('>')) return match;
|
|
136
|
+
const sym = this._mint('LIT', group1);
|
|
137
|
+
redacted++;
|
|
138
|
+
return `'${sym}'`;
|
|
139
|
+
}
|
|
140
|
+
redacted++;
|
|
141
|
+
return this._mint(key, match);
|
|
142
|
+
});
|
|
143
|
+
}
|
|
144
|
+
if (this.forbidRawLiterals) {
|
|
145
|
+
const checkMap = scrubQuotedLiterals ? this.forward : this.sensitiveSecrets;
|
|
146
|
+
for (const raw of checkMap.keys()) {
|
|
147
|
+
if (text.includes(raw)) {
|
|
148
|
+
throw new Error('Strict egress violation: literal remained unmasked');
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
return {
|
|
153
|
+
sanitized: text,
|
|
154
|
+
redactions: redacted,
|
|
155
|
+
symbolCount: this.forward.size,
|
|
156
|
+
dlpChecksums: {
|
|
157
|
+
ibanMod97ValidCount,
|
|
158
|
+
luhnPanValidCount,
|
|
159
|
+
validators: ['ISO-7064-Mod-97-10', 'Luhn-Mod-10'],
|
|
160
|
+
},
|
|
161
|
+
};
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
rehydrate(text) {
|
|
165
|
+
let out = String(text ?? '');
|
|
166
|
+
const entries = [...this.reverse.entries()].reverse();
|
|
167
|
+
for (let pass = 0; pass < 3; pass++) {
|
|
168
|
+
let changed = false;
|
|
169
|
+
for (const [sym, raw] of entries) {
|
|
170
|
+
if (out.includes(sym)) {
|
|
171
|
+
out = out.split(sym).join(raw);
|
|
172
|
+
changed = true;
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
if (!changed) break;
|
|
176
|
+
}
|
|
177
|
+
return out;
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
_getWasmSession() {
|
|
181
|
+
if (!this._wasmSession) {
|
|
182
|
+
this._wasmSession = new Z3WasmEnclaveSession(this.stateDbPath);
|
|
183
|
+
}
|
|
184
|
+
return this._wasmSession;
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
async _dispatchWasm(method, params = {}) {
|
|
188
|
+
const sess = this._getWasmSession();
|
|
189
|
+
if (method === 'verify_mutation') return await sess.verifyMutation(params);
|
|
190
|
+
if (method === 'rollback') return sess.rollback(params);
|
|
191
|
+
if (method === 'flush_escrow') return sess.flushEscrow(params);
|
|
192
|
+
if (method === 'verify_three_way_match') return await sess.verifyThreeWayMatch(params);
|
|
193
|
+
if (method === 'verify_tax_compliance') return await sess.verifyTaxCompliance(params);
|
|
194
|
+
if (method === 'evaluate_policy') return await sess.evaluatePolicy(params);
|
|
195
|
+
if (method === 'bitemporal_insert') return sess.bitemporalInsert(params);
|
|
196
|
+
if (method === 'bitemporal_restate') return sess.bitemporalRestate(params);
|
|
197
|
+
if (method === 'bitemporal_as_of') return sess.bitemporalAsOf(params);
|
|
198
|
+
if (method === 'verify_audit_chain') return sess.verifyAuditChain();
|
|
199
|
+
if (method === 'merkle_inclusion_proof') return sess.generateRfc6962InclusionProof(params?.blockIndex);
|
|
200
|
+
if (method === 'health') return sess.health();
|
|
201
|
+
throw new Error(`Unsupported WASM enclave method: ${method}`);
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
_ensureWorker() {
|
|
205
|
+
if (this._worker && !this._worker.killed) return this._worker;
|
|
206
|
+
if (!fs.existsSync(WORKER_SCRIPT)) {
|
|
207
|
+
throw new Error(`Apodictic worker script missing at ${WORKER_SCRIPT}`);
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
const hasMonorepo = fs.existsSync(path.join(this.repoRoot, 'apodictic_engine', 'src', 'proxy', 'interceptor.py'));
|
|
211
|
+
const env = { ...process.env };
|
|
212
|
+
if (hasMonorepo) env.PYTHONPATH = this.repoRoot;
|
|
213
|
+
if (this.stateDbPath) env.APODICTIC_STATE_DB = this.stateDbPath;
|
|
214
|
+
if (this.airgap) env.APODICTIC_AIRGAP = '1';
|
|
215
|
+
|
|
216
|
+
const child = spawn(this.pythonBin, ['-B', WORKER_SCRIPT], {
|
|
217
|
+
stdio: ['pipe', 'pipe', 'pipe'],
|
|
218
|
+
env,
|
|
219
|
+
});
|
|
220
|
+
|
|
221
|
+
let stderrBuf = '';
|
|
222
|
+
child.stderr.on('data', (chunk) => {
|
|
223
|
+
stderrBuf = (stderrBuf + chunk.toString()).slice(-2048);
|
|
224
|
+
});
|
|
225
|
+
|
|
226
|
+
const rejectAllPending = (errMsg) => {
|
|
227
|
+
for (const [, entry] of this._pending) {
|
|
228
|
+
clearTimeout(entry.timer);
|
|
229
|
+
entry.reject(new Error(errMsg));
|
|
230
|
+
}
|
|
231
|
+
this._pending.clear();
|
|
232
|
+
this._worker = null;
|
|
233
|
+
};
|
|
234
|
+
|
|
235
|
+
child.on('error', (err) => {
|
|
236
|
+
this._pythonUnavailable = true;
|
|
237
|
+
rejectAllPending(`Apodictic Python worker unavailable (${err.code || err.message})`);
|
|
238
|
+
});
|
|
239
|
+
child.stdin.on('error', () => {
|
|
240
|
+
// Handled via child error/exit handlers
|
|
241
|
+
});
|
|
242
|
+
|
|
243
|
+
const rl = readline.createInterface({ input: child.stdout, crlfDelay: Infinity });
|
|
244
|
+
rl.on('line', (line) => {
|
|
245
|
+
try {
|
|
246
|
+
const msg = JSON.parse(line);
|
|
247
|
+
const entry = this._pending.get(msg.id);
|
|
248
|
+
if (!entry) return;
|
|
249
|
+
clearTimeout(entry.timer);
|
|
250
|
+
this._pending.delete(msg.id);
|
|
251
|
+
if (msg.error) entry.reject(new Error(msg.error.message || 'Enclave error'));
|
|
252
|
+
else entry.resolve(msg.result);
|
|
253
|
+
} catch {
|
|
254
|
+
// Ignore non-JSON stderr/debug noise
|
|
255
|
+
}
|
|
256
|
+
});
|
|
257
|
+
|
|
258
|
+
child.on('exit', (code) => {
|
|
259
|
+
if (code === 2 || stderrBuf.includes('z3-solver not found')) {
|
|
260
|
+
this._pythonUnavailable = true;
|
|
261
|
+
}
|
|
262
|
+
const detail = stderrBuf.trim();
|
|
263
|
+
const errMsg = detail
|
|
264
|
+
? `Apodictic enclave worker exited unexpectedly: ${detail}`
|
|
265
|
+
: `Apodictic enclave worker exited unexpectedly (code ${code ?? 'unknown'})`;
|
|
266
|
+
rejectAllPending(errMsg);
|
|
267
|
+
});
|
|
268
|
+
|
|
269
|
+
this._worker = child;
|
|
270
|
+
return child;
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
_callWorker(method, params = {}) {
|
|
274
|
+
const child = this._ensureWorker();
|
|
275
|
+
const id = this._nextReqId++;
|
|
276
|
+
return new Promise((resolve, reject) => {
|
|
277
|
+
const timer = setTimeout(() => {
|
|
278
|
+
this._pending.delete(id);
|
|
279
|
+
reject(new Error(`Apodictic enclave call '${method}' timed out after ${this.timeoutMs}ms`));
|
|
280
|
+
}, this.timeoutMs);
|
|
281
|
+
this._pending.set(id, { resolve, reject, timer });
|
|
282
|
+
try {
|
|
283
|
+
child.stdin.write(JSON.stringify({ id, method, params }) + '\n');
|
|
284
|
+
} catch (err) {
|
|
285
|
+
clearTimeout(timer);
|
|
286
|
+
this._pending.delete(id);
|
|
287
|
+
reject(err);
|
|
288
|
+
}
|
|
289
|
+
});
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
async _callRemote(method, params = {}) {
|
|
293
|
+
const headers = { 'Content-Type': 'application/json' };
|
|
294
|
+
if (this.apiKey) headers.Authorization = `Bearer ${this.apiKey}`;
|
|
295
|
+
const targetUrl = this.endpoint.endsWith('/api/v1/enclave')
|
|
296
|
+
? this.endpoint
|
|
297
|
+
: `${this.endpoint.replace(/\/+$/, '')}`;
|
|
298
|
+
const body = targetUrl.includes('/api/apodictic/verify') && method === 'verify_mutation'
|
|
299
|
+
? {
|
|
300
|
+
payload: params.sql,
|
|
301
|
+
action: params.action,
|
|
302
|
+
amount: params.amount ?? 0,
|
|
303
|
+
currentBalance: params.currentBalance,
|
|
304
|
+
minReserve: params.minReserve,
|
|
305
|
+
maxAutonomousLimit: params.maxAutonomousLimit,
|
|
306
|
+
cfoApproved: params.cfoSigned,
|
|
307
|
+
vatRate: params.statutoryVat,
|
|
308
|
+
expectedVatRate: params.expectedVat,
|
|
309
|
+
targetSystem: params.targetSystem,
|
|
310
|
+
}
|
|
311
|
+
: { method, params };
|
|
312
|
+
|
|
313
|
+
const res = await fetch(targetUrl, {
|
|
314
|
+
method: 'POST',
|
|
315
|
+
headers,
|
|
316
|
+
signal: AbortSignal.timeout(this.timeoutMs),
|
|
317
|
+
body: JSON.stringify(body),
|
|
318
|
+
});
|
|
319
|
+
if (!res.ok) {
|
|
320
|
+
throw new Error(`Apodictic gateway returned HTTP ${res.status}`);
|
|
321
|
+
}
|
|
322
|
+
const data = await res.json();
|
|
323
|
+
if (data.error) {
|
|
324
|
+
throw new Error(data.error.message || String(data.error));
|
|
325
|
+
}
|
|
326
|
+
return data.result ?? data;
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
async _dispatch(method, params = {}) {
|
|
330
|
+
if (this.endpoint && !this.airgap) {
|
|
331
|
+
return this._callRemote(method, params);
|
|
332
|
+
}
|
|
333
|
+
if (this.engine === 'wasm' || this._pythonUnavailable) {
|
|
334
|
+
return this._dispatchWasm(method, params);
|
|
335
|
+
}
|
|
336
|
+
try {
|
|
337
|
+
return await this._callWorker(method, params);
|
|
338
|
+
} catch (err) {
|
|
339
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
340
|
+
const isEnvUnavailable =
|
|
341
|
+
this._pythonUnavailable ||
|
|
342
|
+
msg.includes('ENOENT') ||
|
|
343
|
+
msg.includes('z3-solver not found') ||
|
|
344
|
+
msg.includes('worker unavailable');
|
|
345
|
+
if (this.engine === 'auto' && isEnvUnavailable) {
|
|
346
|
+
this._pythonUnavailable = true;
|
|
347
|
+
return this._dispatchWasm(method, params);
|
|
348
|
+
}
|
|
349
|
+
throw err;
|
|
350
|
+
}
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
_resolveRustKernelPath() {
|
|
354
|
+
const cands = [
|
|
355
|
+
this.rustKernelPath,
|
|
356
|
+
path.join(this.repoRoot, 'apodictic_infra', 'target', 'release', 'apodictic_rust_kernel'),
|
|
357
|
+
path.join(this.repoRoot, 'apodictic_infra', 'target', 'debug', 'apodictic_rust_kernel'),
|
|
358
|
+
].filter(Boolean);
|
|
359
|
+
for (const c of cands) {
|
|
360
|
+
if (fs.existsSync(c)) return c;
|
|
361
|
+
}
|
|
362
|
+
return '';
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
_ensureRustWorker() {
|
|
366
|
+
if (this._rustWorker && !this._rustWorker.killed) return this._rustWorker;
|
|
367
|
+
const binPath = this._resolveRustKernelPath();
|
|
368
|
+
if (!binPath) {
|
|
369
|
+
throw new Error('Native apodictic_rust_kernel binary not found in apodictic_infra/target');
|
|
370
|
+
}
|
|
371
|
+
const child = spawn(binPath, ['--daemon'], {
|
|
372
|
+
stdio: ['pipe', 'pipe', 'pipe'],
|
|
373
|
+
});
|
|
374
|
+
const rejectRustPending = (msg) => {
|
|
375
|
+
for (const [, entry] of this._rustPending) {
|
|
376
|
+
clearTimeout(entry.timer);
|
|
377
|
+
entry.reject(new Error(msg));
|
|
378
|
+
}
|
|
379
|
+
this._rustPending.clear();
|
|
380
|
+
this._rustWorker = null;
|
|
381
|
+
};
|
|
382
|
+
child.on('error', (err) => {
|
|
383
|
+
rejectRustPending(`Apodictic Rust daemon failed to spawn (${err.code || err.message})`);
|
|
384
|
+
});
|
|
385
|
+
child.stdin.on('error', () => {
|
|
386
|
+
// Handled via error/exit events
|
|
387
|
+
});
|
|
388
|
+
const rl = readline.createInterface({ input: child.stdout, crlfDelay: Infinity });
|
|
389
|
+
rl.on('line', (line) => {
|
|
390
|
+
try {
|
|
391
|
+
const msg = JSON.parse(line);
|
|
392
|
+
const entry = this._rustPending.get(Number(msg.id));
|
|
393
|
+
if (!entry) return;
|
|
394
|
+
clearTimeout(entry.timer);
|
|
395
|
+
this._rustPending.delete(Number(msg.id));
|
|
396
|
+
if (msg.error) entry.reject(new Error(String(msg.error)));
|
|
397
|
+
else entry.resolve(msg.result ?? msg);
|
|
398
|
+
} catch {
|
|
399
|
+
// ignore non-JSON debug output
|
|
400
|
+
}
|
|
401
|
+
});
|
|
402
|
+
child.on('exit', () => {
|
|
403
|
+
rejectRustPending('Apodictic Rust daemon exited unexpectedly');
|
|
404
|
+
});
|
|
405
|
+
this._rustWorker = child;
|
|
406
|
+
return child;
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
_callRustWorker(params = {}) {
|
|
410
|
+
const child = this._ensureRustWorker();
|
|
411
|
+
const id = this._nextRustReqId++;
|
|
412
|
+
return new Promise((resolve, reject) => {
|
|
413
|
+
const timer = setTimeout(() => {
|
|
414
|
+
this._rustPending.delete(id);
|
|
415
|
+
reject(new Error(`Apodictic Rust daemon timed out after ${this.timeoutMs}ms`));
|
|
416
|
+
}, this.timeoutMs);
|
|
417
|
+
this._rustPending.set(id, { resolve, reject, timer });
|
|
418
|
+
child.stdin.write(JSON.stringify({ id, params }) + '\n');
|
|
419
|
+
});
|
|
420
|
+
}
|
|
421
|
+
|
|
422
|
+
async verifyMutationNativeRust(input = {}) {
|
|
423
|
+
if (input.amount !== undefined && (!Number.isFinite(Number(input.amount)) || Number(input.amount) < 0)) {
|
|
424
|
+
throw new Error('Invalid mutation amount: must be a non-negative finite number');
|
|
425
|
+
}
|
|
426
|
+
const rawSql = String(input.sql || '').replace(ZERO_WIDTH_RE, '');
|
|
427
|
+
const r = await this._callRustWorker({
|
|
428
|
+
sql: rawSql,
|
|
429
|
+
account: input.accountId || 'sdk_default',
|
|
430
|
+
amount: input.amount ?? 0,
|
|
431
|
+
current_balance: input.currentBalance ?? 250000,
|
|
432
|
+
min_reserve: input.minReserve ?? 50000,
|
|
433
|
+
spending_limit: input.maxAutonomousLimit ?? 50000,
|
|
434
|
+
cfo_signed: Boolean(input.cfoSigned),
|
|
435
|
+
pgoutput_hex: input.pgoutputHex || undefined,
|
|
436
|
+
});
|
|
437
|
+
const ast = r.rust_sql_ast || {};
|
|
438
|
+
const z3 = r.libz3_c_ffi_proof || {};
|
|
439
|
+
const hasZ3 = Boolean(z3 && typeof z3.verdict === 'string' && z3.ffi_linked !== false);
|
|
440
|
+
const astBlocked = Boolean(ast.is_unbounded || ast.has_multi_statement || ['DROP', 'TRUNCATE', 'DELETE', 'ALTER'].includes(String(ast.statement_type || '').toUpperCase()));
|
|
441
|
+
const verified = !astBlocked && hasZ3 && z3.verdict === 'SAT';
|
|
442
|
+
const failReason = astBlocked
|
|
443
|
+
? `UNBOUNDED_OR_DESTRUCTIVE_${ast.statement_type || 'SQL'}`
|
|
444
|
+
: !hasZ3
|
|
445
|
+
? 'Z3_FFI_UNLINKED_FAIL_CLOSED'
|
|
446
|
+
: (z3.unsat_core?.[0] || 'INV_LIBZ3_UNSAT');
|
|
447
|
+
const pseudonymCount = r.pseudonym_map ? Object.keys(r.pseudonym_map).length : 0;
|
|
448
|
+
const totalUs = r.timings_us?.total_rust_kernel_us ?? 0;
|
|
449
|
+
const solveUs = r.timings_us?.libz3_c_ffi_solve_us ?? z3.solve_us ?? 0;
|
|
450
|
+
|
|
451
|
+
return {
|
|
452
|
+
verdict: verified ? 'SAT' : 'UNSAT',
|
|
453
|
+
verified,
|
|
454
|
+
engine: 'apodictic-rust-daemon-libz3-ffi',
|
|
455
|
+
proofId: `rust_worm_${r.worm_sequence_num ?? 1}`,
|
|
456
|
+
proofDigest: z3.proof_digest_sha256 || r.merkle_state_root,
|
|
457
|
+
blockIndex: r.worm_sequence_num,
|
|
458
|
+
merkleStateRoot: r.merkle_state_root,
|
|
459
|
+
rfc6962LeafHash: r.rfc6962_leaf_hash ?? null,
|
|
460
|
+
rfc6962AuditPath: r.rfc6962_audit_path ?? [],
|
|
461
|
+
pseudonymMap: r.pseudonym_map ?? {},
|
|
462
|
+
pgoutputDecoded: r.pgoutput_decoded ?? null,
|
|
463
|
+
z3SolveMs: Number((Number(solveUs) / 1000).toFixed(4)),
|
|
464
|
+
totalLatencyMs: Number((Number(totalUs) / 1000).toFixed(4)),
|
|
465
|
+
redactions: pseudonymCount,
|
|
466
|
+
sanitizedSql: r.sanitized_sql || rawSql,
|
|
467
|
+
unsatCore: verified ? [] : (z3.unsat_core || []),
|
|
468
|
+
reason: verified ? null : failReason,
|
|
469
|
+
};
|
|
470
|
+
}
|
|
471
|
+
|
|
472
|
+
async verifyMutation(input = {}) {
|
|
473
|
+
if (
|
|
474
|
+
!this.endpoint &&
|
|
475
|
+
(input.engine === 'rust' || (this.engine === 'rust' && input.engine !== 'python' && input.engine !== 'wasm'))
|
|
476
|
+
) {
|
|
477
|
+
return this.verifyMutationNativeRust(input);
|
|
478
|
+
}
|
|
479
|
+
if (input.amount !== undefined && (!Number.isFinite(Number(input.amount)) || Number(input.amount) < 0)) {
|
|
480
|
+
throw new Error('Invalid mutation amount: must be a non-negative finite number');
|
|
481
|
+
}
|
|
482
|
+
|
|
483
|
+
const rawSql = String(input.sql || '').replace(ZERO_WIDTH_RE, '');
|
|
484
|
+
const scrubbed = this.scrubSqlAst(rawSql);
|
|
485
|
+
const hasExplicitCurrentBalance = input.currentBalance !== undefined && input.currentBalance !== null;
|
|
486
|
+
const odooEval = evaluateOdoo20Call(input);
|
|
487
|
+
|
|
488
|
+
const payload = {
|
|
489
|
+
sql: this.endpoint ? scrubbed.sanitized : rawSql,
|
|
490
|
+
action: input.action || 'MUTATION',
|
|
491
|
+
accountId: input.accountId || 'sdk_default',
|
|
492
|
+
amount: input.amount,
|
|
493
|
+
currentBalance: input.currentBalance ?? 250000,
|
|
494
|
+
hasExplicitCurrentBalance,
|
|
495
|
+
stateless: Boolean(input.stateless),
|
|
496
|
+
minReserve: input.minReserve ?? 50000,
|
|
497
|
+
maxAutonomousLimit: input.maxAutonomousLimit ?? 50000,
|
|
498
|
+
cfoSigned: Boolean(input.cfoSigned),
|
|
499
|
+
debitTotal: input.debitTotal !== undefined ? Number(input.debitTotal) : odooEval.lineChecks?.debitTotal,
|
|
500
|
+
creditTotal: input.creditTotal !== undefined ? Number(input.creditTotal) : odooEval.lineChecks?.creditTotal,
|
|
501
|
+
statutoryVat: input.statutoryVat ?? 0.14,
|
|
502
|
+
expectedVat: input.expectedVat ?? 0.14,
|
|
503
|
+
targetSystem: input.targetSystem || (odooEval.isOdooCall ? 'odoo_v20' : 'postgresql'),
|
|
504
|
+
odoo: input.odoo,
|
|
505
|
+
};
|
|
506
|
+
|
|
507
|
+
const data = input.engine === 'wasm'
|
|
508
|
+
? await this._dispatchWasm('verify_mutation', payload)
|
|
509
|
+
: await this._dispatch('verify_mutation', payload);
|
|
510
|
+
|
|
511
|
+
// Fail-closed intersection: if Odoo 20 structural/scope/lock guard flagged violations even when backed by Python/HTTP, block immediately
|
|
512
|
+
const odooViolations = odooEval.violations || [];
|
|
513
|
+
const verified = Boolean(data.verified) && odooViolations.length === 0;
|
|
514
|
+
const verdict = verified ? (data.verdict || 'SAT') : 'UNSAT';
|
|
515
|
+
return {
|
|
516
|
+
verdict,
|
|
517
|
+
verified,
|
|
518
|
+
engine: this.endpoint ? (data.engine || 'apodictic-http-gateway-z3-5.4.1') : (data.engine || 'apodictic-local-z3-5.4.1'),
|
|
519
|
+
proofId: data.proof_id,
|
|
520
|
+
proofDigest: data.proof_digest || data.proof_hash,
|
|
521
|
+
blockIndex: data.block_index,
|
|
522
|
+
blockHash: data.block_hash,
|
|
523
|
+
rollbackBatchId: data.rollback_batch_id ?? null,
|
|
524
|
+
escrowStatus: verified ? (data.escrow_status ?? null) : 'VETOED_PRE_COMMIT',
|
|
525
|
+
doubleEntryAccount: data.double_entry_account ?? null,
|
|
526
|
+
walBeforeImage: data.wal_before_image ?? null,
|
|
527
|
+
rfc6962LeafHash: data.rfc6962_leaf_hash ?? null,
|
|
528
|
+
rfc6962TreeRoot: data.rfc6962_tree_root ?? null,
|
|
529
|
+
dlpChecksums: data.dlp_checksums ?? null,
|
|
530
|
+
odoo20Evaluation: odooEval.isOdooCall ? odooEval : undefined,
|
|
531
|
+
z3SolveMs: data.timings?.z3_solve_ms ?? data.z3_solve_ms,
|
|
532
|
+
totalLatencyMs: data.timings?.total_proxy_latency_ms ?? data.execution_time_ms,
|
|
533
|
+
redactions: this.endpoint ? Math.max(scrubbed.redactions, data.pii_entities_redacted ?? data.redactions ?? 0) : (data.redactions ?? 0),
|
|
534
|
+
sanitizedSql: data.sanitized_sql || data.tokenized_payload || scrubbed.sanitized,
|
|
535
|
+
counterfactualPatch: verified ? null : (data.counterfactual_patch ?? data.counterfactualPatch ?? null),
|
|
536
|
+
reason: verified
|
|
537
|
+
? null
|
|
538
|
+
: (odooViolations[0] || data.violation_reason || data.violated_invariants?.[0] || data.unsat_core?.[0] || `INV_Z3_UNSAT (${data.ast_analysis?.statement_type || 'MUTATION'})`),
|
|
539
|
+
};
|
|
540
|
+
}
|
|
541
|
+
|
|
542
|
+
async shadowExecuteAndProve(input = {}) {
|
|
543
|
+
if (!this._shadowVerifier) {
|
|
544
|
+
this._shadowVerifier = new ShadowPostgresVerifier(this);
|
|
545
|
+
}
|
|
546
|
+
return this._shadowVerifier.shadowExecuteAndProve(input);
|
|
547
|
+
}
|
|
548
|
+
|
|
549
|
+
verifySql(sql, options = {}) {
|
|
550
|
+
return this.verifyMutation({ ...options, sql });
|
|
551
|
+
}
|
|
552
|
+
|
|
553
|
+
rollback(batchId) {
|
|
554
|
+
return this._dispatch('rollback', { batchId });
|
|
555
|
+
}
|
|
556
|
+
|
|
557
|
+
verifyThreeWayMatch(input) {
|
|
558
|
+
return this._dispatch('verify_three_way_match', input);
|
|
559
|
+
}
|
|
560
|
+
|
|
561
|
+
verifyTaxCompliance(input) {
|
|
562
|
+
return this._dispatch('verify_tax_compliance', input);
|
|
563
|
+
}
|
|
564
|
+
|
|
565
|
+
bitemporalInsert(input) {
|
|
566
|
+
return this._dispatch('bitemporal_insert', input);
|
|
567
|
+
}
|
|
568
|
+
|
|
569
|
+
bitemporalRestate(input) {
|
|
570
|
+
return this._dispatch('bitemporal_restate', input);
|
|
571
|
+
}
|
|
572
|
+
|
|
573
|
+
bitemporalAsOf(input) {
|
|
574
|
+
return this._dispatch('bitemporal_as_of', input);
|
|
575
|
+
}
|
|
576
|
+
|
|
577
|
+
verifyAuditChain() {
|
|
578
|
+
return this._dispatch('verify_audit_chain', {});
|
|
579
|
+
}
|
|
580
|
+
|
|
581
|
+
flushEscrow(options = {}) {
|
|
582
|
+
return this._dispatch('flush_escrow', options);
|
|
583
|
+
}
|
|
584
|
+
|
|
585
|
+
evaluatePolicy(options = {}) {
|
|
586
|
+
return this._dispatch('evaluate_policy', options);
|
|
587
|
+
}
|
|
588
|
+
|
|
589
|
+
getMerkleInclusionProof(blockIndex) {
|
|
590
|
+
return this._dispatch('merkle_inclusion_proof', blockIndex !== undefined ? { blockIndex } : {});
|
|
591
|
+
}
|
|
592
|
+
|
|
593
|
+
health() {
|
|
594
|
+
return this._dispatch('health', {});
|
|
595
|
+
}
|
|
596
|
+
|
|
597
|
+
async close() {
|
|
598
|
+
if (this._shadowVerifier) {
|
|
599
|
+
await this._shadowVerifier.close();
|
|
600
|
+
this._shadowVerifier = null;
|
|
601
|
+
}
|
|
602
|
+
if (this._wasmSession) {
|
|
603
|
+
this._wasmSession.close();
|
|
604
|
+
this._wasmSession = null;
|
|
605
|
+
} else {
|
|
606
|
+
terminateZ3WasmThreads();
|
|
607
|
+
}
|
|
608
|
+
if (this._worker && !this._worker.killed) {
|
|
609
|
+
this._worker.stdin.end();
|
|
610
|
+
this._worker.kill();
|
|
611
|
+
this._worker = null;
|
|
612
|
+
}
|
|
613
|
+
if (this._rustWorker && !this._rustWorker.killed) {
|
|
614
|
+
this._rustWorker.stdin.end();
|
|
615
|
+
this._rustWorker.kill();
|
|
616
|
+
this._rustWorker = null;
|
|
617
|
+
}
|
|
618
|
+
}
|
|
619
|
+
}
|
|
620
|
+
|
|
621
|
+
export { PGlite, ShadowPostgresVerifier, Z3WasmEnclaveSession, evaluateOdoo20Call, extractOdoo20Call };
|
|
622
|
+
export default SymbolicGateway;
|