@nekzus/liop 2.4.0-alpha.25 → 2.4.0-alpha.26

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.
Files changed (61) hide show
  1. package/dist/bin/agent.js +27 -933
  2. package/dist/bridge.js +1 -5
  3. package/dist/chunk-2XHSALII.js +3 -0
  4. package/dist/chunk-2ZYX736J.js +2 -0
  5. package/dist/chunk-3WRKTVOF.js +2 -0
  6. package/dist/chunk-6KFKO6ZX.js +2 -0
  7. package/dist/chunk-6VK2XALI.js +2 -0
  8. package/dist/chunk-AYDF3IFZ.js +2 -0
  9. package/dist/chunk-CTTTLCGL.js +31 -0
  10. package/dist/chunk-ECRS6N33.js +4 -0
  11. package/dist/chunk-FDJMH4CB.js +2 -0
  12. package/dist/chunk-FTF6AMF6.js +0 -1
  13. package/dist/chunk-GWVSCZUS.js +2 -0
  14. package/dist/chunk-LEXMMIQI.js +15 -0
  15. package/dist/chunk-LM26HOJ6.js +31 -0
  16. package/dist/chunk-MQ5SU26J.js +2 -0
  17. package/dist/chunk-N35BC62H.js +2 -0
  18. package/dist/chunk-P6IJ3VBD.js +3 -0
  19. package/dist/chunk-TKLRW52V.js +2 -0
  20. package/dist/chunk-V35CXJQN.js +2 -0
  21. package/dist/chunk-WP5ER7RH.js +3 -0
  22. package/dist/chunk-XLVEDKM6.js +2 -0
  23. package/dist/chunk-Y675R34Z.js +2 -0
  24. package/dist/chunk-YD2AF2M6.js +46 -0
  25. package/dist/chunk-YLCNV764.js +3 -0
  26. package/dist/chunk-ZZMSFCJP.js +3 -0
  27. package/dist/client.js +1 -12
  28. package/dist/gateway.js +1 -13
  29. package/dist/index.js +4 -320
  30. package/dist/kyber-PULV7PQX.js +2 -0
  31. package/dist/mesh.js +1 -5
  32. package/dist/server.js +1 -10
  33. package/dist/types.js +1 -3
  34. package/dist/verifier-J4NQYZX5.js +2 -0
  35. package/dist/workers/logic-execution.js +1 -355
  36. package/dist/workers/zk-verifier.js +1 -275
  37. package/package.json +1 -1
  38. package/dist/chunk-3664H3CV.js +0 -136
  39. package/dist/chunk-3QH44NKZ.js +0 -115
  40. package/dist/chunk-6MYJBM2E.js +0 -818
  41. package/dist/chunk-7PITYWOV.js +0 -68
  42. package/dist/chunk-DSOB2JKM.js +0 -1507
  43. package/dist/chunk-ET6VRUK2.js +0 -58
  44. package/dist/chunk-FIVRGOA4.js +0 -280
  45. package/dist/chunk-IHKKWXHJ.js +0 -876
  46. package/dist/chunk-IK7CGWAZ.js +0 -24
  47. package/dist/chunk-JPWC6XG6.js +0 -941
  48. package/dist/chunk-K3DGJLUY.js +0 -106
  49. package/dist/chunk-KR5UZUEY.js +0 -98
  50. package/dist/chunk-NXCAFF73.js +0 -59
  51. package/dist/chunk-Q3FKHJ3B.js +0 -345
  52. package/dist/chunk-R52TZEIL.js +0 -426
  53. package/dist/chunk-S3RAZTEM.js +0 -807
  54. package/dist/chunk-V47P2AQR.js +0 -281
  55. package/dist/chunk-WXOWJXY6.js +0 -564
  56. package/dist/chunk-WXYDFCIW.js +0 -293
  57. package/dist/chunk-Y62GORQF.js +0 -51
  58. package/dist/chunk-ZP3VVXOI.js +0 -66
  59. package/dist/chunk-ZU3WVVLC.js +0 -3752
  60. package/dist/kyber-CGOA7Q6A.js +0 -3
  61. package/dist/verifier-55HW6AFN.js +0 -6
@@ -1,356 +1,2 @@
1
- import { ASTGuardian, WasiSandbox } from '../chunk-R52TZEIL.js';
2
- import { sanitizeOutput } from '../chunk-Y62GORQF.js';
3
- import { normalizeLogicSource, deriveLogicImageDigest } from '../chunk-IK7CGWAZ.js';
4
- import { Dilithium65Wrapper } from '../chunk-3664H3CV.js';
5
- import { encodeJournalV2, receiptCodec } from '../chunk-FIVRGOA4.js';
6
- import { Buffer } from 'buffer';
7
- import crypto2 from 'crypto';
8
- import { createMlKem768 } from 'mlkem';
9
-
10
- var DEFAULT_DP_CONFIG = {
11
- epsilon: 1,
12
- sensitivity: 1,
13
- smallDatasetThreshold: 50
14
- };
15
- var EPSILON_FLOOR = 1;
16
- var EPSILON_FLOOR_THRESHOLD = 10;
17
- function laplaceSample(scale, prngState) {
18
- let u;
19
- do {
20
- if (prngState) {
21
- const hash = crypto2.createHash("sha256").update(`${prngState.seed}:${prngState.counter++}`).digest();
22
- u = hash.readUInt32BE(0) / 4294967296 - 0.5;
23
- } else {
24
- const buf = crypto2.randomBytes(4);
25
- const rawVal = buf[0] << 24 | buf[1] << 16 | buf[2] << 8 | buf[3];
26
- const cleanVal = Number.parseInt(rawVal.toString(10), 10);
27
- u = cleanVal / 4294967296;
28
- }
29
- } while (u === 0 || u === -0.5);
30
- return -scale * Math.sign(u) * Math.log(1 - 2 * Math.abs(u));
31
- }
32
- function addLaplaceNoise(value, config = {}, prngState) {
33
- const merged = { ...DEFAULT_DP_CONFIG, ...config };
34
- const scale = merged.sensitivity / merged.epsilon;
35
- const noisyValue = value + laplaceSample(scale, prngState);
36
- return Math.round(noisyValue * 1e4) / 1e4;
37
- }
38
- function deriveFieldSensitivity(key, globalSensitivity, recordCount) {
39
- if (!key) return globalSensitivity;
40
- const lk = key.toLowerCase();
41
- const isCountWord = /count|length|size|num|gainer|loser|positive|negative|nan_|null_|empty_|finite_|non_finite_|instruments|tickers|users|records/i.test(
42
- lk
43
- );
44
- const isTotalCount = lk === "total" || lk === "n" || lk === "total_records" || lk.startsWith("total_") || // Catch total_tickers, total_users
45
- lk.startsWith("num_") || // Catch num_records, num_ticks
46
- /total.*(count|items|entries|rows|records|tickers)/i.test(lk);
47
- if (isCountWord || isTotalCount) return 1;
48
- if (/avg|mean|average|var|variance|std|stddev|ratio|bps|drift|pct|percent|imbalance/i.test(
49
- lk
50
- ) && recordCount > 0) {
51
- return globalSensitivity / recordCount;
52
- }
53
- return globalSensitivity;
54
- }
55
- function applyDpToOutput(output, config = {}, recordCount) {
56
- const merged = { ...DEFAULT_DP_CONFIG, ...config };
57
- if (recordCount >= merged.smallDatasetThreshold) {
58
- return output;
59
- }
60
- if (recordCount < EPSILON_FLOOR_THRESHOLD && merged.epsilon < EPSILON_FLOOR) {
61
- merged.epsilon = EPSILON_FLOOR;
62
- }
63
- let prngState;
64
- if (merged.seed) {
65
- prngState = { seed: merged.seed, counter: 0 };
66
- }
67
- return walkAndNoise(output, merged, recordCount, void 0, prngState);
68
- }
69
- function walkAndNoise(node, config, recordCount, currentKey, prngState) {
70
- if (typeof node === "number" && Number.isFinite(node)) {
71
- const fieldSensitivity = deriveFieldSensitivity(
72
- currentKey,
73
- config.sensitivity,
74
- recordCount
75
- );
76
- let noisyValue = addLaplaceNoise(
77
- node,
78
- {
79
- ...config,
80
- sensitivity: fieldSensitivity
81
- },
82
- prngState
83
- );
84
- const isCountKey = currentKey != null && deriveFieldSensitivity(currentKey, config.sensitivity, recordCount) === 1;
85
- if (Number.isInteger(node) || isCountKey) {
86
- noisyValue = Math.round(noisyValue);
87
- }
88
- if (node >= 0) {
89
- noisyValue = Math.max(0, noisyValue);
90
- }
91
- return noisyValue;
92
- }
93
- if (Array.isArray(node)) {
94
- return node.map(
95
- (item) => walkAndNoise(item, config, recordCount, currentKey, prngState)
96
- );
97
- }
98
- if (node !== null && typeof node === "object") {
99
- const result = {};
100
- for (const [key, value] of Object.entries(
101
- node
102
- )) {
103
- result[key] = walkAndNoise(value, config, recordCount, key, prngState);
104
- }
105
- return result;
106
- }
107
- return node;
108
- }
109
-
110
- // src/workers/logic-execution.ts
111
- async function processLogicExecution(data) {
112
- if (typeof Object.prototype === "object" && !Object.isFrozen(Object.prototype)) {
113
- Object.freeze(Object.prototype);
114
- Object.freeze(Array.prototype);
115
- Object.freeze(String.prototype);
116
- Object.freeze(Number.prototype);
117
- Object.freeze(Boolean.prototype);
118
- Object.freeze(RegExp.prototype);
119
- Object.freeze(Map.prototype);
120
- Object.freeze(Set.prototype);
121
- Object.freeze(Promise.prototype);
122
- Object.freeze(Error.prototype);
123
- }
124
- if (data.isWarmup) {
125
- return {
126
- image_id: "",
127
- output: "warm",
128
- fuel_consumed: 0
129
- };
130
- }
131
- if (data.sessionTimestamp !== void 0) {
132
- const MAX_SESSION_KEY_LIFETIME_MS = 3600 * 1e3;
133
- const age = Date.now() - data.sessionTimestamp;
134
- if (age > MAX_SESSION_KEY_LIFETIME_MS) {
135
- throw new Error(
136
- `[LIOP-PQC] Session secret expired: Age (${Math.round(age / 1e3)}s) exceeds 3600s TTL limit.`
137
- );
138
- }
139
- if (data.sessionTimestamp > Date.now() + 6e4) {
140
- throw new Error(
141
- "[LIOP-PQC] Session secret invalid: Timestamp is in the future."
142
- );
143
- }
144
- }
145
- const {
146
- ciphertext,
147
- secretKeyObj,
148
- wasmBinary,
149
- inputs,
150
- aesNonce,
151
- records,
152
- isEncrypted = true,
153
- dpConfig
154
- } = data;
155
- let decryptedPayload;
156
- const decryptedInputs = {};
157
- let sessionSecret = Buffer.alloc(32);
158
- if (isEncrypted) {
159
- const sk = new Uint8Array(secretKeyObj);
160
- const ct = new Uint8Array(ciphertext);
161
- const kem = await createMlKem768();
162
- const sharedSecret = kem.decap(ct, sk);
163
- const aesKey = Buffer.from(sharedSecret);
164
- sessionSecret = aesKey;
165
- const wasmBuffer = Buffer.from(wasmBinary);
166
- const authTag = wasmBuffer.subarray(-16);
167
- const encryptedData = wasmBuffer.subarray(0, -16);
168
- const decipher = crypto2.createDecipheriv(
169
- "aes-256-gcm",
170
- aesKey,
171
- Buffer.from(aesNonce || new Uint8Array(12))
172
- );
173
- decipher.setAuthTag(authTag);
174
- let decrypted = decipher.update(encryptedData);
175
- decrypted = Buffer.concat([decrypted, decipher.final()]);
176
- decryptedPayload = decrypted;
177
- for (const [key, encValue] of Object.entries(inputs || {})) {
178
- const valBuffer = Buffer.from(encValue);
179
- const inputNonce = valBuffer.subarray(0, 12);
180
- const valTag = valBuffer.subarray(-16);
181
- const valData = valBuffer.subarray(12, -16);
182
- const valDecipher = crypto2.createDecipheriv(
183
- "aes-256-gcm",
184
- aesKey,
185
- inputNonce
186
- );
187
- valDecipher.setAuthTag(valTag);
188
- let valDecrypted = valDecipher.update(valData);
189
- valDecrypted = Buffer.concat([valDecrypted, valDecipher.final()]);
190
- decryptedInputs[key] = JSON.parse(valDecrypted.toString("utf-8"));
191
- }
192
- } else {
193
- if (wasmBinary[0] === 0 && wasmBinary[1] === 97 && wasmBinary[2] === 115 && wasmBinary[3] === 109) {
194
- decryptedPayload = Buffer.from(wasmBinary);
195
- } else {
196
- decryptedPayload = Buffer.from(wasmBinary).toString("utf-8");
197
- }
198
- }
199
- const isWasm = decryptedPayload[0] === 0 && decryptedPayload[1] === 97 && decryptedPayload[2] === 115 && decryptedPayload[3] === 109;
200
- if (decryptedPayload instanceof Buffer && isWasm) {
201
- const wasmBytes = new Uint8Array(decryptedPayload);
202
- const compiledModule = await WebAssembly.compile(wasmBytes);
203
- ASTGuardian.analyze(compiledModule);
204
- } else if (decryptedPayload instanceof Buffer && !isWasm) {
205
- decryptedPayload = decryptedPayload.toString("utf-8");
206
- }
207
- if (typeof decryptedPayload === "string") {
208
- decryptedPayload = normalizeLogicSource(decryptedPayload);
209
- }
210
- const sandbox = new WasiSandbox();
211
- await sandbox.init();
212
- try {
213
- const result = await sandbox.execute(
214
- decryptedPayload,
215
- records,
216
- decryptedInputs
217
- );
218
- let finalOutput = result.output;
219
- let logicBytes;
220
- if (typeof decryptedPayload === "string") {
221
- logicBytes = Buffer.from(decryptedPayload, "utf-8");
222
- } else {
223
- logicBytes = new Uint8Array(decryptedPayload);
224
- }
225
- const imageId = deriveLogicImageDigest(logicBytes).toString("hex");
226
- const datasetHash = crypto2.createHash("sha256").update(JSON.stringify(records || [])).digest("hex");
227
- if (dpConfig) {
228
- finalOutput = applyDpToOutput(
229
- finalOutput,
230
- {
231
- ...dpConfig,
232
- seed: `${datasetHash}:${imageId}`
233
- },
234
- records?.length || 0
235
- );
236
- }
237
- finalOutput = sanitizeOutput(finalOutput);
238
- if (data.proofMode === 1 || data.proofMode === 2) {
239
- const guestImageIdBuf = data.guestImageId ? Buffer.from(data.guestImageId, "hex") : crypto2.createHash("sha256").update("liop-default-guest-v2").digest();
240
- const outputStr = typeof finalOutput === "string" ? finalOutput : finalOutput === void 0 ? "undefined" : JSON.stringify(finalOutput);
241
- const journalV2Buf = encodeJournalV2({
242
- guestImageId: guestImageIdBuf,
243
- logicDigest: Buffer.from(imageId, "hex"),
244
- datasetDigest: Buffer.from(datasetHash, "hex"),
245
- outputDigest: crypto2.createHash("sha256").update(outputStr).digest(),
246
- fuelConsumed: BigInt(result.fuelConsumed),
247
- executionTimestamp: BigInt(Date.now())
248
- });
249
- let proofBuf;
250
- let nativeProver = null;
251
- try {
252
- nativeProver = await import('@nekzus/liop-zk-native');
253
- } catch {
254
- nativeProver = null;
255
- }
256
- if (nativeProver && typeof nativeProver.prove_analytical_query === "function") {
257
- try {
258
- const circuit = typeof decryptedInputs?.operation === "string" ? decryptedInputs.operation : "sum";
259
- const inputsJson = JSON.stringify({
260
- records: Array.isArray(records) ? records.map(
261
- // biome-ignore lint/suspicious/noExplicitAny: record mapping
262
- (r) => Number(r.amount ?? r.value ?? 1)
263
- ) : [1],
264
- expected_sum: typeof finalOutput === "number" ? finalOutput : void 0
265
- });
266
- proofBuf = await nativeProver.prove_analytical_query(
267
- circuit,
268
- inputsJson
269
- );
270
- } catch (err) {
271
- if (data.proofMode === 2 /* PROOF_MODE_ZK_BLOCKING */) {
272
- throw new Error(
273
- `ZK PROOF GENERATION FAILED: Native Groth16 prover execution error: ${err instanceof Error ? err.message : String(err)}`
274
- );
275
- }
276
- proofBuf = Buffer.alloc(128, 66);
277
- }
278
- } else {
279
- if (data.proofMode === 2 /* PROOF_MODE_ZK_BLOCKING */) {
280
- throw new Error(
281
- "ZK PROOF GENERATION FAILED: Native Groth16 prover module unavailable for required policy."
282
- );
283
- }
284
- proofBuf = Buffer.alloc(128, 66);
285
- }
286
- let receiptBuf2;
287
- let effectiveProofType = 2 /* GROTH16 */;
288
- if (data.pqcSigningKey && data.pqcSigningKey.length > 0) {
289
- effectiveProofType = 3 /* GROTH16_PQC_HYBRID */;
290
- const messageToSign = crypto2.createHash("sha256").update(Buffer.concat([journalV2Buf, proofBuf])).digest();
291
- const signature = Dilithium65Wrapper.sign(
292
- messageToSign,
293
- data.pqcSigningKey
294
- );
295
- const publicKey = Dilithium65Wrapper.getPublicKey(data.pqcSigningKey);
296
- receiptBuf2 = receiptCodec.encodeHybridV2(
297
- journalV2Buf,
298
- proofBuf,
299
- Buffer.from(signature),
300
- Buffer.from(publicKey)
301
- );
302
- } else {
303
- receiptBuf2 = receiptCodec.encodeV2(
304
- 2 /* GROTH16 */,
305
- journalV2Buf,
306
- proofBuf
307
- );
308
- }
309
- const zkReceipt2 = receiptBuf2.toString("base64");
310
- return {
311
- image_id: imageId,
312
- zk_receipt: zkReceipt2,
313
- output: finalOutput,
314
- fuel_consumed: result.fuelConsumed,
315
- proof_type: effectiveProofType,
316
- guest_image_id: guestImageIdBuf.toString("hex")
317
- };
318
- }
319
- const journal = Buffer.from(
320
- JSON.stringify({
321
- image_id: imageId,
322
- dataset_hash: datasetHash,
323
- output_hash: crypto2.createHash("sha256").update(
324
- typeof finalOutput === "string" ? finalOutput : finalOutput === void 0 ? "undefined" : JSON.stringify(finalOutput)
325
- ).digest("hex"),
326
- fuel: result.fuelConsumed,
327
- ts: Date.now()
328
- })
329
- );
330
- const seal = crypto2.createHmac("sha256", sessionSecret).update(journal).digest();
331
- const journalLen = Buffer.alloc(2);
332
- journalLen.writeUInt16BE(journal.length);
333
- const receiptBuf = Buffer.concat([
334
- Buffer.from([1]),
335
- // Receipt format v1
336
- journalLen,
337
- journal,
338
- seal
339
- // 32 bytes HMAC
340
- ]);
341
- const zkReceipt = receiptBuf.toString("base64");
342
- return {
343
- image_id: imageId,
344
- zk_receipt: zkReceipt,
345
- output: finalOutput,
346
- fuel_consumed: result.fuelConsumed,
347
- proof_type: 0 /* HMAC_LEGACY */
348
- };
349
- } finally {
350
- await sandbox.teardown();
351
- }
352
- }
353
-
354
- export { processLogicExecution as default };
355
- //# sourceMappingURL=logic-execution.js.map
1
+ import {a as a$1,d}from'../chunk-CTTTLCGL.js';import {a as a$3}from'../chunk-MQ5SU26J.js';import {a as a$2,b}from'../chunk-TKLRW52V.js';import {b as b$1}from'../chunk-2ZYX736J.js';import {f,h}from'../chunk-6VK2XALI.js';import {a}from'../chunk-AYDF3IFZ.js';import {Buffer}from'buffer';import m from'crypto';import {createMlKem768}from'mlkem';var Y={epsilon:1,sensitivity:1,smallDatasetThreshold:50},J=1,ee=10;function te(e,i){let o;do if(i)o=m.createHash("sha256").update(`${i.seed}:${i.counter++}`).digest().readUInt32BE(0)/4294967296-.5;else {let t=m.randomBytes(4),a=t[0]<<24|t[1]<<16|t[2]<<8|t[3];o=Number.parseInt(a.toString(10),10)/4294967296;}while(o===0||o===-0.5);return -e*Math.sign(o)*Math.log(1-2*Math.abs(o))}a(te,"laplaceSample");function re(e,i={},o){let t={...Y,...i},a=t.sensitivity/t.epsilon,c=e+te(a,o);return Math.round(c*1e4)/1e4}a(re,"addLaplaceNoise");function $(e,i,o){if(!e)return i;let t=e.toLowerCase(),a=/count|length|size|num|gainer|loser|positive|negative|nan_|null_|empty_|finite_|non_finite_|instruments|tickers|users|records/i.test(t),c=t==="total"||t==="n"||t==="total_records"||t.startsWith("total_")||t.startsWith("num_")||/total.*(count|items|entries|rows|records|tickers)/i.test(t);return a||c?1:/avg|mean|average|var|variance|std|stddev|ratio|bps|drift|pct|percent|imbalance/i.test(t)&&o>0?i/o:i}a($,"deriveFieldSensitivity");function Z(e,i={},o){let t={...Y,...i};if(o>=t.smallDatasetThreshold)return e;o<ee&&t.epsilon<J&&(t.epsilon=J);let a;return t.seed&&(a={seed:t.seed,counter:0}),R(e,t,o,void 0,a)}a(Z,"applyDpToOutput");function R(e,i,o,t,a){if(typeof e=="number"&&Number.isFinite(e)){let c=$(t,i.sensitivity,o),u=re(e,{...i,sensitivity:c},a),w=t!=null&&$(t,i.sensitivity,o)===1;return (Number.isInteger(e)||w)&&(u=Math.round(u)),e>=0&&(u=Math.max(0,u)),u}if(Array.isArray(e))return e.map(c=>R(c,i,o,t,a));if(e!==null&&typeof e=="object"){let c={};for(let[u,w]of Object.entries(e))c[u]=R(w,i,o,u,a);return c}return e}a(R,"walkAndNoise");async function oe(e){if(typeof Object.prototype=="object"&&!Object.isFrozen(Object.prototype)&&(Object.freeze(Object.prototype),Object.freeze(Array.prototype),Object.freeze(String.prototype),Object.freeze(Number.prototype),Object.freeze(Boolean.prototype),Object.freeze(RegExp.prototype),Object.freeze(Map.prototype),Object.freeze(Set.prototype),Object.freeze(Promise.prototype),Object.freeze(Error.prototype)),e.isWarmup)return {image_id:"",output:"warm",fuel_consumed:0};if(e.sessionTimestamp!==void 0){let n=Date.now()-e.sessionTimestamp;if(n>36e5)throw new Error(`[LIOP-PQC] Session secret expired: Age (${Math.round(n/1e3)}s) exceeds 3600s TTL limit.`);if(e.sessionTimestamp>Date.now()+6e4)throw new Error("[LIOP-PQC] Session secret invalid: Timestamp is in the future.")}let{ciphertext:i,secretKeyObj:o,wasmBinary:t,inputs:a,aesNonce:c,records:u,isEncrypted:w=true,dpConfig:z}=e,s,D={},C=Buffer.alloc(32);if(w){let p=new Uint8Array(o),n=new Uint8Array(i),g=(await createMlKem768()).decap(n,p),d=Buffer.from(g);C=d;let _=Buffer.from(t),k=_.subarray(-16),T=_.subarray(0,-16),A=m.createDecipheriv("aes-256-gcm",d,Buffer.from(c||new Uint8Array(12)));A.setAuthTag(k);let S=A.update(T);S=Buffer.concat([S,A.final()]),s=S;for(let[E,B]of Object.entries(a||{})){let y=Buffer.from(B),f=y.subarray(0,12),h=y.subarray(-16),x=y.subarray(12,-16),O=m.createDecipheriv("aes-256-gcm",d,f);O.setAuthTag(h);let v=O.update(x);v=Buffer.concat([v,O.final()]),D[E]=JSON.parse(v.toString("utf-8"));}}else t[0]===0&&t[1]===97&&t[2]===115&&t[3]===109?s=Buffer.from(t):s=Buffer.from(t).toString("utf-8");let K=s[0]===0&&s[1]===97&&s[2]===115&&s[3]===109;if(s instanceof Buffer&&K){let p=new Uint8Array(s),n=await WebAssembly.compile(p);a$1.analyze(n);}else s instanceof Buffer&&!K&&(s=s.toString("utf-8"));typeof s=="string"&&(s=a$2(s));let N=new d;await N.init();try{let p=await N.execute(s,u,D),n=p.output,I;typeof s=="string"?I=Buffer.from(s,"utf-8"):I=new Uint8Array(s);let g=b(I).toString("hex"),d=m.createHash("sha256").update(JSON.stringify(u||[])).digest("hex");if(z&&(n=Z(n,{...z,seed:`${d}:${g}`},u?.length||0)),n=a$3(n),e.proofMode===1||e.proofMode===2){let E=e.guestImageId?Buffer.from(e.guestImageId,"hex"):m.createHash("sha256").update("liop-default-guest-v2").digest(),B=typeof n=="string"?n:n===void 0?"undefined":JSON.stringify(n),y=f({guestImageId:E,logicDigest:Buffer.from(g,"hex"),datasetDigest:Buffer.from(d,"hex"),outputDigest:m.createHash("sha256").update(B).digest(),fuelConsumed:BigInt(p.fuelConsumed),executionTimestamp:BigInt(Date.now())}),f$1,h$1=null;try{h$1=await import('@nekzus/liop-zk-native');}catch{h$1=null;}if(h$1&&typeof h$1.prove_analytical_query=="function")try{let b=typeof D?.operation=="string"?D.operation:"sum",M=JSON.stringify({records:Array.isArray(u)?u.map(P=>Number(P.amount??P.value??1)):[1],expected_sum:typeof n=="number"?n:void 0});f$1=await h$1.prove_analytical_query(b,M);}catch(b){if(e.proofMode===2)throw new Error(`ZK PROOF GENERATION FAILED: Native Groth16 prover execution error: ${b instanceof Error?b.message:String(b)}`);f$1=Buffer.alloc(128,66);}else {if(e.proofMode===2)throw new Error("ZK PROOF GENERATION FAILED: Native Groth16 prover module unavailable for required policy.");f$1=Buffer.alloc(128,66);}let x,O=2;if(e.pqcSigningKey&&e.pqcSigningKey.length>0){O=3;let b=m.createHash("sha256").update(Buffer.concat([y,f$1])).digest(),M=b$1.sign(b,e.pqcSigningKey),P=b$1.getPublicKey(e.pqcSigningKey);x=h.encodeHybridV2(y,f$1,Buffer.from(M),Buffer.from(P));}else x=h.encodeV2(2,y,f$1);let v=x.toString("base64");return {image_id:g,zk_receipt:v,output:n,fuel_consumed:p.fuelConsumed,proof_type:O,guest_image_id:E.toString("hex")}}let _=Buffer.from(JSON.stringify({image_id:g,dataset_hash:d,output_hash:m.createHash("sha256").update(typeof n=="string"?n:n===void 0?"undefined":JSON.stringify(n)).digest("hex"),fuel:p.fuelConsumed,ts:Date.now()})),k=m.createHmac("sha256",C).update(_).digest(),T=Buffer.alloc(2);T.writeUInt16BE(_.length);let S=Buffer.concat([Buffer.from([1]),T,_,k]).toString("base64");return {image_id:g,zk_receipt:S,output:n,fuel_consumed:p.fuelConsumed,proof_type:0}}finally{await N.teardown();}}a(oe,"processLogicExecution");export{oe as default};//# sourceMappingURL=logic-execution.js.map
356
2
  //# sourceMappingURL=logic-execution.js.map
@@ -1,276 +1,2 @@
1
- import { deserializeVKey, deserializeGrothProof, verifyGroth16Proof } from '../chunk-ET6VRUK2.js';
2
- import { deriveLogicImageDigest } from '../chunk-IK7CGWAZ.js';
3
- import { Dilithium65Wrapper } from '../chunk-3664H3CV.js';
4
- import { receiptCodec, RECEIPT_VERSION_V1, RECEIPT_VERSION_V2, decodeJournalV2 } from '../chunk-FIVRGOA4.js';
5
- import crypto from 'crypto';
6
- import 'worker_threads';
7
-
8
- function deriveImageId(logicPayload) {
9
- return deriveLogicImageDigest(logicPayload);
10
- }
11
- function tryExtractProxyOutput(logicPayload) {
12
- try {
13
- const logicStr = Buffer.from(logicPayload).toString("utf-8").trim();
14
- if (!logicStr.includes("__liop_proxy_tool")) {
15
- return null;
16
- }
17
- const firstBraceIdx = logicStr.indexOf("{");
18
- if (firstBraceIdx === -1) {
19
- return null;
20
- }
21
- let braceCount = 0;
22
- let inDoubleQuote = false;
23
- let inSingleQuote = false;
24
- let inBacktick = false;
25
- let escaped = false;
26
- let lastBraceIdx = -1;
27
- for (let i = firstBraceIdx; i < logicStr.length; i++) {
28
- const char = logicStr[i];
29
- if (escaped) {
30
- escaped = false;
31
- continue;
32
- }
33
- if (char === "\\") {
34
- escaped = true;
35
- continue;
36
- }
37
- if (char === '"' && !inSingleQuote && !inBacktick) {
38
- inDoubleQuote = !inDoubleQuote;
39
- continue;
40
- }
41
- if (char === "'" && !inDoubleQuote && !inBacktick) {
42
- inSingleQuote = !inSingleQuote;
43
- continue;
44
- }
45
- if (char === "`" && !inDoubleQuote && !inSingleQuote) {
46
- inBacktick = !inBacktick;
47
- continue;
48
- }
49
- if (!inDoubleQuote && !inSingleQuote && !inBacktick) {
50
- if (char === "{") {
51
- braceCount++;
52
- } else if (char === "}") {
53
- braceCount--;
54
- if (braceCount === 0) {
55
- lastBraceIdx = i;
56
- break;
57
- }
58
- }
59
- }
60
- }
61
- if (lastBraceIdx !== -1) {
62
- const jsonStr = logicStr.slice(firstBraceIdx, lastBraceIdx + 1);
63
- const parsed = JSON.parse(jsonStr);
64
- if (parsed?.__liop_proxy_tool) {
65
- return parsed;
66
- }
67
- }
68
- } catch (_e) {
69
- }
70
- return null;
71
- }
72
- async function verifyZkReceipt(payload) {
73
- const {
74
- logicPayload,
75
- remoteImageIdHex,
76
- guestImageIdHex,
77
- zkReceipt,
78
- sessionSecret,
79
- vkeyRaw,
80
- expectedOutput,
81
- zkPolicy
82
- } = payload;
83
- if (!logicPayload || !remoteImageIdHex || !zkReceipt) {
84
- return {
85
- verified: false,
86
- message: "Missing required verification fields."
87
- };
88
- }
89
- let decodedReceipt;
90
- try {
91
- decodedReceipt = receiptCodec.decode(Buffer.from(zkReceipt));
92
- } catch (err) {
93
- return {
94
- verified: false,
95
- message: `Receipt Decode Failed: ${err.message}`
96
- };
97
- }
98
- if (decodedReceipt.version === RECEIPT_VERSION_V1) {
99
- if (zkPolicy === "required") {
100
- return {
101
- verified: false,
102
- message: "Policy Violation: Clearance Tier requires ZK proof (Groth16), but received legacy HMAC."
103
- };
104
- }
105
- const localImageId = deriveImageId(logicPayload);
106
- const localImageIdHex = localImageId.toString("hex");
107
- if (localImageIdHex !== remoteImageIdHex) {
108
- return {
109
- verified: false,
110
- message: `Integrity Violation: Local (${localImageIdHex.slice(0, 8)}) != Remote (${remoteImageIdHex.slice(0, 8)})`
111
- };
112
- }
113
- let journalData;
114
- try {
115
- journalData = JSON.parse(decodedReceipt.journal.toString());
116
- if (journalData.image_id !== localImageIdHex) {
117
- return {
118
- verified: false,
119
- message: `Journal ImageID mismatch: ${journalData.image_id.slice(0, 8)} != ${localImageIdHex.slice(0, 8)}`
120
- };
121
- }
122
- } catch (_e) {
123
- return { verified: false, message: "Failed to parse journal data." };
124
- }
125
- if (sessionSecret && sessionSecret.length > 0) {
126
- const expectedSeal = crypto.createHmac("sha256", sessionSecret).update(decodedReceipt.journal).digest();
127
- if (!crypto.timingSafeEqual(decodedReceipt.proof, expectedSeal)) {
128
- return {
129
- verified: false,
130
- message: "Invalid seal: HMAC verification failed."
131
- };
132
- }
133
- }
134
- if (expectedOutput !== void 0) {
135
- const proxyOutput = tryExtractProxyOutput(logicPayload);
136
- const actualExpected = proxyOutput !== null ? proxyOutput : expectedOutput;
137
- const expectedOutputStr = typeof actualExpected === "string" ? actualExpected : actualExpected === void 0 ? "undefined" : JSON.stringify(actualExpected);
138
- const expectedOutputHash = crypto.createHash("sha256").update(expectedOutputStr).digest("hex");
139
- if (journalData.output_hash !== expectedOutputHash) {
140
- return {
141
- verified: false,
142
- message: `Output Hash Mismatch (Replay/Tamper attempt): Journal output_hash (${journalData.output_hash.slice(0, 8)}) != Calculated output_hash (${expectedOutputHash.slice(0, 8)})`
143
- };
144
- }
145
- }
146
- return {
147
- verified: true,
148
- message: "HMAC Commitment Verified: Integrity intact.",
149
- proofType: "hmac"
150
- };
151
- }
152
- if (decodedReceipt.version === RECEIPT_VERSION_V2) {
153
- if (decodedReceipt.proofType !== 2 /* GROTH16 */ && decodedReceipt.proofType !== 3 /* GROTH16_PQC_HYBRID */) {
154
- return {
155
- verified: false,
156
- message: `Unsupported ZK proof type in v2 receipt: ${decodedReceipt.proofType}`
157
- };
158
- }
159
- if (decodedReceipt.proofType === 3 /* GROTH16_PQC_HYBRID */) {
160
- const { pqcSignature, pqcPublicKey } = decodedReceipt;
161
- if (!pqcSignature || !pqcPublicKey) {
162
- return {
163
- verified: false,
164
- message: "Hybrid Receipt Error: Missing ML-DSA-65 signature or public key."
165
- };
166
- }
167
- const messageDigest = crypto.createHash("sha256").update(Buffer.concat([decodedReceipt.journal, decodedReceipt.proof])).digest();
168
- try {
169
- const isPqcValid = Dilithium65Wrapper.verify(
170
- new Uint8Array(pqcSignature),
171
- messageDigest,
172
- new Uint8Array(pqcPublicKey)
173
- );
174
- if (!isPqcValid) {
175
- return {
176
- verified: false,
177
- message: "PQC Signature Verification Failed: ML-DSA-65 co-sign is forged or corrupted."
178
- };
179
- }
180
- } catch (err) {
181
- return {
182
- verified: false,
183
- message: `PQC Verification Error: ${err.message}`
184
- };
185
- }
186
- }
187
- let journalV2;
188
- try {
189
- journalV2 = decodeJournalV2(decodedReceipt.journal);
190
- } catch (err) {
191
- return {
192
- verified: false,
193
- message: `Failed to decode ZkJournalV2: ${err.message}`
194
- };
195
- }
196
- if (guestImageIdHex) {
197
- const actualGuestId = journalV2.guestImageId.toString("hex");
198
- if (actualGuestId !== guestImageIdHex) {
199
- return {
200
- verified: false,
201
- message: `Guest ImageID Mismatch: Injected guest environment tampered (${actualGuestId.slice(0, 8)} != ${guestImageIdHex.slice(0, 8)}).`
202
- };
203
- }
204
- }
205
- const expectedLogicDigest = deriveImageId(logicPayload);
206
- if (!journalV2.logicDigest.equals(expectedLogicDigest)) {
207
- return {
208
- verified: false,
209
- message: `Logic Digest Mismatch: Remote origin executed unexpected logic (${journalV2.logicDigest.toString("hex").slice(0, 8)} != ${expectedLogicDigest.toString("hex").slice(0, 8)})`
210
- };
211
- }
212
- if (vkeyRaw && vkeyRaw.length > 0) {
213
- try {
214
- const vkey = deserializeVKey(Buffer.from(vkeyRaw));
215
- const proofWithSignals = deserializeGrothProof(decodedReceipt.proof);
216
- const isMathValid = verifyGroth16Proof(vkey, proofWithSignals);
217
- if (!isMathValid) {
218
- return {
219
- verified: false,
220
- message: "Groth16 mathematical pairing verification failed: invalid proof."
221
- };
222
- }
223
- } catch (err) {
224
- return {
225
- verified: false,
226
- message: `Groth16 verification failed to execute: ${err.message}`
227
- };
228
- }
229
- }
230
- if (expectedOutput !== void 0) {
231
- const proxyOutput = tryExtractProxyOutput(logicPayload);
232
- const actualExpected = proxyOutput !== null ? proxyOutput : expectedOutput;
233
- const expectedOutputStr = typeof actualExpected === "string" ? actualExpected : actualExpected === void 0 ? "undefined" : JSON.stringify(actualExpected);
234
- const expectedOutputDigest = crypto.createHash("sha256").update(expectedOutputStr).digest();
235
- if (!journalV2.outputDigest.equals(expectedOutputDigest)) {
236
- return {
237
- verified: false,
238
- message: `Output Digest Mismatch (Replay/Tamper attempt): Journal (${journalV2.outputDigest.toString("hex").slice(0, 8)}) != Calculated (${expectedOutputDigest.toString("hex").slice(0, 8)})`
239
- };
240
- }
241
- }
242
- const isHybrid = decodedReceipt.proofType === 3 /* GROTH16_PQC_HYBRID */;
243
- return {
244
- verified: true,
245
- message: isHybrid ? "Groth16 + ML-DSA-65 Post-Quantum Hybrid Receipt Certified." : vkeyRaw && vkeyRaw.length > 0 ? "Groth16 Zero-Knowledge Proof Mathematically Certified." : "Groth16 Receipt Structure and Journal Integrity Certified.",
246
- proofType: isHybrid ? "groth16_pqc_hybrid" : "groth16"
247
- };
248
- }
249
- return {
250
- verified: false,
251
- message: `Unsupported receipt version: ${decodedReceipt.version}`
252
- };
253
- }
254
- async function workerHandler(task) {
255
- try {
256
- if (task.action === "warmup") {
257
- return {
258
- verified: true,
259
- message: "warm"
260
- };
261
- }
262
- if (task.action === "verify_receipt") {
263
- return await verifyZkReceipt(task);
264
- }
265
- throw new Error("Unknown action in ZkVerifier Worker.");
266
- } catch (error) {
267
- return {
268
- verified: false,
269
- message: `Verification Error: ${error.message}`
270
- };
271
- }
272
- }
273
-
274
- export { workerHandler as default };
275
- //# sourceMappingURL=zk-verifier.js.map
1
+ import {d,f,b as b$3}from'../chunk-FDJMH4CB.js';import {b}from'../chunk-TKLRW52V.js';import {b as b$2}from'../chunk-2ZYX736J.js';import {h,b as b$1,c,g}from'../chunk-6VK2XALI.js';import {a}from'../chunk-AYDF3IFZ.js';import v from'crypto';import'worker_threads';function D(s){return b(s)}a(D,"deriveImageId");function O(s){try{let i=Buffer.from(s).toString("utf-8").trim();if(!i.includes("__liop_proxy_tool"))return null;let d=i.indexOf("{");if(d===-1)return null;let p=0,c=!1,n=!1,o=!1,f=!1,y=-1;for(let e=d;e<i.length;e++){let t=i[e];if(f){f=!1;continue}if(t==="\\"){f=!0;continue}if(t==='"'&&!n&&!o){c=!c;continue}if(t==="'"&&!c&&!o){n=!n;continue}if(t==="`"&&!c&&!n){o=!o;continue}if(!c&&!n&&!o){if(t==="{")p++;else if(t==="}"&&(p--,p===0)){y=e;break}}}if(y!==-1){let e=i.slice(d,y+1),t=JSON.parse(e);if(t?.__liop_proxy_tool)return t}}catch{}return null}a(O,"tryExtractProxyOutput");async function T(s){let{logicPayload:i,remoteImageIdHex:d$1,guestImageIdHex:p,zkReceipt:c$1,sessionSecret:n,vkeyRaw:o,expectedOutput:f$1,zkPolicy:y}=s;if(!i||!d$1||!c$1)return {verified:false,message:"Missing required verification fields."};let e;try{e=h.decode(Buffer.from(c$1));}catch(t){return {verified:false,message:`Receipt Decode Failed: ${t.message}`}}if(e.version===b$1){if(y==="required")return {verified:false,message:"Policy Violation: Clearance Tier requires ZK proof (Groth16), but received legacy HMAC."};let g=D(i).toString("hex");if(g!==d$1)return {verified:false,message:`Integrity Violation: Local (${g.slice(0,8)}) != Remote (${d$1.slice(0,8)})`};let u;try{if(u=JSON.parse(e.journal.toString()),u.image_id!==g)return {verified:!1,message:`Journal ImageID mismatch: ${u.image_id.slice(0,8)} != ${g.slice(0,8)}`}}catch{return {verified:false,message:"Failed to parse journal data."}}if(n&&n.length>0){let r=v.createHmac("sha256",n).update(e.journal).digest();if(!v.timingSafeEqual(e.proof,r))return {verified:false,message:"Invalid seal: HMAC verification failed."}}if(f$1!==void 0){let r=O(i),a=r!==null?r:f$1,m=typeof a=="string"?a:a===void 0?"undefined":JSON.stringify(a),l=v.createHash("sha256").update(m).digest("hex");if(u.output_hash!==l)return {verified:false,message:`Output Hash Mismatch (Replay/Tamper attempt): Journal output_hash (${u.output_hash.slice(0,8)}) != Calculated output_hash (${l.slice(0,8)})`}}return {verified:true,message:"HMAC Commitment Verified: Integrity intact.",proofType:"hmac"}}if(e.version===c){if(e.proofType!==2&&e.proofType!==3)return {verified:false,message:`Unsupported ZK proof type in v2 receipt: ${e.proofType}`};if(e.proofType===3){let{pqcSignature:r,pqcPublicKey:a}=e;if(!r||!a)return {verified:false,message:"Hybrid Receipt Error: Missing ML-DSA-65 signature or public key."};let m=v.createHash("sha256").update(Buffer.concat([e.journal,e.proof])).digest();try{if(!b$2.verify(new Uint8Array(r),m,new Uint8Array(a)))return {verified:!1,message:"PQC Signature Verification Failed: ML-DSA-65 co-sign is forged or corrupted."}}catch(l){return {verified:false,message:`PQC Verification Error: ${l.message}`}}}let t;try{t=g(e.journal);}catch(r){return {verified:false,message:`Failed to decode ZkJournalV2: ${r.message}`}}if(p){let r=t.guestImageId.toString("hex");if(r!==p)return {verified:false,message:`Guest ImageID Mismatch: Injected guest environment tampered (${r.slice(0,8)} != ${p.slice(0,8)}).`}}let g$1=D(i);if(!t.logicDigest.equals(g$1))return {verified:false,message:`Logic Digest Mismatch: Remote origin executed unexpected logic (${t.logicDigest.toString("hex").slice(0,8)} != ${g$1.toString("hex").slice(0,8)})`};if(o&&o.length>0)try{let r=d(Buffer.from(o)),a=f(e.proof);if(!b$3(r,a))return {verified:!1,message:"Groth16 mathematical pairing verification failed: invalid proof."}}catch(r){return {verified:false,message:`Groth16 verification failed to execute: ${r.message}`}}if(f$1!==void 0){let r=O(i),a=r!==null?r:f$1,m=typeof a=="string"?a:a===void 0?"undefined":JSON.stringify(a),l=v.createHash("sha256").update(m).digest();if(!t.outputDigest.equals(l))return {verified:false,message:`Output Digest Mismatch (Replay/Tamper attempt): Journal (${t.outputDigest.toString("hex").slice(0,8)}) != Calculated (${l.toString("hex").slice(0,8)})`}}let u=e.proofType===3;return {verified:true,message:u?"Groth16 + ML-DSA-65 Post-Quantum Hybrid Receipt Certified.":o&&o.length>0?"Groth16 Zero-Knowledge Proof Mathematically Certified.":"Groth16 Receipt Structure and Journal Integrity Certified.",proofType:u?"groth16_pqc_hybrid":"groth16"}}return {verified:false,message:`Unsupported receipt version: ${e.version}`}}a(T,"verifyZkReceipt");async function C(s){try{if(s.action==="warmup")return {verified:!0,message:"warm"};if(s.action==="verify_receipt")return await T(s);throw new Error("Unknown action in ZkVerifier Worker.")}catch(i){return {verified:false,message:`Verification Error: ${i.message}`}}}a(C,"workerHandler");export{C as default};//# sourceMappingURL=zk-verifier.js.map
276
2
  //# sourceMappingURL=zk-verifier.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nekzus/liop",
3
- "version": "2.4.0-alpha.25",
3
+ "version": "2.4.0-alpha.26",
4
4
  "description": "Official SDK for Logic-Injection-on-Origin Protocol (LIOP). Deploy Logic-on-Origin with WebAssembly at gRPC speed and bidirectional MCP compatibility.",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",