@enclave-vm/core 0.0.1 → 2.9.0

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/esm/index.mjs +11172 -0
  2. package/esm/package.json +6 -0
  3. package/index.js +11268 -0
  4. package/package.json +11 -10
  5. package/src/adapters/vm-adapter.js +0 -1140
  6. package/src/adapters/vm-adapter.js.map +0 -1
  7. package/src/adapters/worker-pool/config.js +0 -129
  8. package/src/adapters/worker-pool/config.js.map +0 -1
  9. package/src/adapters/worker-pool/errors.js +0 -181
  10. package/src/adapters/worker-pool/errors.js.map +0 -1
  11. package/src/adapters/worker-pool/execution-queue.js +0 -179
  12. package/src/adapters/worker-pool/execution-queue.js.map +0 -1
  13. package/src/adapters/worker-pool/index.js +0 -73
  14. package/src/adapters/worker-pool/index.js.map +0 -1
  15. package/src/adapters/worker-pool/memory-monitor.js +0 -184
  16. package/src/adapters/worker-pool/memory-monitor.js.map +0 -1
  17. package/src/adapters/worker-pool/protocol.js +0 -143
  18. package/src/adapters/worker-pool/protocol.js.map +0 -1
  19. package/src/adapters/worker-pool/rate-limiter.js +0 -101
  20. package/src/adapters/worker-pool/rate-limiter.js.map +0 -1
  21. package/src/adapters/worker-pool/safe-deserialize.js +0 -141
  22. package/src/adapters/worker-pool/safe-deserialize.js.map +0 -1
  23. package/src/adapters/worker-pool/worker-pool-adapter.js +0 -506
  24. package/src/adapters/worker-pool/worker-pool-adapter.js.map +0 -1
  25. package/src/adapters/worker-pool/worker-script.js +0 -770
  26. package/src/adapters/worker-pool/worker-script.js.map +0 -1
  27. package/src/adapters/worker-pool/worker-slot.js +0 -301
  28. package/src/adapters/worker-pool/worker-slot.js.map +0 -1
  29. package/src/babel/babel-wrapper.js +0 -395
  30. package/src/babel/babel-wrapper.js.map +0 -1
  31. package/src/babel/index.js +0 -17
  32. package/src/babel/index.js.map +0 -1
  33. package/src/babel/multi-file-transform.js +0 -344
  34. package/src/babel/multi-file-transform.js.map +0 -1
  35. package/src/double-vm/double-vm-wrapper.js +0 -523
  36. package/src/double-vm/double-vm-wrapper.js.map +0 -1
  37. package/src/double-vm/index.js +0 -34
  38. package/src/double-vm/index.js.map +0 -1
  39. package/src/double-vm/parent-vm-bootstrap.js +0 -1695
  40. package/src/double-vm/parent-vm-bootstrap.js.map +0 -1
  41. package/src/double-vm/suspicious-patterns.js +0 -304
  42. package/src/double-vm/suspicious-patterns.js.map +0 -1
  43. package/src/double-vm/types.js +0 -11
  44. package/src/double-vm/types.js.map +0 -1
  45. package/src/double-vm/wrap-adapter.js +0 -59
  46. package/src/double-vm/wrap-adapter.js.map +0 -1
  47. package/src/enclave.js +0 -671
  48. package/src/enclave.js.map +0 -1
  49. package/src/globals-validator.js +0 -206
  50. package/src/globals-validator.js.map +0 -1
  51. package/src/index.js +0 -130
  52. package/src/index.js.map +0 -1
  53. package/src/memory-proxy.js +0 -310
  54. package/src/memory-proxy.js.map +0 -1
  55. package/src/memory-tracker.js +0 -230
  56. package/src/memory-tracker.js.map +0 -1
  57. package/src/safe-error.js +0 -76
  58. package/src/safe-error.js.map +0 -1
  59. package/src/safe-runtime.js +0 -656
  60. package/src/safe-runtime.js.map +0 -1
  61. package/src/scoring/cache.js +0 -158
  62. package/src/scoring/cache.js.map +0 -1
  63. package/src/scoring/feature-extractor.js +0 -366
  64. package/src/scoring/feature-extractor.js.map +0 -1
  65. package/src/scoring/index.js +0 -53
  66. package/src/scoring/index.js.map +0 -1
  67. package/src/scoring/scorer.interface.js +0 -49
  68. package/src/scoring/scorer.interface.js.map +0 -1
  69. package/src/scoring/scorers/disabled.scorer.js +0 -34
  70. package/src/scoring/scorers/disabled.scorer.js.map +0 -1
  71. package/src/scoring/scorers/external-api.scorer.js +0 -141
  72. package/src/scoring/scorers/external-api.scorer.js.map +0 -1
  73. package/src/scoring/scorers/index.js +0 -22
  74. package/src/scoring/scorers/index.js.map +0 -1
  75. package/src/scoring/scorers/local-llm.scorer.js +0 -474
  76. package/src/scoring/scorers/local-llm.scorer.js.map +0 -1
  77. package/src/scoring/scorers/progressive.scorer.js +0 -199
  78. package/src/scoring/scorers/progressive.scorer.js.map +0 -1
  79. package/src/scoring/scorers/rule-based.scorer.js +0 -316
  80. package/src/scoring/scorers/rule-based.scorer.js.map +0 -1
  81. package/src/scoring/scoring-gate.js +0 -246
  82. package/src/scoring/scoring-gate.js.map +0 -1
  83. package/src/scoring/types.js +0 -107
  84. package/src/scoring/types.js.map +0 -1
  85. package/src/secure-proxy.js +0 -609
  86. package/src/secure-proxy.js.map +0 -1
  87. package/src/session/channels/embedded-channel.js +0 -130
  88. package/src/session/channels/embedded-channel.js.map +0 -1
  89. package/src/session/channels/index.js +0 -14
  90. package/src/session/channels/index.js.map +0 -1
  91. package/src/session/index.js +0 -27
  92. package/src/session/index.js.map +0 -1
  93. package/src/session/session-emitter.js +0 -253
  94. package/src/session/session-emitter.js.map +0 -1
  95. package/src/session/session-state-machine.js +0 -182
  96. package/src/session/session-state-machine.js.map +0 -1
  97. package/src/session/session.js +0 -398
  98. package/src/session/session.js.map +0 -1
  99. package/src/session-types.js +0 -39
  100. package/src/session-types.js.map +0 -1
  101. package/src/sidecar/index.js +0 -31
  102. package/src/sidecar/index.js.map +0 -1
  103. package/src/sidecar/reference-config.js +0 -118
  104. package/src/sidecar/reference-config.js.map +0 -1
  105. package/src/sidecar/reference-resolver.js +0 -262
  106. package/src/sidecar/reference-resolver.js.map +0 -1
  107. package/src/sidecar/reference-sidecar.js +0 -226
  108. package/src/sidecar/reference-sidecar.js.map +0 -1
  109. package/src/tool-bridge.js +0 -306
  110. package/src/tool-bridge.js.map +0 -1
  111. package/src/types.js +0 -187
  112. package/src/types.js.map +0 -1
  113. package/src/value-sanitizer.js +0 -421
  114. package/src/value-sanitizer.js.map +0 -1
  115. /package/{src/adapters → adapters}/vm-adapter.d.ts +0 -0
  116. /package/{src/adapters → adapters}/worker-pool/config.d.ts +0 -0
  117. /package/{src/adapters → adapters}/worker-pool/errors.d.ts +0 -0
  118. /package/{src/adapters → adapters}/worker-pool/execution-queue.d.ts +0 -0
  119. /package/{src/adapters → adapters}/worker-pool/index.d.ts +0 -0
  120. /package/{src/adapters → adapters}/worker-pool/memory-monitor.d.ts +0 -0
  121. /package/{src/adapters → adapters}/worker-pool/protocol.d.ts +0 -0
  122. /package/{src/adapters → adapters}/worker-pool/rate-limiter.d.ts +0 -0
  123. /package/{src/adapters → adapters}/worker-pool/safe-deserialize.d.ts +0 -0
  124. /package/{src/adapters → adapters}/worker-pool/worker-pool-adapter.d.ts +0 -0
  125. /package/{src/adapters → adapters}/worker-pool/worker-script.d.ts +0 -0
  126. /package/{src/adapters → adapters}/worker-pool/worker-slot.d.ts +0 -0
  127. /package/{src/babel → babel}/babel-wrapper.d.ts +0 -0
  128. /package/{src/babel → babel}/index.d.ts +0 -0
  129. /package/{src/babel → babel}/multi-file-transform.d.ts +0 -0
  130. /package/{src/double-vm → double-vm}/double-vm-wrapper.d.ts +0 -0
  131. /package/{src/double-vm → double-vm}/index.d.ts +0 -0
  132. /package/{src/double-vm → double-vm}/parent-vm-bootstrap.d.ts +0 -0
  133. /package/{src/double-vm → double-vm}/suspicious-patterns.d.ts +0 -0
  134. /package/{src/double-vm → double-vm}/types.d.ts +0 -0
  135. /package/{src/double-vm → double-vm}/wrap-adapter.d.ts +0 -0
  136. /package/{src/enclave.d.ts → enclave.d.ts} +0 -0
  137. /package/{src/globals-validator.d.ts → globals-validator.d.ts} +0 -0
  138. /package/{src/index.d.ts → index.d.ts} +0 -0
  139. /package/{src/memory-proxy.d.ts → memory-proxy.d.ts} +0 -0
  140. /package/{src/memory-tracker.d.ts → memory-tracker.d.ts} +0 -0
  141. /package/{src/safe-error.d.ts → safe-error.d.ts} +0 -0
  142. /package/{src/safe-runtime.d.ts → safe-runtime.d.ts} +0 -0
  143. /package/{src/scoring → scoring}/cache.d.ts +0 -0
  144. /package/{src/scoring → scoring}/feature-extractor.d.ts +0 -0
  145. /package/{src/scoring → scoring}/index.d.ts +0 -0
  146. /package/{src/scoring → scoring}/scorer.interface.d.ts +0 -0
  147. /package/{src/scoring → scoring}/scorers/disabled.scorer.d.ts +0 -0
  148. /package/{src/scoring → scoring}/scorers/external-api.scorer.d.ts +0 -0
  149. /package/{src/scoring → scoring}/scorers/index.d.ts +0 -0
  150. /package/{src/scoring → scoring}/scorers/local-llm.scorer.d.ts +0 -0
  151. /package/{src/scoring → scoring}/scorers/progressive.scorer.d.ts +0 -0
  152. /package/{src/scoring → scoring}/scorers/rule-based.scorer.d.ts +0 -0
  153. /package/{src/scoring → scoring}/scoring-gate.d.ts +0 -0
  154. /package/{src/scoring → scoring}/types.d.ts +0 -0
  155. /package/{src/secure-proxy.d.ts → secure-proxy.d.ts} +0 -0
  156. /package/{src/session → session}/channels/embedded-channel.d.ts +0 -0
  157. /package/{src/session → session}/channels/index.d.ts +0 -0
  158. /package/{src/session → session}/index.d.ts +0 -0
  159. /package/{src/session → session}/session-emitter.d.ts +0 -0
  160. /package/{src/session → session}/session-state-machine.d.ts +0 -0
  161. /package/{src/session → session}/session.d.ts +0 -0
  162. /package/{src/session-types.d.ts → session-types.d.ts} +0 -0
  163. /package/{src/sidecar → sidecar}/index.d.ts +0 -0
  164. /package/{src/sidecar → sidecar}/reference-config.d.ts +0 -0
  165. /package/{src/sidecar → sidecar}/reference-resolver.d.ts +0 -0
  166. /package/{src/sidecar → sidecar}/reference-sidecar.d.ts +0 -0
  167. /package/{src/tool-bridge.d.ts → tool-bridge.d.ts} +0 -0
  168. /package/{src/types.d.ts → types.d.ts} +0 -0
  169. /package/{src/value-sanitizer.d.ts → value-sanitizer.d.ts} +0 -0
@@ -1,395 +0,0 @@
1
- "use strict";
2
- /**
3
- * Babel Wrapper for Enclave
4
- *
5
- * Provides a restricted Babel.transform() API for use inside the enclave sandbox.
6
- * Uses @babel/standalone for browser-compatible transformation.
7
- *
8
- * SECURITY: Babel transforms run in an isolated VM context with NO access to:
9
- * - File system (fs, path)
10
- * - Process/environment (process, env)
11
- * - Network (http, https, net)
12
- * - Child processes (child_process)
13
- * - Module loading (require, import)
14
- *
15
- * Only pure JavaScript transformation is allowed.
16
- *
17
- * @packageDocumentation
18
- */
19
- Object.defineProperty(exports, "__esModule", { value: true });
20
- exports.createRestrictedBabel = createRestrictedBabel;
21
- exports.getAvailableBabelPresets = getAvailableBabelPresets;
22
- exports.resetBabelContext = resetBabelContext;
23
- const tslib_1 = require("tslib");
24
- const vm = tslib_1.__importStar(require("vm"));
25
- const BabelStandalone = tslib_1.__importStar(require("@babel/standalone"));
26
- const ast_1 = require("@enclave-vm/ast");
27
- /**
28
- * Sanitize filename to prevent path traversal attacks
29
- */
30
- function sanitizeFilename(filename) {
31
- // Remove any path separators and parent directory references
32
- const sanitized = filename
33
- .replace(/\.\./g, '') // Remove parent directory references
34
- .replace(/[/\\]/g, '') // Remove path separators
35
- .replace(/[<>:"|?*]/g, '') // Remove invalid filename chars
36
- .slice(0, 255); // Limit length
37
- return sanitized || 'input.tsx';
38
- }
39
- /**
40
- * Create an isolated VM context for Babel transforms
41
- *
42
- * SECURITY: This context has NO access to Node.js APIs.
43
- * Only safe JavaScript globals are provided.
44
- */
45
- function createIsolatedBabelContext() {
46
- // Create a fresh context with minimal globals
47
- const context = vm.createContext({}, {
48
- // Disable code generation from strings (extra safety)
49
- codeGeneration: {
50
- strings: false,
51
- wasm: false,
52
- },
53
- });
54
- // Inject ONLY the safe globals needed for Babel to work
55
- // These are pure JavaScript APIs with no I/O capabilities
56
- const safeGlobals = {
57
- // Core JavaScript types (needed for Babel's internal operations)
58
- Object,
59
- Array,
60
- String,
61
- Number,
62
- Boolean,
63
- Symbol,
64
- Map,
65
- Set,
66
- WeakMap,
67
- WeakSet,
68
- Date,
69
- RegExp,
70
- Error,
71
- TypeError,
72
- SyntaxError,
73
- RangeError,
74
- ReferenceError,
75
- // Math and JSON (pure functions, no I/O)
76
- Math,
77
- JSON,
78
- // Essential functions
79
- parseInt,
80
- parseFloat,
81
- isNaN,
82
- isFinite,
83
- encodeURI,
84
- decodeURI,
85
- encodeURIComponent,
86
- decodeURIComponent,
87
- // Primitives
88
- undefined,
89
- NaN,
90
- Infinity,
91
- // Console for debugging (optional, could be removed for stricter security)
92
- // Intentionally empty - these are no-op stubs to prevent errors in sandbox code
93
- console: {
94
- log: () => {
95
- /* intentionally empty - no-op stub for sandbox */
96
- },
97
- warn: () => {
98
- /* intentionally empty - no-op stub for sandbox */
99
- },
100
- error: () => {
101
- /* intentionally empty - no-op stub for sandbox */
102
- },
103
- info: () => {
104
- /* intentionally empty - no-op stub for sandbox */
105
- },
106
- },
107
- };
108
- // Add safe globals to context
109
- for (const [key, value] of Object.entries(safeGlobals)) {
110
- Object.defineProperty(context, key, {
111
- value,
112
- writable: false,
113
- configurable: false,
114
- enumerable: true,
115
- });
116
- }
117
- // EXPLICITLY BLOCK dangerous Node.js globals by setting them to undefined
118
- // This prevents any accidental access even if @babel/standalone tries
119
- const blockedGlobals = [
120
- // Node.js core
121
- 'process',
122
- 'global',
123
- 'globalThis',
124
- 'Buffer',
125
- 'require',
126
- 'module',
127
- 'exports',
128
- '__dirname',
129
- '__filename',
130
- // File system
131
- 'fs',
132
- 'path',
133
- // Network
134
- 'http',
135
- 'https',
136
- 'net',
137
- 'dgram',
138
- 'dns',
139
- 'tls',
140
- // Process management
141
- 'child_process',
142
- 'cluster',
143
- 'worker_threads',
144
- // Other dangerous APIs
145
- 'vm', // Prevent nested VM escape
146
- 'eval',
147
- 'Function',
148
- 'Proxy',
149
- 'Reflect',
150
- // Browser APIs that shouldn't exist in Node but block anyway
151
- 'fetch',
152
- 'XMLHttpRequest',
153
- 'WebSocket',
154
- 'localStorage',
155
- 'sessionStorage',
156
- 'indexedDB',
157
- ];
158
- for (const name of blockedGlobals) {
159
- try {
160
- Object.defineProperty(context, name, {
161
- value: undefined,
162
- writable: false,
163
- configurable: false,
164
- enumerable: false,
165
- });
166
- }
167
- catch {
168
- // Ignore if we can't define it
169
- }
170
- }
171
- return context;
172
- }
173
- // Cache the isolated context and Babel instance for performance
174
- let isolatedContext = null;
175
- let babelInContext = null;
176
- /**
177
- * Get or create the isolated Babel context
178
- */
179
- function getIsolatedBabel() {
180
- if (babelInContext) {
181
- return babelInContext;
182
- }
183
- // Create isolated context
184
- isolatedContext = createIsolatedBabelContext();
185
- // Inject Babel into the isolated context
186
- // We serialize the Babel transform function and create a wrapper
187
- Object.defineProperty(isolatedContext, '__babel_transform__', {
188
- value: BabelStandalone.transform.bind(BabelStandalone),
189
- writable: false,
190
- configurable: false,
191
- enumerable: false,
192
- });
193
- // Create a script that returns the transform function
194
- const wrapperScript = new vm.Script(`
195
- (function() {
196
- var transform = __babel_transform__;
197
- return {
198
- transform: function(code, options) {
199
- return transform(code, options);
200
- }
201
- };
202
- })()
203
- `);
204
- // Run the script in the isolated context
205
- babelInContext = wrapperScript.runInContext(isolatedContext);
206
- return babelInContext;
207
- }
208
- /**
209
- * Create a restricted Babel object for sandbox use
210
- *
211
- * SECURITY: All transforms run in an isolated VM context with:
212
- * - NO access to fs, process, require, or any Node.js APIs
213
- * - NO access to network APIs
214
- * - NO ability to load external code
215
- * - Timeout enforcement
216
- * - Input/output size limits
217
- * - Preset whitelist
218
- *
219
- * @param config - Configuration from security level
220
- * @returns Restricted Babel object with transform() method
221
- *
222
- * @example
223
- * ```typescript
224
- * const babel = createRestrictedBabel({
225
- * maxInputSize: 1024 * 1024,
226
- * maxOutputSize: 5 * 1024 * 1024,
227
- * allowedPresets: ['typescript', 'react'],
228
- * transformTimeout: 15000,
229
- * });
230
- *
231
- * const result = babel.transform(tsxCode, {
232
- * filename: 'App.tsx',
233
- * presets: ['typescript', 'react'],
234
- * });
235
- *
236
- * console.log(result.code);
237
- * ```
238
- */
239
- function createRestrictedBabel(config) {
240
- const allowedPresets = new Set(config.allowedPresets);
241
- return {
242
- transform(code, options) {
243
- // 1. Validate input code type
244
- if (typeof code !== 'string') {
245
- throw new TypeError('Code must be a string');
246
- }
247
- // 2. Check for null bytes (potential injection)
248
- if (code.includes('\0')) {
249
- throw new Error('Code contains invalid null bytes');
250
- }
251
- // 3. Validate input size
252
- const inputBytes = Buffer.byteLength(code, 'utf-8');
253
- if (inputBytes > config.maxInputSize) {
254
- throw new Error(`Code exceeds maximum size (${inputBytes} bytes > ${config.maxInputSize} bytes). ` +
255
- `Reduce input size or use a higher security level.`);
256
- }
257
- // 4. Validate and filter presets against security-level allowlist
258
- const requestedPresets = options?.presets ?? [];
259
- if (!Array.isArray(requestedPresets)) {
260
- throw new TypeError('Presets must be an array');
261
- }
262
- for (const preset of requestedPresets) {
263
- if (typeof preset !== 'string') {
264
- throw new TypeError('Each preset must be a string');
265
- }
266
- if (!allowedPresets.has(preset)) {
267
- throw new Error(`Preset "${preset}" is not allowed at this security level. ` +
268
- `Allowed presets: ${[...allowedPresets].join(', ')}`);
269
- }
270
- }
271
- // 5. Sanitize filename
272
- const filename = sanitizeFilename(options?.filename ?? 'input.tsx');
273
- // 6. Validate sourceType
274
- const sourceType = options?.sourceType ?? 'module';
275
- if (sourceType !== 'module' && sourceType !== 'script') {
276
- throw new Error('sourceType must be "module" or "script"');
277
- }
278
- // 7. Build safe options - explicitly disable dangerous features
279
- const safeOptions = {
280
- filename,
281
- presets: requestedPresets,
282
- sourceType,
283
- // Security: Explicitly disable dangerous options
284
- plugins: [], // NO plugins allowed - they execute arbitrary code
285
- sourceMaps: false, // No source maps (path leakage risk)
286
- ast: false, // No AST output
287
- code: true, // Only code output
288
- // Disable other potentially dangerous options
289
- inputSourceMap: undefined,
290
- sourceFileName: undefined,
291
- sourceRoot: undefined,
292
- babelrc: false, // Don't load .babelrc files
293
- configFile: false, // Don't load babel.config.js
294
- };
295
- // 8. Execute the transform in isolated context with timeout
296
- let result;
297
- try {
298
- // Ensure the isolated context is initialized
299
- getIsolatedBabel();
300
- // Create a script that calls transform with our options
301
- // This runs in the isolated context with timeout
302
- const transformScript = new vm.Script(`
303
- __babel_result__ = __babel_transform__(__babel_code__, __babel_options__);
304
- `);
305
- // Inject the code and options into the isolated context
306
- Object.defineProperty(isolatedContext, '__babel_code__', {
307
- value: code,
308
- writable: true,
309
- configurable: true,
310
- enumerable: false,
311
- });
312
- Object.defineProperty(isolatedContext, '__babel_options__', {
313
- value: safeOptions,
314
- writable: true,
315
- configurable: true,
316
- enumerable: false,
317
- });
318
- Object.defineProperty(isolatedContext, '__babel_result__', {
319
- value: null,
320
- writable: true,
321
- configurable: true,
322
- enumerable: false,
323
- });
324
- // Run with timeout
325
- transformScript.runInContext(isolatedContext, {
326
- timeout: config.transformTimeout,
327
- });
328
- // Get the result
329
- result = isolatedContext['__babel_result__'];
330
- // Clean up temporary variables
331
- delete isolatedContext['__babel_code__'];
332
- delete isolatedContext['__babel_options__'];
333
- delete isolatedContext['__babel_result__'];
334
- }
335
- catch (error) {
336
- // Re-throw with sanitized message (remove file paths)
337
- const err = error;
338
- const sanitizedMessage = (err.message || 'Unknown transform error')
339
- .replace(/\/[^\s:]+/g, '<path>') // Remove file paths
340
- .replace(/at\s+[^\s]+\s+\([^)]+\)/g, '') // Remove stack locations
341
- .replace(/evalmachine\.<anonymous>/g, '<transform>') // Remove VM internals
342
- .trim();
343
- // Check for timeout
344
- if (err.message?.includes('Script execution timed out')) {
345
- throw new Error(`Babel transform timed out after ${config.transformTimeout}ms. ` +
346
- `The code may be too complex or contain infinite loops.`);
347
- }
348
- throw new Error(`Babel transform failed: ${sanitizedMessage}`);
349
- }
350
- // 9. Validate output
351
- let outputCode = result?.code ?? '';
352
- if (typeof outputCode !== 'string') {
353
- throw new Error('Transform produced invalid output');
354
- }
355
- // 10. Apply import rewriting if configured
356
- if (options?.importRewrite?.enabled) {
357
- try {
358
- const rewriteResult = (0, ast_1.rewriteImports)(outputCode, options.importRewrite);
359
- outputCode = rewriteResult.code;
360
- }
361
- catch (rewriteError) {
362
- throw new Error(`Import rewrite failed: ${rewriteError.message}`);
363
- }
364
- }
365
- // 11. Check output size
366
- const outputBytes = Buffer.byteLength(outputCode, 'utf-8');
367
- if (outputBytes > config.maxOutputSize) {
368
- throw new Error(`Output exceeds maximum size (${outputBytes} bytes > ${config.maxOutputSize} bytes). ` +
369
- `The transformed code is too large.`);
370
- }
371
- // 12. Return only the code (not AST, not source map, not metadata)
372
- return { code: outputCode };
373
- },
374
- };
375
- }
376
- /**
377
- * Get available presets in @babel/standalone
378
- *
379
- * This is useful for documentation and validation.
380
- * Note: Not all presets are allowed in the enclave - see BABEL_SECURITY_CONFIGS.
381
- */
382
- function getAvailableBabelPresets() {
383
- return ['env', 'react', 'typescript', 'flow'];
384
- }
385
- /**
386
- * Reset the isolated Babel context
387
- *
388
- * Useful for testing or if you want to ensure a fresh context.
389
- * Note: This is generally not needed as the context is reused for performance.
390
- */
391
- function resetBabelContext() {
392
- isolatedContext = null;
393
- babelInContext = null;
394
- }
395
- //# sourceMappingURL=babel-wrapper.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"babel-wrapper.js","sourceRoot":"","sources":["../../../src/babel/babel-wrapper.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;GAgBG;;AAmTH,sDAsKC;AAQD,4DAEC;AAQD,8CAGC;;AA5eD,+CAAyB;AACzB,2EAAqD;AACrD,yCAA2E;AA+D3E;;GAEG;AACH,SAAS,gBAAgB,CAAC,QAAgB;IACxC,6DAA6D;IAC7D,MAAM,SAAS,GAAG,QAAQ;SACvB,OAAO,CAAC,OAAO,EAAE,EAAE,CAAC,CAAC,qCAAqC;SAC1D,OAAO,CAAC,QAAQ,EAAE,EAAE,CAAC,CAAC,yBAAyB;SAC/C,OAAO,CAAC,YAAY,EAAE,EAAE,CAAC,CAAC,gCAAgC;SAC1D,KAAK,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC,CAAC,eAAe;IAEjC,OAAO,SAAS,IAAI,WAAW,CAAC;AAClC,CAAC;AAED;;;;;GAKG;AACH,SAAS,0BAA0B;IACjC,8CAA8C;IAC9C,MAAM,OAAO,GAAG,EAAE,CAAC,aAAa,CAC9B,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AAE,UAAU,EAAE,CAAC;QAC9B,CAAC;KACF,CAAC;AACJ,CAAC;AAED;;;;;GAKG;AACH,SAAgB,wBAAwB;IACtC,OAAO,CAAC,KAAK,EAAE,OAAO,EAAE,YAAY,EAAE,MAAM,CAAC,CAAC;AAChD,CAAC;AAED;;;;;GAKG;AACH,SAAgB,iBAAiB;IAC/B,eAAe,GAAG,IAAI,CAAC;IACvB,cAAc,GAAG,IAAI,CAAC;AACxB,CAAC","sourcesContent":["/**\n * Babel Wrapper for Enclave\n *\n * Provides a restricted Babel.transform() API for use inside the enclave sandbox.\n * Uses @babel/standalone for browser-compatible transformation.\n *\n * SECURITY: Babel transforms run in an isolated VM context with NO access to:\n * - File system (fs, path)\n * - Process/environment (process, env)\n * - Network (http, https, net)\n * - Child processes (child_process)\n * - Module loading (require, import)\n *\n * Only pure JavaScript transformation is allowed.\n *\n * @packageDocumentation\n */\n\nimport * as vm from 'vm';\nimport * as BabelStandalone from '@babel/standalone';\nimport { rewriteImports, type ImportRewriteConfig } from '@enclave-vm/ast';\n\n/**\n * Safe transform options that can be passed by sandbox code\n */\nexport interface SafeTransformOptions {\n /**\n * Filename for error messages (no path traversal allowed)\n */\n filename?: string;\n\n /**\n * Presets to use (must be in allowed list)\n */\n presets?: string[];\n\n /**\n * Source type for parsing\n */\n sourceType?: 'module' | 'script';\n\n /**\n * Import rewrite configuration for transforming npm imports to CDN URLs\n */\n importRewrite?: ImportRewriteConfig;\n}\n\n/**\n * Safe transform result (only code, no AST or source maps)\n */\nexport interface SafeTransformResult {\n /**\n * The transformed code\n */\n code: string;\n}\n\n/**\n * Configuration for the Babel wrapper\n * These values come from security level via getBabelConfig()\n */\nexport interface BabelWrapperConfig {\n /**\n * Maximum input code size in bytes\n */\n maxInputSize: number;\n\n /**\n * Maximum output code size in bytes\n */\n maxOutputSize: number;\n\n /**\n * Allowed preset names\n */\n allowedPresets: string[];\n\n /**\n * Transform timeout in milliseconds\n */\n transformTimeout: number;\n}\n\n/**\n * Sanitize filename to prevent path traversal attacks\n */\nfunction sanitizeFilename(filename: string): string {\n // Remove any path separators and parent directory references\n const sanitized = filename\n .replace(/\\.\\./g, '') // Remove parent directory references\n .replace(/[/\\\\]/g, '') // Remove path separators\n .replace(/[<>:\"|?*]/g, '') // Remove invalid filename chars\n .slice(0, 255); // Limit length\n\n return sanitized || 'input.tsx';\n}\n\n/**\n * Create an isolated VM context for Babel transforms\n *\n * SECURITY: This context has NO access to Node.js APIs.\n * Only safe JavaScript globals are provided.\n */\nfunction createIsolatedBabelContext(): vm.Context {\n // Create a fresh context with minimal globals\n const context = vm.createContext(\n {},\n {\n // Disable code generation from strings (extra safety)\n codeGeneration: {\n strings: false,\n wasm: false,\n },\n },\n );\n\n // Inject ONLY the safe globals needed for Babel to work\n // These are pure JavaScript APIs with no I/O capabilities\n const safeGlobals = {\n // Core JavaScript types (needed for Babel's internal operations)\n Object,\n Array,\n String,\n Number,\n Boolean,\n Symbol,\n Map,\n Set,\n WeakMap,\n WeakSet,\n Date,\n RegExp,\n Error,\n TypeError,\n SyntaxError,\n RangeError,\n ReferenceError,\n\n // Math and JSON (pure functions, no I/O)\n Math,\n JSON,\n\n // Essential functions\n parseInt,\n parseFloat,\n isNaN,\n isFinite,\n encodeURI,\n decodeURI,\n encodeURIComponent,\n decodeURIComponent,\n\n // Primitives\n undefined,\n NaN,\n Infinity,\n\n // Console for debugging (optional, could be removed for stricter security)\n // Intentionally empty - these are no-op stubs to prevent errors in sandbox code\n console: {\n log: () => {\n /* intentionally empty - no-op stub for sandbox */\n },\n warn: () => {\n /* intentionally empty - no-op stub for sandbox */\n },\n error: () => {\n /* intentionally empty - no-op stub for sandbox */\n },\n info: () => {\n /* intentionally empty - no-op stub for sandbox */\n },\n },\n };\n\n // Add safe globals to context\n for (const [key, value] of Object.entries(safeGlobals)) {\n Object.defineProperty(context, key, {\n value,\n writable: false,\n configurable: false,\n enumerable: true,\n });\n }\n\n // EXPLICITLY BLOCK dangerous Node.js globals by setting them to undefined\n // This prevents any accidental access even if @babel/standalone tries\n const blockedGlobals = [\n // Node.js core\n 'process',\n 'global',\n 'globalThis',\n 'Buffer',\n 'require',\n 'module',\n 'exports',\n '__dirname',\n '__filename',\n\n // File system\n 'fs',\n 'path',\n\n // Network\n 'http',\n 'https',\n 'net',\n 'dgram',\n 'dns',\n 'tls',\n\n // Process management\n 'child_process',\n 'cluster',\n 'worker_threads',\n\n // Other dangerous APIs\n 'vm', // Prevent nested VM escape\n 'eval',\n 'Function',\n 'Proxy',\n 'Reflect',\n\n // Browser APIs that shouldn't exist in Node but block anyway\n 'fetch',\n 'XMLHttpRequest',\n 'WebSocket',\n 'localStorage',\n 'sessionStorage',\n 'indexedDB',\n ];\n\n for (const name of blockedGlobals) {\n try {\n Object.defineProperty(context, name, {\n value: undefined,\n writable: false,\n configurable: false,\n enumerable: false,\n });\n } catch {\n // Ignore if we can't define it\n }\n }\n\n return context;\n}\n\n// Cache the isolated context and Babel instance for performance\nlet isolatedContext: vm.Context | null = null;\nlet babelInContext: { transform: (code: string, options: unknown) => { code: string } } | null = null;\n\n/**\n * Get or create the isolated Babel context\n */\nfunction getIsolatedBabel(): { transform: (code: string, options: unknown) => { code: string } } {\n if (babelInContext) {\n return babelInContext;\n }\n\n // Create isolated context\n isolatedContext = createIsolatedBabelContext();\n\n // Inject Babel into the isolated context\n // We serialize the Babel transform function and create a wrapper\n Object.defineProperty(isolatedContext, '__babel_transform__', {\n value: BabelStandalone.transform.bind(BabelStandalone),\n writable: false,\n configurable: false,\n enumerable: false,\n });\n\n // Create a script that returns the transform function\n const wrapperScript = new vm.Script(`\n (function() {\n var transform = __babel_transform__;\n return {\n transform: function(code, options) {\n return transform(code, options);\n }\n };\n })()\n `);\n\n // Run the script in the isolated context\n babelInContext = wrapperScript.runInContext(isolatedContext) as {\n transform: (code: string, options: unknown) => { code: string };\n };\n\n return babelInContext;\n}\n\n/**\n * Create a restricted Babel object for sandbox use\n *\n * SECURITY: All transforms run in an isolated VM context with:\n * - NO access to fs, process, require, or any Node.js APIs\n * - NO access to network APIs\n * - NO ability to load external code\n * - Timeout enforcement\n * - Input/output size limits\n * - Preset whitelist\n *\n * @param config - Configuration from security level\n * @returns Restricted Babel object with transform() method\n *\n * @example\n * ```typescript\n * const babel = createRestrictedBabel({\n * maxInputSize: 1024 * 1024,\n * maxOutputSize: 5 * 1024 * 1024,\n * allowedPresets: ['typescript', 'react'],\n * transformTimeout: 15000,\n * });\n *\n * const result = babel.transform(tsxCode, {\n * filename: 'App.tsx',\n * presets: ['typescript', 'react'],\n * });\n *\n * console.log(result.code);\n * ```\n */\nexport function createRestrictedBabel(config: BabelWrapperConfig): {\n transform: (code: string, options?: SafeTransformOptions) => SafeTransformResult;\n} {\n const allowedPresets = new Set(config.allowedPresets);\n\n return {\n transform(code: string, options?: SafeTransformOptions): SafeTransformResult {\n // 1. Validate input code type\n if (typeof code !== 'string') {\n throw new TypeError('Code must be a string');\n }\n\n // 2. Check for null bytes (potential injection)\n if (code.includes('\\0')) {\n throw new Error('Code contains invalid null bytes');\n }\n\n // 3. Validate input size\n const inputBytes = Buffer.byteLength(code, 'utf-8');\n if (inputBytes > config.maxInputSize) {\n throw new Error(\n `Code exceeds maximum size (${inputBytes} bytes > ${config.maxInputSize} bytes). ` +\n `Reduce input size or use a higher security level.`,\n );\n }\n\n // 4. Validate and filter presets against security-level allowlist\n const requestedPresets = options?.presets ?? [];\n\n if (!Array.isArray(requestedPresets)) {\n throw new TypeError('Presets must be an array');\n }\n\n for (const preset of requestedPresets) {\n if (typeof preset !== 'string') {\n throw new TypeError('Each preset must be a string');\n }\n if (!allowedPresets.has(preset)) {\n throw new Error(\n `Preset \"${preset}\" is not allowed at this security level. ` +\n `Allowed presets: ${[...allowedPresets].join(', ')}`,\n );\n }\n }\n\n // 5. Sanitize filename\n const filename = sanitizeFilename(options?.filename ?? 'input.tsx');\n\n // 6. Validate sourceType\n const sourceType = options?.sourceType ?? 'module';\n if (sourceType !== 'module' && sourceType !== 'script') {\n throw new Error('sourceType must be \"module\" or \"script\"');\n }\n\n // 7. Build safe options - explicitly disable dangerous features\n const safeOptions = {\n filename,\n presets: requestedPresets,\n sourceType,\n // Security: Explicitly disable dangerous options\n plugins: [], // NO plugins allowed - they execute arbitrary code\n sourceMaps: false, // No source maps (path leakage risk)\n ast: false, // No AST output\n code: true, // Only code output\n // Disable other potentially dangerous options\n inputSourceMap: undefined,\n sourceFileName: undefined,\n sourceRoot: undefined,\n babelrc: false, // Don't load .babelrc files\n configFile: false, // Don't load babel.config.js\n };\n\n // 8. Execute the transform in isolated context with timeout\n let result: { code: string };\n try {\n // Ensure the isolated context is initialized\n getIsolatedBabel();\n\n // Create a script that calls transform with our options\n // This runs in the isolated context with timeout\n const transformScript = new vm.Script(`\n __babel_result__ = __babel_transform__(__babel_code__, __babel_options__);\n `);\n\n // Inject the code and options into the isolated context\n Object.defineProperty(isolatedContext!, '__babel_code__', {\n value: code,\n writable: true,\n configurable: true,\n enumerable: false,\n });\n Object.defineProperty(isolatedContext!, '__babel_options__', {\n value: safeOptions,\n writable: true,\n configurable: true,\n enumerable: false,\n });\n Object.defineProperty(isolatedContext!, '__babel_result__', {\n value: null,\n writable: true,\n configurable: true,\n enumerable: false,\n });\n\n // Run with timeout\n transformScript.runInContext(isolatedContext!, {\n timeout: config.transformTimeout,\n });\n\n // Get the result\n result = (isolatedContext as Record<string, unknown>)['__babel_result__'] as { code: string };\n\n // Clean up temporary variables\n delete (isolatedContext as Record<string, unknown>)['__babel_code__'];\n delete (isolatedContext as Record<string, unknown>)['__babel_options__'];\n delete (isolatedContext as Record<string, unknown>)['__babel_result__'];\n } catch (error) {\n // Re-throw with sanitized message (remove file paths)\n const err = error as Error;\n const sanitizedMessage = (err.message || 'Unknown transform error')\n .replace(/\\/[^\\s:]+/g, '<path>') // Remove file paths\n .replace(/at\\s+[^\\s]+\\s+\\([^)]+\\)/g, '') // Remove stack locations\n .replace(/evalmachine\\.<anonymous>/g, '<transform>') // Remove VM internals\n .trim();\n\n // Check for timeout\n if (err.message?.includes('Script execution timed out')) {\n throw new Error(\n `Babel transform timed out after ${config.transformTimeout}ms. ` +\n `The code may be too complex or contain infinite loops.`,\n );\n }\n\n throw new Error(`Babel transform failed: ${sanitizedMessage}`);\n }\n\n // 9. Validate output\n let outputCode = result?.code ?? '';\n\n if (typeof outputCode !== 'string') {\n throw new Error('Transform produced invalid output');\n }\n\n // 10. Apply import rewriting if configured\n if (options?.importRewrite?.enabled) {\n try {\n const rewriteResult = rewriteImports(outputCode, options.importRewrite);\n outputCode = rewriteResult.code;\n } catch (rewriteError) {\n throw new Error(`Import rewrite failed: ${(rewriteError as Error).message}`);\n }\n }\n\n // 11. Check output size\n const outputBytes = Buffer.byteLength(outputCode, 'utf-8');\n if (outputBytes > config.maxOutputSize) {\n throw new Error(\n `Output exceeds maximum size (${outputBytes} bytes > ${config.maxOutputSize} bytes). ` +\n `The transformed code is too large.`,\n );\n }\n\n // 12. Return only the code (not AST, not source map, not metadata)\n return { code: outputCode };\n },\n };\n}\n\n/**\n * Get available presets in @babel/standalone\n *\n * This is useful for documentation and validation.\n * Note: Not all presets are allowed in the enclave - see BABEL_SECURITY_CONFIGS.\n */\nexport function getAvailableBabelPresets(): string[] {\n return ['env', 'react', 'typescript', 'flow'];\n}\n\n/**\n * Reset the isolated Babel context\n *\n * Useful for testing or if you want to ensure a fresh context.\n * Note: This is generally not needed as the context is reused for performance.\n */\nexport function resetBabelContext(): void {\n isolatedContext = null;\n babelInContext = null;\n}\n"]}
@@ -1,17 +0,0 @@
1
- "use strict";
2
- /**
3
- * Babel Transform Module for Enclave
4
- *
5
- * Provides secure Babel transformation capabilities inside the enclave sandbox.
6
- *
7
- * @packageDocumentation
8
- */
9
- Object.defineProperty(exports, "__esModule", { value: true });
10
- exports.transformMultiple = exports.resetBabelContext = exports.getAvailableBabelPresets = exports.createRestrictedBabel = void 0;
11
- var babel_wrapper_1 = require("./babel-wrapper");
12
- Object.defineProperty(exports, "createRestrictedBabel", { enumerable: true, get: function () { return babel_wrapper_1.createRestrictedBabel; } });
13
- Object.defineProperty(exports, "getAvailableBabelPresets", { enumerable: true, get: function () { return babel_wrapper_1.getAvailableBabelPresets; } });
14
- Object.defineProperty(exports, "resetBabelContext", { enumerable: true, get: function () { return babel_wrapper_1.resetBabelContext; } });
15
- var multi_file_transform_1 = require("./multi-file-transform");
16
- Object.defineProperty(exports, "transformMultiple", { enumerable: true, get: function () { return multi_file_transform_1.transformMultiple; } });
17
- //# sourceMappingURL=index.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/babel/index.ts"],"names":[],"mappings":";AAAA;;;;;;GAMG;;;AAEH,iDAOyB;AANvB,sHAAA,qBAAqB,OAAA;AACrB,yHAAA,wBAAwB,OAAA;AACxB,kHAAA,iBAAiB,OAAA;AAMnB,+DAMgC;AAL9B,yHAAA,iBAAiB,OAAA","sourcesContent":["/**\n * Babel Transform Module for Enclave\n *\n * Provides secure Babel transformation capabilities inside the enclave sandbox.\n *\n * @packageDocumentation\n */\n\nexport {\n createRestrictedBabel,\n getAvailableBabelPresets,\n resetBabelContext,\n type SafeTransformOptions,\n type SafeTransformResult,\n type BabelWrapperConfig,\n} from './babel-wrapper';\n\nexport {\n transformMultiple,\n type MultiFileInput,\n type MultiFileTransformOptions,\n type MultiFileTransformResult,\n type MultiFileLimits,\n} from './multi-file-transform';\n"]}