@enclave-vm/core 0.0.1

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 (169) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +732 -0
  3. package/SECURITY-AUDIT.md +916 -0
  4. package/package.json +59 -0
  5. package/src/adapters/vm-adapter.d.ts +32 -0
  6. package/src/adapters/vm-adapter.js +1140 -0
  7. package/src/adapters/vm-adapter.js.map +1 -0
  8. package/src/adapters/worker-pool/config.d.ts +149 -0
  9. package/src/adapters/worker-pool/config.js +129 -0
  10. package/src/adapters/worker-pool/config.js.map +1 -0
  11. package/src/adapters/worker-pool/errors.d.ts +109 -0
  12. package/src/adapters/worker-pool/errors.js +181 -0
  13. package/src/adapters/worker-pool/errors.js.map +1 -0
  14. package/src/adapters/worker-pool/execution-queue.d.ts +85 -0
  15. package/src/adapters/worker-pool/execution-queue.js +179 -0
  16. package/src/adapters/worker-pool/execution-queue.js.map +1 -0
  17. package/src/adapters/worker-pool/index.d.ts +48 -0
  18. package/src/adapters/worker-pool/index.js +73 -0
  19. package/src/adapters/worker-pool/index.js.map +1 -0
  20. package/src/adapters/worker-pool/memory-monitor.d.ts +106 -0
  21. package/src/adapters/worker-pool/memory-monitor.js +184 -0
  22. package/src/adapters/worker-pool/memory-monitor.js.map +1 -0
  23. package/src/adapters/worker-pool/protocol.d.ts +314 -0
  24. package/src/adapters/worker-pool/protocol.js +143 -0
  25. package/src/adapters/worker-pool/protocol.js.map +1 -0
  26. package/src/adapters/worker-pool/rate-limiter.d.ts +60 -0
  27. package/src/adapters/worker-pool/rate-limiter.js +101 -0
  28. package/src/adapters/worker-pool/rate-limiter.js.map +1 -0
  29. package/src/adapters/worker-pool/safe-deserialize.d.ts +50 -0
  30. package/src/adapters/worker-pool/safe-deserialize.js +141 -0
  31. package/src/adapters/worker-pool/safe-deserialize.js.map +1 -0
  32. package/src/adapters/worker-pool/worker-pool-adapter.d.ts +84 -0
  33. package/src/adapters/worker-pool/worker-pool-adapter.js +506 -0
  34. package/src/adapters/worker-pool/worker-pool-adapter.js.map +1 -0
  35. package/src/adapters/worker-pool/worker-script.d.ts +12 -0
  36. package/src/adapters/worker-pool/worker-script.js +770 -0
  37. package/src/adapters/worker-pool/worker-script.js.map +1 -0
  38. package/src/adapters/worker-pool/worker-slot.d.ts +116 -0
  39. package/src/adapters/worker-pool/worker-slot.js +301 -0
  40. package/src/adapters/worker-pool/worker-slot.js.map +1 -0
  41. package/src/babel/babel-wrapper.d.ts +118 -0
  42. package/src/babel/babel-wrapper.js +395 -0
  43. package/src/babel/babel-wrapper.js.map +1 -0
  44. package/src/babel/index.d.ts +9 -0
  45. package/src/babel/index.js +17 -0
  46. package/src/babel/index.js.map +1 -0
  47. package/src/babel/multi-file-transform.d.ts +122 -0
  48. package/src/babel/multi-file-transform.js +344 -0
  49. package/src/babel/multi-file-transform.js.map +1 -0
  50. package/src/double-vm/double-vm-wrapper.d.ts +65 -0
  51. package/src/double-vm/double-vm-wrapper.js +523 -0
  52. package/src/double-vm/double-vm-wrapper.js.map +1 -0
  53. package/src/double-vm/index.d.ts +31 -0
  54. package/src/double-vm/index.js +34 -0
  55. package/src/double-vm/index.js.map +1 -0
  56. package/src/double-vm/parent-vm-bootstrap.d.ts +63 -0
  57. package/src/double-vm/parent-vm-bootstrap.js +1695 -0
  58. package/src/double-vm/parent-vm-bootstrap.js.map +1 -0
  59. package/src/double-vm/suspicious-patterns.d.ts +57 -0
  60. package/src/double-vm/suspicious-patterns.js +304 -0
  61. package/src/double-vm/suspicious-patterns.js.map +1 -0
  62. package/src/double-vm/types.d.ts +178 -0
  63. package/src/double-vm/types.js +11 -0
  64. package/src/double-vm/types.js.map +1 -0
  65. package/src/double-vm/wrap-adapter.d.ts +36 -0
  66. package/src/double-vm/wrap-adapter.js +59 -0
  67. package/src/double-vm/wrap-adapter.js.map +1 -0
  68. package/src/enclave.d.ts +159 -0
  69. package/src/enclave.js +671 -0
  70. package/src/enclave.js.map +1 -0
  71. package/src/globals-validator.d.ts +80 -0
  72. package/src/globals-validator.js +206 -0
  73. package/src/globals-validator.js.map +1 -0
  74. package/src/index.d.ts +29 -0
  75. package/src/index.js +130 -0
  76. package/src/index.js.map +1 -0
  77. package/src/memory-proxy.d.ts +69 -0
  78. package/src/memory-proxy.js +310 -0
  79. package/src/memory-proxy.js.map +1 -0
  80. package/src/memory-tracker.d.ts +170 -0
  81. package/src/memory-tracker.js +230 -0
  82. package/src/memory-tracker.js.map +1 -0
  83. package/src/safe-error.d.ts +18 -0
  84. package/src/safe-error.js +76 -0
  85. package/src/safe-error.js.map +1 -0
  86. package/src/safe-runtime.d.ts +72 -0
  87. package/src/safe-runtime.js +656 -0
  88. package/src/safe-runtime.js.map +1 -0
  89. package/src/scoring/cache.d.ts +68 -0
  90. package/src/scoring/cache.js +158 -0
  91. package/src/scoring/cache.js.map +1 -0
  92. package/src/scoring/feature-extractor.d.ts +61 -0
  93. package/src/scoring/feature-extractor.js +366 -0
  94. package/src/scoring/feature-extractor.js.map +1 -0
  95. package/src/scoring/index.d.ts +33 -0
  96. package/src/scoring/index.js +53 -0
  97. package/src/scoring/index.js.map +1 -0
  98. package/src/scoring/scorer.interface.d.ts +65 -0
  99. package/src/scoring/scorer.interface.js +49 -0
  100. package/src/scoring/scorer.interface.js.map +1 -0
  101. package/src/scoring/scorers/disabled.scorer.d.ts +19 -0
  102. package/src/scoring/scorers/disabled.scorer.js +34 -0
  103. package/src/scoring/scorers/disabled.scorer.js.map +1 -0
  104. package/src/scoring/scorers/external-api.scorer.d.ts +29 -0
  105. package/src/scoring/scorers/external-api.scorer.js +141 -0
  106. package/src/scoring/scorers/external-api.scorer.js.map +1 -0
  107. package/src/scoring/scorers/index.d.ts +10 -0
  108. package/src/scoring/scorers/index.js +22 -0
  109. package/src/scoring/scorers/index.js.map +1 -0
  110. package/src/scoring/scorers/local-llm.scorer.d.ts +116 -0
  111. package/src/scoring/scorers/local-llm.scorer.js +474 -0
  112. package/src/scoring/scorers/local-llm.scorer.js.map +1 -0
  113. package/src/scoring/scorers/progressive.scorer.d.ts +77 -0
  114. package/src/scoring/scorers/progressive.scorer.js +199 -0
  115. package/src/scoring/scorers/progressive.scorer.js.map +1 -0
  116. package/src/scoring/scorers/rule-based.scorer.d.ts +66 -0
  117. package/src/scoring/scorers/rule-based.scorer.js +316 -0
  118. package/src/scoring/scorers/rule-based.scorer.js.map +1 -0
  119. package/src/scoring/scoring-gate.d.ts +76 -0
  120. package/src/scoring/scoring-gate.js +246 -0
  121. package/src/scoring/scoring-gate.js.map +1 -0
  122. package/src/scoring/types.d.ts +690 -0
  123. package/src/scoring/types.js +107 -0
  124. package/src/scoring/types.js.map +1 -0
  125. package/src/secure-proxy.d.ts +157 -0
  126. package/src/secure-proxy.js +609 -0
  127. package/src/secure-proxy.js.map +1 -0
  128. package/src/session/channels/embedded-channel.d.ts +76 -0
  129. package/src/session/channels/embedded-channel.js +130 -0
  130. package/src/session/channels/embedded-channel.js.map +1 -0
  131. package/src/session/channels/index.d.ts +9 -0
  132. package/src/session/channels/index.js +14 -0
  133. package/src/session/channels/index.js.map +1 -0
  134. package/src/session/index.d.ts +15 -0
  135. package/src/session/index.js +27 -0
  136. package/src/session/index.js.map +1 -0
  137. package/src/session/session-emitter.d.ts +119 -0
  138. package/src/session/session-emitter.js +253 -0
  139. package/src/session/session-emitter.js.map +1 -0
  140. package/src/session/session-state-machine.d.ts +108 -0
  141. package/src/session/session-state-machine.js +182 -0
  142. package/src/session/session-state-machine.js.map +1 -0
  143. package/src/session/session.d.ts +135 -0
  144. package/src/session/session.js +398 -0
  145. package/src/session/session.js.map +1 -0
  146. package/src/session-types.d.ts +313 -0
  147. package/src/session-types.js +39 -0
  148. package/src/session-types.js.map +1 -0
  149. package/src/sidecar/index.d.ts +12 -0
  150. package/src/sidecar/index.js +31 -0
  151. package/src/sidecar/index.js.map +1 -0
  152. package/src/sidecar/reference-config.d.ts +81 -0
  153. package/src/sidecar/reference-config.js +118 -0
  154. package/src/sidecar/reference-config.js.map +1 -0
  155. package/src/sidecar/reference-resolver.d.ts +115 -0
  156. package/src/sidecar/reference-resolver.js +262 -0
  157. package/src/sidecar/reference-resolver.js.map +1 -0
  158. package/src/sidecar/reference-sidecar.d.ts +161 -0
  159. package/src/sidecar/reference-sidecar.js +226 -0
  160. package/src/sidecar/reference-sidecar.js.map +1 -0
  161. package/src/tool-bridge.d.ts +4 -0
  162. package/src/tool-bridge.js +306 -0
  163. package/src/tool-bridge.js.map +1 -0
  164. package/src/types.d.ts +775 -0
  165. package/src/types.js +187 -0
  166. package/src/types.js.map +1 -0
  167. package/src/value-sanitizer.d.ts +133 -0
  168. package/src/value-sanitizer.js +421 -0
  169. package/src/value-sanitizer.js.map +1 -0
@@ -0,0 +1,143 @@
1
+ "use strict";
2
+ /**
3
+ * Worker Pool Message Protocol
4
+ *
5
+ * Type definitions for messages exchanged between main thread and worker threads.
6
+ * All messages are JSON-serialized to prevent structured clone attacks.
7
+ *
8
+ * @packageDocumentation
9
+ */
10
+ Object.defineProperty(exports, "__esModule", { value: true });
11
+ exports.workerToMainMessageSchema = exports.workerReadyMessageSchema = exports.consoleMessageSchema = exports.memoryReportResultMessageSchema = exports.executionResultMessageSchema = exports.toolCallMessageSchema = void 0;
12
+ exports.isToolCallMessage = isToolCallMessage;
13
+ exports.isExecutionResultMessage = isExecutionResultMessage;
14
+ exports.isMemoryReportResultMessage = isMemoryReportResultMessage;
15
+ exports.isConsoleMessage = isConsoleMessage;
16
+ exports.isWorkerReadyMessage = isWorkerReadyMessage;
17
+ const zod_1 = require("zod");
18
+ // ============================================================================
19
+ // Message Validation Schemas
20
+ // ============================================================================
21
+ /**
22
+ * Tool name regex pattern
23
+ * Allows: letters, numbers, colons, underscores, hyphens
24
+ * Must start with a letter
25
+ */
26
+ const TOOL_NAME_PATTERN = /^[a-zA-Z][a-zA-Z0-9:_-]*$/;
27
+ /**
28
+ * UUID-like pattern for request/call IDs
29
+ */
30
+ const ID_PATTERN = /^[a-zA-Z0-9-]+$/;
31
+ /**
32
+ * Zod schema for tool call messages
33
+ */
34
+ exports.toolCallMessageSchema = zod_1.z
35
+ .object({
36
+ type: zod_1.z.literal('tool-call'),
37
+ requestId: zod_1.z.string().min(1).max(100).regex(ID_PATTERN),
38
+ callId: zod_1.z.string().min(1).max(100).regex(ID_PATTERN),
39
+ toolName: zod_1.z.string().min(1).max(256).regex(TOOL_NAME_PATTERN),
40
+ args: zod_1.z.record(zod_1.z.string(), zod_1.z.unknown()),
41
+ })
42
+ .strict();
43
+ /**
44
+ * Zod schema for execution result messages
45
+ */
46
+ exports.executionResultMessageSchema = zod_1.z
47
+ .object({
48
+ type: zod_1.z.literal('result'),
49
+ requestId: zod_1.z.string().min(1).max(100).regex(ID_PATTERN),
50
+ success: zod_1.z.boolean(),
51
+ value: zod_1.z.unknown().optional(),
52
+ error: zod_1.z
53
+ .object({
54
+ name: zod_1.z.string().max(100),
55
+ message: zod_1.z.string().max(10000),
56
+ code: zod_1.z.string().max(100).optional(),
57
+ stack: zod_1.z.string().max(10000).optional(),
58
+ })
59
+ .optional(),
60
+ stats: zod_1.z.object({
61
+ duration: zod_1.z.number().nonnegative(),
62
+ toolCallCount: zod_1.z.number().nonnegative().int(),
63
+ iterationCount: zod_1.z.number().nonnegative().int(),
64
+ startTime: zod_1.z.number().nonnegative(),
65
+ endTime: zod_1.z.number().nonnegative(),
66
+ }),
67
+ })
68
+ .strict();
69
+ /**
70
+ * Zod schema for memory report result messages
71
+ */
72
+ exports.memoryReportResultMessageSchema = zod_1.z
73
+ .object({
74
+ type: zod_1.z.literal('memory-report-result'),
75
+ usage: zod_1.z.object({
76
+ rss: zod_1.z.number().nonnegative(),
77
+ heapTotal: zod_1.z.number().nonnegative(),
78
+ heapUsed: zod_1.z.number().nonnegative(),
79
+ external: zod_1.z.number().nonnegative(),
80
+ arrayBuffers: zod_1.z.number().nonnegative(),
81
+ }),
82
+ })
83
+ .strict();
84
+ /**
85
+ * Zod schema for console messages
86
+ */
87
+ exports.consoleMessageSchema = zod_1.z
88
+ .object({
89
+ type: zod_1.z.literal('console'),
90
+ requestId: zod_1.z.string().min(1).max(100).regex(ID_PATTERN),
91
+ level: zod_1.z.enum(['log', 'warn', 'error', 'info']),
92
+ args: zod_1.z.array(zod_1.z.unknown()).max(100),
93
+ })
94
+ .strict();
95
+ /**
96
+ * Zod schema for worker ready messages
97
+ */
98
+ exports.workerReadyMessageSchema = zod_1.z
99
+ .object({
100
+ type: zod_1.z.literal('ready'),
101
+ })
102
+ .strict();
103
+ /**
104
+ * Union schema for all worker-to-main messages
105
+ */
106
+ exports.workerToMainMessageSchema = zod_1.z.discriminatedUnion('type', [
107
+ exports.workerReadyMessageSchema,
108
+ exports.toolCallMessageSchema,
109
+ exports.executionResultMessageSchema,
110
+ exports.memoryReportResultMessageSchema,
111
+ exports.consoleMessageSchema,
112
+ ]);
113
+ /**
114
+ * Type guard for tool call messages
115
+ */
116
+ function isToolCallMessage(msg) {
117
+ return msg.type === 'tool-call';
118
+ }
119
+ /**
120
+ * Type guard for execution result messages
121
+ */
122
+ function isExecutionResultMessage(msg) {
123
+ return msg.type === 'result';
124
+ }
125
+ /**
126
+ * Type guard for memory report result messages
127
+ */
128
+ function isMemoryReportResultMessage(msg) {
129
+ return msg.type === 'memory-report-result';
130
+ }
131
+ /**
132
+ * Type guard for console messages
133
+ */
134
+ function isConsoleMessage(msg) {
135
+ return msg.type === 'console';
136
+ }
137
+ /**
138
+ * Type guard for worker ready messages
139
+ */
140
+ function isWorkerReadyMessage(msg) {
141
+ return msg.type === 'ready';
142
+ }
143
+ //# sourceMappingURL=protocol.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"protocol.js","sourceRoot":"","sources":["../../../../src/adapters/worker-pool/protocol.ts"],"names":[],"mappings":";AAAA;;;;;;;GAOG;;;AA2TH,8CAEC;AAKD,4DAEC;AAKD,kEAEC;AAKD,4CAEC;AAKD,oDAEC;AAvVD,6BAAwB;AA8MxB,+EAA+E;AA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AI,KAAK,SAAS,CAAC;AAChC,CAAC;AAED;;GAEG;AACH,SAAgB,oBAAoB,CAAC,GAAwB;IAC3D,OAAO,GAAG,CAAC,IAAI,KAAK,OAAO,CAAC;AAC9B,CAAC","sourcesContent":["/**\n * Worker Pool Message Protocol\n *\n * Type definitions for messages exchanged between main thread and worker threads.\n * All messages are JSON-serialized to prevent structured clone attacks.\n *\n * @packageDocumentation\n */\n\nimport { z } from 'zod';\nimport type { ResourceUsage } from './config';\n\n/**\n * Serialized error format for cross-thread communication\n * Errors are serialized to prevent prototype pollution\n */\nexport interface SerializedError {\n /** Error name/type */\n name: string;\n /** Error message */\n message: string;\n /** Error code if available */\n code?: string;\n /** Sanitized stack trace (only if sanitizeStackTraces is false) */\n stack?: string;\n}\n\n/**\n * Execution statistics from the worker\n */\nexport interface WorkerExecutionStats {\n /** Total execution duration in milliseconds */\n duration: number;\n /** Number of tool calls made */\n toolCallCount: number;\n /** Number of loop iterations */\n iterationCount: number;\n /** Start timestamp */\n startTime: number;\n /** End timestamp */\n endTime: number;\n}\n\n/**\n * Serializable configuration sent to worker\n * Excludes non-serializable fields like functions\n */\nexport interface SerializedConfig {\n /** Execution timeout in milliseconds */\n timeout: number;\n /** Maximum loop iterations */\n maxIterations: number;\n /** Maximum tool calls */\n maxToolCalls: number;\n /** Maximum console output in bytes */\n maxConsoleOutputBytes: number;\n /** Maximum console calls */\n maxConsoleCalls: number;\n /** Whether to sanitize stack traces */\n sanitizeStackTraces: boolean;\n /** Maximum sanitization depth */\n maxSanitizeDepth: number;\n /** Maximum properties per object in sanitized values */\n maxSanitizeProperties: number;\n /** Custom globals (serializable values only) */\n globals?: Record<string, unknown>;\n /**\n * Security level - determines which globals are available in sandbox\n * Used for defense-in-depth with AST guard\n */\n securityLevel: 'STRICT' | 'SECURE' | 'STANDARD' | 'PERMISSIVE';\n}\n\n// ============================================================================\n// Main Thread → Worker Messages\n// ============================================================================\n\n/**\n * Execute code in the worker\n */\nexport interface ExecuteMessage {\n type: 'execute';\n /** Unique request identifier */\n requestId: string;\n /** Code to execute (already transformed) */\n code: string;\n /** Serialized execution config */\n config: SerializedConfig;\n}\n\n/**\n * Response to a tool call from the worker\n */\nexport interface ToolResponseMessage {\n type: 'tool-response';\n /** Original request identifier */\n requestId: string;\n /** Tool call identifier */\n callId: string;\n /** Tool result (if successful) */\n result?: unknown;\n /** Error (if failed) */\n error?: SerializedError;\n}\n\n/**\n * Request memory usage report from worker\n */\nexport interface MemoryReportRequestMessage {\n type: 'memory-report';\n}\n\n/**\n * Abort a running execution\n */\nexport interface AbortMessage {\n type: 'abort';\n /** Request to abort */\n requestId: string;\n}\n\n/**\n * Terminate the worker\n */\nexport interface TerminateMessage {\n type: 'terminate';\n /** Whether to wait for current execution to finish */\n graceful: boolean;\n}\n\n/**\n * Union of all messages from main thread to worker\n */\nexport type MainToWorkerMessage =\n | ExecuteMessage\n | ToolResponseMessage\n | MemoryReportRequestMessage\n | AbortMessage\n | TerminateMessage;\n\n// ============================================================================\n// Worker → Main Thread Messages\n// ============================================================================\n\n/**\n * Worker is ready to receive executions\n */\nexport interface WorkerReadyMessage {\n type: 'ready';\n}\n\n/**\n * Tool call request from worker\n */\nexport interface ToolCallMessage {\n type: 'tool-call';\n /** Execution request identifier */\n requestId: string;\n /** Unique identifier for this tool call */\n callId: string;\n /** Name of the tool to call */\n toolName: string;\n /** Arguments for the tool (must be object to match Zod schema) */\n args: Record<string, unknown>;\n}\n\n/**\n * Execution result from worker\n */\nexport interface ExecutionResultMessage {\n type: 'result';\n /** Request identifier */\n requestId: string;\n /** Whether execution succeeded */\n success: boolean;\n /** Return value (if successful) */\n value?: unknown;\n /** Error (if failed) */\n error?: SerializedError;\n /** Execution statistics */\n stats: WorkerExecutionStats;\n}\n\n/**\n * Memory usage report from worker\n */\nexport interface MemoryReportResultMessage {\n type: 'memory-report-result';\n /** Memory usage statistics */\n usage: ResourceUsage;\n}\n\n/**\n * Console output from worker\n */\nexport interface ConsoleMessage {\n type: 'console';\n /** Execution request identifier */\n requestId: string;\n /** Console level */\n level: 'log' | 'warn' | 'error' | 'info';\n /** Console arguments */\n args: unknown[];\n}\n\n/**\n * Union of all messages from worker to main thread\n */\nexport type WorkerToMainMessage =\n | WorkerReadyMessage\n | ToolCallMessage\n | ExecutionResultMessage\n | MemoryReportResultMessage\n | ConsoleMessage;\n\n// ============================================================================\n// Message Validation Schemas\n// ============================================================================\n\n/**\n * Tool name regex pattern\n * Allows: letters, numbers, colons, underscores, hyphens\n * Must start with a letter\n */\nconst TOOL_NAME_PATTERN = /^[a-zA-Z][a-zA-Z0-9:_-]*$/;\n\n/**\n * UUID-like pattern for request/call IDs\n */\nconst ID_PATTERN = /^[a-zA-Z0-9-]+$/;\n\n/**\n * Zod schema for tool call messages\n */\nexport const toolCallMessageSchema = z\n .object({\n type: z.literal('tool-call'),\n requestId: z.string().min(1).max(100).regex(ID_PATTERN),\n callId: z.string().min(1).max(100).regex(ID_PATTERN),\n toolName: z.string().min(1).max(256).regex(TOOL_NAME_PATTERN),\n args: z.record(z.string(), z.unknown()),\n })\n .strict();\n\n/**\n * Zod schema for execution result messages\n */\nexport const executionResultMessageSchema = z\n .object({\n type: z.literal('result'),\n requestId: z.string().min(1).max(100).regex(ID_PATTERN),\n success: z.boolean(),\n value: z.unknown().optional(),\n error: z\n .object({\n name: z.string().max(100),\n message: z.string().max(10000),\n code: z.string().max(100).optional(),\n stack: z.string().max(10000).optional(),\n })\n .optional(),\n stats: z.object({\n duration: z.number().nonnegative(),\n toolCallCount: z.number().nonnegative().int(),\n iterationCount: z.number().nonnegative().int(),\n startTime: z.number().nonnegative(),\n endTime: z.number().nonnegative(),\n }),\n })\n .strict();\n\n/**\n * Zod schema for memory report result messages\n */\nexport const memoryReportResultMessageSchema = z\n .object({\n type: z.literal('memory-report-result'),\n usage: z.object({\n rss: z.number().nonnegative(),\n heapTotal: z.number().nonnegative(),\n heapUsed: z.number().nonnegative(),\n external: z.number().nonnegative(),\n arrayBuffers: z.number().nonnegative(),\n }),\n })\n .strict();\n\n/**\n * Zod schema for console messages\n */\nexport const consoleMessageSchema = z\n .object({\n type: z.literal('console'),\n requestId: z.string().min(1).max(100).regex(ID_PATTERN),\n level: z.enum(['log', 'warn', 'error', 'info']),\n args: z.array(z.unknown()).max(100),\n })\n .strict();\n\n/**\n * Zod schema for worker ready messages\n */\nexport const workerReadyMessageSchema = z\n .object({\n type: z.literal('ready'),\n })\n .strict();\n\n/**\n * Union schema for all worker-to-main messages\n */\nexport const workerToMainMessageSchema = z.discriminatedUnion('type', [\n workerReadyMessageSchema,\n toolCallMessageSchema,\n executionResultMessageSchema,\n memoryReportResultMessageSchema,\n consoleMessageSchema,\n]);\n\n/**\n * Type guard for tool call messages\n */\nexport function isToolCallMessage(msg: WorkerToMainMessage): msg is ToolCallMessage {\n return msg.type === 'tool-call';\n}\n\n/**\n * Type guard for execution result messages\n */\nexport function isExecutionResultMessage(msg: WorkerToMainMessage): msg is ExecutionResultMessage {\n return msg.type === 'result';\n}\n\n/**\n * Type guard for memory report result messages\n */\nexport function isMemoryReportResultMessage(msg: WorkerToMainMessage): msg is MemoryReportResultMessage {\n return msg.type === 'memory-report-result';\n}\n\n/**\n * Type guard for console messages\n */\nexport function isConsoleMessage(msg: WorkerToMainMessage): msg is ConsoleMessage {\n return msg.type === 'console';\n}\n\n/**\n * Type guard for worker ready messages\n */\nexport function isWorkerReadyMessage(msg: WorkerToMainMessage): msg is WorkerReadyMessage {\n return msg.type === 'ready';\n}\n"]}
@@ -0,0 +1,60 @@
1
+ /**
2
+ * Rate Limiter
3
+ *
4
+ * Prevents message flooding attacks from worker threads.
5
+ *
6
+ * @packageDocumentation
7
+ */
8
+ /**
9
+ * Rate limiter configuration
10
+ */
11
+ export interface RateLimiterConfig {
12
+ /** Maximum messages per window */
13
+ maxMessagesPerWindow: number;
14
+ /** Window duration in milliseconds */
15
+ windowMs: number;
16
+ }
17
+ /**
18
+ * Sliding window rate limiter
19
+ *
20
+ * Tracks message rates per slot ID and enforces limits.
21
+ */
22
+ export declare class RateLimiter {
23
+ private readonly windows;
24
+ private readonly config;
25
+ constructor(config: RateLimiterConfig);
26
+ /**
27
+ * Check if a message from a slot is allowed
28
+ *
29
+ * @param slotId - Worker slot identifier
30
+ * @throws MessageFloodError if rate limit exceeded
31
+ */
32
+ checkLimit(slotId: string): void;
33
+ /**
34
+ * Reset the rate limit for a slot
35
+ * Called when a worker is recycled
36
+ *
37
+ * @param slotId - Worker slot identifier
38
+ */
39
+ reset(slotId: string): void;
40
+ /**
41
+ * Clear all rate limit tracking
42
+ */
43
+ clear(): void;
44
+ /**
45
+ * Get current rate for a slot
46
+ *
47
+ * @param slotId - Worker slot identifier
48
+ * @returns Current message count in window, or 0 if no window
49
+ */
50
+ getCurrentRate(slotId: string): number;
51
+ /**
52
+ * Prune expired windows
53
+ * Should be called periodically to prevent memory leaks
54
+ */
55
+ prune(): number;
56
+ }
57
+ /**
58
+ * Create a rate limiter from worker pool config
59
+ */
60
+ export declare function createRateLimiter(maxMessagesPerSecond: number): RateLimiter;
@@ -0,0 +1,101 @@
1
+ "use strict";
2
+ /**
3
+ * Rate Limiter
4
+ *
5
+ * Prevents message flooding attacks from worker threads.
6
+ *
7
+ * @packageDocumentation
8
+ */
9
+ Object.defineProperty(exports, "__esModule", { value: true });
10
+ exports.RateLimiter = void 0;
11
+ exports.createRateLimiter = createRateLimiter;
12
+ const errors_1 = require("./errors");
13
+ /**
14
+ * Sliding window rate limiter
15
+ *
16
+ * Tracks message rates per slot ID and enforces limits.
17
+ */
18
+ class RateLimiter {
19
+ windows = new Map();
20
+ config;
21
+ constructor(config) {
22
+ this.config = config;
23
+ }
24
+ /**
25
+ * Check if a message from a slot is allowed
26
+ *
27
+ * @param slotId - Worker slot identifier
28
+ * @throws MessageFloodError if rate limit exceeded
29
+ */
30
+ checkLimit(slotId) {
31
+ const now = Date.now();
32
+ let window = this.windows.get(slotId);
33
+ // Create new window or reset if expired
34
+ if (!window || now - window.windowStart >= this.config.windowMs) {
35
+ window = { count: 0, windowStart: now };
36
+ this.windows.set(slotId, window);
37
+ }
38
+ // Increment and check
39
+ window.count++;
40
+ if (window.count > this.config.maxMessagesPerWindow) {
41
+ throw new errors_1.MessageFloodError(slotId);
42
+ }
43
+ }
44
+ /**
45
+ * Reset the rate limit for a slot
46
+ * Called when a worker is recycled
47
+ *
48
+ * @param slotId - Worker slot identifier
49
+ */
50
+ reset(slotId) {
51
+ this.windows.delete(slotId);
52
+ }
53
+ /**
54
+ * Clear all rate limit tracking
55
+ */
56
+ clear() {
57
+ this.windows.clear();
58
+ }
59
+ /**
60
+ * Get current rate for a slot
61
+ *
62
+ * @param slotId - Worker slot identifier
63
+ * @returns Current message count in window, or 0 if no window
64
+ */
65
+ getCurrentRate(slotId) {
66
+ const window = this.windows.get(slotId);
67
+ if (!window)
68
+ return 0;
69
+ const now = Date.now();
70
+ if (now - window.windowStart >= this.config.windowMs) {
71
+ return 0; // Window expired
72
+ }
73
+ return window.count;
74
+ }
75
+ /**
76
+ * Prune expired windows
77
+ * Should be called periodically to prevent memory leaks
78
+ */
79
+ prune() {
80
+ const now = Date.now();
81
+ let pruned = 0;
82
+ for (const [slotId, window] of this.windows) {
83
+ if (now - window.windowStart >= this.config.windowMs * 2) {
84
+ this.windows.delete(slotId);
85
+ pruned++;
86
+ }
87
+ }
88
+ return pruned;
89
+ }
90
+ }
91
+ exports.RateLimiter = RateLimiter;
92
+ /**
93
+ * Create a rate limiter from worker pool config
94
+ */
95
+ function createRateLimiter(maxMessagesPerSecond) {
96
+ return new RateLimiter({
97
+ maxMessagesPerWindow: maxMessagesPerSecond,
98
+ windowMs: 1000,
99
+ });
100
+ }
101
+ //# sourceMappingURL=rate-limiter.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"rate-limiter.js","sourceRoot":"","sources":["../../../../src/adapters/worker-pool/rate-limiter.ts"],"names":[],"mappings":";AAAA;;;;;;GAMG;;;AAqHH,8CAKC;AAxHD,qCAA6C;AAsB7C;;;;GAI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ACvB,IAAI,GAAG,GAAG,MAAM,CAAC,WAAW,IAAI,IAAI,CAAC,MAAM,CAAC,QAAQ,EAAE,CAAC;YACrD,OAAO,CAAC,CAAC,CAAC,iBAAiB;QAC7B,CAAC;QAED,OAAO,MAAM,CAAC,KAAK,CAAC;IACtB,CAAC;IAED;;;OAGG;IACH,KAAK;QACH,MAAM,GAAG,GAAG,IAAI,CAAC,GAAG,EAAE,CAAC;QACvB,IAAI,MAAM,GAAG,CAAC,CAAC;QAEf,KAAK,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,IAAI,IAAI,CAAC,OAAO,EAAE,CAAC;YAC5C,IAAI,GAAG,GAAG,MAAM,CAAC,WAAW,IAAI,IAAI,CAAC,MAAM,CAAC,QAAQ,GAAG,CAAC,EAAE,CAAC;gBACzD,IAAI,CAAC,OAAO,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC;gBAC5B,MAAM,EAAE,CAAC;YACX,CAAC;QACH,CAAC;QAED,OAAO,MAAM,CAAC;IAChB,CAAC;CACF;AAnFD,kCAmFC;AAED;;GAEG;AACH,SAAgB,iBAAiB,CAAC,oBAA4B;IAC5D,OAAO,IAAI,WAAW,CAAC;QACrB,oBAAoB,EAAE,oBAAoB;QAC1C,QAAQ,EAAE,IAAI;KACf,CAAC,CAAC;AACL,CAAC","sourcesContent":["/**\n * Rate Limiter\n *\n * Prevents message flooding attacks from worker threads.\n *\n * @packageDocumentation\n */\n\nimport { MessageFloodError } from './errors';\n\n/**\n * Rate limiter configuration\n */\nexport interface RateLimiterConfig {\n /** Maximum messages per window */\n maxMessagesPerWindow: number;\n /** Window duration in milliseconds */\n windowMs: number;\n}\n\n/**\n * Rate window tracking\n */\ninterface RateWindow {\n /** Message count in current window */\n count: number;\n /** Window start time */\n windowStart: number;\n}\n\n/**\n * Sliding window rate limiter\n *\n * Tracks message rates per slot ID and enforces limits.\n */\nexport class RateLimiter {\n private readonly windows = new Map<string, RateWindow>();\n private readonly config: RateLimiterConfig;\n\n constructor(config: RateLimiterConfig) {\n this.config = config;\n }\n\n /**\n * Check if a message from a slot is allowed\n *\n * @param slotId - Worker slot identifier\n * @throws MessageFloodError if rate limit exceeded\n */\n checkLimit(slotId: string): void {\n const now = Date.now();\n let window = this.windows.get(slotId);\n\n // Create new window or reset if expired\n if (!window || now - window.windowStart >= this.config.windowMs) {\n window = { count: 0, windowStart: now };\n this.windows.set(slotId, window);\n }\n\n // Increment and check\n window.count++;\n if (window.count > this.config.maxMessagesPerWindow) {\n throw new MessageFloodError(slotId);\n }\n }\n\n /**\n * Reset the rate limit for a slot\n * Called when a worker is recycled\n *\n * @param slotId - Worker slot identifier\n */\n reset(slotId: string): void {\n this.windows.delete(slotId);\n }\n\n /**\n * Clear all rate limit tracking\n */\n clear(): void {\n this.windows.clear();\n }\n\n /**\n * Get current rate for a slot\n *\n * @param slotId - Worker slot identifier\n * @returns Current message count in window, or 0 if no window\n */\n getCurrentRate(slotId: string): number {\n const window = this.windows.get(slotId);\n if (!window) return 0;\n\n const now = Date.now();\n if (now - window.windowStart >= this.config.windowMs) {\n return 0; // Window expired\n }\n\n return window.count;\n }\n\n /**\n * Prune expired windows\n * Should be called periodically to prevent memory leaks\n */\n prune(): number {\n const now = Date.now();\n let pruned = 0;\n\n for (const [slotId, window] of this.windows) {\n if (now - window.windowStart >= this.config.windowMs * 2) {\n this.windows.delete(slotId);\n pruned++;\n }\n }\n\n return pruned;\n }\n}\n\n/**\n * Create a rate limiter from worker pool config\n */\nexport function createRateLimiter(maxMessagesPerSecond: number): RateLimiter {\n return new RateLimiter({\n maxMessagesPerWindow: maxMessagesPerSecond,\n windowMs: 1000,\n });\n}\n"]}
@@ -0,0 +1,50 @@
1
+ /**
2
+ * Safe JSON Deserialization
3
+ *
4
+ * Provides prototype-pollution-safe JSON parsing for worker messages.
5
+ * All messages are JSON-serialized (not structured clone) to prevent attacks.
6
+ *
7
+ * @packageDocumentation
8
+ */
9
+ /**
10
+ * Safely deserialize a JSON string
11
+ *
12
+ * Security measures:
13
+ * - Strips __proto__, constructor, prototype keys
14
+ * - Creates null-prototype objects to prevent prototype chain attacks
15
+ * - Enforces maximum nesting depth
16
+ * - Enforces maximum message size
17
+ *
18
+ * Note: We parse first, then sanitize recursively. This ensures proper depth
19
+ * tracking (the JSON.parse reviver processes bottom-up which makes depth
20
+ * tracking unreliable).
21
+ *
22
+ * @param raw - Raw JSON string
23
+ * @param maxSizeBytes - Maximum allowed message size (optional)
24
+ * @returns Deserialized value
25
+ * @throws MessageSizeError if message exceeds size limit
26
+ * @throws MessageValidationError if JSON is invalid
27
+ */
28
+ export declare function safeDeserialize(raw: string, maxSizeBytes?: number): unknown;
29
+ /**
30
+ * Safely serialize a value to JSON
31
+ *
32
+ * Strips dangerous keys before serialization.
33
+ *
34
+ * @param value - Value to serialize
35
+ * @returns JSON string
36
+ */
37
+ export declare function safeSerialize(value: unknown): string;
38
+ /**
39
+ * Check if a key is dangerous (would cause prototype pollution)
40
+ */
41
+ export declare function isDangerousKey(key: string): boolean;
42
+ /**
43
+ * Sanitize an object by removing dangerous keys recursively
44
+ * Used for tool call arguments and results
45
+ *
46
+ * @param value - Value to sanitize
47
+ * @param depth - Current recursion depth (internal)
48
+ * @returns Sanitized value
49
+ */
50
+ export declare function sanitizeObject(value: unknown, depth?: number): unknown;
@@ -0,0 +1,141 @@
1
+ "use strict";
2
+ /**
3
+ * Safe JSON Deserialization
4
+ *
5
+ * Provides prototype-pollution-safe JSON parsing for worker messages.
6
+ * All messages are JSON-serialized (not structured clone) to prevent attacks.
7
+ *
8
+ * @packageDocumentation
9
+ */
10
+ Object.defineProperty(exports, "__esModule", { value: true });
11
+ exports.safeDeserialize = safeDeserialize;
12
+ exports.safeSerialize = safeSerialize;
13
+ exports.isDangerousKey = isDangerousKey;
14
+ exports.sanitizeObject = sanitizeObject;
15
+ const errors_1 = require("./errors");
16
+ /**
17
+ * Keys that are dangerous to include in deserialized objects
18
+ */
19
+ const DANGEROUS_KEYS = new Set(['__proto__', 'constructor', 'prototype']);
20
+ /**
21
+ * Maximum nesting depth for deserialized objects
22
+ */
23
+ const MAX_DEPTH = 50;
24
+ /**
25
+ * Safely deserialize a JSON string
26
+ *
27
+ * Security measures:
28
+ * - Strips __proto__, constructor, prototype keys
29
+ * - Creates null-prototype objects to prevent prototype chain attacks
30
+ * - Enforces maximum nesting depth
31
+ * - Enforces maximum message size
32
+ *
33
+ * Note: We parse first, then sanitize recursively. This ensures proper depth
34
+ * tracking (the JSON.parse reviver processes bottom-up which makes depth
35
+ * tracking unreliable).
36
+ *
37
+ * @param raw - Raw JSON string
38
+ * @param maxSizeBytes - Maximum allowed message size (optional)
39
+ * @returns Deserialized value
40
+ * @throws MessageSizeError if message exceeds size limit
41
+ * @throws MessageValidationError if JSON is invalid
42
+ */
43
+ function safeDeserialize(raw, maxSizeBytes) {
44
+ // Check size limit (use actual byte length, not character count)
45
+ if (maxSizeBytes !== undefined) {
46
+ const byteLength = Buffer.byteLength(raw, 'utf-8');
47
+ if (byteLength > maxSizeBytes) {
48
+ throw new errors_1.MessageSizeError(byteLength, maxSizeBytes);
49
+ }
50
+ }
51
+ try {
52
+ const parsed = JSON.parse(raw);
53
+ // Use sanitizeObject for proper recursive depth tracking
54
+ return sanitizeObjectWithDepthCheck(parsed, 0);
55
+ }
56
+ catch (error) {
57
+ if (error instanceof errors_1.MessageValidationError || error instanceof errors_1.MessageSizeError) {
58
+ throw error;
59
+ }
60
+ throw new errors_1.MessageValidationError('Invalid JSON');
61
+ }
62
+ }
63
+ /**
64
+ * Internal sanitization with depth checking that throws on exceeded depth
65
+ */
66
+ function sanitizeObjectWithDepthCheck(value, depth) {
67
+ if (depth > MAX_DEPTH) {
68
+ throw new errors_1.MessageValidationError(`Message exceeds maximum depth of ${MAX_DEPTH}`);
69
+ }
70
+ if (value === null || value === undefined) {
71
+ return value;
72
+ }
73
+ if (typeof value !== 'object') {
74
+ return value;
75
+ }
76
+ if (Array.isArray(value)) {
77
+ return value.map((item) => sanitizeObjectWithDepthCheck(item, depth + 1));
78
+ }
79
+ // Create a null-prototype object
80
+ const result = Object.create(null);
81
+ for (const key of Object.keys(value)) {
82
+ if (!DANGEROUS_KEYS.has(key)) {
83
+ result[key] = sanitizeObjectWithDepthCheck(value[key], depth + 1);
84
+ }
85
+ }
86
+ return result;
87
+ }
88
+ /**
89
+ * Safely serialize a value to JSON
90
+ *
91
+ * Strips dangerous keys before serialization.
92
+ *
93
+ * @param value - Value to serialize
94
+ * @returns JSON string
95
+ */
96
+ function safeSerialize(value) {
97
+ return JSON.stringify(value, (key, val) => {
98
+ // Strip dangerous keys
99
+ if (DANGEROUS_KEYS.has(key)) {
100
+ return undefined;
101
+ }
102
+ return val;
103
+ });
104
+ }
105
+ /**
106
+ * Check if a key is dangerous (would cause prototype pollution)
107
+ */
108
+ function isDangerousKey(key) {
109
+ return DANGEROUS_KEYS.has(key);
110
+ }
111
+ /**
112
+ * Sanitize an object by removing dangerous keys recursively
113
+ * Used for tool call arguments and results
114
+ *
115
+ * @param value - Value to sanitize
116
+ * @param depth - Current recursion depth (internal)
117
+ * @returns Sanitized value
118
+ */
119
+ function sanitizeObject(value, depth = 0) {
120
+ if (depth > MAX_DEPTH) {
121
+ return undefined;
122
+ }
123
+ if (value === null || value === undefined) {
124
+ return value;
125
+ }
126
+ if (typeof value !== 'object') {
127
+ return value;
128
+ }
129
+ if (Array.isArray(value)) {
130
+ return value.map((item) => sanitizeObject(item, depth + 1));
131
+ }
132
+ // Create a null-prototype object
133
+ const result = Object.create(null);
134
+ for (const key of Object.keys(value)) {
135
+ if (!DANGEROUS_KEYS.has(key)) {
136
+ result[key] = sanitizeObject(value[key], depth + 1);
137
+ }
138
+ }
139
+ return result;
140
+ }
141
+ //# sourceMappingURL=safe-deserialize.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"safe-deserialize.js","sourceRoot":"","sources":["../../../../src/adapters/worker-pool/safe-deserialize.ts"],"names":[],"mappings":";AAAA;;;;;;;GAOG;;AAiCH,0CAmBC;AA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KAAK,IAAI,IAAI,KAAK,KAAK,SAAS,EAAE,CAAC;QAC1C,OAAO,KAAK,CAAC;IACf,CAAC;IAED,IAAI,OAAO,KAAK,KAAK,QAAQ,EAAE,CAAC;QAC9B,OAAO,KAAK,CAAC;IACf,CAAC;IAED,IAAI,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,EAAE,CAAC;QACzB,OAAO,KAAK,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,cAAc,CAAC,IAAI,EAAE,KAAK,GAAG,CAAC,CAAC,CAAC,CAAC;IAC9D,CAAC;IAED,iCAAiC;IACjC,MAAM,MAAM,GAAG,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC;IAEnC,KAAK,MAAM,GAAG,IAAI,MAAM,CAAC,IAAI,CAAC,KAAe,CAAC,EAAE,CAAC;QAC/C,IAAI,CAAC,cAAc,CAAC,GAAG,CAAC,GAAG,CAAC,EAAE,CAAC;YAC7B,MAAM,CAAC,GAAG,CAAC,GAAG,cAAc,CAAE,KAAiC,CAAC,GAAG,CAAC,EAAE,KAAK,GAAG,CAAC,CAAC,CAAC;QACnF,CAAC;IACH,CAAC;IAED,OAAO,MAAM,CAAC;AAChB,CAAC","sourcesContent":["/**\n * Safe JSON Deserialization\n *\n * Provides prototype-pollution-safe JSON parsing for worker messages.\n * All messages are JSON-serialized (not structured clone) to prevent attacks.\n *\n * @packageDocumentation\n */\n\nimport { MessageValidationError, MessageSizeError } from './errors';\n\n/**\n * Keys that are dangerous to include in deserialized objects\n */\nconst DANGEROUS_KEYS = new Set(['__proto__', 'constructor', 'prototype']);\n\n/**\n * Maximum nesting depth for deserialized objects\n */\nconst MAX_DEPTH = 50;\n\n/**\n * Safely deserialize a JSON string\n *\n * Security measures:\n * - Strips __proto__, constructor, prototype keys\n * - Creates null-prototype objects to prevent prototype chain attacks\n * - Enforces maximum nesting depth\n * - Enforces maximum message size\n *\n * Note: We parse first, then sanitize recursively. This ensures proper depth\n * tracking (the JSON.parse reviver processes bottom-up which makes depth\n * tracking unreliable).\n *\n * @param raw - Raw JSON string\n * @param maxSizeBytes - Maximum allowed message size (optional)\n * @returns Deserialized value\n * @throws MessageSizeError if message exceeds size limit\n * @throws MessageValidationError if JSON is invalid\n */\nexport function safeDeserialize(raw: string, maxSizeBytes?: number): unknown {\n // Check size limit (use actual byte length, not character count)\n if (maxSizeBytes !== undefined) {\n const byteLength = Buffer.byteLength(raw, 'utf-8');\n if (byteLength > maxSizeBytes) {\n throw new MessageSizeError(byteLength, maxSizeBytes);\n }\n }\n\n try {\n const parsed = JSON.parse(raw);\n // Use sanitizeObject for proper recursive depth tracking\n return sanitizeObjectWithDepthCheck(parsed, 0);\n } catch (error) {\n if (error instanceof MessageValidationError || error instanceof MessageSizeError) {\n throw error;\n }\n throw new MessageValidationError('Invalid JSON');\n }\n}\n\n/**\n * Internal sanitization with depth checking that throws on exceeded depth\n */\nfunction sanitizeObjectWithDepthCheck(value: unknown, depth: number): unknown {\n if (depth > MAX_DEPTH) {\n throw new MessageValidationError(`Message exceeds maximum depth of ${MAX_DEPTH}`);\n }\n\n if (value === null || value === undefined) {\n return value;\n }\n\n if (typeof value !== 'object') {\n return value;\n }\n\n if (Array.isArray(value)) {\n return value.map((item) => sanitizeObjectWithDepthCheck(item, depth + 1));\n }\n\n // Create a null-prototype object\n const result = Object.create(null);\n\n for (const key of Object.keys(value as object)) {\n if (!DANGEROUS_KEYS.has(key)) {\n result[key] = sanitizeObjectWithDepthCheck((value as Record<string, unknown>)[key], depth + 1);\n }\n }\n\n return result;\n}\n\n/**\n * Safely serialize a value to JSON\n *\n * Strips dangerous keys before serialization.\n *\n * @param value - Value to serialize\n * @returns JSON string\n */\nexport function safeSerialize(value: unknown): string {\n return JSON.stringify(value, (key, val) => {\n // Strip dangerous keys\n if (DANGEROUS_KEYS.has(key)) {\n return undefined;\n }\n return val;\n });\n}\n\n/**\n * Check if a key is dangerous (would cause prototype pollution)\n */\nexport function isDangerousKey(key: string): boolean {\n return DANGEROUS_KEYS.has(key);\n}\n\n/**\n * Sanitize an object by removing dangerous keys recursively\n * Used for tool call arguments and results\n *\n * @param value - Value to sanitize\n * @param depth - Current recursion depth (internal)\n * @returns Sanitized value\n */\nexport function sanitizeObject(value: unknown, depth = 0): unknown {\n if (depth > MAX_DEPTH) {\n return undefined;\n }\n\n if (value === null || value === undefined) {\n return value;\n }\n\n if (typeof value !== 'object') {\n return value;\n }\n\n if (Array.isArray(value)) {\n return value.map((item) => sanitizeObject(item, depth + 1));\n }\n\n // Create a null-prototype object\n const result = Object.create(null);\n\n for (const key of Object.keys(value as object)) {\n if (!DANGEROUS_KEYS.has(key)) {\n result[key] = sanitizeObject((value as Record<string, unknown>)[key], depth + 1);\n }\n }\n\n return result;\n}\n"]}
@@ -0,0 +1,84 @@
1
+ /**
2
+ * Worker Pool Adapter
3
+ *
4
+ * Implements the SandboxAdapter interface using a pool of worker threads.
5
+ * Provides OS-level memory isolation, hard halt capability, and full pool management.
6
+ *
7
+ * @packageDocumentation
8
+ */
9
+ import type { SandboxAdapter, ExecutionContext, ExecutionResult, SecurityLevel } from '../../types';
10
+ import type { WorkerPoolConfig, WorkerPoolMetrics } from './config';
11
+ /**
12
+ * Worker Pool Adapter
13
+ *
14
+ * Provides a worker thread-based sandbox adapter with:
15
+ * - OS-level memory isolation
16
+ * - Hard halt capability via worker.terminate()
17
+ * - Pool management with min/max workers
18
+ * - Memory monitoring and enforcement
19
+ * - Rate limiting for message flood protection
20
+ */
21
+ export declare class WorkerPoolAdapter implements SandboxAdapter {
22
+ private readonly config;
23
+ private readonly securityLevel;
24
+ private readonly slots;
25
+ private readonly executionQueue;
26
+ private readonly memoryMonitor;
27
+ private readonly rateLimiter;
28
+ private disposed;
29
+ private initialized;
30
+ private _totalExecutions;
31
+ private _successfulExecutions;
32
+ private _failedExecutions;
33
+ private _timeoutExecutions;
34
+ private _workerRecycles;
35
+ private _forcedTerminations;
36
+ constructor(config?: Partial<WorkerPoolConfig>, securityLevel?: SecurityLevel);
37
+ /**
38
+ * Initialize the worker pool
39
+ * Must be called before execute()
40
+ */
41
+ initialize(): Promise<void>;
42
+ /**
43
+ * Execute code in a worker
44
+ */
45
+ execute<T = unknown>(code: string, context: ExecutionContext): Promise<ExecutionResult<T>>;
46
+ /**
47
+ * Dispose the adapter and all workers
48
+ */
49
+ dispose(): void;
50
+ private createAndAddSlot;
51
+ private acquireSlot;
52
+ private releaseSlot;
53
+ private handleSlotRecycling;
54
+ private handleMemoryExceeded;
55
+ private checkIdleSlots;
56
+ private executeInSlot;
57
+ private handleToolCall;
58
+ private handleConsoleMessage;
59
+ /**
60
+ * Build result from worker message.
61
+ *
62
+ * Note: The `msg.value as T` assertion is inherent to cross-thread
63
+ * serialization boundaries. The worker sanitizes output via sanitizeObject()
64
+ * before sending, but full runtime type validation would require schema
65
+ * definitions which are not available at this layer.
66
+ */
67
+ private buildResult;
68
+ /**
69
+ * Get pool metrics
70
+ */
71
+ getMetrics(): WorkerPoolMetrics;
72
+ /**
73
+ * Get current configuration
74
+ */
75
+ getConfig(): Required<WorkerPoolConfig>;
76
+ /**
77
+ * Check if adapter is initialized
78
+ */
79
+ isInitialized(): boolean;
80
+ /**
81
+ * Check if adapter is disposed
82
+ */
83
+ isDisposed(): boolean;
84
+ }