@nekzus/liop 2.0.0-alpha.3 → 2.0.0-alpha.31
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 +73 -16
- package/dist/bin/agent.js +3 -3
- package/dist/bin/agent.js.map +1 -1
- package/dist/bridge.d.ts +4 -2
- package/dist/bridge.js +1 -1
- package/dist/chunk-2MGFSIXN.js +2 -0
- package/dist/chunk-2MGFSIXN.js.map +1 -0
- package/dist/chunk-4C666HHU.js +2 -0
- package/dist/chunk-4C666HHU.js.map +1 -0
- package/dist/{chunk-PPCOS2NU.js → chunk-DQ6UW6L7.js} +2 -2
- package/dist/chunk-DQ6UW6L7.js.map +1 -0
- package/dist/chunk-L5A64CNT.js +54 -0
- package/dist/chunk-L5A64CNT.js.map +1 -0
- package/dist/chunk-N6FGTZ6A.js +3 -0
- package/dist/chunk-N6FGTZ6A.js.map +1 -0
- package/dist/chunk-RYYRR4N5.js +31 -0
- package/dist/chunk-RYYRR4N5.js.map +1 -0
- package/dist/chunk-SB5XJXKV.js +2 -0
- package/dist/chunk-SB5XJXKV.js.map +1 -0
- package/dist/chunk-SW53FNSN.js +2 -0
- package/dist/chunk-SW53FNSN.js.map +1 -0
- package/dist/chunk-TYVG6TXQ.js +2 -0
- package/dist/chunk-TYVG6TXQ.js.map +1 -0
- package/dist/chunk-V5MKJT6S.js +2 -0
- package/dist/chunk-V5MKJT6S.js.map +1 -0
- package/dist/chunk-VGXNGTIC.js +33 -0
- package/dist/chunk-VGXNGTIC.js.map +1 -0
- package/dist/chunk-W2QGWRTT.js +3 -0
- package/dist/chunk-W2QGWRTT.js.map +1 -0
- package/dist/chunk-YZVCAJJO.js +13 -0
- package/dist/chunk-YZVCAJJO.js.map +1 -0
- package/dist/client.d.ts +3 -2
- package/dist/client.js +1 -1
- package/dist/gateway.d.ts +14 -3
- package/dist/gateway.js +1 -1
- package/dist/{index-CyxNLlz7.d.ts → index-B_Vbrb_I.d.ts} +23 -1
- package/dist/index-CL8m1L1d.d.ts +500 -0
- package/dist/index.d.ts +124 -6
- package/dist/index.js +17 -4
- package/dist/index.js.map +1 -1
- package/dist/kyber-NONMBQNH.js +2 -0
- package/dist/{kyber-2WDOTUQX.js.map → kyber-NONMBQNH.js.map} +1 -1
- package/dist/mesh.d.ts +3 -0
- package/dist/mesh.js +1 -1
- package/dist/server.d.ts +5 -324
- package/dist/server.js +1 -1
- package/dist/types-DzEXgi4s.d.ts +228 -0
- package/dist/types.d.ts +3 -148
- package/dist/types.js +1 -1
- package/dist/verifier-Z26UC7M4.js +2 -0
- package/dist/{verifier-RQRYXA4C.js.map → verifier-Z26UC7M4.js.map} +1 -1
- package/dist/workers/logic-execution.d.ts +12 -6
- package/dist/workers/logic-execution.js +1 -1
- package/dist/workers/logic-execution.js.map +1 -1
- package/dist/workers/zk-verifier.d.ts +4 -4
- package/dist/workers/zk-verifier.js +1 -1
- package/dist/workers/zk-verifier.js.map +1 -1
- package/package.json +56 -48
- package/dist/chunk-7MAGL6ON.js +0 -33
- package/dist/chunk-7MAGL6ON.js.map +0 -1
- package/dist/chunk-FW6CICSY.js +0 -29
- package/dist/chunk-FW6CICSY.js.map +0 -1
- package/dist/chunk-HM77MWB6.js +0 -2
- package/dist/chunk-HM77MWB6.js.map +0 -1
- package/dist/chunk-HNDVAKEK.js +0 -24
- package/dist/chunk-HNDVAKEK.js.map +0 -1
- package/dist/chunk-HQZHZM6U.js +0 -2
- package/dist/chunk-HQZHZM6U.js.map +0 -1
- package/dist/chunk-JBMEAXYU.js +0 -13
- package/dist/chunk-JBMEAXYU.js.map +0 -1
- package/dist/chunk-LYULZHZO.js +0 -3
- package/dist/chunk-LYULZHZO.js.map +0 -1
- package/dist/chunk-P52IE4L6.js +0 -2
- package/dist/chunk-P52IE4L6.js.map +0 -1
- package/dist/chunk-PPCOS2NU.js.map +0 -1
- package/dist/chunk-UVTEJYHN.js +0 -2
- package/dist/chunk-UVTEJYHN.js.map +0 -1
- package/dist/kyber-2WDOTUQX.js +0 -2
- package/dist/verifier-RQRYXA4C.js +0 -2
|
@@ -0,0 +1,228 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
import * as jose from 'jose';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* LIOP JWT Validator — Token Verification Engine
|
|
6
|
+
*
|
|
7
|
+
* Validates JWT Access Tokens using the `jose` library.
|
|
8
|
+
* Supports two modes:
|
|
9
|
+
* - Local JWKS (Nexus role): Keys in memory, zero network latency.
|
|
10
|
+
* - Remote JWKS (Node role): Fetched from Nexus /oidc/jwks with 10min cache.
|
|
11
|
+
*
|
|
12
|
+
* Standards: NIST SP 800-207 (continuous verification), OWASP API-A01
|
|
13
|
+
* Source: panva/jose DeepWiki — createRemoteJWKSet, jwtVerify
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* Authorization context extracted from a validated JWT.
|
|
18
|
+
* Compatible with MCP TypeScript SDK AuthInfo interface.
|
|
19
|
+
*/
|
|
20
|
+
interface AuthInfo {
|
|
21
|
+
/** Raw JWT string. */
|
|
22
|
+
token: string;
|
|
23
|
+
/** Subject claim (client_id for M2M flows). */
|
|
24
|
+
clientId: string;
|
|
25
|
+
/** Space-delimited scopes parsed into an array. */
|
|
26
|
+
scopes: string[];
|
|
27
|
+
/** Token expiration timestamp (Unix seconds). */
|
|
28
|
+
expiresAt?: number;
|
|
29
|
+
}
|
|
30
|
+
/**
|
|
31
|
+
* JWT Validator with dual-mode JWKS resolution.
|
|
32
|
+
*
|
|
33
|
+
* - Nexus role: `new JwtValidator(issuer, audience, localJwks)` (createLocalJWKSet)
|
|
34
|
+
* - Node role: `new JwtValidator(issuer, audience, new URL(jwksUri))` (createRemoteJWKSet)
|
|
35
|
+
*/
|
|
36
|
+
declare class JwtValidator {
|
|
37
|
+
private readonly jwksResolver;
|
|
38
|
+
private readonly issuer;
|
|
39
|
+
private readonly audience;
|
|
40
|
+
constructor(issuer: string, audience: string, jwksSource: URL | jose.JSONWebKeySet);
|
|
41
|
+
/**
|
|
42
|
+
* Validates a JWT access token and extracts authorization context.
|
|
43
|
+
*
|
|
44
|
+
* Checks performed (jose.jwtVerify):
|
|
45
|
+
* - Cryptographic signature verification (EdDSA or ES256)
|
|
46
|
+
* - Issuer claim matches configured issuer
|
|
47
|
+
* - Audience claim matches configured audience
|
|
48
|
+
* - Token is not expired (with clock tolerance for mesh skew)
|
|
49
|
+
* - Required claims (sub, scope) are present
|
|
50
|
+
*
|
|
51
|
+
* @throws JOSEError if validation fails (expired, wrong issuer, bad signature, etc.)
|
|
52
|
+
*/
|
|
53
|
+
validate(token: string): Promise<AuthInfo>;
|
|
54
|
+
/**
|
|
55
|
+
* Builds a complete set of issuer URL aliases for the LIOP demo topology.
|
|
56
|
+
*
|
|
57
|
+
* The LIOP mesh runs on Docker Desktop with the following network layout:
|
|
58
|
+
* Container hostnames: "nexus", "liop-nexus" (internal port 3000)
|
|
59
|
+
* Host-published ports: 13000 (HTTP/MCP), 13001 (libp2p TCP)
|
|
60
|
+
* Loopback addresses: 127.0.0.1, localhost
|
|
61
|
+
*
|
|
62
|
+
* The Nexus OAuth server may set its issuer to any of these depending on
|
|
63
|
+
* how it was configured, and nodes may resolve it via LIOP_NEXUS_URL
|
|
64
|
+
* which varies by context. This method generates all equivalent aliases
|
|
65
|
+
* so that jose.jwtVerify accepts the token regardless of which alias
|
|
66
|
+
* was used as `iss` in the JWT.
|
|
67
|
+
*
|
|
68
|
+
* Security note: This does NOT weaken validation — the cryptographic
|
|
69
|
+
* signature is still verified against the same JWKS keys. Only the
|
|
70
|
+
* string comparison of the `iss` claim is relaxed across known aliases.
|
|
71
|
+
*/
|
|
72
|
+
private buildIssuerAliases;
|
|
73
|
+
/**
|
|
74
|
+
* Returns the configured issuer URL for PRM (RFC 9728) metadata.
|
|
75
|
+
*/
|
|
76
|
+
getIssuer(): string;
|
|
77
|
+
/**
|
|
78
|
+
* Returns the configured audience for PRM metadata.
|
|
79
|
+
*/
|
|
80
|
+
getAudience(): string;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* Base Protocol Types representing parity with Model Context Protocol
|
|
85
|
+
*/
|
|
86
|
+
declare const ToolSchema: z.ZodObject<{
|
|
87
|
+
name: z.ZodString;
|
|
88
|
+
description: z.ZodOptional<z.ZodString>;
|
|
89
|
+
inputSchema: z.ZodRecord<z.ZodString, z.ZodUnknown>;
|
|
90
|
+
}, "strip", z.ZodTypeAny, {
|
|
91
|
+
name: string;
|
|
92
|
+
inputSchema: Record<string, unknown>;
|
|
93
|
+
description?: string | undefined;
|
|
94
|
+
}, {
|
|
95
|
+
name: string;
|
|
96
|
+
inputSchema: Record<string, unknown>;
|
|
97
|
+
description?: string | undefined;
|
|
98
|
+
}>;
|
|
99
|
+
type Tool = z.infer<typeof ToolSchema>;
|
|
100
|
+
declare const ResourceSchema: z.ZodObject<{
|
|
101
|
+
uri: z.ZodString;
|
|
102
|
+
name: z.ZodString;
|
|
103
|
+
description: z.ZodOptional<z.ZodString>;
|
|
104
|
+
mimeType: z.ZodOptional<z.ZodString>;
|
|
105
|
+
}, "strip", z.ZodTypeAny, {
|
|
106
|
+
name: string;
|
|
107
|
+
uri: string;
|
|
108
|
+
description?: string | undefined;
|
|
109
|
+
mimeType?: string | undefined;
|
|
110
|
+
}, {
|
|
111
|
+
name: string;
|
|
112
|
+
uri: string;
|
|
113
|
+
description?: string | undefined;
|
|
114
|
+
mimeType?: string | undefined;
|
|
115
|
+
}>;
|
|
116
|
+
type Resource = z.infer<typeof ResourceSchema>;
|
|
117
|
+
declare const PromptSchema: z.ZodObject<{
|
|
118
|
+
name: z.ZodString;
|
|
119
|
+
description: z.ZodOptional<z.ZodString>;
|
|
120
|
+
arguments: z.ZodOptional<z.ZodArray<z.ZodObject<{
|
|
121
|
+
name: z.ZodString;
|
|
122
|
+
description: z.ZodOptional<z.ZodString>;
|
|
123
|
+
required: z.ZodOptional<z.ZodBoolean>;
|
|
124
|
+
}, "strip", z.ZodTypeAny, {
|
|
125
|
+
name: string;
|
|
126
|
+
description?: string | undefined;
|
|
127
|
+
required?: boolean | undefined;
|
|
128
|
+
}, {
|
|
129
|
+
name: string;
|
|
130
|
+
description?: string | undefined;
|
|
131
|
+
required?: boolean | undefined;
|
|
132
|
+
}>, "many">>;
|
|
133
|
+
}, "strip", z.ZodTypeAny, {
|
|
134
|
+
name: string;
|
|
135
|
+
description?: string | undefined;
|
|
136
|
+
arguments?: {
|
|
137
|
+
name: string;
|
|
138
|
+
description?: string | undefined;
|
|
139
|
+
required?: boolean | undefined;
|
|
140
|
+
}[] | undefined;
|
|
141
|
+
}, {
|
|
142
|
+
name: string;
|
|
143
|
+
description?: string | undefined;
|
|
144
|
+
arguments?: {
|
|
145
|
+
name: string;
|
|
146
|
+
description?: string | undefined;
|
|
147
|
+
required?: boolean | undefined;
|
|
148
|
+
}[] | undefined;
|
|
149
|
+
}>;
|
|
150
|
+
type Prompt = z.infer<typeof PromptSchema>;
|
|
151
|
+
interface CallToolRequest {
|
|
152
|
+
name: string;
|
|
153
|
+
arguments?: Record<string, unknown>;
|
|
154
|
+
}
|
|
155
|
+
interface CallToolResult {
|
|
156
|
+
content: Array<{
|
|
157
|
+
type: "text" | "image" | "resource";
|
|
158
|
+
text?: string;
|
|
159
|
+
data?: string;
|
|
160
|
+
mimeType?: string;
|
|
161
|
+
resource?: {
|
|
162
|
+
uri: string;
|
|
163
|
+
text?: string;
|
|
164
|
+
blob?: string;
|
|
165
|
+
};
|
|
166
|
+
}>;
|
|
167
|
+
isError?: boolean;
|
|
168
|
+
}
|
|
169
|
+
interface GetPromptRequest {
|
|
170
|
+
name: string;
|
|
171
|
+
arguments?: Record<string, string>;
|
|
172
|
+
}
|
|
173
|
+
interface GetPromptResult {
|
|
174
|
+
description?: string;
|
|
175
|
+
messages: Array<{
|
|
176
|
+
role: "user" | "assistant";
|
|
177
|
+
content: {
|
|
178
|
+
type: "text";
|
|
179
|
+
text: string;
|
|
180
|
+
} | {
|
|
181
|
+
type: "image";
|
|
182
|
+
data: string;
|
|
183
|
+
mimeType: string;
|
|
184
|
+
} | {
|
|
185
|
+
type: "resource";
|
|
186
|
+
resource: {
|
|
187
|
+
uri: string;
|
|
188
|
+
text?: string;
|
|
189
|
+
blob?: string;
|
|
190
|
+
};
|
|
191
|
+
};
|
|
192
|
+
}>;
|
|
193
|
+
}
|
|
194
|
+
interface ServerInfo {
|
|
195
|
+
name: string;
|
|
196
|
+
version: string;
|
|
197
|
+
capabilities?: {
|
|
198
|
+
prompts?: {
|
|
199
|
+
listChanged?: boolean;
|
|
200
|
+
};
|
|
201
|
+
resources?: {
|
|
202
|
+
subscribe?: boolean;
|
|
203
|
+
listChanged?: boolean;
|
|
204
|
+
};
|
|
205
|
+
tools?: {
|
|
206
|
+
listChanged?: boolean;
|
|
207
|
+
};
|
|
208
|
+
logging?: Record<string, unknown>;
|
|
209
|
+
};
|
|
210
|
+
}
|
|
211
|
+
interface McpRequest {
|
|
212
|
+
method: string;
|
|
213
|
+
params?: unknown;
|
|
214
|
+
id?: string | number | null;
|
|
215
|
+
jsonrpc?: "2.0";
|
|
216
|
+
}
|
|
217
|
+
interface McpResponse {
|
|
218
|
+
jsonrpc: "2.0";
|
|
219
|
+
id?: string | number | null;
|
|
220
|
+
result?: unknown;
|
|
221
|
+
error?: {
|
|
222
|
+
code: number;
|
|
223
|
+
message: string;
|
|
224
|
+
data?: unknown;
|
|
225
|
+
};
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
export { type AuthInfo as A, type CallToolRequest as C, type GetPromptRequest as G, JwtValidator as J, type McpRequest as M, type Prompt as P, type Resource as R, type ServerInfo as S, type Tool as T, type CallToolResult as a, type McpResponse as b, type GetPromptResult as c, PromptSchema as d, ResourceSchema as e, ToolSchema as f };
|
package/dist/types.d.ts
CHANGED
|
@@ -1,148 +1,3 @@
|
|
|
1
|
-
import
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
* Base Protocol Types representing parity with Model Context Protocol
|
|
5
|
-
*/
|
|
6
|
-
declare const ToolSchema: z.ZodObject<{
|
|
7
|
-
name: z.ZodString;
|
|
8
|
-
description: z.ZodOptional<z.ZodString>;
|
|
9
|
-
inputSchema: z.ZodRecord<z.ZodString, z.ZodUnknown>;
|
|
10
|
-
}, "strip", z.ZodTypeAny, {
|
|
11
|
-
name: string;
|
|
12
|
-
inputSchema: Record<string, unknown>;
|
|
13
|
-
description?: string | undefined;
|
|
14
|
-
}, {
|
|
15
|
-
name: string;
|
|
16
|
-
inputSchema: Record<string, unknown>;
|
|
17
|
-
description?: string | undefined;
|
|
18
|
-
}>;
|
|
19
|
-
type Tool = z.infer<typeof ToolSchema>;
|
|
20
|
-
declare const ResourceSchema: z.ZodObject<{
|
|
21
|
-
uri: z.ZodString;
|
|
22
|
-
name: z.ZodString;
|
|
23
|
-
description: z.ZodOptional<z.ZodString>;
|
|
24
|
-
mimeType: z.ZodOptional<z.ZodString>;
|
|
25
|
-
}, "strip", z.ZodTypeAny, {
|
|
26
|
-
name: string;
|
|
27
|
-
uri: string;
|
|
28
|
-
description?: string | undefined;
|
|
29
|
-
mimeType?: string | undefined;
|
|
30
|
-
}, {
|
|
31
|
-
name: string;
|
|
32
|
-
uri: string;
|
|
33
|
-
description?: string | undefined;
|
|
34
|
-
mimeType?: string | undefined;
|
|
35
|
-
}>;
|
|
36
|
-
type Resource = z.infer<typeof ResourceSchema>;
|
|
37
|
-
declare const PromptSchema: z.ZodObject<{
|
|
38
|
-
name: z.ZodString;
|
|
39
|
-
description: z.ZodOptional<z.ZodString>;
|
|
40
|
-
arguments: z.ZodOptional<z.ZodArray<z.ZodObject<{
|
|
41
|
-
name: z.ZodString;
|
|
42
|
-
description: z.ZodOptional<z.ZodString>;
|
|
43
|
-
required: z.ZodOptional<z.ZodBoolean>;
|
|
44
|
-
}, "strip", z.ZodTypeAny, {
|
|
45
|
-
name: string;
|
|
46
|
-
description?: string | undefined;
|
|
47
|
-
required?: boolean | undefined;
|
|
48
|
-
}, {
|
|
49
|
-
name: string;
|
|
50
|
-
description?: string | undefined;
|
|
51
|
-
required?: boolean | undefined;
|
|
52
|
-
}>, "many">>;
|
|
53
|
-
}, "strip", z.ZodTypeAny, {
|
|
54
|
-
name: string;
|
|
55
|
-
description?: string | undefined;
|
|
56
|
-
arguments?: {
|
|
57
|
-
name: string;
|
|
58
|
-
description?: string | undefined;
|
|
59
|
-
required?: boolean | undefined;
|
|
60
|
-
}[] | undefined;
|
|
61
|
-
}, {
|
|
62
|
-
name: string;
|
|
63
|
-
description?: string | undefined;
|
|
64
|
-
arguments?: {
|
|
65
|
-
name: string;
|
|
66
|
-
description?: string | undefined;
|
|
67
|
-
required?: boolean | undefined;
|
|
68
|
-
}[] | undefined;
|
|
69
|
-
}>;
|
|
70
|
-
type Prompt = z.infer<typeof PromptSchema>;
|
|
71
|
-
interface CallToolRequest {
|
|
72
|
-
name: string;
|
|
73
|
-
arguments?: Record<string, unknown>;
|
|
74
|
-
}
|
|
75
|
-
interface CallToolResult {
|
|
76
|
-
content: Array<{
|
|
77
|
-
type: "text" | "image" | "resource";
|
|
78
|
-
text?: string;
|
|
79
|
-
data?: string;
|
|
80
|
-
mimeType?: string;
|
|
81
|
-
resource?: {
|
|
82
|
-
uri: string;
|
|
83
|
-
text?: string;
|
|
84
|
-
blob?: string;
|
|
85
|
-
};
|
|
86
|
-
}>;
|
|
87
|
-
isError?: boolean;
|
|
88
|
-
}
|
|
89
|
-
interface GetPromptRequest {
|
|
90
|
-
name: string;
|
|
91
|
-
arguments?: Record<string, string>;
|
|
92
|
-
}
|
|
93
|
-
interface GetPromptResult {
|
|
94
|
-
description?: string;
|
|
95
|
-
messages: Array<{
|
|
96
|
-
role: "user" | "assistant";
|
|
97
|
-
content: {
|
|
98
|
-
type: "text";
|
|
99
|
-
text: string;
|
|
100
|
-
} | {
|
|
101
|
-
type: "image";
|
|
102
|
-
data: string;
|
|
103
|
-
mimeType: string;
|
|
104
|
-
} | {
|
|
105
|
-
type: "resource";
|
|
106
|
-
resource: {
|
|
107
|
-
uri: string;
|
|
108
|
-
text?: string;
|
|
109
|
-
blob?: string;
|
|
110
|
-
};
|
|
111
|
-
};
|
|
112
|
-
}>;
|
|
113
|
-
}
|
|
114
|
-
interface ServerInfo {
|
|
115
|
-
name: string;
|
|
116
|
-
version: string;
|
|
117
|
-
capabilities?: {
|
|
118
|
-
prompts?: {
|
|
119
|
-
listChanged?: boolean;
|
|
120
|
-
};
|
|
121
|
-
resources?: {
|
|
122
|
-
subscribe?: boolean;
|
|
123
|
-
listChanged?: boolean;
|
|
124
|
-
};
|
|
125
|
-
tools?: {
|
|
126
|
-
listChanged?: boolean;
|
|
127
|
-
};
|
|
128
|
-
logging?: Record<string, unknown>;
|
|
129
|
-
};
|
|
130
|
-
}
|
|
131
|
-
interface McpRequest {
|
|
132
|
-
method: string;
|
|
133
|
-
params?: unknown;
|
|
134
|
-
id?: string | number | null;
|
|
135
|
-
jsonrpc?: "2.0";
|
|
136
|
-
}
|
|
137
|
-
interface McpResponse {
|
|
138
|
-
jsonrpc: "2.0";
|
|
139
|
-
id?: string | number | null;
|
|
140
|
-
result?: unknown;
|
|
141
|
-
error?: {
|
|
142
|
-
code: number;
|
|
143
|
-
message: string;
|
|
144
|
-
data?: unknown;
|
|
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 };
|
|
1
|
+
import 'zod';
|
|
2
|
+
export { A as AuthInfo, C as CallToolRequest, a as CallToolResult, G as GetPromptRequest, c as GetPromptResult, M as McpRequest, b as McpResponse, P as Prompt, d as PromptSchema, R as Resource, e as ResourceSchema, S as ServerInfo, T as Tool, f as ToolSchema } from './types-DzEXgi4s.js';
|
|
3
|
+
import 'jose';
|
package/dist/types.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
export{c as PromptSchema,b as ResourceSchema,a as ToolSchema}from'./chunk-
|
|
1
|
+
export{c as PromptSchema,b as ResourceSchema,a as ToolSchema}from'./chunk-TYVG6TXQ.js';import'./chunk-2MGFSIXN.js';import'./chunk-4C666HHU.js';//# sourceMappingURL=types.js.map
|
|
2
2
|
//# sourceMappingURL=types.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":[],"names":[],"mappings":"","file":"verifier-
|
|
1
|
+
{"version":3,"sources":[],"names":[],"mappings":"","file":"verifier-Z26UC7M4.js"}
|
|
@@ -1,13 +1,19 @@
|
|
|
1
1
|
interface WorkerData {
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
2
|
+
isWarmup?: boolean;
|
|
3
|
+
ciphertext?: Uint8Array;
|
|
4
|
+
secretKeyObj?: ArrayLike<number>;
|
|
5
|
+
kyberPublicKey?: Uint8Array;
|
|
6
|
+
wasmBinary?: Uint8Array;
|
|
7
|
+
inputs?: Record<string, Uint8Array>;
|
|
7
8
|
records?: Record<string, unknown>[];
|
|
8
|
-
sessionToken
|
|
9
|
+
sessionToken?: string;
|
|
9
10
|
isEncrypted?: boolean;
|
|
10
11
|
aesNonce?: Uint8Array;
|
|
12
|
+
dpConfig?: {
|
|
13
|
+
epsilon: number;
|
|
14
|
+
sensitivity: number;
|
|
15
|
+
smallDatasetThreshold: number;
|
|
16
|
+
};
|
|
11
17
|
}
|
|
12
18
|
declare function processLogicExecution(data: WorkerData): Promise<{
|
|
13
19
|
image_id: string;
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import {a,
|
|
1
|
+
import {a,c}from'../chunk-RYYRR4N5.js';import {a as a$1,b}from'../chunk-ANFXJGMP.js';import'../chunk-4C666HHU.js';import {Buffer}from'buffer';import g from'crypto';import {createMlKem768}from'mlkem';var R={epsilon:1,sensitivity:1,smallDatasetThreshold:50},L=1,K=10;function V(t,n){let r;do n?r=g.createHash("sha256").update(`${n.seed}:${n.counter++}`).digest().readUInt32BE(0)/4294967296-.5:r=g.randomBytes(4).readUInt32BE(0)/4294967296-.5;while(r===0||r===-0.5);return -t*Math.sign(r)*Math.log(1-2*Math.abs(r))}function G(t,n={},r){let e={...R,...n},o=e.sensitivity/e.epsilon,a=t+V(o,r);return Math.round(a*1e4)/1e4}function E(t,n,r){if(!t)return n;let e=t.toLowerCase(),o=/count|length|size|num|gainer|loser|positive|negative|nan_|null_|empty_|finite_|non_finite_|instruments|tickers|users|records/i.test(e),a=e==="total"||e==="n"||e==="total_records"||e.startsWith("total_")||e.startsWith("num_")||/total.*(count|items|entries|rows|records|tickers)/i.test(e);return o||a?1:/avg|mean|average|var|variance|std|stddev|ratio|bps|drift|pct|percent|imbalance/i.test(e)&&r>0?n/r:n}function W(t,n={},r){let e={...R,...n};if(r>=e.smallDatasetThreshold)return t;r<K&&e.epsilon<L&&(e.epsilon=L);let o;return e.seed&&(o={seed:e.seed,counter:0}),v(t,e,r,void 0,o)}function v(t,n,r,e,o){if(typeof t=="number"&&Number.isFinite(t)){let a=E(e,n.sensitivity,r),c=G(t,{...n,sensitivity:a},o),m=e!=null&&E(e,n.sensitivity,r)===1;return (Number.isInteger(t)||m)&&(c=Math.round(c)),t>=0&&(c=Math.max(0,c)),c}if(Array.isArray(t))return t.map(a=>v(a,n,r,e,o));if(t!==null&&typeof t=="object"){let a={};for(let[c,m]of Object.entries(t))a[c]=v(m,n,r,c,o);return a}return t}async function Q(t){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)),t.isWarmup)return {image_id:"",output:"warm",fuel_consumed:0};let{ciphertext:n,secretKeyObj:r,wasmBinary:e,inputs:o,aesNonce:a$2,records:c$1,isEncrypted:m=true,dpConfig:j}=t,s,S={},A=Buffer.alloc(32);if(m){let p=new Uint8Array(r),u=new Uint8Array(n),d=(await createMlKem768()).decap(u,p),f=Buffer.from(d);A=f;let l=Buffer.from(e),x=l.subarray(-16),h=l.subarray(0,-16),O=g.createDecipheriv("aes-256-gcm",f,Buffer.from(a$2||new Uint8Array(12)));O.setAuthTag(x);let y=O.update(h);y=Buffer.concat([y,O.final()]),s=y;for(let[I,M]of Object.entries(o||{})){let k=Buffer.from(M),C=k.subarray(0,12),F=k.subarray(-16),H=k.subarray(12,-16),D=g.createDecipheriv("aes-256-gcm",f,C);D.setAuthTag(F);let _=D.update(H);_=Buffer.concat([_,D.final()]),S[I]=JSON.parse(_.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 z=s[0]===0&&s[1]===97&&s[2]===115&&s[3]===109;if(s instanceof Buffer&&z){let p=new Uint8Array(s),u=await WebAssembly.compile(p);a.analyze(u);}else s instanceof Buffer&&!z&&(s=s.toString("utf-8"));typeof s=="string"&&(s=a$1(s));let w=new c;await w.init();try{let p=await w.execute(s,c$1,S),u=p.output,b$1;typeof s=="string"?b$1=Buffer.from(s,"utf-8"):b$1=new Uint8Array(s);let d=b(b$1).toString("hex"),f=g.createHash("sha256").update(JSON.stringify(c$1||[])).digest("hex");j&&(u=W(u,{...j,seed:`${f}:${d}`},c$1?.length||0));let l=Buffer.from(JSON.stringify({image_id:d,dataset_hash:f,output_hash:g.createHash("sha256").update(typeof u=="string"?u:u===void 0?"undefined":JSON.stringify(u)).digest("hex"),fuel:p.fuelConsumed,ts:Date.now()})),x=g.createHmac("sha256",A).update(l).digest(),h=Buffer.alloc(2);h.writeUInt16BE(l.length);let y=Buffer.concat([Buffer.from([1]),h,l,x]).toString("base64");return {image_id:d,zk_receipt:y,output:u,fuel_consumed:p.fuelConsumed}}finally{await w.teardown();}}export{Q as default};//# sourceMappingURL=logic-execution.js.map
|
|
2
2
|
//# sourceMappingURL=logic-execution.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/workers/logic-execution.ts"],"names":["processLogicExecution","data","ciphertext","secretKeyObj","wasmBinary","inputs","aesNonce","records","isEncrypted","decryptedPayload","decryptedInputs","sessionSecret","Buffer","sk","ct","sharedSecret","createMlKem768","aesKey","wasmBuffer","authTag","encryptedData","decipher","crypto","decrypted","key","encValue","valBuffer","inputNonce","valTag","valData","valDecipher","valDecrypted","isWasm","wasmBytes","compiledModule","ASTGuardian","normalizeLogicSource","sandbox","WasiSandbox","result","logicBytes","imageId","deriveLogicImageDigest","journal","seal","journalLen","zkReceipt"],"mappings":"iLAsBA,eAAOA,EAA6CC,CAAAA,CAKjD,CACF,GAAM,CACL,UAAA,CAAAC,EACA,YAAA,CAAAC,CAAAA,CACA,UAAA,CAAAC,CAAAA,CACA,MAAA,CAAAC,CAAAA,CACA,SAAAC,CAAAA,CACA,OAAA,CAAAC,EACA,WAAA,CAAAC,CAAAA,CAAc,IACf,CAAA,CAAIP,CAAAA,CAEAQ,CAAAA,CACEC,CAAAA,CAA2C,EAAC,CAC9CC,EAAgBC,MAAAA,CAAO,KAAA,CAAM,EAAE,CAAA,CAEnC,GAAIJ,CAAAA,CAAa,CAEhB,IAAMK,CAAAA,CAAK,IAAI,UAAA,CAAWV,CAAY,CAAA,CAChCW,EAAK,IAAI,UAAA,CAAWZ,CAAU,CAAA,CAE9Ba,CAAAA,CAAAA,CADM,MAAMC,cAAAA,EAAe,EACR,KAAA,CAAMF,CAAAA,CAAID,CAAE,CAAA,CAC/BI,EAASL,MAAAA,CAAO,IAAA,CAAKG,CAAY,CAAA,CACvCJ,CAAAA,CAAgBM,EAIhB,IAAMC,CAAAA,CAAaN,MAAAA,CAAO,IAAA,CAAKR,CAAU,CAAA,CACnCe,EAAUD,CAAAA,CAAW,QAAA,CAAS,GAAG,CAAA,CACjCE,CAAAA,CAAgBF,E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IAAMgC,EAAUC,GAAAA,CAAuBF,CAAU,EAAE,QAAA,CAAS,KAAK,EAE3DG,CAAAA,CAAU/B,MAAAA,CAAO,IAAA,CACtB,IAAA,CAAK,SAAA,CAAU,CACd,SAAU6B,CAAAA,CACV,WAAA,CAAanB,EACX,UAAA,CAAW,QAAQ,EACnB,MAAA,CACA,OAAOiB,CAAAA,CAAO,MAAA,EAAW,QAAA,CACtBA,CAAAA,CAAO,OACP,IAAA,CAAK,SAAA,CAAUA,EAAO,MAAM,CAChC,EACC,MAAA,CAAO,KAAK,CAAA,CACd,IAAA,CAAMA,CAAAA,CAAO,YAAA,CACb,GAAI,IAAA,CAAK,GAAA,EACV,CAAC,CACF,CAAA,CAEMK,EAAOtB,CAAAA,CACX,UAAA,CAAW,QAAA,CAAUX,CAAa,CAAA,CAClC,MAAA,CAAOgC,CAAO,CAAA,CACd,MAAA,GACIE,CAAAA,CAAajC,MAAAA,CAAO,MAAM,CAAC,CAAA,CACjCiC,CAAAA,CAAW,aAAA,CAAcF,CAAAA,CAAQ,MAAM,EAOvC,IAAMG,CAAAA,CANalC,MAAAA,CAAO,MAAA,CAAO,CAChCA,MAAAA,CAAO,KAAK,CAAC,CAAI,CAAC,CAAA,CAClBiC,CAAAA,CACAF,CAAAA,CACAC,CACD,CAAC,CAAA,CAC4B,SAAS,QAAQ,CAAA,CAE9C,OAAO,CACN,QAAA,CAAUH,CAAAA,CACV,UAAA,CAAYK,CAAAA,CACZ,MAAA,CAAQP,EAAO,MAAA,CACf,aAAA,CAAeA,CAAAA,CAAO,YACvB,CACD,CAAA,OAAE,CACD,MAAMF,CAAAA,CAAQ,QAAA,GACf,CACD","file":"logic-execution.js","sourcesContent":["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\";\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}\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} = 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\t// 5. Generate Cryptographic Proof of Execution (HMAC-SHA256 Commitment)\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\tconst journal = Buffer.from(\n\t\t\tJSON.stringify({\n\t\t\t\timage_id: imageId,\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 result.output === \"string\"\n\t\t\t\t\t\t\t? result.output\n\t\t\t\t\t\t\t: JSON.stringify(result.output),\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: result.output,\n\t\t\tfuel_consumed: result.fuelConsumed,\n\t\t};\n\t} finally {\n\t\tawait sandbox.teardown();\n\t}\n}\n"]}
|
|
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":"uMAqDA,IAAMA,CAAAA,CAA8B,CACnC,OAAA,CAAS,CAAA,CACT,YAAa,CAAA,CACb,qBAAA,CAAuB,EACxB,CAAA,CAOMC,CAAAA,CAAgB,CAAA,CAChBC,EAA0B,EAAA,CAyBhC,SAASC,EAAcC,CAAAA,CAAeC,CAAAA,CAA+B,CACpE,IAAIC,CAAAA,CACJ,GACKD,CAAAA,CAMHC,CAAAA,CALaC,CAAAA,CACX,WAAW,QAAQ,CAAA,CACnB,MAAA,CAAO,CAAA,EAAGF,CAAAA,CAAU,IAAI,IAAIA,CAAAA,CAAU,OAAA,EAAS,CAAA,CAAE,CAAA,CACjD,MAAA,EAAO,CAEA,aAAa,CAAC,CA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A,CAAM,CAAA,EAAGiC,CAAW,IAAIF,CAAO,CAAA,CAChC,EACAjC,GAAAA,EAAS,MAAA,EAAU,CACpB,CAAA,CAAA,CAKD,IAAMoC,CAAAA,CAAU9B,MAAAA,CAAO,IAAA,CACtB,IAAA,CAAK,UAAU,CACd,QAAA,CAAU2B,CAAAA,CACV,YAAA,CAAcE,CAAAA,CACd,WAAA,CAAahE,EACX,UAAA,CAAW,QAAQ,CAAA,CACnB,MAAA,CACA,OAAO4D,CAAAA,EAAgB,SACpBA,CAAAA,CACAA,CAAAA,GAAgB,KAAA,CAAA,CACf,WAAA,CACA,IAAA,CAAK,SAAA,CAAUA,CAAW,CAC/B,CAAA,CACC,MAAA,CAAO,KAAK,CAAA,CACd,IAAA,CAAMvC,EAAO,YAAA,CACb,EAAA,CAAI,IAAA,CAAK,GAAA,EACV,CAAC,CACF,CAAA,CAEM6C,CAAAA,CAAOlE,CAAAA,CACX,UAAA,CAAW,QAAA,CAAUkC,CAAa,EAClC,MAAA,CAAO+B,CAAO,EACd,MAAA,EAAO,CACHE,EAAahC,MAAAA,CAAO,KAAA,CAAM,CAAC,CAAA,CACjCgC,CAAAA,CAAW,aAAA,CAAcF,EAAQ,MAAM,CAAA,CAOvC,IAAMG,CAAAA,CANajC,MAAAA,CAAO,MAAA,CAAO,CAChCA,MAAAA,CAAO,IAAA,CAAK,CAAC,CAAI,CAAC,CAAA,CAClBgC,EACAF,CAAAA,CACAC,CACD,CAAC,CAAA,CAC4B,QAAA,CAAS,QAAQ,EAE9C,OAAO,CACN,QAAA,CAAUJ,CAAAA,CACV,UAAA,CAAYM,CAAAA,CACZ,OAAQR,CAAAA,CACR,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\t// codeql[js/biased-cryptographic-random]\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\t// codeql[js/biased-cryptographic-random]\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|gainer|loser|positive|negative|nan_|null_|empty_|finite_|non_finite_|instruments|tickers|users|records/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\tlk.startsWith(\"total_\") || // Catch total_tickers, total_users\n\t\tlk.startsWith(\"num_\") || // Catch num_records, num_ticks\n\t\t/total.*(count|items|entries|rows|records|tickers)/i.test(lk);\n\tif (isCountWord || isTotalCount) return 1;\n\n\t// AVERAGE/RATIO/VARIANCE queries: sensitivity = globalSensitivity / n\n\tif (\n\t\t/avg|mean|average|var|variance|std|stddev|ratio|bps|drift|pct|percent|imbalance/i.test(\n\t\t\tlk,\n\t\t) &&\n\t\trecordCount > 0\n\t) {\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\tisWarmup?: boolean;\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\t// Freeze Host prototypes in the Worker thread proactively to completely lock down the Isolate environment\n\tif (\n\t\ttypeof Object.prototype === \"object\" &&\n\t\t!Object.isFrozen(Object.prototype)\n\t) {\n\t\tObject.freeze(Object.prototype);\n\t\tObject.freeze(Array.prototype);\n\t\tObject.freeze(String.prototype);\n\t\tObject.freeze(Number.prototype);\n\t\tObject.freeze(Boolean.prototype);\n\t\tObject.freeze(RegExp.prototype);\n\t\tObject.freeze(Map.prototype);\n\t\tObject.freeze(Set.prototype);\n\t\tObject.freeze(Promise.prototype);\n\t\tObject.freeze(Error.prototype);\n\t}\n\n\tif (data.isWarmup) {\n\t\treturn {\n\t\t\timage_id: \"\",\n\t\t\toutput: \"warm\",\n\t\t\tfuel_consumed: 0,\n\t\t};\n\t}\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 as Required<WorkerData>;\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: finalOutput === undefined\n\t\t\t\t\t\t\t\t? \"undefined\"\n\t\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"]}
|
|
@@ -3,13 +3,13 @@
|
|
|
3
3
|
* Modeled after RISC Zero & SP1 Receipt formats.
|
|
4
4
|
*/
|
|
5
5
|
interface ZkVerificationPayload {
|
|
6
|
-
action: "verify_receipt";
|
|
6
|
+
action: "verify_receipt" | "warmup";
|
|
7
7
|
/** Original logic payload (JS/WASM) sent by client */
|
|
8
|
-
logicPayload
|
|
8
|
+
logicPayload?: Uint8Array;
|
|
9
9
|
/** Expected ImageID (SHA-256) of the execution state */
|
|
10
|
-
remoteImageIdHex
|
|
10
|
+
remoteImageIdHex?: string;
|
|
11
11
|
/** Cbor-encoded or raw buffer containing the execution Receipt (Journal + Seal) */
|
|
12
|
-
zkReceipt
|
|
12
|
+
zkReceipt?: Uint8Array;
|
|
13
13
|
/** Kyber-derived session secret to verify HMAC signature */
|
|
14
14
|
sessionSecret?: Uint8Array;
|
|
15
15
|
}
|
|
@@ -1,2 +1,2 @@
|
|
|
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
|
|
1
|
+
import {b}from'../chunk-ANFXJGMP.js';import'../chunk-4C666HHU.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 f=r.readUInt16BE(1),c=r.subarray(3,3+f),l=r.subarray(3+f);if(l.length!==32)return {verified:false,message:"Invalid seal length (expected 32 bytes HMAC-SHA256)."};try{let i=JSON.parse(c.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(c).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 p(e){try{if(e.action==="warmup")return {verified:!0,message:"warm"};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{p as default};//# sourceMappingURL=zk-verifier.js.map
|
|
2
2
|
//# sourceMappingURL=zk-verifier.js.map
|
|
@@ -1 +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":"
|
|
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":"+GAyBA,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,CAChEH,CAAAA,CAIKI,CAAAA,CADeR,CAAAA,CAAcC,CAAY,CAAA,CACV,QAAA,CAAS,KAAK,CAAA,CAEnD,GAAIO,CAAAA,GAAoBH,CAAAA,CACvB,OAAO,CACN,QAAA,CAAU,KAAA,CACV,OAAA,CAAS,CAAA,4BAAA,EAA+BG,CAAAA,CAAgB,KAAA,CAAM,CAAA,CAAG,CAAC,CAAC,CAAA,aAAA,EAAgBH,CAAAA,CAAiB,KAAA,CAAM,CAAA,CAAG,CAAC,CAAC,CAAA,CAAA,CAChH,CAAA,CAID,IAAMI,CAAAA,CAAa,MAAA,CAAO,IAAA,CAAKH,CAAS,CAAA,CACxC,GAAIG,CAAAA,CAAW,MAAA,CAAS,EAAA,CAEvB,OAAO,CACN,QAAA,CAAU,KAAA,CACV,OAAA,CAAS,sCACV,CAAA,CAGD,IAAMC,CAAAA,CAAUD,CAAAA,CAAW,CAAC,CAAA,CAC5B,GAAIC,CAAAA,GAAY,CAAA,CACf,OA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AAA,CACV,OAAA,CAAS,6CACV,CACD,CAKA,eAAOE,CAAAA,CACNC,CAAAA,CACkD,CAClD,GAAI,CACH,GAAIA,CAAAA,CAAK,MAAA,GAAW,QAAA,CACnB,OAAO,CACN,QAAA,CAAU,CAAA,CAAA,CACV,OAAA,CAAS,MACV,CAAA,CAED,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\" | \"warmup\";\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 } =\n\t\tpayload as Required<ZkVerificationPayload>;\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 === \"warmup\") {\n\t\t\treturn {\n\t\t\t\tverified: true,\n\t\t\t\tmessage: \"warm\",\n\t\t\t};\n\t\t}\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"]}
|