@nekzus/liop 1.3.0-alpha.1 → 2.0.0-alpha.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (122) hide show
  1. package/README.md +41 -17
  2. package/dist/bin/agent.d.ts +0 -1
  3. package/dist/bin/agent.js +5 -306
  4. package/dist/bin/agent.js.map +1 -0
  5. package/dist/{bridge/stream.d.ts → bridge.d.ts} +44 -3
  6. package/dist/bridge.js +2 -0
  7. package/dist/bridge.js.map +1 -0
  8. package/dist/chunk-4ABAFG44.js +33 -0
  9. package/dist/chunk-4ABAFG44.js.map +1 -0
  10. package/dist/chunk-ANFXJGMP.js +2 -0
  11. package/dist/chunk-ANFXJGMP.js.map +1 -0
  12. package/dist/chunk-DBXGYHKY.js +2 -0
  13. package/dist/chunk-DBXGYHKY.js.map +1 -0
  14. package/dist/chunk-HM77MWB6.js +2 -0
  15. package/dist/chunk-HM77MWB6.js.map +1 -0
  16. package/dist/chunk-HNDVAKEK.js +24 -0
  17. package/dist/chunk-HNDVAKEK.js.map +1 -0
  18. package/dist/chunk-HQZHZM6U.js +2 -0
  19. package/dist/chunk-HQZHZM6U.js.map +1 -0
  20. package/dist/chunk-P52IE4L6.js +2 -0
  21. package/dist/chunk-P52IE4L6.js.map +1 -0
  22. package/dist/chunk-PIBCW4BD.js +13 -0
  23. package/dist/chunk-PIBCW4BD.js.map +1 -0
  24. package/dist/chunk-PPCOS2NU.js +2 -0
  25. package/dist/chunk-PPCOS2NU.js.map +1 -0
  26. package/dist/chunk-RWRRBYG4.js +2 -0
  27. package/dist/chunk-RWRRBYG4.js.map +1 -0
  28. package/dist/chunk-S6RJHZV2.js +2 -0
  29. package/dist/chunk-S6RJHZV2.js.map +1 -0
  30. package/dist/chunk-UVTEJYHN.js +2 -0
  31. package/dist/chunk-UVTEJYHN.js.map +1 -0
  32. package/dist/chunk-X6FJATUE.js +29 -0
  33. package/dist/chunk-X6FJATUE.js.map +1 -0
  34. package/dist/chunk-XLVRRGOX.js +3 -0
  35. package/dist/chunk-XLVRRGOX.js.map +1 -0
  36. package/dist/client.d.ts +5 -0
  37. package/dist/client.js +2 -0
  38. package/dist/client.js.map +1 -0
  39. package/dist/{gateway/router.d.ts → gateway.d.ts} +37 -5
  40. package/dist/gateway.js +2 -0
  41. package/dist/gateway.js.map +1 -0
  42. package/dist/{client/index.d.ts → index-CyxNLlz7.d.ts} +24 -5
  43. package/dist/index.d.ts +313 -12
  44. package/dist/index.js +31 -12
  45. package/dist/index.js.map +1 -0
  46. package/dist/kyber-2WDOTUQX.js +2 -0
  47. package/dist/kyber-2WDOTUQX.js.map +1 -0
  48. package/dist/{mesh/node.d.ts → mesh.d.ts} +5 -3
  49. package/dist/mesh.js +2 -0
  50. package/dist/mesh.js.map +1 -0
  51. package/dist/{server/index.d.ts → server.d.ts} +145 -10
  52. package/dist/server.js +2 -0
  53. package/dist/server.js.map +1 -0
  54. package/dist/types.d.ts +17 -14
  55. package/dist/types.js +2 -26
  56. package/dist/types.js.map +1 -0
  57. package/dist/{crypto/verifier.d.ts → verifier-DTCD9imJ.d.ts} +3 -1
  58. package/dist/verifier-RQRYXA4C.js +2 -0
  59. package/dist/verifier-RQRYXA4C.js.map +1 -0
  60. package/dist/workers/logic-execution.d.ts +4 -2
  61. package/dist/workers/logic-execution.js +2 -123
  62. package/dist/workers/logic-execution.js.map +1 -0
  63. package/dist/workers/zk-verifier.d.ts +4 -2
  64. package/dist/workers/zk-verifier.js +2 -98
  65. package/dist/workers/zk-verifier.js.map +1 -0
  66. package/package.json +31 -17
  67. package/dist/bridge/index.d.ts +0 -37
  68. package/dist/bridge/index.js +0 -249
  69. package/dist/bridge/stream.js +0 -210
  70. package/dist/client/index.js +0 -275
  71. package/dist/crypto/logic-image-id.d.ts +0 -3
  72. package/dist/crypto/logic-image-id.js +0 -27
  73. package/dist/crypto/verifier.js +0 -97
  74. package/dist/economy/estimator.d.ts +0 -53
  75. package/dist/economy/estimator.js +0 -69
  76. package/dist/economy/index.d.ts +0 -5
  77. package/dist/economy/index.js +0 -3
  78. package/dist/economy/otel.d.ts +0 -38
  79. package/dist/economy/otel.js +0 -100
  80. package/dist/economy/telemetry.d.ts +0 -77
  81. package/dist/economy/telemetry.js +0 -224
  82. package/dist/errors.d.ts +0 -14
  83. package/dist/errors.js +0 -19
  84. package/dist/gateway/hybrid.d.ts +0 -23
  85. package/dist/gateway/hybrid.js +0 -199
  86. package/dist/gateway/router.js +0 -1036
  87. package/dist/mesh/index.d.ts +0 -1
  88. package/dist/mesh/index.js +0 -1
  89. package/dist/mesh/node.js +0 -853
  90. package/dist/prompts/adapters.d.ts +0 -16
  91. package/dist/prompts/adapters.js +0 -55
  92. package/dist/rpc/client.d.ts +0 -22
  93. package/dist/rpc/client.js +0 -40
  94. package/dist/rpc/codec/lpm.d.ts +0 -20
  95. package/dist/rpc/codec/lpm.js +0 -36
  96. package/dist/rpc/crypto/aes.d.ts +0 -22
  97. package/dist/rpc/crypto/aes.js +0 -47
  98. package/dist/rpc/crypto/kyber.d.ts +0 -27
  99. package/dist/rpc/crypto/kyber.js +0 -70
  100. package/dist/rpc/proto.d.ts +0 -2
  101. package/dist/rpc/proto.js +0 -33
  102. package/dist/rpc/server.d.ts +0 -13
  103. package/dist/rpc/server.js +0 -50
  104. package/dist/rpc/tls.d.ts +0 -26
  105. package/dist/rpc/tls.js +0 -54
  106. package/dist/rpc/types.d.ts +0 -28
  107. package/dist/rpc/types.js +0 -5
  108. package/dist/sandbox/guardian.d.ts +0 -18
  109. package/dist/sandbox/guardian.js +0 -58
  110. package/dist/sandbox/wasi.d.ts +0 -36
  111. package/dist/sandbox/wasi.js +0 -209
  112. package/dist/security/guardian.d.ts +0 -22
  113. package/dist/security/guardian.js +0 -52
  114. package/dist/security/zk.d.ts +0 -37
  115. package/dist/security/zk.js +0 -76
  116. package/dist/server/index.js +0 -937
  117. package/dist/server/pii.d.ts +0 -40
  118. package/dist/server/pii.js +0 -266
  119. package/dist/utils/logger.d.ts +0 -21
  120. package/dist/utils/logger.js +0 -70
  121. package/dist/utils/mcpCompact.d.ts +0 -11
  122. package/dist/utils/mcpCompact.js +0 -29
@@ -1,22 +1,136 @@
1
- import { z } from "zod";
2
- import { MeshNode } from "../mesh/node.js";
3
- import type { CallToolRequest, CallToolResult, GetPromptRequest, GetPromptResult, Prompt, Resource, ServerInfo, Tool } from "../types.js";
4
- import { PII_PATTERNS, PII_PRESETS, type PiiRule, PiiScanner } from "./pii.js";
5
- export { PII_PATTERNS, PII_PRESETS, type PiiRule, PiiScanner };
6
- export type ToolHandler<T extends z.ZodRawShape = z.ZodRawShape> = (args: z.infer<z.ZodObject<T>>, extra: {
1
+ import { z } from 'zod';
2
+ import { MeshNode } from './mesh.js';
3
+ import { ServerInfo, CallToolResult, Prompt, GetPromptRequest, GetPromptResult, CallToolRequest, Tool, Resource } from './types.js';
4
+
5
+ /** Single named entity detected by the NER scanner. */
6
+ interface NerEntity {
7
+ type: "person" | "place" | "organization";
8
+ text: string;
9
+ }
10
+ /** Result of an NER scan operation. */
11
+ interface NerScanResult {
12
+ detected: boolean;
13
+ entities: NerEntity[];
14
+ }
15
+ /**
16
+ * Scans text content for named entities that may represent PII.
17
+ * Uses `compromise/three` for person, place, and organization detection.
18
+ *
19
+ * Designed for egress filtering — optimized for recall over precision
20
+ * to ensure sensitive data does not leak through aliased output keys.
21
+ */
22
+ declare class NerScanner {
23
+ private static nlp;
24
+ /**
25
+ * Lazy loads the compromise library only when needed.
26
+ */
27
+ private getNlp;
28
+ /**
29
+ * Scans a single string value for named entities.
30
+ * Returns detected entities if the text contains recognizable PII.
31
+ */
32
+ scan(text: string): Promise<NerScanResult>;
33
+ /**
34
+ * Recursively scans all string values within an object/array.
35
+ * Stops at the first detection for performance (fail-fast).
36
+ */
37
+ scanDeep(input: unknown, seen?: WeakSet<object>): Promise<NerScanResult>;
38
+ }
39
+
40
+ /**
41
+ * LIOP Professional PII Engine (The Shield V2 - Tier-1 Military Edition)
42
+ * Implements high-fidelity detection based on NIST and OWASP standards.
43
+ * Features Multi-Layer Verification (Regex + Algorithmic Validators).
44
+ */
45
+ type PiiRuleDefinition = {
46
+ name: string;
47
+ pattern: string | RegExp;
48
+ validator?: (match: string) => boolean;
49
+ };
50
+ type PiiRule = string | RegExp | PiiRuleDefinition;
51
+ declare const PII_PATTERNS: {
52
+ EMAIL: PiiRuleDefinition;
53
+ CREDIT_CARD: PiiRuleDefinition;
54
+ IP_ADDRESS: PiiRuleDefinition;
55
+ PHONE: PiiRuleDefinition;
56
+ SSN: PiiRuleDefinition;
57
+ IBAN: PiiRuleDefinition;
58
+ PASSPORT_MRZ: PiiRuleDefinition;
59
+ };
60
+ /**
61
+ * Regional and Cultural Security Presets for Out-Of-The-Box compliance.
62
+ * Developers can override, merge, or omit these based on local laws.
63
+ */
64
+ declare const PII_PRESETS: {
65
+ GLOBAL_STRICT: PiiRuleDefinition[];
66
+ US_COMPLIANT: PiiRuleDefinition[];
67
+ EU_GDPR: PiiRuleDefinition[];
68
+ };
69
+ declare class PiiScanner {
70
+ private patterns;
71
+ private forbiddenKeysSet;
72
+ private nerScanner;
73
+ /**
74
+ * Safelist of keys that contain forbidden substrings but are NOT PII.
75
+ * Prevents false positives from fuzzy matching (e.g., "grid" contains "id").
76
+ */
77
+ private static readonly KEY_SAFELIST;
78
+ /**
79
+ * Short forbidden tokens (< 4 chars) that require boundary-aware matching.
80
+ * Uses regex boundary detection to avoid false positives.
81
+ */
82
+ private shortTokenBoundaryPatterns;
83
+ /**
84
+ * Long forbidden tokens (>= 4 chars) that use substring containment.
85
+ */
86
+ private longForbiddenTokens;
87
+ constructor(patterns?: PiiRule[], forbiddenKeys?: string[], nerScanner?: NerScanner | null);
88
+ /**
89
+ * Scans any input (string, object, array) for PII violations.
90
+ * Returns the pattern/rule name that triggered the violation, or null if safe.
91
+ *
92
+ * Detection pipeline (fail-fast):
93
+ * 1. Exact key match (O(1) Set lookup)
94
+ * 2. Fuzzy key match (boundary detection for short tokens, substring for long)
95
+ * 3. Regex/algorithmic pattern match on string values
96
+ * 4. NER content scan on string values (if enabled)
97
+ */
98
+ scan(input: unknown, seen?: WeakSet<object>): Promise<string | null>;
99
+ /**
100
+ * Checks a key against fuzzy matching rules.
101
+ * Short tokens use boundary-aware regex; long tokens use substring containment.
102
+ */
103
+ private checkKeyFuzzy;
104
+ private checkString;
105
+ }
106
+
107
+ type ToolHandler<T extends z.ZodRawShape = z.ZodRawShape> = (args: z.infer<z.ZodObject<T>>, extra: {
7
108
  signal?: AbortSignal;
8
109
  }) => Promise<CallToolResult>;
9
- export interface LiopServerOptions {
110
+ interface LiopServerOptions {
10
111
  capabilities?: Record<string, unknown>;
11
112
  workerPool?: {
12
113
  enabled?: boolean;
13
114
  minThreads?: number;
14
115
  maxThreads?: number;
15
116
  idleTimeout?: number;
117
+ /** Max heap memory per worker in MB (default: 64). Prevents heap bomb DoS. */
118
+ maxHeapMb?: number;
16
119
  };
17
120
  security?: {
18
121
  piiPatterns?: PiiRule[];
19
122
  forbiddenKeys?: string[];
123
+ /** Enable NLP-based Named Entity Recognition scanning on output values. */
124
+ enableNerScanning?: boolean;
125
+ /** Rate limiting configuration for tool calls (OWASP A01). */
126
+ rateLimit?: {
127
+ /** Maximum calls per window per tool (default: 15). */
128
+ maxPerWindow?: number;
129
+ /** Maximum calls per window across ALL tools combined (default: 40). */
130
+ globalMaxPerWindow?: number;
131
+ /** Sliding window duration in milliseconds (default: 60000 = 1 min). */
132
+ windowMs?: number;
133
+ };
20
134
  };
21
135
  taxonomy?: {
22
136
  domain?: string;
@@ -24,13 +138,13 @@ export interface LiopServerOptions {
24
138
  executionTypes?: string[];
25
139
  };
26
140
  }
27
- export interface AggregationPolicy {
141
+ interface AggregationPolicy {
28
142
  /** Maximum number of object-type array elements allowed (default: 10) */
29
143
  maxOutputRows?: number;
30
144
  /** Allow arrays containing only primitive values (default: true) */
31
145
  allowPrimitiveArrays?: boolean;
32
146
  }
33
- export interface LogicExecutionPolicy {
147
+ interface LogicExecutionPolicy {
34
148
  /**
35
149
  * Validate the business payload returned by sandbox logic (post-execution).
36
150
  * This runs before final egress checks and blocks non-conforming outputs.
@@ -45,7 +159,7 @@ export interface LogicExecutionPolicy {
45
159
  */
46
160
  preflightDenyPatterns?: RegExp[];
47
161
  }
48
- export declare class LiopServer {
162
+ declare class LiopServer {
49
163
  private serverInfo;
50
164
  private config?;
51
165
  private logicCache;
@@ -53,6 +167,12 @@ export declare class LiopServer {
53
167
  private readonly CACHE_TTL_MS;
54
168
  private readonly THROTTLE_THRESHOLD;
55
169
  private readonly THROTTLE_COOLDOWN_MS;
170
+ private toolCallWindows;
171
+ private readonly toolCallMaxPerWindow;
172
+ private readonly toolCallWindowMs;
173
+ private globalCallWindow;
174
+ private readonly globalCallMaxPerWindow;
175
+ private readonly taintAnalyzer;
56
176
  private tools;
57
177
  private resources;
58
178
  private prompts;
@@ -128,6 +248,19 @@ export declare class LiopServer {
128
248
  * Manually invalidates the AST Logic Cache (e.g. for Zero-Day patches).
129
249
  */
130
250
  clearAstCache(): void;
251
+ /**
252
+ * Sliding window rate limiter for tool call frequency.
253
+ * Prevents micro-query exfiltration attacks where an attacker
254
+ * makes hundreds of individually-legitimate calls to reconstruct
255
+ * the full dataset field by field. (OWASP A01)
256
+ */
257
+ private checkToolCallRateLimit;
258
+ /**
259
+ * Global cross-tool rate limiter.
260
+ * Prevents attackers from distributing micro-queries across multiple tools
261
+ * to evade per-tool rate limits. (OWASP A01)
262
+ */
263
+ private checkGlobalRateLimit;
131
264
  /**
132
265
  * Emulates calling a tool (used locally or via LIOPMcpBridge)
133
266
  */
@@ -187,3 +320,5 @@ export declare class LiopServer {
187
320
  */
188
321
  close(): Promise<void>;
189
322
  }
323
+
324
+ export { type AggregationPolicy, LiopServer, type LiopServerOptions, type LogicExecutionPolicy, NerScanner, PII_PATTERNS, PII_PRESETS, type PiiRule, PiiScanner, type ToolHandler };
package/dist/server.js ADDED
@@ -0,0 +1,2 @@
1
+ export{f as LiopServer,b as NerScanner,c as PII_PATTERNS,d as PII_PRESETS,e as PiiScanner}from'./chunk-X6FJATUE.js';import'./chunk-HM77MWB6.js';import'./chunk-PPCOS2NU.js';import'./chunk-S6RJHZV2.js';//# sourceMappingURL=server.js.map
2
+ //# sourceMappingURL=server.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":[],"names":[],"mappings":"","file":"server.js"}
package/dist/types.d.ts CHANGED
@@ -1,8 +1,9 @@
1
- import { z } from "zod";
1
+ import { z } from 'zod';
2
+
2
3
  /**
3
4
  * Base Protocol Types representing parity with Model Context Protocol
4
5
  */
5
- export declare const ToolSchema: z.ZodObject<{
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
- export type Tool = z.infer<typeof ToolSchema>;
19
- export declare const ResourceSchema: z.ZodObject<{
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
- export type Resource = z.infer<typeof ResourceSchema>;
36
- export declare const PromptSchema: z.ZodObject<{
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
- export type Prompt = z.infer<typeof PromptSchema>;
70
- export interface CallToolRequest {
70
+ type Prompt = z.infer<typeof PromptSchema>;
71
+ interface CallToolRequest {
71
72
  name: string;
72
73
  arguments?: Record<string, unknown>;
73
74
  }
74
- export interface CallToolResult {
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
- export interface GetPromptRequest {
89
+ interface GetPromptRequest {
89
90
  name: string;
90
91
  arguments?: Record<string, string>;
91
92
  }
92
- export interface GetPromptResult {
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
- export interface ServerInfo {
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
- export interface McpRequest {
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
- export interface McpResponse {
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
- import { z } from "zod";
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
- export declare class LiopVerifier {
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,2 @@
1
+ export{a as LiopVerifier}from'./chunk-UVTEJYHN.js';import'./chunk-ANFXJGMP.js';import'./chunk-S6RJHZV2.js';//# sourceMappingURL=verifier-RQRYXA4C.js.map
2
+ //# sourceMappingURL=verifier-RQRYXA4C.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":[],"names":[],"mappings":"","file":"verifier-RQRYXA4C.js"}
@@ -1,4 +1,4 @@
1
- export interface WorkerData {
1
+ interface WorkerData {
2
2
  ciphertext: Uint8Array;
3
3
  secretKeyObj: ArrayLike<number>;
4
4
  kyberPublicKey: Uint8Array;
@@ -9,9 +9,11 @@ export interface WorkerData {
9
9
  isEncrypted?: boolean;
10
10
  aesNonce?: Uint8Array;
11
11
  }
12
- export default function processLogicExecution(data: WorkerData): Promise<{
12
+ declare function processLogicExecution(data: WorkerData): Promise<{
13
13
  image_id: string;
14
14
  output: unknown;
15
15
  fuel_consumed: number;
16
16
  zk_receipt?: string;
17
17
  }>;
18
+
19
+ export { type WorkerData, processLogicExecution as default };
@@ -1,123 +1,2 @@
1
- import { Buffer } from "node:buffer";
2
- import crypto from "node:crypto";
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 c from'crypto';import {createMlKem768}from'mlkem';async function I(B){let{ciphertext:D,secretKeyObj:v,wasmBinary:n,inputs:_,aesNonce:N,records:O,isEncrypted:T=true}=B,e,w={},x=Buffer.alloc(32);if(T){let r=new Uint8Array(v),o=new Uint8Array(D),a=(await createMlKem768()).decap(o,r),s=Buffer.from(a);x=s;let i=Buffer.from(n),h=i.subarray(-16),p=i.subarray(0,-16),m=c.createDecipheriv("aes-256-gcm",s,Buffer.from(N||new Uint8Array(12)));m.setAuthTag(h);let y=m.update(p);y=Buffer.concat([y,m.final()]),e=y;for(let[j,z]of Object.entries(_||{})){let l=Buffer.from(z),K=l.subarray(0,12),L=l.subarray(-16),W=l.subarray(12,-16),d=c.createDecipheriv("aes-256-gcm",s,K);d.setAuthTag(L);let g=d.update(W);g=Buffer.concat([g,d.final()]),w[j]=JSON.parse(g.toString("utf-8"));}}else n[0]===0&&n[1]===97&&n[2]===115&&n[3]===109?e=Buffer.from(n):e=Buffer.from(n).toString("utf-8");let b$2=e[0]===0&&e[1]===97&&e[2]===115&&e[3]===109;if(e instanceof Buffer&&b$2){let r=new Uint8Array(e),o=await WebAssembly.compile(r);a.analyze(o);}else e instanceof Buffer&&!b$2&&(e=e.toString("utf-8"));typeof e=="string"&&(e=a$1(e));let u=new b;await u.init();try{let r=await u.execute(e,O,w),o;typeof e=="string"?o=Buffer.from(e,"utf-8"):o=new Uint8Array(e);let f=b$1(o).toString("hex"),a=Buffer.from(JSON.stringify({image_id:f,output_hash:c.createHash("sha256").update(typeof r.output=="string"?r.output:JSON.stringify(r.output)).digest("hex"),fuel:r.fuelConsumed,ts:Date.now()})),s=c.createHmac("sha256",x).update(a).digest(),i=Buffer.alloc(2);i.writeUInt16BE(a.length);let p=Buffer.concat([Buffer.from([1]),i,a,s]).toString("base64");return {image_id:f,zk_receipt:p,output:r.output,fuel_consumed:r.fuelConsumed}}finally{await u.teardown();}}export{I as default};//# sourceMappingURL=logic-execution.js.map
2
+ //# sourceMappingURL=logic-execution.js.map
@@ -0,0 +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,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ACd,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"]}
@@ -2,7 +2,7 @@
2
2
  * ZK Verification Payload Structure.
3
3
  * Modeled after RISC Zero & SP1 Receipt formats.
4
4
  */
5
- export interface ZkVerificationPayload {
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
- export default function workerHandler(task: ZkVerificationPayload): Promise<{
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 "node:crypto";
2
- import { parentPort } from "node:worker_threads";
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