-
Notifications
You must be signed in to change notification settings - Fork 43
Expand file tree
/
Copy pathexecution-driver.ts
More file actions
1712 lines (1616 loc) · 59.4 KB
/
execution-driver.ts
File metadata and controls
1712 lines (1616 loc) · 59.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { createResolutionCache } from "./package-bundler.js";
import { getConsoleSetupCode } from "@secure-exec/core/internal/shared/console-formatter";
import { getRequireSetupCode } from "@secure-exec/core/internal/shared/require-setup";
import { getIsolateRuntimeSource, getInitialBridgeGlobalsSetupCode } from "@secure-exec/core";
import {
createCommandExecutorStub,
createFsStub,
createNetworkStub,
filterEnv,
wrapCommandExecutor,
wrapFileSystem,
wrapNetworkAdapter,
} from "@secure-exec/core/internal/shared/permissions";
import type { NetworkAdapter, RuntimeDriver } from "@secure-exec/core";
import type {
StdioHook,
ExecOptions,
ExecResult,
RunResult,
TimingMitigation,
} from "@secure-exec/core/internal/shared/api-types";
import type { V8ExecutionOptions, V8Runtime, V8Session, V8SessionOptions } from "@secure-exec/v8";
import { createV8Runtime } from "@secure-exec/v8";
import { getRawBridgeCode, getBridgeAttachCode } from "./bridge-loader.js";
import {
type NodeExecutionDriverOptions,
createBudgetState,
clearActiveHostTimers,
killActiveChildProcesses,
normalizePayloadLimit,
getExecutionTimeoutMs,
getTimingMitigation,
PAYLOAD_LIMIT_ERROR_CODE,
DEFAULT_BRIDGE_BASE64_TRANSFER_BYTES,
DEFAULT_ISOLATE_JSON_PAYLOAD_BYTES,
DEFAULT_MAX_TIMERS,
DEFAULT_MAX_HANDLES,
DEFAULT_SANDBOX_CWD,
DEFAULT_SANDBOX_HOME,
DEFAULT_SANDBOX_TMPDIR,
} from "./isolate-bootstrap.js";
import { transformSourceForRequireSync } from "./module-source.js";
import { shouldRunAsESM } from "./module-resolver.js";
import {
TIMEOUT_ERROR_MESSAGE,
TIMEOUT_EXIT_CODE,
ProcessTable,
SocketTable,
TimerTable,
} from "@secure-exec/core";
import {
type BridgeHandlers,
buildCryptoBridgeHandlers,
buildConsoleBridgeHandlers,
buildKernelHandleDispatchHandlers,
buildKernelStdinDispatchHandlers,
buildKernelTimerDispatchHandlers,
buildModuleLoadingBridgeHandlers,
buildMimeBridgeHandlers,
buildTimerBridgeHandlers,
buildFsBridgeHandlers,
buildKernelFdBridgeHandlers,
buildChildProcessBridgeHandlers,
buildNetworkBridgeHandlers,
buildNetworkSocketBridgeHandlers,
buildModuleResolutionBridgeHandlers,
buildPtyBridgeHandlers,
createProcessConfigForExecution,
resolveHttpServerResponse,
} from "./bridge-handlers.js";
import type {
Permissions,
VirtualFileSystem,
} from "@secure-exec/core";
import type {
CommandExecutor,
SpawnedProcess,
} from "@secure-exec/core";
import type { ResolutionCache } from "./package-bundler.js";
import type {
OSConfig,
ProcessConfig,
} from "@secure-exec/core/internal/shared/api-types";
import type { BudgetState } from "./isolate-bootstrap.js";
import { type FlattenedBinding, flattenBindingTree, BINDING_PREFIX } from "./bindings.js";
import { createNodeHostNetworkAdapter } from "./host-network-adapter.js";
export { NodeExecutionDriverOptions };
const MAX_ERROR_MESSAGE_CHARS = 8192;
type LoopbackAwareNetworkAdapter = NetworkAdapter & {
__setLoopbackPortChecker?: (checker: (hostname: string, port: number) => boolean) => void;
};
function boundErrorMessage(message: string): string {
if (message.length <= MAX_ERROR_MESSAGE_CHARS) return message;
return `${message.slice(0, MAX_ERROR_MESSAGE_CHARS)}...[Truncated]`;
}
function createBridgeDriverProcess(): import("@secure-exec/core").DriverProcess {
return {
writeStdin() {},
closeStdin() {},
kill() {},
wait: async () => 0,
onStdout: null,
onStderr: null,
onExit: null,
};
}
/** Internal state for the execution driver. */
interface DriverState {
filesystem: VirtualFileSystem;
commandExecutor: CommandExecutor;
networkAdapter: NetworkAdapter;
permissions?: Permissions;
processConfig: ProcessConfig;
osConfig: OSConfig;
onStdio?: StdioHook;
cpuTimeLimitMs?: number;
timingMitigation: TimingMitigation;
bridgeBase64TransferLimitBytes: number;
isolateJsonPayloadLimitBytes: number;
maxOutputBytes?: number;
maxBridgeCalls?: number;
maxTimers?: number;
maxChildProcesses?: number;
maxHandles?: number;
budgetState: BudgetState;
activeHttpServerIds: Set<number>;
activeHttpServerClosers: Map<number, () => Promise<void>>;
pendingHttpServerStarts: { count: number };
activeHttpClientRequests: { count: number };
activeChildProcesses: Map<number, SpawnedProcess>;
activeHostTimers: Set<ReturnType<typeof setTimeout>>;
moduleFormatCache: Map<string, "esm" | "cjs" | "json">;
packageTypeCache: Map<string, "module" | "commonjs" | null>;
resolutionCache: ResolutionCache;
onPtySetRawMode?: (mode: boolean) => void;
liveStdinSource?: NodeExecutionDriverOptions["liveStdinSource"];
/** Pre-built bridge code for this driver, based on includeNodeShims setting. */
bridgeCode: string;
/** Whether this driver includes Node.js polyfill shims on globalThis. */
includeNodeShims: boolean;
}
// Shared V8 runtime process — one per Node.js process, lazy-initialized
let sharedV8Runtime: V8Runtime | null = null;
let sharedV8RuntimePromise: Promise<V8Runtime> | null = null;
let sharedV8RuntimeUsers = 0;
async function getSharedV8Runtime(): Promise<V8Runtime> {
if (sharedV8Runtime?.isAlive) return sharedV8Runtime;
if (sharedV8RuntimePromise) return sharedV8RuntimePromise;
// Build bridge code for snapshot warmup (always with shims for the shared runtime)
const bridgeCode = buildFullBridgeCode(true);
sharedV8RuntimePromise = createV8Runtime({
warmupBridgeCode: bridgeCode,
}).then((rt) => {
sharedV8Runtime = rt;
sharedV8RuntimePromise = null;
return rt;
});
return sharedV8RuntimePromise;
}
async function releaseSharedV8Runtime(): Promise<void> {
if (sharedV8RuntimeUsers > 0) {
sharedV8RuntimeUsers -= 1;
}
if (sharedV8RuntimeUsers !== 0) {
return;
}
if (sharedV8RuntimePromise) {
void sharedV8RuntimePromise
.then(async (runtime) => {
if (sharedV8RuntimeUsers !== 0 || sharedV8Runtime !== runtime) {
return;
}
sharedV8Runtime = null;
await runtime.dispose().catch(() => {});
})
.catch(() => {});
return;
}
if (!sharedV8Runtime) {
return;
}
const runtime = sharedV8Runtime;
sharedV8Runtime = null;
await runtime.dispose().catch(() => {});
}
// Minimal polyfills for APIs the bridge IIFE expects but the Rust V8 runtime doesn't provide.
const REGEXP_COMPAT_POLYFILL = String.raw`
if (typeof globalThis.RegExp === 'function' && !globalThis.RegExp.__secureExecRgiEmojiCompat) {
const NativeRegExp = globalThis.RegExp;
const RGI_EMOJI_PATTERN = '^\\p{RGI_Emoji}$';
const RGI_EMOJI_BASE_CLASS = '[\\u{00A9}\\u{00AE}\\u{203C}\\u{2049}\\u{2122}\\u{2139}\\u{2194}-\\u{21AA}\\u{231A}-\\u{23FF}\\u{24C2}\\u{25AA}-\\u{27BF}\\u{2934}-\\u{2935}\\u{2B05}-\\u{2B55}\\u{3030}\\u{303D}\\u{3297}\\u{3299}\\u{1F000}-\\u{1FAFF}]';
const RGI_EMOJI_KEYCAP = '[#*0-9]\\uFE0F?\\u20E3';
const RGI_EMOJI_FALLBACK_SOURCE =
'^(?:' +
RGI_EMOJI_KEYCAP +
'|\\p{Regional_Indicator}{2}|' +
RGI_EMOJI_BASE_CLASS +
'(?:\\uFE0F|\\u200D(?:' +
RGI_EMOJI_KEYCAP +
'|' +
RGI_EMOJI_BASE_CLASS +
')|[\\u{1F3FB}-\\u{1F3FF}])*)$';
try {
new NativeRegExp(RGI_EMOJI_PATTERN, 'v');
} catch (error) {
if (String(error && error.message || error).includes('RGI_Emoji')) {
function CompatRegExp(pattern, flags) {
const normalizedPattern =
pattern instanceof NativeRegExp && flags === undefined
? pattern.source
: String(pattern);
const normalizedFlags =
flags === undefined
? (pattern instanceof NativeRegExp ? pattern.flags : '')
: String(flags);
try {
return new NativeRegExp(pattern, flags);
} catch (innerError) {
if (normalizedPattern === RGI_EMOJI_PATTERN && normalizedFlags === 'v') {
return new NativeRegExp(RGI_EMOJI_FALLBACK_SOURCE, 'u');
}
throw innerError;
}
}
Object.setPrototypeOf(CompatRegExp, NativeRegExp);
CompatRegExp.prototype = NativeRegExp.prototype;
Object.defineProperty(CompatRegExp.prototype, 'constructor', {
value: CompatRegExp,
writable: true,
configurable: true,
});
CompatRegExp.__secureExecRgiEmojiCompat = true;
globalThis.RegExp = CompatRegExp;
}
}
}
`;
const V8_POLYFILLS = `
if (typeof global === 'undefined') {
globalThis.global = globalThis;
}
${REGEXP_COMPAT_POLYFILL}
if (typeof SharedArrayBuffer === 'undefined') {
globalThis.SharedArrayBuffer = class SharedArrayBuffer extends ArrayBuffer {};
var _abBL = Object.getOwnPropertyDescriptor(ArrayBuffer.prototype, 'byteLength');
if (_abBL) Object.defineProperty(SharedArrayBuffer.prototype, 'byteLength', _abBL);
Object.defineProperty(SharedArrayBuffer.prototype, 'growable', { get() { return false; } });
}
if (!Object.getOwnPropertyDescriptor(ArrayBuffer.prototype, 'resizable')) {
Object.defineProperty(ArrayBuffer.prototype, 'resizable', { get() { return false; } });
}
if (typeof queueMicrotask === 'undefined') globalThis.queueMicrotask = (fn) => Promise.resolve().then(fn);
if (typeof atob === 'undefined') {
globalThis.atob = (s) => {
const b = typeof Buffer !== 'undefined' ? Buffer : null;
if (b) return b.from(s, 'base64').toString('binary');
// Fallback: manual base64 decode
const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
let out = ''; for (let i = 0; i < s.length;) {
const a = chars.indexOf(s[i++]), b2 = chars.indexOf(s[i++]), c = chars.indexOf(s[i++]), d = chars.indexOf(s[i++]);
out += String.fromCharCode((a<<2)|(b2>>4)); if (c!==64) out += String.fromCharCode(((b2&15)<<4)|(c>>2)); if (d!==64) out += String.fromCharCode(((c&3)<<6)|d);
} return out;
};
globalThis.btoa = (s) => {
const b = typeof Buffer !== 'undefined' ? Buffer : null;
if (b) return b.from(s, 'binary').toString('base64');
const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
let out = ''; for (let i = 0; i < s.length;) {
const a = s.charCodeAt(i++), b2 = s.charCodeAt(i++), c = s.charCodeAt(i++);
out += chars[a>>2] + chars[((a&3)<<4)|(b2>>4)] + (isNaN(b2) ? '=' : chars[((b2&15)<<2)|(c>>4)]) + (isNaN(c) ? '=' : chars[c&63]);
} return out;
};
}
if (typeof TextEncoder === 'undefined') {
const _encodeUtf8 = (str = '') => {
const bytes = [];
for (let i = 0; i < str.length; i++) {
const codeUnit = str.charCodeAt(i);
let codePoint = codeUnit;
if (codeUnit >= 0xD800 && codeUnit <= 0xDBFF) {
const next = i + 1 < str.length ? str.charCodeAt(i + 1) : 0;
if (next >= 0xDC00 && next <= 0xDFFF) {
codePoint = 0x10000 + ((codeUnit - 0xD800) << 10) + (next - 0xDC00);
i++;
} else {
codePoint = 0xFFFD;
}
} else if (codeUnit >= 0xDC00 && codeUnit <= 0xDFFF) {
codePoint = 0xFFFD;
}
if (codePoint < 0x80) bytes.push(codePoint);
else if (codePoint < 0x800) bytes.push(0xC0 | (codePoint >> 6), 0x80 | (codePoint & 63));
else if (codePoint < 0x10000) bytes.push(0xE0 | (codePoint >> 12), 0x80 | ((codePoint >> 6) & 63), 0x80 | (codePoint & 63));
else bytes.push(0xF0 | (codePoint >> 18), 0x80 | ((codePoint >> 12) & 63), 0x80 | ((codePoint >> 6) & 63), 0x80 | (codePoint & 63));
}
return new Uint8Array(bytes);
};
globalThis.TextEncoder = class TextEncoder {
encode(str = '') { return _encodeUtf8(String(str)); }
get encoding() { return 'utf-8'; }
};
}
if (typeof TextDecoder === 'undefined') {
globalThis.TextDecoder = class TextDecoder {
constructor() {}
decode(buf) { if (!buf) return ''; const u8 = new Uint8Array(buf.buffer || buf); let s = ''; for (let i = 0; i < u8.length;) { const b = u8[i++]; if (b < 128) s += String.fromCharCode(b); else if (b < 224) s += String.fromCharCode(((b&31)<<6)|(u8[i++]&63)); else if (b < 240) { const b2 = u8[i++]; s += String.fromCharCode(((b&15)<<12)|((b2&63)<<6)|(u8[i++]&63)); } else { const b2 = u8[i++], b3 = u8[i++], cp = ((b&7)<<18)|((b2&63)<<12)|((b3&63)<<6)|(u8[i++]&63); if (cp>0xFFFF) { const s2 = cp-0x10000; s += String.fromCharCode(0xD800+(s2>>10), 0xDC00+(s2&0x3FF)); } else s += String.fromCharCode(cp); } } return s; }
get encoding() { return 'utf-8'; }
};
}
if (typeof URL === 'undefined') {
globalThis.URL = class URL {
constructor(url, base) { const m = String(base ? new URL(base).href : ''); const full = url.startsWith('http') ? url : m.replace(/\\/[^\\/]*$/, '/') + url; const pm = full.match(/^(\\w+:)\\/\\/([^/:]+)(:\\d+)?(.*)$/); this.protocol = pm?.[1]||''; this.hostname = pm?.[2]||''; this.port = (pm?.[3]||'').slice(1); this.pathname = (pm?.[4]||'/').split('?')[0].split('#')[0]; this.search = full.includes('?') ? '?'+full.split('?')[1].split('#')[0] : ''; this.hash = full.includes('#') ? '#'+full.split('#')[1] : ''; this.host = this.hostname + (this.port ? ':'+this.port : ''); this.href = this.protocol+'//'+this.host+this.pathname+this.search+this.hash; this.origin = this.protocol+'//'+this.host; this.searchParams = typeof URLSearchParams !== 'undefined' ? new URLSearchParams(this.search) : { get:()=>null }; }
toString() { return this.href; }
};
}
if (typeof URLSearchParams === 'undefined') {
globalThis.URLSearchParams = class URLSearchParams {
constructor(init) { this._map = new Map(); if (typeof init === 'string') { for (const p of init.replace(/^\\?/,'').split('&')) { const [k,...v] = p.split('='); if (k) this._map.set(decodeURIComponent(k), decodeURIComponent(v.join('='))); } } }
get(k) { return this._map.get(k) ?? null; }
has(k) { return this._map.has(k); }
toString() { return [...this._map].map(([k,v])=>encodeURIComponent(k)+'='+encodeURIComponent(v)).join('&'); }
};
}
if (typeof structuredClone === 'undefined') {
globalThis.structuredClone = (obj) => JSON.parse(JSON.stringify(obj));
}
if (typeof performance === 'undefined') {
globalThis.performance = { now: () => Date.now(), timeOrigin: Date.now() };
}
if (
typeof AbortController === 'undefined' ||
typeof AbortSignal === 'undefined' ||
typeof AbortSignal.prototype?.addEventListener !== 'function' ||
typeof AbortSignal.prototype?.removeEventListener !== 'function'
) {
const abortSignalState = new WeakMap();
function getAbortSignalState(signal) {
const state = abortSignalState.get(signal);
if (!state) throw new Error('Invalid AbortSignal');
return state;
}
class AbortSignal {
constructor() {
this.onabort = null;
abortSignalState.set(this, {
aborted: false,
reason: undefined,
listeners: [],
});
}
get aborted() {
return getAbortSignalState(this).aborted;
}
get reason() {
return getAbortSignalState(this).reason;
}
get _listeners() {
return getAbortSignalState(this).listeners.slice();
}
getEventListeners(type) {
if (type !== 'abort') return [];
return getAbortSignalState(this).listeners.slice();
}
addEventListener(type, listener) {
if (type !== 'abort' || typeof listener !== 'function') return;
getAbortSignalState(this).listeners.push(listener);
}
removeEventListener(type, listener) {
if (type !== 'abort' || typeof listener !== 'function') return;
const listeners = getAbortSignalState(this).listeners;
const index = listeners.indexOf(listener);
if (index !== -1) {
listeners.splice(index, 1);
}
}
dispatchEvent(event) {
if (!event || event.type !== 'abort') return false;
if (typeof this.onabort === 'function') {
try {
this.onabort.call(this, event);
} catch {}
}
const listeners = getAbortSignalState(this).listeners.slice();
for (const listener of listeners) {
try {
listener.call(this, event);
} catch {}
}
return true;
}
}
globalThis.AbortSignal = AbortSignal;
globalThis.AbortController = class AbortController {
constructor() {
this.signal = new AbortSignal();
}
abort(reason) {
const state = getAbortSignalState(this.signal);
if (state.aborted) return;
state.aborted = true;
state.reason = reason;
this.signal.dispatchEvent({ type: 'abort' });
}
};
}
if (
typeof globalThis.AbortSignal === 'function' &&
typeof globalThis.AbortController === 'function' &&
typeof globalThis.AbortSignal.abort !== 'function'
) {
globalThis.AbortSignal.abort = function abort(reason) {
const controller = new globalThis.AbortController();
controller.abort(reason);
return controller.signal;
};
}
if (
typeof globalThis.AbortSignal === 'function' &&
typeof globalThis.AbortController === 'function' &&
typeof globalThis.AbortSignal.timeout !== 'function'
) {
globalThis.AbortSignal.timeout = function timeout(milliseconds) {
const delay = Number(milliseconds);
if (!Number.isFinite(delay) || delay < 0) {
throw new RangeError('The value of "milliseconds" is out of range. It must be a finite, non-negative number.');
}
const controller = new globalThis.AbortController();
const timer = setTimeout(() => {
controller.abort(
new globalThis.DOMException(
'The operation was aborted due to timeout',
'TimeoutError',
),
);
}, delay);
if (typeof timer?.unref === 'function') {
timer.unref();
}
return controller.signal;
};
}
if (
typeof globalThis.AbortSignal === 'function' &&
typeof globalThis.AbortController === 'function' &&
typeof globalThis.AbortSignal.any !== 'function'
) {
globalThis.AbortSignal.any = function any(signals) {
if (
signals === null ||
signals === undefined ||
typeof signals[Symbol.iterator] !== 'function'
) {
throw new TypeError('The "signals" argument must be an iterable.');
}
const controller = new globalThis.AbortController();
const cleanup = [];
const abortFromSignal = (signal) => {
for (const dispose of cleanup) {
dispose();
}
cleanup.length = 0;
controller.abort(signal.reason);
};
for (const signal of signals) {
if (
!signal ||
typeof signal.aborted !== 'boolean' ||
typeof signal.addEventListener !== 'function' ||
typeof signal.removeEventListener !== 'function'
) {
throw new TypeError('The "signals" argument must contain only AbortSignal instances.');
}
if (signal.aborted) {
abortFromSignal(signal);
break;
}
const listener = () => {
abortFromSignal(signal);
};
signal.addEventListener('abort', listener, { once: true });
cleanup.push(() => {
signal.removeEventListener('abort', listener);
});
}
return controller.signal;
};
}
if (typeof navigator === 'undefined') {
globalThis.navigator = { userAgent: 'secure-exec-v8' };
}
if (typeof DOMException === 'undefined') {
const DOM_EXCEPTION_LEGACY_CODES = {
IndexSizeError: 1,
DOMStringSizeError: 2,
HierarchyRequestError: 3,
WrongDocumentError: 4,
InvalidCharacterError: 5,
NoDataAllowedError: 6,
NoModificationAllowedError: 7,
NotFoundError: 8,
NotSupportedError: 9,
InUseAttributeError: 10,
InvalidStateError: 11,
SyntaxError: 12,
InvalidModificationError: 13,
NamespaceError: 14,
InvalidAccessError: 15,
ValidationError: 16,
TypeMismatchError: 17,
SecurityError: 18,
NetworkError: 19,
AbortError: 20,
URLMismatchError: 21,
QuotaExceededError: 22,
TimeoutError: 23,
InvalidNodeTypeError: 24,
DataCloneError: 25,
};
class DOMException extends Error {
constructor(message = '', name = 'Error') {
super(String(message));
this.name = String(name);
this.code = DOM_EXCEPTION_LEGACY_CODES[this.name] ?? 0;
}
get [Symbol.toStringTag]() { return 'DOMException'; }
}
for (const [name, code] of Object.entries(DOM_EXCEPTION_LEGACY_CODES)) {
const constantName = name.replace(/([a-z0-9])([A-Z])/g, '$1_$2').toUpperCase();
Object.defineProperty(DOMException, constantName, {
value: code,
writable: false,
configurable: false,
enumerable: true,
});
Object.defineProperty(DOMException.prototype, constantName, {
value: code,
writable: false,
configurable: false,
enumerable: true,
});
}
Object.defineProperty(globalThis, 'DOMException', {
value: DOMException,
writable: false,
configurable: false,
enumerable: true,
});
}
if (typeof Blob === 'undefined') {
globalThis.Blob = class Blob {
constructor(parts = [], options = {}) {
this._parts = Array.isArray(parts) ? parts.slice() : [];
this.type = options && options.type ? String(options.type).toLowerCase() : '';
this.size = this._parts.reduce((total, part) => {
if (typeof part === 'string') return total + part.length;
if (part && typeof part.byteLength === 'number') return total + part.byteLength;
return total;
}, 0);
}
arrayBuffer() { return Promise.resolve(new ArrayBuffer(0)); }
text() { return Promise.resolve(''); }
slice() { return new globalThis.Blob(); }
stream() { throw new Error('Blob.stream is not supported in sandbox'); }
get [Symbol.toStringTag]() { return 'Blob'; }
};
Object.defineProperty(globalThis, 'Blob', {
value: globalThis.Blob,
writable: false,
configurable: false,
enumerable: true,
});
}
if (typeof File === 'undefined') {
globalThis.File = class File extends globalThis.Blob {
constructor(parts = [], name = '', options = {}) {
super(parts, options);
this.name = String(name);
this.lastModified =
options && typeof options.lastModified === 'number'
? options.lastModified
: Date.now();
this.webkitRelativePath = '';
}
get [Symbol.toStringTag]() { return 'File'; }
};
Object.defineProperty(globalThis, 'File', {
value: globalThis.File,
writable: false,
configurable: false,
enumerable: true,
});
}
if (typeof FormData === 'undefined') {
class FormData {
constructor() {
this._entries = [];
}
append(name, value) {
this._entries.push([String(name), value]);
}
get(name) {
const key = String(name);
for (const entry of this._entries) {
if (entry[0] === key) return entry[1];
}
return null;
}
getAll(name) {
const key = String(name);
return this._entries.filter((entry) => entry[0] === key).map((entry) => entry[1]);
}
has(name) {
return this.get(name) !== null;
}
delete(name) {
const key = String(name);
this._entries = this._entries.filter((entry) => entry[0] !== key);
}
entries() {
return this._entries[Symbol.iterator]();
}
[Symbol.iterator]() {
return this.entries();
}
get [Symbol.toStringTag]() { return 'FormData'; }
}
Object.defineProperty(globalThis, 'FormData', {
value: FormData,
writable: false,
configurable: false,
enumerable: true,
});
}
if (typeof MessageEvent === 'undefined') {
globalThis.MessageEvent = class MessageEvent {
constructor(type, options = {}) {
this.type = String(type);
this.data = Object.prototype.hasOwnProperty.call(options, 'data')
? options.data
: undefined;
}
};
}
if (typeof MessagePort === 'undefined') {
globalThis.MessagePort = class MessagePort {
constructor() {
this.onmessage = null;
this._pairedPort = null;
}
postMessage(data) {
const target = this._pairedPort;
if (!target) return;
const event = new globalThis.MessageEvent('message', { data });
if (typeof target.onmessage === 'function') {
target.onmessage.call(target, event);
}
}
start() {}
close() {
this._pairedPort = null;
}
};
}
if (typeof MessageChannel === 'undefined') {
globalThis.MessageChannel = class MessageChannel {
constructor() {
this.port1 = new globalThis.MessagePort();
this.port2 = new globalThis.MessagePort();
this.port1._pairedPort = this.port2;
this.port2._pairedPort = this.port1;
}
};
}
`;
// Shim for ivm.Reference methods used by bridge code.
// Bridge globals in the V8 runtime are plain functions, but the bridge code
// (compiled from @secure-exec/core) calls them via .applySync(), .apply(), and
// .applySyncPromise() which are ivm Reference calling patterns.
// Shim for native bridge functions (runs early in postRestoreScript)
const BRIDGE_NATIVE_SHIM = `
(function() {
var _origApply = Function.prototype.apply;
function shimBridgeGlobal(name) {
var fn = globalThis[name];
if (typeof fn !== 'function' || fn.applySync) return;
fn.applySync = function(_, args) { return _origApply.call(fn, null, args || []); };
fn.applySyncPromise = function(_, args) { return _origApply.call(fn, null, args || []); };
fn.derefInto = function() { return fn; };
}
var keys = Object.getOwnPropertyNames(globalThis).filter(function(k) { return k.startsWith('_') && typeof globalThis[k] === 'function'; });
keys.forEach(shimBridgeGlobal);
})();
`;
// Dispatch shim for bridge globals not natively supported by the V8 binary.
// Installs dispatch wrappers for ALL known bridge globals that aren't already
// functions. This runs BEFORE require-setup so the crypto/net module code
// detects the dispatch-wrapped globals and installs the corresponding APIs.
function buildBridgeDispatchShim(): string {
const K = HOST_BRIDGE_GLOBAL_KEYS;
// Collect all bridge global names from the contract
const allGlobals = Object.values(K).filter(v => typeof v === "string") as string[];
return `
(function() {
var _origApply = Function.prototype.apply;
function encodeDispatchArgs(args) {
return JSON.stringify(args, function(_key, value) {
if (value === undefined) {
return { __secureExecDispatchType: 'undefined' };
}
return value;
});
}
var names = ${JSON.stringify(allGlobals)};
for (var i = 0; i < names.length; i++) {
var name = names[i];
if (typeof globalThis[name] === 'function') continue;
(function(n) {
function reviveDispatchError(payload) {
var error = new Error(payload && payload.message ? payload.message : String(payload));
if (payload && payload.name) error.name = payload.name;
if (payload && payload.code !== undefined) error.code = payload.code;
if (payload && payload.stack) error.stack = payload.stack;
return error;
}
var fn = function() {
var args = Array.prototype.slice.call(arguments);
var encoded = "__bd:" + n + ":" + encodeDispatchArgs(args);
var resultJson = _loadPolyfill.applySyncPromise(undefined, [encoded]);
if (resultJson === null) return undefined;
try {
var parsed = JSON.parse(resultJson);
if (parsed.__bd_error) throw reviveDispatchError(parsed.__bd_error);
return parsed.__bd_result;
} catch (e) {
if (e.message && e.message.startsWith('No handler:')) return undefined;
throw e;
}
};
fn.applySync = function(_, args) { return _origApply.call(fn, null, args || []); };
fn.applySyncPromise = function(_, args) { return _origApply.call(fn, null, args || []); };
fn.derefInto = function() { return fn; };
globalThis[n] = fn;
})(name);
}
})();
`;
}
const BRIDGE_DISPATCH_SHIM = buildBridgeDispatchShim();
// Cache assembled bridge code (same across all executions)
// Keyed by includeNodeShims flag so drivers with different settings get correct code
const bridgeCodeCache = new Map<boolean, string>();
function buildFullBridgeCode(includeNodeShims: boolean = true): string {
const cached = bridgeCodeCache.get(includeNodeShims);
if (cached !== undefined) return cached;
// Assemble the full bridge code IIFE from component scripts.
// Only include code that can run without bridge calls (snapshot phase).
// Console/require/fsFacade setup goes in postRestoreScript where bridge calls work.
const parts = [
// Polyfill missing Web APIs for the Rust V8 runtime
V8_POLYFILLS,
getIsolateRuntimeSource("globalExposureHelpers"),
getInitialBridgeGlobalsSetupCode(),
];
// Only include Node.js shims (fs, http, process globals, etc.) when explicitly requested.
// For AI agent use cases, users may want a clean globalThis with no injected polyfills.
if (includeNodeShims) {
parts.push(getRawBridgeCode());
parts.push(getBridgeAttachCode());
}
const code = parts.join("\n");
bridgeCodeCache.set(includeNodeShims, code);
return code;
}
export class NodeExecutionDriver implements RuntimeDriver {
private state: DriverState;
private memoryLimit: number;
private disposed: boolean = false;
private flattenedBindings: FlattenedBinding[] | null = null;
// Unwrapped filesystem for path translation (toHostPath/toSandboxPath)
private rawFilesystem: VirtualFileSystem | undefined;
// Kernel socket table for routing net.connect through kernel
private socketTable?: import("@secure-exec/core").SocketTable;
// Kernel process table for child process registration
private processTable?: import("@secure-exec/core").ProcessTable;
private timerTable: import("@secure-exec/core").TimerTable;
private ownsProcessTable: boolean;
private ownsTimerTable: boolean;
private configuredMaxTimers?: number;
private configuredMaxHandles?: number;
private pid?: number;
// Track the current V8 session so it can be destroyed on terminate/dispose
private _currentSession: V8Session | null = null;
constructor(options: NodeExecutionDriverOptions) {
sharedV8RuntimeUsers += 1;
this.memoryLimit = options.memoryLimit ?? 128;
const budgets = options.resourceBudgets;
this.socketTable = options.socketTable;
this.processTable = options.processTable ?? new ProcessTable();
this.timerTable = options.timerTable ?? new TimerTable();
this.ownsProcessTable = options.processTable === undefined;
this.ownsTimerTable = options.timerTable === undefined;
this.configuredMaxTimers = budgets?.maxTimers;
this.configuredMaxHandles = budgets?.maxHandles;
this.pid = options.pid ?? 1;
const system = options.system;
const permissions = system.permissions;
if (!this.socketTable) {
this.socketTable = new SocketTable({
hostAdapter: system.network ? createNodeHostNetworkAdapter() : undefined,
networkCheck: permissions?.network,
});
}
// Keep unwrapped filesystem for path translation (toHostPath/toSandboxPath)
this.rawFilesystem = system.filesystem;
const filesystem = this.rawFilesystem
? wrapFileSystem(this.rawFilesystem, permissions)
: createFsStub();
const commandExecutor = system.commandExecutor
? wrapCommandExecutor(system.commandExecutor, permissions)
: createCommandExecutorStub();
const rawNetworkAdapter = system.network;
const networkAdapter = rawNetworkAdapter
? wrapNetworkAdapter(rawNetworkAdapter, permissions)
: createNetworkStub();
const loopbackAwareAdapter = networkAdapter as LoopbackAwareNetworkAdapter;
if (loopbackAwareAdapter.__setLoopbackPortChecker && this.socketTable) {
loopbackAwareAdapter.__setLoopbackPortChecker((_hostname, port) =>
this.socketTable?.findListener({ host: "127.0.0.1", port }) !== null,
);
}
const processConfig = { ...(options.runtime.process ?? {}) };
processConfig.cwd ??= DEFAULT_SANDBOX_CWD;
processConfig.env = filterEnv(processConfig.env, permissions);
const osConfig = { ...(options.runtime.os ?? {}) };
osConfig.homedir ??= DEFAULT_SANDBOX_HOME;
osConfig.tmpdir ??= DEFAULT_SANDBOX_TMPDIR;
// Determine whether to include Node.js polyfill shims on globalThis.
// When false, globalThis has no injected fs, http, process, Buffer, etc.
// Useful for AI agent use cases that need a clean global scope.
const includeNodeShims = (options.runtime as any).includeNodeShims ?? true;
const bridgeBase64TransferLimitBytes = normalizePayloadLimit(
options.payloadLimits?.base64TransferBytes,
DEFAULT_BRIDGE_BASE64_TRANSFER_BYTES,
"payloadLimits.base64TransferBytes",
);
const isolateJsonPayloadLimitBytes = normalizePayloadLimit(
options.payloadLimits?.jsonPayloadBytes,
DEFAULT_ISOLATE_JSON_PAYLOAD_BYTES,
"payloadLimits.jsonPayloadBytes",
);
this.state = {
filesystem,
commandExecutor,
networkAdapter,
permissions,
processConfig,
osConfig,
onStdio: options.onStdio,
cpuTimeLimitMs: options.cpuTimeLimitMs,
timingMitigation: options.timingMitigation ?? "freeze",
bridgeBase64TransferLimitBytes,
isolateJsonPayloadLimitBytes,
maxOutputBytes: budgets?.maxOutputBytes,
maxBridgeCalls: budgets?.maxBridgeCalls,
maxChildProcesses: budgets?.maxChildProcesses,
maxTimers: budgets?.maxTimers,
maxHandles: budgets?.maxHandles,
budgetState: createBudgetState(),
activeHttpServerIds: new Set(),
activeHttpServerClosers: new Map(),
pendingHttpServerStarts: { count: 0 },
activeHttpClientRequests: { count: 0 },
activeChildProcesses: new Map(),
activeHostTimers: new Set(),
moduleFormatCache: new Map(),
packageTypeCache: new Map(),
resolutionCache: createResolutionCache(),
onPtySetRawMode: options.onPtySetRawMode,
liveStdinSource: options.liveStdinSource,
bridgeCode: buildFullBridgeCode(includeNodeShims),
includeNodeShims,
};
// Validate and flatten bindings once at construction time
if (options.bindings) {
this.flattenedBindings = flattenBindingTree(options.bindings);
}
}
get network(): Pick<NetworkAdapter, "fetch" | "dnsLookup" | "httpRequest"> {
const adapter = this.state.networkAdapter ?? createNetworkStub();
return {
fetch: (url, options) => adapter.fetch(url, options),
dnsLookup: (hostname) => adapter.dnsLookup(hostname),
httpRequest: (url, options) => adapter.httpRequest(url, options),
};
}
get unsafeIsolate(): unknown { return null; }
private hasManagedResources(): boolean {
const hasBridgeHandles =
this.pid !== undefined &&
this.processTable !== undefined &&
(() => {
try {
return this.processTable.getHandles(this.pid!).size > 0;
} catch {
return false;
}
})();
return (
hasBridgeHandles ||
this.state.pendingHttpServerStarts.count > 0 ||
this.state.activeHttpClientRequests.count > 0 ||
this.state.activeHttpServerIds.size > 0 ||
this.state.activeChildProcesses.size > 0 ||
(!this.ownsProcessTable && this.state.activeHostTimers.size > 0)
);
}
private async waitForManagedResources(): Promise<void> {
const graceDeadline = Date.now() + 100;
// Give async bridge callbacks a moment to register their host-side handles.
while (!this.disposed && !this.hasManagedResources() && Date.now() < graceDeadline) {
await new Promise((resolve) => setTimeout(resolve, 10));
}
// Keep the session alive while host-managed resources are still active.
while (!this.disposed && this.hasManagedResources()) {
await new Promise((resolve) => setTimeout(resolve, 10));
}
}
private ensureBridgeProcessEntry(processConfig: ProcessConfig): void {
if (this.pid === undefined || !this.processTable) return;
const entry = this.processTable.get(this.pid);
if (!entry || entry.status === "exited") {
this.processTable.register(
this.pid,
"node",
"node",
[],
{
pid: this.pid,
ppid: 0,
env: processConfig.env ?? {},
cwd: processConfig.cwd ?? DEFAULT_SANDBOX_CWD,
fds: { stdin: 0, stdout: 1, stderr: 2 },
stdinIsTTY: processConfig.stdinIsTTY,
stdoutIsTTY: processConfig.stdoutIsTTY,
stderrIsTTY: processConfig.stderrIsTTY,
},
createBridgeDriverProcess(),
);
}
if (this.ownsProcessTable || this.configuredMaxHandles !== undefined) {
this.processTable.setHandleLimit(
this.pid,
this.configuredMaxHandles ?? DEFAULT_MAX_HANDLES,
);
}
if (this.ownsTimerTable || this.configuredMaxTimers !== undefined) {