@secure-exec/core 0.1.1-rc.3 → 0.2.0-rc.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 (102) hide show
  1. package/dist/esm-compiler.d.ts +5 -1
  2. package/dist/esm-compiler.js +5 -1
  3. package/dist/fs-helpers.d.ts +1 -1
  4. package/dist/generated/isolate-runtime.d.ts +15 -15
  5. package/dist/generated/isolate-runtime.js +15 -15
  6. package/dist/index.d.ts +24 -5
  7. package/dist/index.js +23 -3
  8. package/dist/isolate-runtime/apply-custom-global-policy.js +3 -3
  9. package/dist/isolate-runtime/apply-timing-mitigation-freeze.js +2 -2
  10. package/dist/isolate-runtime/apply-timing-mitigation-off.js +2 -2
  11. package/dist/isolate-runtime/bridge-attach.js +2 -2
  12. package/dist/isolate-runtime/bridge-initial-globals.js +145 -6
  13. package/dist/isolate-runtime/eval-script-result.js +1 -1
  14. package/dist/isolate-runtime/global-exposure-helpers.js +2 -2
  15. package/dist/isolate-runtime/init-commonjs-module-globals.js +2 -2
  16. package/dist/isolate-runtime/override-process-cwd.js +1 -1
  17. package/dist/isolate-runtime/override-process-env.js +1 -1
  18. package/dist/isolate-runtime/require-setup.js +2868 -494
  19. package/dist/isolate-runtime/set-commonjs-file-globals.js +2 -2
  20. package/dist/isolate-runtime/set-stdin-data.js +1 -1
  21. package/dist/isolate-runtime/setup-dynamic-import.js +78 -19
  22. package/dist/isolate-runtime/setup-fs-facade.js +62 -23
  23. package/dist/kernel/command-registry.d.ts +44 -0
  24. package/dist/kernel/command-registry.js +114 -0
  25. package/dist/kernel/device-layer.d.ts +12 -0
  26. package/dist/kernel/device-layer.js +262 -0
  27. package/dist/kernel/dns-cache.d.ts +29 -0
  28. package/dist/kernel/dns-cache.js +52 -0
  29. package/dist/kernel/fd-table.d.ts +84 -0
  30. package/dist/kernel/fd-table.js +278 -0
  31. package/dist/kernel/file-lock.d.ts +34 -0
  32. package/dist/kernel/file-lock.js +122 -0
  33. package/dist/kernel/host-adapter.d.ts +50 -0
  34. package/dist/kernel/host-adapter.js +8 -0
  35. package/dist/kernel/index.d.ts +36 -0
  36. package/dist/kernel/index.js +34 -0
  37. package/dist/kernel/inode-table.d.ts +43 -0
  38. package/dist/kernel/inode-table.js +85 -0
  39. package/dist/kernel/kernel.d.ts +9 -0
  40. package/dist/kernel/kernel.js +1393 -0
  41. package/dist/kernel/permissions.d.ts +27 -0
  42. package/dist/kernel/permissions.js +118 -0
  43. package/dist/kernel/pipe-manager.d.ts +64 -0
  44. package/dist/kernel/pipe-manager.js +267 -0
  45. package/dist/kernel/proc-layer.d.ts +11 -0
  46. package/dist/kernel/proc-layer.js +501 -0
  47. package/dist/kernel/process-table.d.ts +124 -0
  48. package/dist/kernel/process-table.js +631 -0
  49. package/dist/kernel/pty.d.ts +108 -0
  50. package/dist/kernel/pty.js +541 -0
  51. package/dist/kernel/socket-table.d.ts +312 -0
  52. package/dist/kernel/socket-table.js +1188 -0
  53. package/dist/kernel/timer-table.d.ts +54 -0
  54. package/dist/kernel/timer-table.js +108 -0
  55. package/dist/kernel/types.d.ts +500 -0
  56. package/dist/kernel/types.js +89 -0
  57. package/dist/kernel/user.d.ts +29 -0
  58. package/dist/kernel/user.js +35 -0
  59. package/dist/kernel/vfs.d.ts +54 -0
  60. package/dist/kernel/vfs.js +8 -0
  61. package/dist/kernel/wait.d.ts +45 -0
  62. package/dist/kernel/wait.js +112 -0
  63. package/dist/kernel/wstatus.d.ts +21 -0
  64. package/dist/kernel/wstatus.js +33 -0
  65. package/dist/module-resolver.d.ts +4 -0
  66. package/dist/module-resolver.js +4 -0
  67. package/dist/package-bundler.d.ts +6 -1
  68. package/dist/runtime-driver.d.ts +3 -1
  69. package/dist/shared/bridge-contract.d.ts +349 -22
  70. package/dist/shared/bridge-contract.js +62 -5
  71. package/dist/shared/console-formatter.js +8 -4
  72. package/dist/shared/global-exposure.js +364 -19
  73. package/dist/shared/in-memory-fs.d.ts +33 -11
  74. package/dist/shared/in-memory-fs.js +439 -130
  75. package/dist/shared/permissions.d.ts +4 -6
  76. package/dist/shared/permissions.js +19 -39
  77. package/dist/types.d.ts +8 -159
  78. package/dist/types.js +5 -0
  79. package/package.json +12 -22
  80. package/dist/bridge/active-handles.d.ts +0 -22
  81. package/dist/bridge/active-handles.js +0 -55
  82. package/dist/bridge/child-process.d.ts +0 -99
  83. package/dist/bridge/child-process.js +0 -670
  84. package/dist/bridge/fs.d.ts +0 -281
  85. package/dist/bridge/fs.js +0 -2235
  86. package/dist/bridge/index.d.ts +0 -10
  87. package/dist/bridge/index.js +0 -41
  88. package/dist/bridge/module.d.ts +0 -75
  89. package/dist/bridge/module.js +0 -308
  90. package/dist/bridge/network.d.ts +0 -350
  91. package/dist/bridge/network.js +0 -2050
  92. package/dist/bridge/os.d.ts +0 -13
  93. package/dist/bridge/os.js +0 -256
  94. package/dist/bridge/polyfills.d.ts +0 -2
  95. package/dist/bridge/polyfills.js +0 -11
  96. package/dist/bridge/process.d.ts +0 -89
  97. package/dist/bridge/process.js +0 -1015
  98. package/dist/bridge.js +0 -12496
  99. package/dist/python-runtime.d.ts +0 -16
  100. package/dist/python-runtime.js +0 -45
  101. package/dist/runtime.d.ts +0 -31
  102. package/dist/runtime.js +0 -69
@@ -1,1015 +0,0 @@
1
- // Process module polyfill for isolated-vm
2
- // Provides Node.js process object and global polyfills for sandbox compatibility
3
- // Re-export TextEncoder/TextDecoder from polyfills (polyfills.ts is imported first in index.ts)
4
- import { TextEncoder, TextDecoder } from "./polyfills.js";
5
- // Use whatwg-url for spec-compliant URL implementation
6
- import { URL as WhatwgURL, URLSearchParams as WhatwgURLSearchParams } from "whatwg-url";
7
- // Use buffer package for spec-compliant Buffer implementation
8
- import { Buffer as BufferPolyfill } from "buffer";
9
- import { exposeCustomGlobal, exposeMutableRuntimeStateGlobal, } from "../shared/global-exposure.js";
10
- // Get config with defaults
11
- const config = {
12
- platform: (typeof _processConfig !== "undefined" && _processConfig.platform) ||
13
- "linux",
14
- arch: (typeof _processConfig !== "undefined" && _processConfig.arch) || "x64",
15
- version: (typeof _processConfig !== "undefined" && _processConfig.version) ||
16
- "v22.0.0",
17
- cwd: (typeof _processConfig !== "undefined" && _processConfig.cwd) || "/root",
18
- env: (typeof _processConfig !== "undefined" && _processConfig.env) || {},
19
- argv: (typeof _processConfig !== "undefined" && _processConfig.argv) || [
20
- "node",
21
- "script.js",
22
- ],
23
- execPath: (typeof _processConfig !== "undefined" && _processConfig.execPath) ||
24
- "/usr/bin/node",
25
- pid: (typeof _processConfig !== "undefined" && _processConfig.pid) || 1,
26
- ppid: (typeof _processConfig !== "undefined" && _processConfig.ppid) || 0,
27
- uid: (typeof _processConfig !== "undefined" && _processConfig.uid) || 0,
28
- gid: (typeof _processConfig !== "undefined" && _processConfig.gid) || 0,
29
- timingMitigation: (typeof _processConfig !== "undefined" && _processConfig.timingMitigation) ||
30
- "off",
31
- frozenTimeMs: typeof _processConfig !== "undefined" ? _processConfig.frozenTimeMs : undefined,
32
- };
33
- /** Get the current timestamp, returning a frozen value when timing mitigation is active. */
34
- function getNowMs() {
35
- if (config.timingMitigation === "freeze" &&
36
- typeof config.frozenTimeMs === "number") {
37
- return config.frozenTimeMs;
38
- }
39
- return typeof performance !== "undefined" && performance.now
40
- ? performance.now()
41
- : Date.now();
42
- }
43
- // Start time for uptime calculation
44
- const _processStartTime = getNowMs();
45
- const BUFFER_MAX_LENGTH = typeof BufferPolyfill.kMaxLength ===
46
- "number"
47
- ? BufferPolyfill.kMaxLength
48
- : 2147483647;
49
- const BUFFER_MAX_STRING_LENGTH = typeof BufferPolyfill.kStringMaxLength ===
50
- "number"
51
- ? BufferPolyfill.kStringMaxLength
52
- : 536870888;
53
- const BUFFER_CONSTANTS = Object.freeze({
54
- MAX_LENGTH: BUFFER_MAX_LENGTH,
55
- MAX_STRING_LENGTH: BUFFER_MAX_STRING_LENGTH,
56
- });
57
- const bufferPolyfillMutable = BufferPolyfill;
58
- if (typeof bufferPolyfillMutable.kMaxLength !== "number") {
59
- bufferPolyfillMutable.kMaxLength = BUFFER_MAX_LENGTH;
60
- }
61
- if (typeof bufferPolyfillMutable.kStringMaxLength !== "number") {
62
- bufferPolyfillMutable.kStringMaxLength = BUFFER_MAX_STRING_LENGTH;
63
- }
64
- if (typeof bufferPolyfillMutable.constants !== "object" ||
65
- bufferPolyfillMutable.constants === null) {
66
- bufferPolyfillMutable.constants = {
67
- MAX_LENGTH: BUFFER_MAX_LENGTH,
68
- MAX_STRING_LENGTH: BUFFER_MAX_STRING_LENGTH,
69
- };
70
- }
71
- // Exit code tracking
72
- let _exitCode = 0;
73
- let _exited = false;
74
- /**
75
- * Thrown by `process.exit()` to unwind the sandbox call stack. The host
76
- * catches this to extract the exit code without killing the isolate.
77
- */
78
- export class ProcessExitError extends Error {
79
- code;
80
- constructor(code) {
81
- super("process.exit(" + code + ")");
82
- this.name = "ProcessExitError";
83
- this.code = code;
84
- }
85
- }
86
- // Make available globally
87
- exposeCustomGlobal("ProcessExitError", ProcessExitError);
88
- // Signal name → number mapping (POSIX standard)
89
- const _signalNumbers = {
90
- SIGHUP: 1, SIGINT: 2, SIGQUIT: 3, SIGILL: 4, SIGTRAP: 5, SIGABRT: 6,
91
- SIGBUS: 7, SIGFPE: 8, SIGKILL: 9, SIGUSR1: 10, SIGSEGV: 11, SIGUSR2: 12,
92
- SIGPIPE: 13, SIGALRM: 14, SIGTERM: 15, SIGCHLD: 17, SIGCONT: 18,
93
- SIGSTOP: 19, SIGTSTP: 20, SIGTTIN: 21, SIGTTOU: 22, SIGURG: 23,
94
- SIGXCPU: 24, SIGXFSZ: 25, SIGVTALRM: 26, SIGPROF: 27, SIGWINCH: 28,
95
- SIGIO: 29, SIGPWR: 30, SIGSYS: 31,
96
- };
97
- function _resolveSignal(signal) {
98
- if (signal === undefined || signal === null)
99
- return 15; // default SIGTERM
100
- if (typeof signal === "number")
101
- return signal;
102
- const num = _signalNumbers[signal];
103
- if (num !== undefined)
104
- return num;
105
- throw new Error("Unknown signal: " + signal);
106
- }
107
- const _processListeners = {};
108
- const _processOnceListeners = {};
109
- let _processMaxListeners = 10;
110
- const _processMaxListenersWarned = new Set();
111
- function _addListener(event, listener, once = false) {
112
- const target = once ? _processOnceListeners : _processListeners;
113
- if (!target[event]) {
114
- target[event] = [];
115
- }
116
- target[event].push(listener);
117
- // Warn when exceeding maxListeners (Node.js behavior: warn, don't crash)
118
- if (_processMaxListeners > 0 && !_processMaxListenersWarned.has(event)) {
119
- const total = (_processListeners[event]?.length ?? 0) + (_processOnceListeners[event]?.length ?? 0);
120
- if (total > _processMaxListeners) {
121
- _processMaxListenersWarned.add(event);
122
- const warning = `MaxListenersExceededWarning: Possible EventEmitter memory leak detected. ${total} ${event} listeners added to [process]. MaxListeners is ${_processMaxListeners}. Use emitter.setMaxListeners() to increase limit`;
123
- // Use console.error to emit warning without recursion risk
124
- if (typeof _error !== "undefined") {
125
- _error.applySync(undefined, [warning]);
126
- }
127
- }
128
- }
129
- return process;
130
- }
131
- function _removeListener(event, listener) {
132
- if (_processListeners[event]) {
133
- const idx = _processListeners[event].indexOf(listener);
134
- if (idx !== -1)
135
- _processListeners[event].splice(idx, 1);
136
- }
137
- if (_processOnceListeners[event]) {
138
- const idx = _processOnceListeners[event].indexOf(listener);
139
- if (idx !== -1)
140
- _processOnceListeners[event].splice(idx, 1);
141
- }
142
- return process;
143
- }
144
- function _emit(event, ...args) {
145
- let handled = false;
146
- // Regular listeners
147
- if (_processListeners[event]) {
148
- for (const listener of _processListeners[event]) {
149
- listener(...args);
150
- handled = true;
151
- }
152
- }
153
- // Once listeners (remove after calling)
154
- if (_processOnceListeners[event]) {
155
- const listeners = _processOnceListeners[event].slice();
156
- _processOnceListeners[event] = [];
157
- for (const listener of listeners) {
158
- listener(...args);
159
- handled = true;
160
- }
161
- }
162
- return handled;
163
- }
164
- // Resolve isTTY flags from config
165
- const _stdinIsTTY = (typeof _processConfig !== "undefined" && _processConfig.stdinIsTTY) || false;
166
- const _stdoutIsTTY = (typeof _processConfig !== "undefined" && _processConfig.stdoutIsTTY) || false;
167
- const _stderrIsTTY = (typeof _processConfig !== "undefined" && _processConfig.stderrIsTTY) || false;
168
- // Stdout stream
169
- const _stdout = {
170
- write(data) {
171
- if (typeof _log !== "undefined") {
172
- _log.applySync(undefined, [String(data).replace(/\n$/, "")]);
173
- }
174
- return true;
175
- },
176
- end() {
177
- return this;
178
- },
179
- on() {
180
- return this;
181
- },
182
- once() {
183
- return this;
184
- },
185
- emit() {
186
- return false;
187
- },
188
- writable: true,
189
- isTTY: _stdoutIsTTY,
190
- columns: 80,
191
- rows: 24,
192
- };
193
- // Stderr stream
194
- const _stderr = {
195
- write(data) {
196
- if (typeof _error !== "undefined") {
197
- _error.applySync(undefined, [String(data).replace(/\n$/, "")]);
198
- }
199
- return true;
200
- },
201
- end() {
202
- return this;
203
- },
204
- on() {
205
- return this;
206
- },
207
- once() {
208
- return this;
209
- },
210
- emit() {
211
- return false;
212
- },
213
- writable: true,
214
- isTTY: _stderrIsTTY,
215
- columns: 80,
216
- rows: 24,
217
- };
218
- const _stdinListeners = {};
219
- const _stdinOnceListeners = {};
220
- // Initialize stdin state as globals for external access
221
- exposeMutableRuntimeStateGlobal("_stdinData", (typeof _processConfig !== "undefined" && _processConfig.stdin) || "");
222
- exposeMutableRuntimeStateGlobal("_stdinPosition", 0);
223
- exposeMutableRuntimeStateGlobal("_stdinEnded", false);
224
- exposeMutableRuntimeStateGlobal("_stdinFlowMode", false);
225
- // Getters for the globals
226
- function getStdinData() { return globalThis._stdinData; }
227
- function setStdinDataValue(v) { globalThis._stdinData = v; }
228
- function getStdinPosition() { return globalThis._stdinPosition; }
229
- function setStdinPosition(v) { globalThis._stdinPosition = v; }
230
- function getStdinEnded() { return globalThis._stdinEnded; }
231
- function setStdinEnded(v) { globalThis._stdinEnded = v; }
232
- function getStdinFlowMode() { return globalThis._stdinFlowMode; }
233
- function setStdinFlowMode(v) { globalThis._stdinFlowMode = v; }
234
- function _emitStdinData() {
235
- if (getStdinEnded() || !getStdinData())
236
- return;
237
- // In flowing mode, emit all remaining data
238
- if (getStdinFlowMode() && getStdinPosition() < getStdinData().length) {
239
- const chunk = getStdinData().slice(getStdinPosition());
240
- setStdinPosition(getStdinData().length);
241
- // Emit data event
242
- const dataListeners = [...(_stdinListeners["data"] || []), ...(_stdinOnceListeners["data"] || [])];
243
- _stdinOnceListeners["data"] = [];
244
- for (const listener of dataListeners) {
245
- listener(chunk);
246
- }
247
- // Emit end after all data
248
- setStdinEnded(true);
249
- const endListeners = [...(_stdinListeners["end"] || []), ...(_stdinOnceListeners["end"] || [])];
250
- _stdinOnceListeners["end"] = [];
251
- for (const listener of endListeners) {
252
- listener();
253
- }
254
- // Emit close
255
- const closeListeners = [...(_stdinListeners["close"] || []), ...(_stdinOnceListeners["close"] || [])];
256
- _stdinOnceListeners["close"] = [];
257
- for (const listener of closeListeners) {
258
- listener();
259
- }
260
- }
261
- }
262
- const _stdin = {
263
- readable: true,
264
- paused: true,
265
- encoding: null,
266
- read(size) {
267
- if (getStdinPosition() >= getStdinData().length)
268
- return null;
269
- const chunk = size ? getStdinData().slice(getStdinPosition(), getStdinPosition() + size) : getStdinData().slice(getStdinPosition());
270
- setStdinPosition(getStdinPosition() + chunk.length);
271
- return chunk;
272
- },
273
- on(event, listener) {
274
- if (!_stdinListeners[event])
275
- _stdinListeners[event] = [];
276
- _stdinListeners[event].push(listener);
277
- // When 'end' listener is added and we have data, emit everything synchronously
278
- // This works because typical patterns register 'data' then 'end' listeners
279
- if (event === "end" && getStdinData() && !getStdinEnded()) {
280
- setStdinFlowMode(true);
281
- // Emit synchronously - all listeners should be registered by now
282
- _emitStdinData();
283
- }
284
- return this;
285
- },
286
- once(event, listener) {
287
- if (!_stdinOnceListeners[event])
288
- _stdinOnceListeners[event] = [];
289
- _stdinOnceListeners[event].push(listener);
290
- return this;
291
- },
292
- off(event, listener) {
293
- if (_stdinListeners[event]) {
294
- const idx = _stdinListeners[event].indexOf(listener);
295
- if (idx !== -1)
296
- _stdinListeners[event].splice(idx, 1);
297
- }
298
- return this;
299
- },
300
- removeListener(event, listener) {
301
- return this.off(event, listener);
302
- },
303
- emit(event, ...args) {
304
- const listeners = [...(_stdinListeners[event] || []), ...(_stdinOnceListeners[event] || [])];
305
- _stdinOnceListeners[event] = [];
306
- for (const listener of listeners) {
307
- listener(args[0]);
308
- }
309
- return listeners.length > 0;
310
- },
311
- pause() {
312
- this.paused = true;
313
- setStdinFlowMode(false);
314
- return this;
315
- },
316
- resume() {
317
- this.paused = false;
318
- setStdinFlowMode(true);
319
- _emitStdinData();
320
- return this;
321
- },
322
- setEncoding(enc) {
323
- this.encoding = enc;
324
- return this;
325
- },
326
- setRawMode(mode) {
327
- if (!_stdinIsTTY) {
328
- throw new Error("setRawMode is not supported when stdin is not a TTY");
329
- }
330
- if (typeof _ptySetRawMode !== "undefined") {
331
- _ptySetRawMode.applySync(undefined, [mode]);
332
- }
333
- return this;
334
- },
335
- isTTY: _stdinIsTTY,
336
- // For readline compatibility
337
- [Symbol.asyncIterator]: async function* () {
338
- const lines = getStdinData().split("\n");
339
- for (const line of lines) {
340
- if (line)
341
- yield line;
342
- }
343
- },
344
- };
345
- // hrtime function with bigint method
346
- function hrtime(prev) {
347
- const now = getNowMs();
348
- const seconds = Math.floor(now / 1000);
349
- const nanoseconds = Math.floor((now % 1000) * 1e6);
350
- if (prev) {
351
- let diffSec = seconds - prev[0];
352
- let diffNano = nanoseconds - prev[1];
353
- if (diffNano < 0) {
354
- diffSec -= 1;
355
- diffNano += 1e9;
356
- }
357
- return [diffSec, diffNano];
358
- }
359
- return [seconds, nanoseconds];
360
- }
361
- hrtime.bigint = function () {
362
- const now = getNowMs();
363
- return BigInt(Math.floor(now * 1e6));
364
- };
365
- // Internal state
366
- let _cwd = config.cwd;
367
- let _umask = 0o022;
368
- // The process object — typed loosely as a polyfill, cast to typeof nodeProcess on export
369
- const process = {
370
- // Static properties
371
- platform: config.platform,
372
- arch: config.arch,
373
- version: config.version,
374
- versions: {
375
- node: config.version.replace(/^v/, ""),
376
- v8: "11.3.244.8",
377
- uv: "1.44.2",
378
- zlib: "1.2.13",
379
- brotli: "1.0.9",
380
- ares: "1.19.0",
381
- modules: "108",
382
- nghttp2: "1.52.0",
383
- napi: "8",
384
- llhttp: "8.1.0",
385
- openssl: "3.0.8",
386
- cldr: "42.0",
387
- icu: "72.1",
388
- tz: "2022g",
389
- unicode: "15.0",
390
- },
391
- pid: config.pid,
392
- ppid: config.ppid,
393
- execPath: config.execPath,
394
- execArgv: [],
395
- argv: config.argv,
396
- argv0: config.argv[0] || "node",
397
- title: "node",
398
- env: config.env,
399
- // Config stubs
400
- config: {
401
- target_defaults: {
402
- cflags: [],
403
- default_configuration: "Release",
404
- defines: [],
405
- include_dirs: [],
406
- libraries: [],
407
- },
408
- variables: {
409
- node_prefix: "/usr",
410
- node_shared_libuv: false,
411
- },
412
- },
413
- release: {
414
- name: "node",
415
- sourceUrl: "https://nodejs.org/download/release/v20.0.0/node-v20.0.0.tar.gz",
416
- headersUrl: "https://nodejs.org/download/release/v20.0.0/node-v20.0.0-headers.tar.gz",
417
- },
418
- // Feature flags
419
- features: {
420
- inspector: false,
421
- debug: false,
422
- uv: true,
423
- ipv6: true,
424
- tls_alpn: true,
425
- tls_sni: true,
426
- tls_ocsp: true,
427
- tls: true,
428
- },
429
- // Methods
430
- cwd() {
431
- return _cwd;
432
- },
433
- chdir(dir) {
434
- // Validate directory exists in VFS before setting cwd
435
- let statJson;
436
- try {
437
- statJson = _fs.stat.applySyncPromise(undefined, [dir]);
438
- }
439
- catch {
440
- const err = new Error(`ENOENT: no such file or directory, chdir '${dir}'`);
441
- err.code = "ENOENT";
442
- err.errno = -2;
443
- err.syscall = "chdir";
444
- err.path = dir;
445
- throw err;
446
- }
447
- const parsed = JSON.parse(statJson);
448
- if (!parsed.isDirectory) {
449
- const err = new Error(`ENOTDIR: not a directory, chdir '${dir}'`);
450
- err.code = "ENOTDIR";
451
- err.errno = -20;
452
- err.syscall = "chdir";
453
- err.path = dir;
454
- throw err;
455
- }
456
- _cwd = dir;
457
- },
458
- get exitCode() {
459
- return _exitCode;
460
- },
461
- set exitCode(code) {
462
- _exitCode = code ?? 0;
463
- },
464
- exit(code) {
465
- const exitCode = code !== undefined ? code : _exitCode;
466
- _exitCode = exitCode;
467
- _exited = true;
468
- // Fire exit event
469
- try {
470
- _emit("exit", exitCode);
471
- }
472
- catch (_e) {
473
- // Ignore errors in exit handlers
474
- }
475
- // Throw to stop execution
476
- throw new ProcessExitError(exitCode);
477
- },
478
- abort() {
479
- return process.exit(1);
480
- },
481
- nextTick(callback, ...args) {
482
- if (typeof queueMicrotask === "function") {
483
- queueMicrotask(() => callback(...args));
484
- }
485
- else {
486
- Promise.resolve().then(() => callback(...args));
487
- }
488
- },
489
- hrtime: hrtime,
490
- getuid() {
491
- return config.uid;
492
- },
493
- getgid() {
494
- return config.gid;
495
- },
496
- geteuid() {
497
- return config.uid;
498
- },
499
- getegid() {
500
- return config.gid;
501
- },
502
- getgroups() {
503
- return [config.gid];
504
- },
505
- setuid() { },
506
- setgid() { },
507
- seteuid() { },
508
- setegid() { },
509
- setgroups() { },
510
- umask(mask) {
511
- const oldMask = _umask;
512
- if (mask !== undefined) {
513
- _umask = mask;
514
- }
515
- return oldMask;
516
- },
517
- uptime() {
518
- return (getNowMs() - _processStartTime) / 1000;
519
- },
520
- memoryUsage() {
521
- return {
522
- rss: 50 * 1024 * 1024,
523
- heapTotal: 20 * 1024 * 1024,
524
- heapUsed: 10 * 1024 * 1024,
525
- external: 1 * 1024 * 1024,
526
- arrayBuffers: 500 * 1024,
527
- };
528
- },
529
- cpuUsage(prev) {
530
- const usage = {
531
- user: 1000000,
532
- system: 500000,
533
- };
534
- if (prev) {
535
- return {
536
- user: usage.user - prev.user,
537
- system: usage.system - prev.system,
538
- };
539
- }
540
- return usage;
541
- },
542
- resourceUsage() {
543
- return {
544
- userCPUTime: 1000000,
545
- systemCPUTime: 500000,
546
- maxRSS: 50 * 1024,
547
- sharedMemorySize: 0,
548
- unsharedDataSize: 0,
549
- unsharedStackSize: 0,
550
- minorPageFault: 0,
551
- majorPageFault: 0,
552
- swappedOut: 0,
553
- fsRead: 0,
554
- fsWrite: 0,
555
- ipcSent: 0,
556
- ipcReceived: 0,
557
- signalsCount: 0,
558
- voluntaryContextSwitches: 0,
559
- involuntaryContextSwitches: 0,
560
- };
561
- },
562
- kill(pid, signal) {
563
- if (pid !== process.pid) {
564
- const err = new Error("Operation not permitted");
565
- err.code = "EPERM";
566
- err.errno = -1;
567
- err.syscall = "kill";
568
- throw err;
569
- }
570
- // Resolve signal name to number (default SIGTERM)
571
- const sigNum = _resolveSignal(signal);
572
- // Self-kill - exit with 128 + signal number (POSIX convention)
573
- return process.exit(128 + sigNum);
574
- },
575
- // EventEmitter methods
576
- on(event, listener) {
577
- return _addListener(event, listener);
578
- },
579
- once(event, listener) {
580
- return _addListener(event, listener, true);
581
- },
582
- removeListener(event, listener) {
583
- return _removeListener(event, listener);
584
- },
585
- // off is an alias for removeListener (assigned below to be same reference)
586
- off: null,
587
- removeAllListeners(event) {
588
- if (event) {
589
- delete _processListeners[event];
590
- delete _processOnceListeners[event];
591
- }
592
- else {
593
- Object.keys(_processListeners).forEach((k) => delete _processListeners[k]);
594
- Object.keys(_processOnceListeners).forEach((k) => delete _processOnceListeners[k]);
595
- }
596
- return process;
597
- },
598
- addListener(event, listener) {
599
- return _addListener(event, listener);
600
- },
601
- emit(event, ...args) {
602
- return _emit(event, ...args);
603
- },
604
- listeners(event) {
605
- return [
606
- ...(_processListeners[event] || []),
607
- ...(_processOnceListeners[event] || []),
608
- ];
609
- },
610
- listenerCount(event) {
611
- return ((_processListeners[event] || []).length +
612
- (_processOnceListeners[event] || []).length);
613
- },
614
- prependListener(event, listener) {
615
- if (!_processListeners[event]) {
616
- _processListeners[event] = [];
617
- }
618
- _processListeners[event].unshift(listener);
619
- return process;
620
- },
621
- prependOnceListener(event, listener) {
622
- if (!_processOnceListeners[event]) {
623
- _processOnceListeners[event] = [];
624
- }
625
- _processOnceListeners[event].unshift(listener);
626
- return process;
627
- },
628
- eventNames() {
629
- return [
630
- ...new Set([
631
- ...Object.keys(_processListeners),
632
- ...Object.keys(_processOnceListeners),
633
- ]),
634
- ];
635
- },
636
- setMaxListeners(n) {
637
- _processMaxListeners = n;
638
- return process;
639
- },
640
- getMaxListeners() {
641
- return _processMaxListeners;
642
- },
643
- rawListeners(event) {
644
- return process.listeners(event);
645
- },
646
- // Stdio streams
647
- stdout: _stdout,
648
- stderr: _stderr,
649
- stdin: _stdin,
650
- // Process state
651
- connected: false,
652
- // Module info (will be set by createRequire)
653
- mainModule: undefined,
654
- // No-op methods for compatibility
655
- emitWarning(warning) {
656
- const msg = typeof warning === "string" ? warning : warning.message;
657
- _emit("warning", { message: msg, name: "Warning" });
658
- },
659
- binding(_name) {
660
- throw new Error("process.binding is not supported in sandbox");
661
- },
662
- _linkedBinding(_name) {
663
- throw new Error("process._linkedBinding is not supported in sandbox");
664
- },
665
- dlopen() {
666
- throw new Error("process.dlopen is not supported");
667
- },
668
- hasUncaughtExceptionCaptureCallback() {
669
- return false;
670
- },
671
- setUncaughtExceptionCaptureCallback() { },
672
- // Send for IPC (no-op)
673
- send() {
674
- return false;
675
- },
676
- disconnect() { },
677
- // Report
678
- report: {
679
- directory: "",
680
- filename: "",
681
- compact: false,
682
- signal: "SIGUSR2",
683
- reportOnFatalError: false,
684
- reportOnSignal: false,
685
- reportOnUncaughtException: false,
686
- getReport() {
687
- return {};
688
- },
689
- writeReport() {
690
- return "";
691
- },
692
- },
693
- // Debug port
694
- debugPort: 9229,
695
- // Internal state
696
- _cwd: config.cwd,
697
- _umask: 0o022,
698
- };
699
- // Make process.off === process.removeListener (same function reference)
700
- process.off = process.removeListener;
701
- // Add memoryUsage.rss
702
- process.memoryUsage.rss =
703
- function () {
704
- return 50 * 1024 * 1024;
705
- };
706
- // Match Node.js Object.prototype.toString.call(process) === '[object process]'
707
- Object.defineProperty(process, Symbol.toStringTag, {
708
- value: "process",
709
- writable: false,
710
- configurable: true,
711
- enumerable: false,
712
- });
713
- export default process;
714
- // ============================================================================
715
- // Global polyfills
716
- // ============================================================================
717
- // Timer implementation
718
- let _timerId = 0;
719
- const _timers = new Map();
720
- const _intervals = new Map();
721
- /** Check timer budget. _maxTimers is injected by the host when resourceBudgets.maxTimers is set. */
722
- function _checkTimerBudget() {
723
- if (typeof _maxTimers !== "undefined" && (_timers.size + _intervals.size) >= _maxTimers) {
724
- throw new Error("ERR_RESOURCE_BUDGET_EXCEEDED: maximum number of timers exceeded");
725
- }
726
- }
727
- // queueMicrotask fallback
728
- const _queueMicrotask = typeof queueMicrotask === "function"
729
- ? queueMicrotask
730
- : function (fn) {
731
- Promise.resolve().then(fn);
732
- };
733
- /**
734
- * Timer handle that mimics Node.js Timeout (ref/unref/Symbol.toPrimitive).
735
- * Timers with delay > 0 use the host's `_scheduleTimer` bridge to sleep
736
- * without blocking the isolate's event loop.
737
- */
738
- class TimerHandle {
739
- _id;
740
- _destroyed;
741
- constructor(id) {
742
- this._id = id;
743
- this._destroyed = false;
744
- }
745
- ref() {
746
- return this;
747
- }
748
- unref() {
749
- return this;
750
- }
751
- hasRef() {
752
- return true;
753
- }
754
- refresh() {
755
- return this;
756
- }
757
- [Symbol.toPrimitive]() {
758
- return this._id;
759
- }
760
- }
761
- export function setTimeout(callback, delay, ...args) {
762
- _checkTimerBudget();
763
- const id = ++_timerId;
764
- const handle = new TimerHandle(id);
765
- _timers.set(id, handle);
766
- const actualDelay = delay ?? 0;
767
- // Use host timer for actual delays if available and delay > 0
768
- if (typeof _scheduleTimer !== "undefined" && actualDelay > 0) {
769
- // _scheduleTimer.apply() returns a Promise that resolves after the delay
770
- // Using { result: { promise: true } } tells isolated-vm to wait for the
771
- // host Promise to resolve before resolving the apply() Promise
772
- _scheduleTimer
773
- .apply(undefined, [actualDelay], { result: { promise: true } })
774
- .then(() => {
775
- if (_timers.has(id)) {
776
- _timers.delete(id);
777
- try {
778
- callback(...args);
779
- }
780
- catch (_e) {
781
- // Ignore timer callback errors
782
- }
783
- }
784
- });
785
- }
786
- else {
787
- // Use microtask for zero delay or when host timer is unavailable
788
- _queueMicrotask(() => {
789
- if (_timers.has(id)) {
790
- _timers.delete(id);
791
- try {
792
- callback(...args);
793
- }
794
- catch (_e) {
795
- // Ignore timer callback errors
796
- }
797
- }
798
- });
799
- }
800
- return handle;
801
- }
802
- export function clearTimeout(timer) {
803
- const id = timer && typeof timer === "object" && timer._id !== undefined
804
- ? timer._id
805
- : timer;
806
- _timers.delete(id);
807
- }
808
- export function setInterval(callback, delay, ...args) {
809
- _checkTimerBudget();
810
- const id = ++_timerId;
811
- const handle = new TimerHandle(id);
812
- _intervals.set(id, handle);
813
- // Enforce minimum 1ms delay to prevent microtask CPU spin
814
- const actualDelay = Math.max(1, delay ?? 0);
815
- // Schedule interval execution
816
- const scheduleNext = () => {
817
- if (!_intervals.has(id))
818
- return; // Interval was cleared
819
- if (typeof _scheduleTimer !== "undefined" && actualDelay > 0) {
820
- // Use host timer for actual delays
821
- _scheduleTimer
822
- .apply(undefined, [actualDelay], { result: { promise: true } })
823
- .then(() => {
824
- if (_intervals.has(id)) {
825
- try {
826
- callback(...args);
827
- }
828
- catch (_e) {
829
- // Ignore timer callback errors
830
- }
831
- // Schedule next iteration
832
- scheduleNext();
833
- }
834
- });
835
- }
836
- else {
837
- // Use microtask for zero delay or when host timer unavailable
838
- _queueMicrotask(() => {
839
- if (_intervals.has(id)) {
840
- try {
841
- callback(...args);
842
- }
843
- catch (_e) {
844
- // Ignore timer callback errors
845
- }
846
- // Schedule next iteration
847
- scheduleNext();
848
- }
849
- });
850
- }
851
- };
852
- // Start the interval
853
- scheduleNext();
854
- return handle;
855
- }
856
- export function clearInterval(timer) {
857
- const id = timer && typeof timer === "object" && timer._id !== undefined
858
- ? timer._id
859
- : timer;
860
- _intervals.delete(id);
861
- }
862
- export function setImmediate(callback, ...args) {
863
- return setTimeout(callback, 0, ...args);
864
- }
865
- export function clearImmediate(id) {
866
- clearTimeout(id);
867
- }
868
- // URL and URLSearchParams - use whatwg-url for spec-compliant implementation
869
- export const URL = WhatwgURL;
870
- export const URLSearchParams = WhatwgURLSearchParams;
871
- // TextEncoder and TextDecoder - re-export from polyfills
872
- export { TextEncoder, TextDecoder };
873
- // Buffer - use buffer package polyfill
874
- export const Buffer = BufferPolyfill;
875
- // Patch internal V8 Buffer slice/write methods used by native-protocol libraries
876
- // (ssh2, msgpack, protobuf, etc.). The polyfill supports these encodings through
877
- // toString()/write() but doesn't expose the fast-path internal methods.
878
- const bp = BufferPolyfill.prototype;
879
- const sliceEncodings = ["utf8", "ascii", "latin1", "binary", "hex", "base64", "ucs2", "utf16le"];
880
- for (const enc of sliceEncodings) {
881
- const sliceKey = `${enc}Slice`;
882
- if (typeof bp[sliceKey] !== "function") {
883
- bp[sliceKey] = function (start, end) {
884
- return this.toString(enc, start, end);
885
- };
886
- }
887
- const writeKey = `${enc}Write`;
888
- if (typeof bp[writeKey] !== "function") {
889
- bp[writeKey] = function (str, offset, length) {
890
- return this.write(str, offset, length, enc);
891
- };
892
- }
893
- }
894
- function throwUnsupportedCryptoApi(api) {
895
- throw new Error(`crypto.${api} is not supported in sandbox`);
896
- }
897
- /**
898
- * Crypto polyfill that delegates to the host for entropy. `getRandomValues`
899
- * calls the host's `_cryptoRandomFill` bridge to get cryptographically secure
900
- * random bytes. Subtle crypto operations are unsupported.
901
- */
902
- export const cryptoPolyfill = {
903
- getRandomValues(array) {
904
- if (typeof _cryptoRandomFill === "undefined") {
905
- throwUnsupportedCryptoApi("getRandomValues");
906
- }
907
- // Web Crypto API spec caps getRandomValues at 65536 bytes.
908
- if (array.byteLength > 65536) {
909
- throw new RangeError(`The ArrayBufferView's byte length (${array.byteLength}) exceeds the number of bytes of entropy available via this API (65536)`);
910
- }
911
- const bytes = new Uint8Array(array.buffer, array.byteOffset, array.byteLength);
912
- try {
913
- const base64 = _cryptoRandomFill.applySync(undefined, [bytes.byteLength]);
914
- const hostBytes = BufferPolyfill.from(base64, "base64");
915
- if (hostBytes.byteLength !== bytes.byteLength) {
916
- throw new Error("invalid host entropy size");
917
- }
918
- bytes.set(hostBytes);
919
- return array;
920
- }
921
- catch {
922
- throwUnsupportedCryptoApi("getRandomValues");
923
- }
924
- },
925
- randomUUID() {
926
- if (typeof _cryptoRandomUUID === "undefined") {
927
- throwUnsupportedCryptoApi("randomUUID");
928
- }
929
- try {
930
- const uuid = _cryptoRandomUUID.applySync(undefined, []);
931
- if (typeof uuid !== "string") {
932
- throw new Error("invalid host uuid");
933
- }
934
- return uuid;
935
- }
936
- catch {
937
- throwUnsupportedCryptoApi("randomUUID");
938
- }
939
- },
940
- subtle: {
941
- digest() {
942
- throw new Error("crypto.subtle.digest is not supported in sandbox");
943
- },
944
- encrypt() {
945
- throw new Error("crypto.subtle.encrypt is not supported in sandbox");
946
- },
947
- decrypt() {
948
- throw new Error("crypto.subtle.decrypt is not supported in sandbox");
949
- },
950
- },
951
- };
952
- /**
953
- * Install all process/timer/URL/Buffer/crypto polyfills onto `globalThis`.
954
- * Called once during bridge initialization before user code runs.
955
- */
956
- export function setupGlobals() {
957
- const g = globalThis;
958
- // Process - simple assignment is sufficient since we use external: ["process"]
959
- // in polyfills.ts, which prevents node-stdlib-browser's process shim from being
960
- // bundled and overwriting our process object.
961
- g.process = process;
962
- // Timers
963
- g.setTimeout = setTimeout;
964
- g.clearTimeout = clearTimeout;
965
- g.setInterval = setInterval;
966
- g.clearInterval = clearInterval;
967
- g.setImmediate = setImmediate;
968
- g.clearImmediate = clearImmediate;
969
- // queueMicrotask
970
- if (typeof g.queueMicrotask === "undefined") {
971
- g.queueMicrotask = _queueMicrotask;
972
- }
973
- // URL
974
- if (typeof g.URL === "undefined") {
975
- g.URL = URL;
976
- }
977
- if (typeof g.URLSearchParams === "undefined") {
978
- g.URLSearchParams = URLSearchParams;
979
- }
980
- // TextEncoder/TextDecoder
981
- if (typeof g.TextEncoder === "undefined") {
982
- g.TextEncoder = TextEncoder;
983
- }
984
- if (typeof g.TextDecoder === "undefined") {
985
- g.TextDecoder = TextDecoder;
986
- }
987
- // Buffer
988
- if (typeof g.Buffer === "undefined") {
989
- g.Buffer = Buffer;
990
- }
991
- const globalBuffer = g.Buffer;
992
- if (typeof globalBuffer.kMaxLength !== "number") {
993
- globalBuffer.kMaxLength = BUFFER_MAX_LENGTH;
994
- }
995
- if (typeof globalBuffer.kStringMaxLength !== "number") {
996
- globalBuffer.kStringMaxLength = BUFFER_MAX_STRING_LENGTH;
997
- }
998
- if (typeof globalBuffer.constants !== "object" ||
999
- globalBuffer.constants === null) {
1000
- globalBuffer.constants = BUFFER_CONSTANTS;
1001
- }
1002
- // Crypto
1003
- if (typeof g.crypto === "undefined") {
1004
- g.crypto = cryptoPolyfill;
1005
- }
1006
- else {
1007
- const cryptoObj = g.crypto;
1008
- if (typeof cryptoObj.getRandomValues === "undefined") {
1009
- cryptoObj.getRandomValues = cryptoPolyfill.getRandomValues;
1010
- }
1011
- if (typeof cryptoObj.randomUUID === "undefined") {
1012
- cryptoObj.randomUUID = cryptoPolyfill.randomUUID;
1013
- }
1014
- }
1015
- }