@nekzus/liop 2.0.0-alpha.1 → 2.0.0-alpha.11
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 +54 -24
- package/dist/bin/agent.d.ts +0 -1
- package/dist/bin/agent.js +5 -306
- package/dist/bin/agent.js.map +1 -0
- package/dist/{bridge/stream.d.ts → bridge.d.ts} +44 -3
- package/dist/bridge.js +2 -0
- package/dist/bridge.js.map +1 -0
- package/dist/chunk-5OAZNVIU.js +31 -0
- package/dist/chunk-5OAZNVIU.js.map +1 -0
- package/dist/chunk-62YQHKSS.js +3 -0
- package/dist/chunk-62YQHKSS.js.map +1 -0
- package/dist/chunk-7MAGL6ON.js +33 -0
- package/dist/chunk-7MAGL6ON.js.map +1 -0
- package/dist/chunk-ANFXJGMP.js +2 -0
- package/dist/chunk-ANFXJGMP.js.map +1 -0
- package/dist/chunk-DBXGYHKY.js +2 -0
- package/dist/chunk-DBXGYHKY.js.map +1 -0
- package/dist/chunk-HM77MWB6.js +2 -0
- package/dist/chunk-HM77MWB6.js.map +1 -0
- package/dist/chunk-HNDVAKEK.js +24 -0
- package/dist/chunk-HNDVAKEK.js.map +1 -0
- package/dist/chunk-HQZHZM6U.js +2 -0
- package/dist/chunk-HQZHZM6U.js.map +1 -0
- package/dist/chunk-JBMEAXYU.js +13 -0
- package/dist/chunk-JBMEAXYU.js.map +1 -0
- package/dist/chunk-P52IE4L6.js +2 -0
- package/dist/chunk-P52IE4L6.js.map +1 -0
- package/dist/chunk-PPCOS2NU.js +2 -0
- package/dist/chunk-PPCOS2NU.js.map +1 -0
- package/dist/chunk-RWRRBYG4.js +2 -0
- package/dist/chunk-RWRRBYG4.js.map +1 -0
- package/dist/chunk-S6RJHZV2.js +2 -0
- package/dist/chunk-S6RJHZV2.js.map +1 -0
- package/dist/chunk-UVTEJYHN.js +2 -0
- package/dist/chunk-UVTEJYHN.js.map +1 -0
- package/dist/client.d.ts +5 -0
- package/dist/client.js +2 -0
- package/dist/client.js.map +1 -0
- package/dist/{gateway/router.d.ts → gateway.d.ts} +30 -5
- package/dist/gateway.js +2 -0
- package/dist/gateway.js.map +1 -0
- package/dist/{client/index.d.ts → index-CyxNLlz7.d.ts} +24 -5
- package/dist/index.d.ts +313 -12
- package/dist/index.js +31 -12
- package/dist/index.js.map +1 -0
- package/dist/kyber-2WDOTUQX.js +2 -0
- package/dist/kyber-2WDOTUQX.js.map +1 -0
- package/dist/{mesh/node.d.ts → mesh.d.ts} +5 -3
- package/dist/mesh.js +2 -0
- package/dist/mesh.js.map +1 -0
- package/dist/{server/index.d.ts → server.d.ts} +143 -12
- package/dist/server.js +2 -0
- package/dist/server.js.map +1 -0
- package/dist/types.d.ts +17 -14
- package/dist/types.js +2 -26
- package/dist/types.js.map +1 -0
- package/dist/{crypto/verifier.d.ts → verifier-DTCD9imJ.d.ts} +3 -1
- package/dist/verifier-RQRYXA4C.js +2 -0
- package/dist/verifier-RQRYXA4C.js.map +1 -0
- package/dist/workers/logic-execution.d.ts +9 -2
- package/dist/workers/logic-execution.js +2 -123
- package/dist/workers/logic-execution.js.map +1 -0
- package/dist/workers/zk-verifier.d.ts +4 -2
- package/dist/workers/zk-verifier.js +2 -98
- package/dist/workers/zk-verifier.js.map +1 -0
- package/package.json +35 -22
- package/dist/bridge/index.d.ts +0 -37
- package/dist/bridge/index.js +0 -249
- package/dist/bridge/stream.js +0 -210
- package/dist/client/index.js +0 -275
- package/dist/crypto/logic-image-id.d.ts +0 -3
- package/dist/crypto/logic-image-id.js +0 -27
- package/dist/crypto/verifier.js +0 -97
- package/dist/economy/estimator.d.ts +0 -53
- package/dist/economy/estimator.js +0 -69
- package/dist/economy/index.d.ts +0 -5
- package/dist/economy/index.js +0 -3
- package/dist/economy/otel.d.ts +0 -38
- package/dist/economy/otel.js +0 -100
- package/dist/economy/telemetry.d.ts +0 -77
- package/dist/economy/telemetry.js +0 -224
- package/dist/errors.d.ts +0 -14
- package/dist/errors.js +0 -19
- package/dist/gateway/hybrid.d.ts +0 -23
- package/dist/gateway/hybrid.js +0 -199
- package/dist/gateway/router.js +0 -1054
- package/dist/mesh/index.d.ts +0 -1
- package/dist/mesh/index.js +0 -1
- package/dist/mesh/node.js +0 -853
- package/dist/prompts/adapters.d.ts +0 -16
- package/dist/prompts/adapters.js +0 -55
- package/dist/rpc/client.d.ts +0 -22
- package/dist/rpc/client.js +0 -40
- package/dist/rpc/codec/lpm.d.ts +0 -20
- package/dist/rpc/codec/lpm.js +0 -36
- package/dist/rpc/crypto/aes.d.ts +0 -22
- package/dist/rpc/crypto/aes.js +0 -47
- package/dist/rpc/crypto/kyber.d.ts +0 -27
- package/dist/rpc/crypto/kyber.js +0 -70
- package/dist/rpc/proto.d.ts +0 -2
- package/dist/rpc/proto.js +0 -33
- package/dist/rpc/server.d.ts +0 -13
- package/dist/rpc/server.js +0 -50
- package/dist/rpc/tls.d.ts +0 -26
- package/dist/rpc/tls.js +0 -54
- package/dist/rpc/types.d.ts +0 -28
- package/dist/rpc/types.js +0 -5
- package/dist/sandbox/guardian.d.ts +0 -18
- package/dist/sandbox/guardian.js +0 -58
- package/dist/sandbox/wasi.d.ts +0 -36
- package/dist/sandbox/wasi.js +0 -233
- package/dist/security/guardian.d.ts +0 -22
- package/dist/security/guardian.js +0 -52
- package/dist/security/zk.d.ts +0 -37
- package/dist/security/zk.js +0 -76
- package/dist/server/index.js +0 -1047
- package/dist/server/ner-scanner.d.ts +0 -29
- package/dist/server/ner-scanner.js +0 -141
- package/dist/server/pii.d.ts +0 -66
- package/dist/server/pii.js +0 -428
- package/dist/utils/logger.d.ts +0 -21
- package/dist/utils/logger.js +0 -70
- package/dist/utils/mcpCompact.d.ts +0 -11
- package/dist/utils/mcpCompact.js +0 -29
package/dist/types.d.ts
CHANGED
|
@@ -1,8 +1,9 @@
|
|
|
1
|
-
import { z } from
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
|
|
2
3
|
/**
|
|
3
4
|
* Base Protocol Types representing parity with Model Context Protocol
|
|
4
5
|
*/
|
|
5
|
-
|
|
6
|
+
declare const ToolSchema: z.ZodObject<{
|
|
6
7
|
name: z.ZodString;
|
|
7
8
|
description: z.ZodOptional<z.ZodString>;
|
|
8
9
|
inputSchema: z.ZodRecord<z.ZodString, z.ZodUnknown>;
|
|
@@ -15,8 +16,8 @@ export declare const ToolSchema: z.ZodObject<{
|
|
|
15
16
|
inputSchema: Record<string, unknown>;
|
|
16
17
|
description?: string | undefined;
|
|
17
18
|
}>;
|
|
18
|
-
|
|
19
|
-
|
|
19
|
+
type Tool = z.infer<typeof ToolSchema>;
|
|
20
|
+
declare const ResourceSchema: z.ZodObject<{
|
|
20
21
|
uri: z.ZodString;
|
|
21
22
|
name: z.ZodString;
|
|
22
23
|
description: z.ZodOptional<z.ZodString>;
|
|
@@ -32,8 +33,8 @@ export declare const ResourceSchema: z.ZodObject<{
|
|
|
32
33
|
description?: string | undefined;
|
|
33
34
|
mimeType?: string | undefined;
|
|
34
35
|
}>;
|
|
35
|
-
|
|
36
|
-
|
|
36
|
+
type Resource = z.infer<typeof ResourceSchema>;
|
|
37
|
+
declare const PromptSchema: z.ZodObject<{
|
|
37
38
|
name: z.ZodString;
|
|
38
39
|
description: z.ZodOptional<z.ZodString>;
|
|
39
40
|
arguments: z.ZodOptional<z.ZodArray<z.ZodObject<{
|
|
@@ -66,12 +67,12 @@ export declare const PromptSchema: z.ZodObject<{
|
|
|
66
67
|
required?: boolean | undefined;
|
|
67
68
|
}[] | undefined;
|
|
68
69
|
}>;
|
|
69
|
-
|
|
70
|
-
|
|
70
|
+
type Prompt = z.infer<typeof PromptSchema>;
|
|
71
|
+
interface CallToolRequest {
|
|
71
72
|
name: string;
|
|
72
73
|
arguments?: Record<string, unknown>;
|
|
73
74
|
}
|
|
74
|
-
|
|
75
|
+
interface CallToolResult {
|
|
75
76
|
content: Array<{
|
|
76
77
|
type: "text" | "image" | "resource";
|
|
77
78
|
text?: string;
|
|
@@ -85,11 +86,11 @@ export interface CallToolResult {
|
|
|
85
86
|
}>;
|
|
86
87
|
isError?: boolean;
|
|
87
88
|
}
|
|
88
|
-
|
|
89
|
+
interface GetPromptRequest {
|
|
89
90
|
name: string;
|
|
90
91
|
arguments?: Record<string, string>;
|
|
91
92
|
}
|
|
92
|
-
|
|
93
|
+
interface GetPromptResult {
|
|
93
94
|
description?: string;
|
|
94
95
|
messages: Array<{
|
|
95
96
|
role: "user" | "assistant";
|
|
@@ -110,7 +111,7 @@ export interface GetPromptResult {
|
|
|
110
111
|
};
|
|
111
112
|
}>;
|
|
112
113
|
}
|
|
113
|
-
|
|
114
|
+
interface ServerInfo {
|
|
114
115
|
name: string;
|
|
115
116
|
version: string;
|
|
116
117
|
capabilities?: {
|
|
@@ -127,13 +128,13 @@ export interface ServerInfo {
|
|
|
127
128
|
logging?: Record<string, unknown>;
|
|
128
129
|
};
|
|
129
130
|
}
|
|
130
|
-
|
|
131
|
+
interface McpRequest {
|
|
131
132
|
method: string;
|
|
132
133
|
params?: unknown;
|
|
133
134
|
id?: string | number | null;
|
|
134
135
|
jsonrpc?: "2.0";
|
|
135
136
|
}
|
|
136
|
-
|
|
137
|
+
interface McpResponse {
|
|
137
138
|
jsonrpc: "2.0";
|
|
138
139
|
id?: string | number | null;
|
|
139
140
|
result?: unknown;
|
|
@@ -143,3 +144,5 @@ export interface McpResponse {
|
|
|
143
144
|
data?: unknown;
|
|
144
145
|
};
|
|
145
146
|
}
|
|
147
|
+
|
|
148
|
+
export { type CallToolRequest, type CallToolResult, type GetPromptRequest, type GetPromptResult, type McpRequest, type McpResponse, type Prompt, PromptSchema, type Resource, ResourceSchema, type ServerInfo, type Tool, ToolSchema };
|
package/dist/types.js
CHANGED
|
@@ -1,26 +1,2 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
* Base Protocol Types representing parity with Model Context Protocol
|
|
4
|
-
*/
|
|
5
|
-
export const ToolSchema = z.object({
|
|
6
|
-
name: z.string(),
|
|
7
|
-
description: z.string().optional(),
|
|
8
|
-
inputSchema: z.record(z.string(), z.unknown()), // Represents a JSON Schema
|
|
9
|
-
});
|
|
10
|
-
export const ResourceSchema = z.object({
|
|
11
|
-
uri: z.string(),
|
|
12
|
-
name: z.string(),
|
|
13
|
-
description: z.string().optional(),
|
|
14
|
-
mimeType: z.string().optional(),
|
|
15
|
-
});
|
|
16
|
-
export const PromptSchema = z.object({
|
|
17
|
-
name: z.string(),
|
|
18
|
-
description: z.string().optional(),
|
|
19
|
-
arguments: z
|
|
20
|
-
.array(z.object({
|
|
21
|
-
name: z.string(),
|
|
22
|
-
description: z.string().optional(),
|
|
23
|
-
required: z.boolean().optional(),
|
|
24
|
-
}))
|
|
25
|
-
.optional(),
|
|
26
|
-
});
|
|
1
|
+
export{c as PromptSchema,b as ResourceSchema,a as ToolSchema}from'./chunk-HQZHZM6U.js';//# sourceMappingURL=types.js.map
|
|
2
|
+
//# sourceMappingURL=types.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":[],"names":[],"mappings":"","file":"types.js"}
|
|
@@ -5,7 +5,7 @@
|
|
|
5
5
|
* It validates both the integrity of the code (ZkImageID) and the mathematical proof
|
|
6
6
|
* of its execution (ZkSeal), as well as hardware-level attestation (TEE).
|
|
7
7
|
*/
|
|
8
|
-
|
|
8
|
+
declare class LiopVerifier {
|
|
9
9
|
private static zkWorkerPool;
|
|
10
10
|
private getZkPool;
|
|
11
11
|
/**
|
|
@@ -27,3 +27,5 @@ export declare class LiopVerifier {
|
|
|
27
27
|
*/
|
|
28
28
|
deriveImageId(logicPayload: Buffer): Buffer;
|
|
29
29
|
}
|
|
30
|
+
|
|
31
|
+
export { LiopVerifier as L };
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":[],"names":[],"mappings":"","file":"verifier-RQRYXA4C.js"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
|
|
1
|
+
interface WorkerData {
|
|
2
2
|
ciphertext: Uint8Array;
|
|
3
3
|
secretKeyObj: ArrayLike<number>;
|
|
4
4
|
kyberPublicKey: Uint8Array;
|
|
@@ -8,10 +8,17 @@ export interface WorkerData {
|
|
|
8
8
|
sessionToken: string;
|
|
9
9
|
isEncrypted?: boolean;
|
|
10
10
|
aesNonce?: Uint8Array;
|
|
11
|
+
dpConfig?: {
|
|
12
|
+
epsilon: number;
|
|
13
|
+
sensitivity: number;
|
|
14
|
+
smallDatasetThreshold: number;
|
|
15
|
+
};
|
|
11
16
|
}
|
|
12
|
-
|
|
17
|
+
declare function processLogicExecution(data: WorkerData): Promise<{
|
|
13
18
|
image_id: string;
|
|
14
19
|
output: unknown;
|
|
15
20
|
fuel_consumed: number;
|
|
16
21
|
zk_receipt?: string;
|
|
17
22
|
}>;
|
|
23
|
+
|
|
24
|
+
export { type WorkerData, processLogicExecution as default };
|
|
@@ -1,123 +1,2 @@
|
|
|
1
|
-
import { Buffer } from "
|
|
2
|
-
|
|
3
|
-
import { createMlKem768 } from "mlkem";
|
|
4
|
-
import { deriveLogicImageDigest, normalizeLogicSource, } from "../crypto/logic-image-id.js";
|
|
5
|
-
import { ASTGuardian } from "../sandbox/guardian.js";
|
|
6
|
-
import { WasiSandbox } from "../sandbox/wasi.js";
|
|
7
|
-
export default async function processLogicExecution(data) {
|
|
8
|
-
const { ciphertext, secretKeyObj, wasmBinary, inputs, aesNonce, records, isEncrypted = true, } = data;
|
|
9
|
-
let decryptedPayload;
|
|
10
|
-
const decryptedInputs = {};
|
|
11
|
-
let sessionSecret = Buffer.alloc(32); // Fallback if plain text (no PQC)
|
|
12
|
-
if (isEncrypted) {
|
|
13
|
-
// 1. Decapsulate Kyber secret
|
|
14
|
-
const sk = new Uint8Array(secretKeyObj);
|
|
15
|
-
const ct = new Uint8Array(ciphertext);
|
|
16
|
-
const kem = await createMlKem768();
|
|
17
|
-
const sharedSecret = kem.decap(ct, sk);
|
|
18
|
-
const aesKey = Buffer.from(sharedSecret);
|
|
19
|
-
sessionSecret = aesKey;
|
|
20
|
-
// 2. Decrypt Main Payload (WASM/JS Code)
|
|
21
|
-
// LIOP Serialization: Ciphertext = EncryptedData + 16-byte AuthTag
|
|
22
|
-
const wasmBuffer = Buffer.from(wasmBinary);
|
|
23
|
-
const authTag = wasmBuffer.subarray(-16);
|
|
24
|
-
const encryptedData = wasmBuffer.subarray(0, -16);
|
|
25
|
-
const decipher = crypto.createDecipheriv("aes-256-gcm", aesKey, Buffer.from(aesNonce || new Uint8Array(12)));
|
|
26
|
-
decipher.setAuthTag(authTag);
|
|
27
|
-
let decrypted = decipher.update(encryptedData);
|
|
28
|
-
decrypted = Buffer.concat([decrypted, decipher.final()]);
|
|
29
|
-
decryptedPayload = decrypted;
|
|
30
|
-
// 3. Decrypt Inputs
|
|
31
|
-
for (const [key, encValue] of Object.entries(inputs || {})) {
|
|
32
|
-
const valBuffer = Buffer.from(encValue);
|
|
33
|
-
// Extract 12-byte prepended nonce, ciphertext, and 16-byte AuthTag
|
|
34
|
-
const inputNonce = valBuffer.subarray(0, 12);
|
|
35
|
-
const valTag = valBuffer.subarray(-16);
|
|
36
|
-
const valData = valBuffer.subarray(12, -16);
|
|
37
|
-
const valDecipher = crypto.createDecipheriv("aes-256-gcm", aesKey, inputNonce);
|
|
38
|
-
valDecipher.setAuthTag(valTag);
|
|
39
|
-
let valDecrypted = valDecipher.update(valData);
|
|
40
|
-
valDecrypted = Buffer.concat([valDecrypted, valDecipher.final()]);
|
|
41
|
-
decryptedInputs[key] = JSON.parse(valDecrypted.toString("utf-8"));
|
|
42
|
-
}
|
|
43
|
-
}
|
|
44
|
-
else {
|
|
45
|
-
// Transparent mode: payload is provided directly
|
|
46
|
-
// If it's WASM (Magic bytes: \0asm), keep as Buffer
|
|
47
|
-
if (wasmBinary[0] === 0x00 &&
|
|
48
|
-
wasmBinary[1] === 0x61 &&
|
|
49
|
-
wasmBinary[2] === 0x73 &&
|
|
50
|
-
wasmBinary[3] === 0x6d) {
|
|
51
|
-
decryptedPayload = Buffer.from(wasmBinary);
|
|
52
|
-
}
|
|
53
|
-
else {
|
|
54
|
-
decryptedPayload = Buffer.from(wasmBinary).toString("utf-8");
|
|
55
|
-
}
|
|
56
|
-
}
|
|
57
|
-
// 3. Inspect AST with Guardian-TS (if WASM)
|
|
58
|
-
const isWasm = decryptedPayload[0] === 0x00 &&
|
|
59
|
-
decryptedPayload[1] === 0x61 &&
|
|
60
|
-
decryptedPayload[2] === 0x73 &&
|
|
61
|
-
decryptedPayload[3] === 0x6d;
|
|
62
|
-
if (decryptedPayload instanceof Buffer && isWasm) {
|
|
63
|
-
// Ensure we pass a compatible BufferSource
|
|
64
|
-
const wasmBytes = new Uint8Array(decryptedPayload);
|
|
65
|
-
const compiledModule = await WebAssembly.compile(wasmBytes);
|
|
66
|
-
ASTGuardian.analyze(compiledModule);
|
|
67
|
-
}
|
|
68
|
-
else if (decryptedPayload instanceof Buffer && !isWasm) {
|
|
69
|
-
decryptedPayload = decryptedPayload.toString("utf-8");
|
|
70
|
-
}
|
|
71
|
-
// Strip only a whole-document LIOP envelope (see logic-image-id.ts).
|
|
72
|
-
if (typeof decryptedPayload === "string") {
|
|
73
|
-
decryptedPayload = normalizeLogicSource(decryptedPayload);
|
|
74
|
-
}
|
|
75
|
-
// 4. Instantiate and Execute WASI Sandbox (or V8 Fallback)
|
|
76
|
-
const sandbox = new WasiSandbox();
|
|
77
|
-
await sandbox.init();
|
|
78
|
-
try {
|
|
79
|
-
const result = await sandbox.execute(decryptedPayload, records, decryptedInputs);
|
|
80
|
-
// 5. Generate Cryptographic Proof of Execution (HMAC-SHA256 Commitment)
|
|
81
|
-
let logicBytes;
|
|
82
|
-
if (typeof decryptedPayload === "string") {
|
|
83
|
-
logicBytes = Buffer.from(decryptedPayload, "utf-8");
|
|
84
|
-
}
|
|
85
|
-
else {
|
|
86
|
-
logicBytes = new Uint8Array(decryptedPayload);
|
|
87
|
-
}
|
|
88
|
-
const imageId = deriveLogicImageDigest(logicBytes).toString("hex");
|
|
89
|
-
const journal = Buffer.from(JSON.stringify({
|
|
90
|
-
image_id: imageId,
|
|
91
|
-
output_hash: crypto
|
|
92
|
-
.createHash("sha256")
|
|
93
|
-
.update(typeof result.output === "string"
|
|
94
|
-
? result.output
|
|
95
|
-
: JSON.stringify(result.output))
|
|
96
|
-
.digest("hex"),
|
|
97
|
-
fuel: result.fuelConsumed,
|
|
98
|
-
ts: Date.now(),
|
|
99
|
-
}));
|
|
100
|
-
const seal = crypto
|
|
101
|
-
.createHmac("sha256", sessionSecret)
|
|
102
|
-
.update(journal)
|
|
103
|
-
.digest();
|
|
104
|
-
const journalLen = Buffer.alloc(2);
|
|
105
|
-
journalLen.writeUInt16BE(journal.length);
|
|
106
|
-
const receiptBuf = Buffer.concat([
|
|
107
|
-
Buffer.from([0x01]), // Receipt format v1
|
|
108
|
-
journalLen,
|
|
109
|
-
journal,
|
|
110
|
-
seal, // 32 bytes HMAC
|
|
111
|
-
]);
|
|
112
|
-
const zkReceipt = receiptBuf.toString("base64");
|
|
113
|
-
return {
|
|
114
|
-
image_id: imageId,
|
|
115
|
-
zk_receipt: zkReceipt,
|
|
116
|
-
output: result.output,
|
|
117
|
-
fuel_consumed: result.fuelConsumed,
|
|
118
|
-
};
|
|
119
|
-
}
|
|
120
|
-
finally {
|
|
121
|
-
await sandbox.teardown();
|
|
122
|
-
}
|
|
123
|
-
}
|
|
1
|
+
import {a,b}from'../chunk-HNDVAKEK.js';import {a as a$1,b as b$1}from'../chunk-ANFXJGMP.js';import {Buffer}from'buffer';import g from'crypto';import {createMlKem768}from'mlkem';var C={epsilon:1,sensitivity:1,smallDatasetThreshold:50},I=1,K=10;function V(t,r){let n;do r?n=g.createHash("sha256").update(`${r.seed}:${r.counter++}`).digest().readUInt32BE(0)/4294967296-.5:n=g.randomBytes(4).readUInt32BE(0)/4294967296-.5;while(n===0||n===-0.5);return -t*Math.sign(n)*Math.log(1-2*Math.abs(n))}function G(t,r={},n){let e={...C,...r},a=e.sensitivity/e.epsilon,o=t+V(a,n);return Math.round(o*1e4)/1e4}function R(t,r,n){if(!t)return r;let e=t.toLowerCase(),a=/count|length|size|num|nan_|negative_|positive_|null_|empty_|finite_|non_finite_/i.test(e),o=e==="total"||e==="n"||e==="total_records"||/total.*(count|items|entries|rows|records)/i.test(e);return a||o?1:/avg|mean|average/.test(e)&&n>0?r/n:r}function M(t,r={},n){let e={...C,...r};if(n>=e.smallDatasetThreshold)return t;n<K&&e.epsilon<I&&(e.epsilon=I);let a;return e.seed&&(a={seed:e.seed,counter:0}),A(t,e,n,void 0,a)}function A(t,r,n,e,a){if(typeof t=="number"&&Number.isFinite(t)){let o=R(e,r.sensitivity,n),u=G(t,{...r,sensitivity:o},a),p=e!=null&&R(e,r.sensitivity,n)===1;return (Number.isInteger(t)||p)&&(u=Math.round(u)),t>=0&&(u=Math.max(0,u)),u}if(Array.isArray(t))return t.map(o=>A(o,r,n,e,a));if(t!==null&&typeof t=="object"){let o={};for(let[u,p]of Object.entries(t))o[u]=A(p,r,n,u,a);return o}return t}async function Q(t){let{ciphertext:r,secretKeyObj:n,wasmBinary:e,inputs:a$2,aesNonce:o,records:u,isEncrypted:p=true,dpConfig:S}=t,s,O={},T=Buffer.alloc(32);if(p){let l=new Uint8Array(n),c=new Uint8Array(r),d=(await createMlKem768()).decap(c,l),f=Buffer.from(d);T=f;let m=Buffer.from(e),D=m.subarray(-16),b=m.subarray(0,-16),w=g.createDecipheriv("aes-256-gcm",f,Buffer.from(o||new Uint8Array(12)));w.setAuthTag(D);let y=w.update(b);y=Buffer.concat([y,w.final()]),s=y;for(let[j,H]of Object.entries(a$2||{})){let k=Buffer.from(H),z=k.subarray(0,12),F=k.subarray(-16),W=k.subarray(12,-16),_=g.createDecipheriv("aes-256-gcm",f,z);_.setAuthTag(F);let v=_.update(W);v=Buffer.concat([v,_.final()]),O[j]=JSON.parse(v.toString("utf-8"));}}else e[0]===0&&e[1]===97&&e[2]===115&&e[3]===109?s=Buffer.from(e):s=Buffer.from(e).toString("utf-8");let U=s[0]===0&&s[1]===97&&s[2]===115&&s[3]===109;if(s instanceof Buffer&&U){let l=new Uint8Array(s),c=await WebAssembly.compile(l);a.analyze(c);}else s instanceof Buffer&&!U&&(s=s.toString("utf-8"));typeof s=="string"&&(s=a$1(s));let x=new b;await x.init();try{let l=await x.execute(s,u,O),c=l.output,h;typeof s=="string"?h=Buffer.from(s,"utf-8"):h=new Uint8Array(s);let d=b$1(h).toString("hex"),f=g.createHash("sha256").update(JSON.stringify(u||[])).digest("hex");S&&(c=M(c,{...S,seed:`${f}:${d}`},u?.length||0));let m=Buffer.from(JSON.stringify({image_id:d,dataset_hash:f,output_hash:g.createHash("sha256").update(typeof c=="string"?c:JSON.stringify(c)).digest("hex"),fuel:l.fuelConsumed,ts:Date.now()})),D=g.createHmac("sha256",T).update(m).digest(),b=Buffer.alloc(2);b.writeUInt16BE(m.length);let y=Buffer.concat([Buffer.from([1]),b,m,D]).toString("base64");return {image_id:d,zk_receipt:y,output:c,fuel_consumed:l.fuelConsumed}}finally{await x.teardown();}}export{Q as default};//# sourceMappingURL=logic-execution.js.map
|
|
2
|
+
//# sourceMappingURL=logic-execution.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/security/dp-engine.ts","../../src/workers/logic-execution.ts"],"names":["DEFAULT_DP_CONFIG","EPSILON_FLOOR","EPSILON_FLOOR_THRESHOLD","laplaceSample","scale","prngState","u","crypto","addLaplaceNoise","value","config","merged","noisyValue","deriveFieldSensitivity","key","globalSensitivity","recordCount","lk","isCountWord","isTotalCount","applyDpToOutput","output","walkAndNoise","node","currentKey","fieldSensitivity","isCountKey","item","result","processLogicExecution","data","ciphertext","secretKeyObj","wasmBinary","inputs","aesNonce","records","isEncrypted","dpConfig","decryptedPayload","decryptedInputs","sessionSecret","Buffer","sk","ct","sharedSecret","createMlKem768","aesKey","wasmBuffer","authTag","encryptedData","decipher","decrypted","encValue","valBuffer","inputNonce","valTag","valData","valDecipher","valDecrypted","isWasm","wasmBytes","compiledModule","ASTGuardian","normalizeLogicSource","sandbox","WasiSandbox","finalOutput","logicBytes","imageId","deriveLogicImageDigest","datasetHash","journal","seal","journalLen","zkReceipt"],"mappings":"iLAqDA,IAAMA,CAAAA,CAA8B,CACnC,QAAS,CAAA,CACT,WAAA,CAAa,EACb,qBAAA,CAAuB,EACxB,EAOMC,CAAAA,CAAgB,CAAA,CAChBC,EAA0B,EAAA,CAyBhC,SAASC,EAAcC,CAAAA,CAAeC,CAAAA,CAA+B,CACpE,IAAIC,CAAAA,CACJ,GACKD,CAAAA,CAMHC,CAAAA,CALaC,EACX,UAAA,CAAW,QAAQ,EACnB,MAAA,CAAO,CAAA,EAAGF,CAAAA,CAAU,IAAI,CAAA,CAAA,EAAIA,CAAAA,CAAU,SAAS,CAAA,CAAE,CAAA,CACjD,QAAO,CAEA,YAAA,CAAa,CAAC,CAAA,CAAI,UAAA,CAAc,GAGzCC,CAAAA,CADYC,CAAAA,CAAO,YAAY,CAAC,CAAA,CACxB,aAAa,CAAC,CAAA,CAAI,WAAc,EAAA,CAAA,MAEjCD,CAAAA,GAAM,CAAA,EAAKA,CAAAA,GAAM,IAAA,EAC1B,OAAO,CAACF,CAAAA,CAAQ,IAAA,CAAK,KAAKE,CAAC,CAAA,CAAI,KAAK,GAAA,CAAI,CAAA,CAAI,EAAI,IAAA,CAAK,GAAA,CAAIA,CAAC,CAAC,CAC5D,CAUO,SAASE,CAAAA,CACfC,EACAC,CAAAA,CAA4B,EAAC,CAC7BL,CAAAA,CACS,CACT,IAAMM,EAAS,CAAE,GAAGX,EAAmB,GAAGU,CAAO,EAC3CN,CAAAA,CAAQO,CAAAA,CAAO,YAAcA,CAAAA,CAAO,OAAA,CACpCC,EAAaH,CAAAA,CAAQN,CAAAA,CAAcC,EAAOC,CAAS,CAAA,CAGzD,OAAO,IAAA,CAAK,KAAA,CAAMO,EAAa,GAAK,CAAA,CAAI,GACzC,CAmBA,SAASC,EACRC,CAAAA,CACAC,CAAAA,CACAC,EACS,CACT,GA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AAahC,MAAAA,CAAO,MAAM,CAAC,CAAA,CACjCgC,EAAW,aAAA,CAAcF,CAAAA,CAAQ,MAAM,CAAA,CAOvC,IAAMG,EANajC,MAAAA,CAAO,MAAA,CAAO,CAChCA,MAAAA,CAAO,IAAA,CAAK,CAAC,CAAI,CAAC,CAAA,CAClBgC,CAAAA,CACAF,CAAAA,CACAC,CACD,CAAC,CAAA,CAC4B,QAAA,CAAS,QAAQ,CAAA,CAE9C,OAAO,CACN,QAAA,CAAUJ,CAAAA,CACV,WAAYM,CAAAA,CACZ,MAAA,CAAQR,EACR,aAAA,CAAevC,CAAAA,CAAO,YACvB,CACD,CAAA,OAAE,CACD,MAAMqC,CAAAA,CAAQ,QAAA,GACf,CACD","file":"logic-execution.js","sourcesContent":["/**\n * LIOP Differential Privacy Engine — Laplace Mechanism (NIST SP 800-226)\n *\n * Applies calibrated Laplace noise to numeric query outputs,\n * providing ε-differential privacy guarantees against differencing\n * and binary search attacks (F-01, F-02 from security audit).\n *\n * Key design decisions (Phase 110 — Industrial Recalibration):\n * 1. CSPRNG: Uses crypto.randomBytes() instead of Math.random()\n * to prevent state-reconstruction attacks on the noise generator.\n * 2. Query-Aware Sensitivity: COUNT keys get sensitivity=1,\n * AVG keys get sensitivity/n, SUM keys use global config.\n * 3. Epsilon Floor: Auto-enforce ε≥1.0 for datasets with n<10\n * to prevent catastrophic utility destruction.\n *\n * Reference: Dwork & Roth 2014, \"The Algorithmic Foundations of Differential Privacy\"\n * Standards: NIST SP 800-226, Google DP Library, US Census TopDown, Apple iOS DP\n * Industry precedent: Apple (ε=2.0 Health, ε=8.0 Keyboard), US Census (ε=1.0–4.0)\n */\n\nimport crypto from \"node:crypto\";\n\n// ── Public Configuration ─────────────────────────────────────────────\n\nexport interface DpConfig {\n\t/**\n\t * Privacy budget per query (default: 1.0).\n\t * Lower = stronger privacy + more noise. Higher = weaker privacy + less noise.\n\t * Industry standard: Apple iOS Health uses ε=2.0, US Census uses ε=1.0–4.0.\n\t */\n\tepsilon: number;\n\t/**\n\t * Max change in output when one record is added/removed.\n\t * For SUM queries: set to the max plausible value of the field.\n\t * For COUNT queries: the engine automatically overrides to 1.\n\t * For AVG queries: the engine automatically divides by recordCount.\n\t * Default: 1.0 (appropriate for counts and ratios).\n\t */\n\tsensitivity: number;\n\t/**\n\t * Only apply DP noise when dataset size is below this threshold.\n\t * Large datasets have natural statistical privacy (k-anonymity).\n\t * Default: 50 (aligned with HIPAA Safe Harbor minimum).\n\t */\n\tsmallDatasetThreshold: number;\n\t/**\n\t * Optional deterministic seed (e.g., datasetHash + imageId).\n\t * Enables Deterministic Differential Privacy (DDP) for audit modes,\n\t * ensuring perfectly reproducible ZK-Receipts while preserving DP.\n\t */\n\tseed?: string;\n}\n\nconst DEFAULT_DP_CONFIG: DpConfig = {\n\tepsilon: 1.0,\n\tsensitivity: 1.0,\n\tsmallDatasetThreshold: 50,\n};\n\n/**\n * Minimum epsilon enforced for very small datasets (n < 10).\n * Apple's most sensitive category (Health Data) uses ε=2.0 on millions of records.\n * Using ε<1.0 on datasets with <10 records destroys utility completely.\n */\nconst EPSILON_FLOOR = 1.0;\nconst EPSILON_FLOOR_THRESHOLD = 10;\n\n// ── Core Laplace Mechanism ───────────────────────────────────────────\n\nexport interface PrngState {\n\tseed: string;\n\tcounter: number;\n}\n\n/**\n * Generates a sample from the Laplace(0, scale) distribution\n * using inverse CDF sampling with a CSPRNG source.\n *\n * SECURITY: Uses crypto.randomBytes() (OS-level entropy pool) instead of\n * Math.random() (Xorshift128+ PRNG). This prevents state-reconstruction\n * attacks where an adversary observing 3-5 noisy outputs could predict\n * all future noise values and strip the DP protection entirely.\n *\n * Deterministic Audit Mode: If prngState is provided, derives cryptographic\n * entropy using SHA-256 over the seed and an auto-incrementing counter,\n * guaranteeing ZK-Receipt determinism while retaining mathematical privacy.\n *\n * Reference: NIST SP 800-226 §3.2 — \"Implementations must use a CSPRNG\n * for noise generation to maintain the mathematical privacy guarantee.\"\n */\nfunction laplaceSample(scale: number, prngState?: PrngState): number {\n\tlet u: number;\n\tdo {\n\t\tif (prngState) {\n\t\t\tconst hash = crypto\n\t\t\t\t.createHash(\"sha256\")\n\t\t\t\t.update(`${prngState.seed}:${prngState.counter++}`)\n\t\t\t\t.digest();\n\t\t\t// 4 bytes → Uint32 → uniform float in (-0.5, 0.5)\n\t\t\tu = hash.readUInt32BE(0) / 0x100000000 - 0.5;\n\t\t} else {\n\t\t\tconst buf = crypto.randomBytes(4);\n\t\t\tu = buf.readUInt32BE(0) / 0x100000000 - 0.5;\n\t\t}\n\t} while (u === 0 || u === -0.5); // Ensure no exactly 0 or -0.5 for log domain\n\treturn -scale * Math.sign(u) * Math.log(1 - 2 * Math.abs(u));\n}\n\n/**\n * Applies Laplace noise to a single numeric value.\n *\n * @param value - The true computed result\n * @param config - DP configuration (epsilon, sensitivity, seed)\n * @param prngState - Optional state tracking for deterministic sampling\n * @returns Noisy value with ε-differential privacy guarantee\n */\nexport function addLaplaceNoise(\n\tvalue: number,\n\tconfig: Partial<DpConfig> = {},\n\tprngState?: PrngState,\n): number {\n\tconst merged = { ...DEFAULT_DP_CONFIG, ...config };\n\tconst scale = merged.sensitivity / merged.epsilon;\n\tconst noisyValue = value + laplaceSample(scale, prngState);\n\t// Round to 4 decimal places to prevent long random digit strings\n\t// from triggering regex-based PII egress filters (e.g. phone numbers)\n\treturn Math.round(noisyValue * 10000) / 10000;\n}\n\n// ── Query-Aware Sensitivity ─────────────────────────────────────────\n\n/**\n * Derives field-level sensitivity based on key name semantics.\n *\n * This follows Google DP's architectural separation of CountParams,\n * SumParams, and MeanParams — each with independent sensitivity.\n *\n * Axioms (Dwork & Roth 2014):\n * - COUNT: Adding/removing one record changes count by at most 1.\n * - SUM: Adding/removing one record changes sum by at most max_value.\n * - AVG: Sensitivity = max_value / n (bounded contribution).\n *\n * @param key - Output field name (e.g., \"count\", \"avg_balance\", \"totalRevenue\")\n * @param globalSensitivity - Operator-configured max change per record\n * @param recordCount - Dataset size for average normalization\n */\nfunction deriveFieldSensitivity(\n\tkey: string | undefined,\n\tglobalSensitivity: number,\n\trecordCount: number,\n): number {\n\tif (!key) return globalSensitivity;\n\n\tconst lk = key.toLowerCase();\n\n\t// COUNT queries: sensitivity is ALWAYS 1 (fundamental DP axiom)\n\t// Match unambiguous count words: count, length, size, num (anywhere in key),\n\t// as well as common filter prefixes used in audits (nan_, negative_, positive_, null_, empty_, finite_, non_finite_).\n\t// \"total\" is ambiguous (\"totalRevenue\" = SUM, \"total\" or \"total_records\" = COUNT).\n\t// Only treat \"total\" as count when it IS the key or ends with a count suffix.\n\tconst isCountWord =\n\t\t/count|length|size|num|nan_|negative_|positive_|null_|empty_|finite_|non_finite_/i.test(\n\t\t\tlk,\n\t\t);\n\tconst isTotalCount =\n\t\tlk === \"total\" ||\n\t\tlk === \"n\" ||\n\t\tlk === \"total_records\" ||\n\t\t/total.*(count|items|entries|rows|records)/i.test(lk);\n\tif (isCountWord || isTotalCount) return 1;\n\n\t// AVERAGE queries: sensitivity = globalSensitivity / n\n\tif (/avg|mean|average/.test(lk) && recordCount > 0) {\n\t\treturn globalSensitivity / recordCount;\n\t}\n\n\t// SUM / unknown: use operator-configured sensitivity\n\treturn globalSensitivity;\n}\n\n// ── Output Walker ────────────────────────────────────────────────────\n\n/**\n * Recursively walks a JSON output object and applies Laplace noise\n * to all finite numeric leaf values. Non-numeric values (strings,\n * booleans, null) are preserved unchanged.\n *\n * IMPORTANT: This function NEVER mutates the input object.\n * It always returns a new object tree, preserving data integrity\n * of the original sandbox output for ZK-Receipt verification.\n *\n * @param output - The sandbox computation result\n * @param config - DP configuration (epsilon, sensitivity, threshold)\n * @param recordCount - Source dataset size (noise only if < threshold)\n * @returns New object with noisy numeric values (never mutates input)\n */\nexport function applyDpToOutput(\n\toutput: unknown,\n\tconfig: Partial<DpConfig> = {},\n\trecordCount: number,\n): unknown {\n\tconst merged = { ...DEFAULT_DP_CONFIG, ...config };\n\n\t// Large datasets have natural statistical privacy — skip noise\n\tif (recordCount >= merged.smallDatasetThreshold) {\n\t\treturn output;\n\t}\n\n\t// NIST SP 800-226: For very small datasets, enforce minimum epsilon\n\t// to prevent catastrophic utility destruction. Apple uses ε≥2.0 even\n\t// for health data on millions of records; using ε<1.0 on n<10 is\n\t// mathematically equivalent to random number generation.\n\tif (recordCount < EPSILON_FLOOR_THRESHOLD && merged.epsilon < EPSILON_FLOOR) {\n\t\tmerged.epsilon = EPSILON_FLOOR;\n\t}\n\n\tlet prngState: PrngState | undefined;\n\tif (merged.seed) {\n\t\tprngState = { seed: merged.seed, counter: 0 };\n\t}\n\n\treturn walkAndNoise(output, merged, recordCount, undefined, prngState);\n}\n\n/**\n * Internal recursive walker that applies noise to numeric leaves.\n * Handles: numbers, arrays, objects (arbitrary nesting depth).\n *\n * Uses query-aware sensitivity: COUNT keys → sensitivity=1,\n * AVG keys → sensitivity/n, SUM/unknown → global sensitivity.\n */\nfunction walkAndNoise(\n\tnode: unknown,\n\tconfig: DpConfig,\n\trecordCount: number,\n\tcurrentKey?: string,\n\tprngState?: PrngState,\n): unknown {\n\tif (typeof node === \"number\" && Number.isFinite(node)) {\n\t\t// Query-aware sensitivity per Google DP / NIST SP 800-226\n\t\tconst fieldSensitivity = deriveFieldSensitivity(\n\t\t\tcurrentKey,\n\t\t\tconfig.sensitivity,\n\t\t\trecordCount,\n\t\t);\n\t\tlet noisyValue = addLaplaceNoise(\n\t\t\tnode,\n\t\t\t{\n\t\t\t\t...config,\n\t\t\t\tsensitivity: fieldSensitivity,\n\t\t\t},\n\t\t\tprngState,\n\t\t);\n\n\t\t// Semantic heuristics to preserve structural invariants:\n\t\t// Reuse the same count-key detection logic as deriveFieldSensitivity\n\t\tconst isCountKey =\n\t\t\tcurrentKey != null &&\n\t\t\tderiveFieldSensitivity(currentKey, config.sensitivity, recordCount) === 1;\n\n\t\t// If original was an integer OR key suggests a count, force integer\n\t\t// (US Census TopDown: all counts must be non-negative integers)\n\t\tif (Number.isInteger(node) || isCountKey) {\n\t\t\tnoisyValue = Math.round(noisyValue);\n\t\t}\n\n\t\t// If original was non-negative, clamp to 0\n\t\t// (US Census TopDown: enforces non-negative constraint in post-processing)\n\t\tif (node >= 0) {\n\t\t\tnoisyValue = Math.max(0, noisyValue);\n\t\t}\n\n\t\treturn noisyValue;\n\t}\n\n\tif (Array.isArray(node)) {\n\t\t// Pass currentKey down for array items so they inherit semantics\n\t\treturn node.map((item) =>\n\t\t\twalkAndNoise(item, config, recordCount, currentKey, prngState),\n\t\t);\n\t}\n\n\tif (node !== null && typeof node === \"object\") {\n\t\tconst result: Record<string, unknown> = {};\n\t\tfor (const [key, value] of Object.entries(\n\t\t\tnode as Record<string, unknown>,\n\t\t)) {\n\t\t\tresult[key] = walkAndNoise(value, config, recordCount, key, prngState);\n\t\t}\n\t\treturn result;\n\t}\n\n\t// Strings, booleans, null — pass through unchanged\n\treturn node;\n}\n","import { Buffer } from \"node:buffer\";\nimport crypto from \"node:crypto\";\nimport { createMlKem768 } from \"mlkem\";\nimport {\n\tderiveLogicImageDigest,\n\tnormalizeLogicSource,\n} from \"../crypto/logic-image-id.js\";\nimport { ASTGuardian } from \"../sandbox/guardian.js\";\nimport { WasiSandbox } from \"../sandbox/wasi.js\";\nimport { applyDpToOutput } from \"../security/dp-engine.js\";\n\nexport interface WorkerData {\n\tciphertext: Uint8Array;\n\tsecretKeyObj: ArrayLike<number>;\n\tkyberPublicKey: Uint8Array;\n\twasmBinary: Uint8Array; // Can also be JS code in non-encrypted mode\n\tinputs: Record<string, Uint8Array>;\n\trecords?: Record<string, unknown>[];\n\tsessionToken: string;\n\tisEncrypted?: boolean;\n\taesNonce?: Uint8Array;\n\tdpConfig?: {\n\t\tepsilon: number;\n\t\tsensitivity: number;\n\t\tsmallDatasetThreshold: number;\n\t};\n}\n\nexport default async function processLogicExecution(data: WorkerData): Promise<{\n\timage_id: string;\n\toutput: unknown;\n\tfuel_consumed: number;\n\tzk_receipt?: string;\n}> {\n\tconst {\n\t\tciphertext,\n\t\tsecretKeyObj,\n\t\twasmBinary,\n\t\tinputs,\n\t\taesNonce,\n\t\trecords,\n\t\tisEncrypted = true,\n\t\tdpConfig,\n\t} = data;\n\n\tlet decryptedPayload: Buffer | string;\n\tconst decryptedInputs: Record<string, unknown> = {};\n\tlet sessionSecret = Buffer.alloc(32); // Fallback if plain text (no PQC)\n\n\tif (isEncrypted) {\n\t\t// 1. Decapsulate Kyber secret\n\t\tconst sk = new Uint8Array(secretKeyObj);\n\t\tconst ct = new Uint8Array(ciphertext);\n\t\tconst kem = await createMlKem768();\n\t\tconst sharedSecret = kem.decap(ct, sk);\n\t\tconst aesKey = Buffer.from(sharedSecret);\n\t\tsessionSecret = aesKey;\n\n\t\t// 2. Decrypt Main Payload (WASM/JS Code)\n\t\t// LIOP Serialization: Ciphertext = EncryptedData + 16-byte AuthTag\n\t\tconst wasmBuffer = Buffer.from(wasmBinary);\n\t\tconst authTag = wasmBuffer.subarray(-16);\n\t\tconst encryptedData = wasmBuffer.subarray(0, -16);\n\n\t\tconst decipher = crypto.createDecipheriv(\n\t\t\t\"aes-256-gcm\",\n\t\t\taesKey,\n\t\t\tBuffer.from(aesNonce || new Uint8Array(12)),\n\t\t);\n\t\tdecipher.setAuthTag(authTag);\n\t\tlet decrypted = decipher.update(encryptedData);\n\t\tdecrypted = Buffer.concat([decrypted, decipher.final()]);\n\t\tdecryptedPayload = decrypted;\n\n\t\t// 3. Decrypt Inputs\n\t\tfor (const [key, encValue] of Object.entries(inputs || {})) {\n\t\t\tconst valBuffer = Buffer.from(encValue);\n\t\t\t// Extract 12-byte prepended nonce, ciphertext, and 16-byte AuthTag\n\t\t\tconst inputNonce = valBuffer.subarray(0, 12);\n\t\t\tconst valTag = valBuffer.subarray(-16);\n\t\t\tconst valData = valBuffer.subarray(12, -16);\n\n\t\t\tconst valDecipher = crypto.createDecipheriv(\n\t\t\t\t\"aes-256-gcm\",\n\t\t\t\taesKey,\n\t\t\t\tinputNonce,\n\t\t\t);\n\t\t\tvalDecipher.setAuthTag(valTag);\n\t\t\tlet valDecrypted = valDecipher.update(valData);\n\t\t\tvalDecrypted = Buffer.concat([valDecrypted, valDecipher.final()]);\n\t\t\tdecryptedInputs[key] = JSON.parse(valDecrypted.toString(\"utf-8\"));\n\t\t}\n\t} else {\n\t\t// Transparent mode: payload is provided directly\n\t\t// If it's WASM (Magic bytes: \\0asm), keep as Buffer\n\t\tif (\n\t\t\twasmBinary[0] === 0x00 &&\n\t\t\twasmBinary[1] === 0x61 &&\n\t\t\twasmBinary[2] === 0x73 &&\n\t\t\twasmBinary[3] === 0x6d\n\t\t) {\n\t\t\tdecryptedPayload = Buffer.from(wasmBinary);\n\t\t} else {\n\t\t\tdecryptedPayload = Buffer.from(wasmBinary).toString(\"utf-8\");\n\t\t}\n\t}\n\n\t// 3. Inspect AST with Guardian-TS (if WASM)\n\tconst isWasm =\n\t\tdecryptedPayload[0] === 0x00 &&\n\t\tdecryptedPayload[1] === 0x61 &&\n\t\tdecryptedPayload[2] === 0x73 &&\n\t\tdecryptedPayload[3] === 0x6d;\n\n\tif (decryptedPayload instanceof Buffer && isWasm) {\n\t\t// Ensure we pass a compatible BufferSource\n\t\tconst wasmBytes = new Uint8Array(decryptedPayload);\n\t\tconst compiledModule = await WebAssembly.compile(wasmBytes);\n\t\tASTGuardian.analyze(compiledModule);\n\t} else if (decryptedPayload instanceof Buffer && !isWasm) {\n\t\tdecryptedPayload = decryptedPayload.toString(\"utf-8\");\n\t}\n\n\t// Strip only a whole-document LIOP envelope (see logic-image-id.ts).\n\tif (typeof decryptedPayload === \"string\") {\n\t\tdecryptedPayload = normalizeLogicSource(decryptedPayload);\n\t}\n\n\t// 4. Instantiate and Execute WASI Sandbox (or V8 Fallback)\n\tconst sandbox = new WasiSandbox();\n\tawait sandbox.init();\n\n\ttry {\n\t\tconst result = await sandbox.execute(\n\t\t\tdecryptedPayload,\n\t\t\trecords,\n\t\t\tdecryptedInputs,\n\t\t);\n\n\t\tlet finalOutput = result.output;\n\n\t\t// Pre-compute Image ID and Dataset Hash for Audit Trail & DP Seeding\n\t\tlet logicBytes: Uint8Array;\n\t\tif (typeof decryptedPayload === \"string\") {\n\t\t\tlogicBytes = Buffer.from(decryptedPayload, \"utf-8\");\n\t\t} else {\n\t\t\tlogicBytes = new Uint8Array(decryptedPayload);\n\t\t}\n\t\tconst imageId = deriveLogicImageDigest(logicBytes).toString(\"hex\");\n\n\t\t// Phase 110: Include dataset_hash for SOX audit trail compliance.\n\t\t// This SHA-256 anchor proves the underlying dataset was identical\n\t\t// across consecutive queries, separating DP noise from data mutation.\n\t\tconst datasetHash = crypto\n\t\t\t.createHash(\"sha256\")\n\t\t\t.update(JSON.stringify(records || []))\n\t\t\t.digest(\"hex\");\n\n\t\t// Apply Differential Privacy before committing to the ZK-Receipt\n\t\tif (dpConfig) {\n\t\t\tfinalOutput = applyDpToOutput(\n\t\t\t\tfinalOutput,\n\t\t\t\t{\n\t\t\t\t\t...dpConfig,\n\t\t\t\t\tseed: `${datasetHash}:${imageId}`,\n\t\t\t\t},\n\t\t\t\trecords?.length || 0,\n\t\t\t);\n\t\t}\n\n\t\t// 5. Generate Cryptographic Proof of Execution (HMAC-SHA256 Commitment)\n\n\t\tconst journal = Buffer.from(\n\t\t\tJSON.stringify({\n\t\t\t\timage_id: imageId,\n\t\t\t\tdataset_hash: datasetHash,\n\t\t\t\toutput_hash: crypto\n\t\t\t\t\t.createHash(\"sha256\")\n\t\t\t\t\t.update(\n\t\t\t\t\t\ttypeof finalOutput === \"string\"\n\t\t\t\t\t\t\t? finalOutput\n\t\t\t\t\t\t\t: JSON.stringify(finalOutput),\n\t\t\t\t\t)\n\t\t\t\t\t.digest(\"hex\"),\n\t\t\t\tfuel: result.fuelConsumed,\n\t\t\t\tts: Date.now(),\n\t\t\t}),\n\t\t);\n\n\t\tconst seal = crypto\n\t\t\t.createHmac(\"sha256\", sessionSecret)\n\t\t\t.update(journal)\n\t\t\t.digest();\n\t\tconst journalLen = Buffer.alloc(2);\n\t\tjournalLen.writeUInt16BE(journal.length);\n\t\tconst receiptBuf = Buffer.concat([\n\t\t\tBuffer.from([0x01]), // Receipt format v1\n\t\t\tjournalLen,\n\t\t\tjournal,\n\t\t\tseal, // 32 bytes HMAC\n\t\t]);\n\t\tconst zkReceipt = receiptBuf.toString(\"base64\");\n\n\t\treturn {\n\t\t\timage_id: imageId,\n\t\t\tzk_receipt: zkReceipt,\n\t\t\toutput: finalOutput,\n\t\t\tfuel_consumed: result.fuelConsumed,\n\t\t};\n\t} finally {\n\t\tawait sandbox.teardown();\n\t}\n}\n"]}
|
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
* ZK Verification Payload Structure.
|
|
3
3
|
* Modeled after RISC Zero & SP1 Receipt formats.
|
|
4
4
|
*/
|
|
5
|
-
|
|
5
|
+
interface ZkVerificationPayload {
|
|
6
6
|
action: "verify_receipt";
|
|
7
7
|
/** Original logic payload (JS/WASM) sent by client */
|
|
8
8
|
logicPayload: Uint8Array;
|
|
@@ -16,7 +16,9 @@ export interface ZkVerificationPayload {
|
|
|
16
16
|
/**
|
|
17
17
|
* Main worker entry point for Piscina.
|
|
18
18
|
*/
|
|
19
|
-
|
|
19
|
+
declare function workerHandler(task: ZkVerificationPayload): Promise<{
|
|
20
20
|
verified: boolean;
|
|
21
21
|
message: string;
|
|
22
22
|
}>;
|
|
23
|
+
|
|
24
|
+
export { type ZkVerificationPayload, workerHandler as default };
|
|
@@ -1,98 +1,2 @@
|
|
|
1
|
-
import crypto from "
|
|
2
|
-
|
|
3
|
-
import { deriveLogicImageDigest } from "../crypto/logic-image-id.js";
|
|
4
|
-
// Ensure this worker is used via Piscina pool
|
|
5
|
-
if (!parentPort) {
|
|
6
|
-
// Not fatal in Piscina, but handled appropriately
|
|
7
|
-
}
|
|
8
|
-
function deriveImageId(logicPayload) {
|
|
9
|
-
return deriveLogicImageDigest(logicPayload);
|
|
10
|
-
}
|
|
11
|
-
/**
|
|
12
|
-
* Simulates heavy ZK-Proof cryptographic verification.
|
|
13
|
-
* In a real environment, this delegates to @risc0/verifier or SP1 FFI bindings.
|
|
14
|
-
*/
|
|
15
|
-
async function verifyZkReceipt(payload) {
|
|
16
|
-
const { logicPayload, remoteImageIdHex, zkReceipt, sessionSecret } = payload;
|
|
17
|
-
// 1. Calculate local ImageID (Integrity Check)
|
|
18
|
-
const localImageId = deriveImageId(logicPayload);
|
|
19
|
-
const localImageIdHex = localImageId.toString("hex");
|
|
20
|
-
if (localImageIdHex !== remoteImageIdHex) {
|
|
21
|
-
return {
|
|
22
|
-
verified: false,
|
|
23
|
-
message: `Integrity Violation: Local (${localImageIdHex.slice(0, 8)}) != Remote (${remoteImageIdHex.slice(0, 8)})`,
|
|
24
|
-
};
|
|
25
|
-
}
|
|
26
|
-
// 2. Structural Verification: Deserialize Binary Receipt
|
|
27
|
-
const receiptBuf = Buffer.from(zkReceipt);
|
|
28
|
-
if (receiptBuf.length < 35) {
|
|
29
|
-
// 1 version + 2 len + 32 seal minimum
|
|
30
|
-
return {
|
|
31
|
-
verified: false,
|
|
32
|
-
message: "Receipt too short for binary format.",
|
|
33
|
-
};
|
|
34
|
-
}
|
|
35
|
-
const version = receiptBuf[0];
|
|
36
|
-
if (version !== 0x01) {
|
|
37
|
-
return {
|
|
38
|
-
verified: false,
|
|
39
|
-
message: `Unknown receipt version: ${version}`,
|
|
40
|
-
};
|
|
41
|
-
}
|
|
42
|
-
const journalLen = receiptBuf.readUInt16BE(1);
|
|
43
|
-
const journal = receiptBuf.subarray(3, 3 + journalLen);
|
|
44
|
-
const seal = receiptBuf.subarray(3 + journalLen);
|
|
45
|
-
if (seal.length !== 32) {
|
|
46
|
-
return {
|
|
47
|
-
verified: false,
|
|
48
|
-
message: "Invalid seal length (expected 32 bytes HMAC-SHA256).",
|
|
49
|
-
};
|
|
50
|
-
}
|
|
51
|
-
// 3. Parse journal and verify imageId
|
|
52
|
-
try {
|
|
53
|
-
const journalData = JSON.parse(journal.toString());
|
|
54
|
-
if (journalData.image_id !== localImageIdHex) {
|
|
55
|
-
return {
|
|
56
|
-
verified: false,
|
|
57
|
-
message: `Journal ImageID mismatch: ${journalData.image_id.slice(0, 8)} != ${localImageIdHex.slice(0, 8)}`,
|
|
58
|
-
};
|
|
59
|
-
}
|
|
60
|
-
}
|
|
61
|
-
catch (_e) {
|
|
62
|
-
return { verified: false, message: "Failed to parse journal data." };
|
|
63
|
-
}
|
|
64
|
-
// 4. Mathematical Verification (HMAC-SHA256)
|
|
65
|
-
if (sessionSecret && sessionSecret.length > 0) {
|
|
66
|
-
const expectedSeal = crypto
|
|
67
|
-
.createHmac("sha256", sessionSecret)
|
|
68
|
-
.update(journal)
|
|
69
|
-
.digest();
|
|
70
|
-
if (!crypto.timingSafeEqual(seal, expectedSeal)) {
|
|
71
|
-
return {
|
|
72
|
-
verified: false,
|
|
73
|
-
message: "Invalid seal: HMAC verification failed.",
|
|
74
|
-
};
|
|
75
|
-
}
|
|
76
|
-
}
|
|
77
|
-
return {
|
|
78
|
-
verified: true,
|
|
79
|
-
message: "HMAC Commitment Verified: Integrity intact.",
|
|
80
|
-
};
|
|
81
|
-
}
|
|
82
|
-
/**
|
|
83
|
-
* Main worker entry point for Piscina.
|
|
84
|
-
*/
|
|
85
|
-
export default async function workerHandler(task) {
|
|
86
|
-
try {
|
|
87
|
-
if (task.action === "verify_receipt") {
|
|
88
|
-
return await verifyZkReceipt(task);
|
|
89
|
-
}
|
|
90
|
-
throw new Error("Unknown action in ZkVerifier Worker.");
|
|
91
|
-
}
|
|
92
|
-
catch (error) {
|
|
93
|
-
return {
|
|
94
|
-
verified: false,
|
|
95
|
-
message: `Verification Error: ${error.message}`,
|
|
96
|
-
};
|
|
97
|
-
}
|
|
98
|
-
}
|
|
1
|
+
import {b}from'../chunk-ANFXJGMP.js';import d from'crypto';import'worker_threads';function u(e){return b(e)}async function y(e){let{logicPayload:t,remoteImageIdHex:o,zkReceipt:g,sessionSecret:n}=e,a=u(t).toString("hex");if(a!==o)return {verified:false,message:`Integrity Violation: Local (${a.slice(0,8)}) != Remote (${o.slice(0,8)})`};let r=Buffer.from(g);if(r.length<35)return {verified:false,message:"Receipt too short for binary format."};let s=r[0];if(s!==1)return {verified:false,message:`Unknown receipt version: ${s}`};let c=r.readUInt16BE(1),f=r.subarray(3,3+c),l=r.subarray(3+c);if(l.length!==32)return {verified:false,message:"Invalid seal length (expected 32 bytes HMAC-SHA256)."};try{let i=JSON.parse(f.toString());if(i.image_id!==a)return {verified:!1,message:`Journal ImageID mismatch: ${i.image_id.slice(0,8)} != ${a.slice(0,8)}`}}catch{return {verified:false,message:"Failed to parse journal data."}}if(n&&n.length>0){let i=d.createHmac("sha256",n).update(f).digest();if(!d.timingSafeEqual(l,i))return {verified:false,message:"Invalid seal: HMAC verification failed."}}return {verified:true,message:"HMAC Commitment Verified: Integrity intact."}}async function v(e){try{if(e.action==="verify_receipt")return await y(e);throw new Error("Unknown action in ZkVerifier Worker.")}catch(t){return {verified:false,message:`Verification Error: ${t.message}`}}}export{v as default};//# sourceMappingURL=zk-verifier.js.map
|
|
2
|
+
//# sourceMappingURL=zk-verifier.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/workers/zk-verifier.ts"],"names":["deriveImageId","logicPayload","deriveLogicImageDigest","verifyZkReceipt","payload","remoteImageIdHex","zkReceipt","sessionSecret","localImageIdHex","receiptBuf","version","journalLen","journal","seal","journalData","expectedSeal","crypto","workerHandler","task","error"],"mappings":"kFAyBA,SAASA,CAAAA,CAAcC,CAAAA,CAAkC,CACxD,OAAOC,CAAAA,CAAuBD,CAAY,CAC3C,CAMA,eAAeE,CAAAA,CACdC,CAAAA,CACkD,CAClD,GAAM,CAAE,YAAA,CAAAH,CAAAA,CAAc,gBAAA,CAAAI,CAAAA,CAAkB,SAAA,CAAAC,CAAAA,CAAW,aAAA,CAAAC,CAAc,CAAA,CAAIH,CAAAA,CAI/DI,CAAAA,CADeR,CAAAA,CAAcC,CAAY,CAAA,CACV,QAAA,CAAS,KAAK,C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A,CAAM,CAAA,CAAG,CAAC,CAAC,CAAA,CACzG,CAEF,CAAA,KAAa,CACZ,OAAO,CAAE,QAAA,CAAU,KAAA,CAAO,OAAA,CAAS,+BAAgC,CACpE,CAGA,GAAID,CAAAA,EAAiBA,CAAAA,CAAc,MAAA,CAAS,CAAA,CAAG,CAC9C,IAAMQ,CAAAA,CAAeC,CAAAA,CACnB,UAAA,CAAW,QAAA,CAAUT,CAAa,CAAA,CAClC,MAAA,CAAOK,CAAO,CAAA,CACd,MAAA,EAAO,CACT,GAAI,CAACI,CAAAA,CAAO,eAAA,CAAgBH,CAAAA,CAAME,CAAY,CAAA,CAC7C,OAAO,CACN,QAAA,CAAU,KAAA,CACV,OAAA,CAAS,yCACV,CAEF,CAEA,OAAO,CACN,QAAA,CAAU,IAAA,CACV,OAAA,CAAS,6CACV,CACD,CAKA,eAAOE,CAAAA,CACNC,CAAAA,CACkD,CAClD,GAAI,CACH,GAAIA,CAAAA,CAAK,MAAA,GAAW,gBAAA,CACnB,OAAO,MAAMf,CAAAA,CAAgBe,CAAI,CAAA,CAElC,MAAM,IAAI,KAAA,CAAM,sCAAsC,CACvD,CAAA,MAASC,CAAAA,CAAO,CACf,OAAO,CACN,QAAA,CAAU,KAAA,CACV,OAAA,CAAS,CAAA,oBAAA,EAAwBA,CAAAA,CAAgB,OAAO,CAAA,CACzD,CACD,CACD","file":"zk-verifier.js","sourcesContent":["import crypto from \"node:crypto\";\nimport { parentPort } from \"node:worker_threads\";\nimport { deriveLogicImageDigest } from \"../crypto/logic-image-id.js\";\n\n// Ensure this worker is used via Piscina pool\nif (!parentPort) {\n\t// Not fatal in Piscina, but handled appropriately\n}\n\n/**\n * ZK Verification Payload Structure.\n * Modeled after RISC Zero & SP1 Receipt formats.\n */\nexport interface ZkVerificationPayload {\n\taction: \"verify_receipt\";\n\t/** Original logic payload (JS/WASM) sent by client */\n\tlogicPayload: Uint8Array;\n\t/** Expected ImageID (SHA-256) of the execution state */\n\tremoteImageIdHex: string;\n\t/** Cbor-encoded or raw buffer containing the execution Receipt (Journal + Seal) */\n\tzkReceipt: Uint8Array;\n\t/** Kyber-derived session secret to verify HMAC signature */\n\tsessionSecret?: Uint8Array;\n}\n\nfunction deriveImageId(logicPayload: Uint8Array): Buffer {\n\treturn deriveLogicImageDigest(logicPayload);\n}\n\n/**\n * Simulates heavy ZK-Proof cryptographic verification.\n * In a real environment, this delegates to @risc0/verifier or SP1 FFI bindings.\n */\nasync function verifyZkReceipt(\n\tpayload: ZkVerificationPayload,\n): Promise<{ verified: boolean; message: string }> {\n\tconst { logicPayload, remoteImageIdHex, zkReceipt, sessionSecret } = payload;\n\n\t// 1. Calculate local ImageID (Integrity Check)\n\tconst localImageId = deriveImageId(logicPayload);\n\tconst localImageIdHex = localImageId.toString(\"hex\");\n\n\tif (localImageIdHex !== remoteImageIdHex) {\n\t\treturn {\n\t\t\tverified: false,\n\t\t\tmessage: `Integrity Violation: Local (${localImageIdHex.slice(0, 8)}) != Remote (${remoteImageIdHex.slice(0, 8)})`,\n\t\t};\n\t}\n\n\t// 2. Structural Verification: Deserialize Binary Receipt\n\tconst receiptBuf = Buffer.from(zkReceipt);\n\tif (receiptBuf.length < 35) {\n\t\t// 1 version + 2 len + 32 seal minimum\n\t\treturn {\n\t\t\tverified: false,\n\t\t\tmessage: \"Receipt too short for binary format.\",\n\t\t};\n\t}\n\n\tconst version = receiptBuf[0];\n\tif (version !== 0x01) {\n\t\treturn {\n\t\t\tverified: false,\n\t\t\tmessage: `Unknown receipt version: ${version}`,\n\t\t};\n\t}\n\n\tconst journalLen = receiptBuf.readUInt16BE(1);\n\tconst journal = receiptBuf.subarray(3, 3 + journalLen);\n\tconst seal = receiptBuf.subarray(3 + journalLen);\n\n\tif (seal.length !== 32) {\n\t\treturn {\n\t\t\tverified: false,\n\t\t\tmessage: \"Invalid seal length (expected 32 bytes HMAC-SHA256).\",\n\t\t};\n\t}\n\n\t// 3. Parse journal and verify imageId\n\ttry {\n\t\tconst journalData = JSON.parse(journal.toString());\n\t\tif (journalData.image_id !== localImageIdHex) {\n\t\t\treturn {\n\t\t\t\tverified: false,\n\t\t\t\tmessage: `Journal ImageID mismatch: ${journalData.image_id.slice(0, 8)} != ${localImageIdHex.slice(0, 8)}`,\n\t\t\t};\n\t\t}\n\t} catch (_e) {\n\t\treturn { verified: false, message: \"Failed to parse journal data.\" };\n\t}\n\n\t// 4. Mathematical Verification (HMAC-SHA256)\n\tif (sessionSecret && sessionSecret.length > 0) {\n\t\tconst expectedSeal = crypto\n\t\t\t.createHmac(\"sha256\", sessionSecret)\n\t\t\t.update(journal)\n\t\t\t.digest();\n\t\tif (!crypto.timingSafeEqual(seal, expectedSeal)) {\n\t\t\treturn {\n\t\t\t\tverified: false,\n\t\t\t\tmessage: \"Invalid seal: HMAC verification failed.\",\n\t\t\t};\n\t\t}\n\t}\n\n\treturn {\n\t\tverified: true,\n\t\tmessage: \"HMAC Commitment Verified: Integrity intact.\",\n\t};\n}\n\n/**\n * Main worker entry point for Piscina.\n */\nexport default async function workerHandler(\n\ttask: ZkVerificationPayload,\n): Promise<{ verified: boolean; message: string }> {\n\ttry {\n\t\tif (task.action === \"verify_receipt\") {\n\t\t\treturn await verifyZkReceipt(task);\n\t\t}\n\t\tthrow new Error(\"Unknown action in ZkVerifier Worker.\");\n\t} catch (error) {\n\t\treturn {\n\t\t\tverified: false,\n\t\t\tmessage: `Verification Error: ${(error as Error).message}`,\n\t\t};\n\t}\n}\n"]}
|
package/package.json
CHANGED
|
@@ -1,12 +1,13 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@nekzus/liop",
|
|
3
|
-
"version": "2.0.0-alpha.
|
|
3
|
+
"version": "2.0.0-alpha.11",
|
|
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",
|
|
7
7
|
"bin": {
|
|
8
|
-
"liop
|
|
8
|
+
"liop": "./dist/bin/agent.js"
|
|
9
9
|
},
|
|
10
|
+
"sideEffects": false,
|
|
10
11
|
"files": [
|
|
11
12
|
"dist",
|
|
12
13
|
"README.md",
|
|
@@ -15,35 +16,35 @@
|
|
|
15
16
|
"exports": {
|
|
16
17
|
".": {
|
|
17
18
|
"types": "./dist/index.d.ts",
|
|
18
|
-
"
|
|
19
|
+
"import": "./dist/index.js"
|
|
19
20
|
},
|
|
20
21
|
"./client": {
|
|
21
|
-
"types": "./dist/client
|
|
22
|
-
"
|
|
22
|
+
"types": "./dist/client.d.ts",
|
|
23
|
+
"import": "./dist/client.js"
|
|
23
24
|
},
|
|
24
25
|
"./server": {
|
|
25
|
-
"types": "./dist/server
|
|
26
|
-
"
|
|
26
|
+
"types": "./dist/server.d.ts",
|
|
27
|
+
"import": "./dist/server.js"
|
|
27
28
|
},
|
|
28
29
|
"./types": {
|
|
29
30
|
"types": "./dist/types.d.ts",
|
|
30
|
-
"
|
|
31
|
+
"import": "./dist/types.js"
|
|
31
32
|
},
|
|
32
33
|
"./bridge": {
|
|
33
|
-
"types": "./dist/bridge
|
|
34
|
-
"
|
|
34
|
+
"types": "./dist/bridge.d.ts",
|
|
35
|
+
"import": "./dist/bridge.js"
|
|
35
36
|
},
|
|
36
37
|
"./gateway": {
|
|
37
|
-
"types": "./dist/gateway
|
|
38
|
-
"
|
|
38
|
+
"types": "./dist/gateway.d.ts",
|
|
39
|
+
"import": "./dist/gateway.js"
|
|
39
40
|
},
|
|
40
41
|
"./mesh": {
|
|
41
|
-
"types": "./dist/mesh
|
|
42
|
-
"
|
|
42
|
+
"types": "./dist/mesh.d.ts",
|
|
43
|
+
"import": "./dist/mesh.js"
|
|
43
44
|
}
|
|
44
45
|
},
|
|
45
46
|
"scripts": {
|
|
46
|
-
"build": "
|
|
47
|
+
"build": "tsup && npx tsx scripts/copy-protos.ts",
|
|
47
48
|
"test": "vitest run --fileParallelism=false",
|
|
48
49
|
"test:all": "vitest run --fileParallelism=false",
|
|
49
50
|
"test:integration": "vitest run tests/integration --fileParallelism=false",
|
|
@@ -107,6 +108,7 @@
|
|
|
107
108
|
"@opentelemetry/sdk-metrics": "^2.7.0",
|
|
108
109
|
"@types/node": "^25.3.1",
|
|
109
110
|
"@vitest/coverage-v8": "^4.0.18",
|
|
111
|
+
"tsup": "^8.5.1",
|
|
110
112
|
"tsx": "^4.21.0",
|
|
111
113
|
"typescript": "^5.9.3",
|
|
112
114
|
"vitest": "^4.0.18"
|
|
@@ -121,18 +123,15 @@
|
|
|
121
123
|
"@libp2p/crypto": "^5.1.14",
|
|
122
124
|
"@libp2p/identify": "^4.0.14",
|
|
123
125
|
"@libp2p/kad-dht": "^16.1.7",
|
|
124
|
-
"@libp2p/mplex": "^12.0.11",
|
|
125
|
-
"@libp2p/noise": "^1.0.1",
|
|
126
126
|
"@libp2p/peer-id": "^4.0.10",
|
|
127
|
-
"@libp2p/peer-id-factory": "^4.0.10",
|
|
128
127
|
"@libp2p/ping": "^3.0.12",
|
|
129
128
|
"@libp2p/tcp": "^11.0.14",
|
|
130
129
|
"@libp2p/websockets": "^10.1.7",
|
|
131
|
-
"@modelcontextprotocol/sdk": "^1.28.0",
|
|
132
130
|
"@multiformats/multiaddr": "^13.0.1",
|
|
133
131
|
"@opentelemetry/api": "^1.9.1",
|
|
134
|
-
"
|
|
135
|
-
"
|
|
132
|
+
"acorn": "^8.16.0",
|
|
133
|
+
"acorn-walk": "^8.3.5",
|
|
134
|
+
"content-type": "^1.0.5",
|
|
136
135
|
"hono": "^4.12.5",
|
|
137
136
|
"it-pipe": "^3.0.1",
|
|
138
137
|
"libp2p": "^3.1.3",
|
|
@@ -140,9 +139,23 @@
|
|
|
140
139
|
"multiformats": "^13.4.2",
|
|
141
140
|
"p-event": "^7.1.0",
|
|
142
141
|
"piscina": "^5.1.4",
|
|
143
|
-
"
|
|
142
|
+
"protobufjs": "^7.5.8",
|
|
143
|
+
"type-is": "^2.0.1",
|
|
144
144
|
"uint8arrays": "^3.1.1",
|
|
145
145
|
"zod": "^3.23.11",
|
|
146
146
|
"zod-to-json-schema": "^3.24.1"
|
|
147
|
+
},
|
|
148
|
+
"optionalDependencies": {
|
|
149
|
+
"@modelcontextprotocol/sdk": "^1.28.0",
|
|
150
|
+
"compromise": "14.15.0",
|
|
151
|
+
"gpt-tokenizer": "^3.4.0"
|
|
152
|
+
},
|
|
153
|
+
"peerDependencies": {
|
|
154
|
+
"@modelcontextprotocol/sdk": "^1.28.0"
|
|
155
|
+
},
|
|
156
|
+
"peerDependenciesMeta": {
|
|
157
|
+
"@modelcontextprotocol/sdk": {
|
|
158
|
+
"optional": true
|
|
159
|
+
}
|
|
147
160
|
}
|
|
148
161
|
}
|