@drsamonline/sandbox 0.0.0-stage → 0.12.3
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.
- package/package.json +23 -4
- package/src/attacks.js +148 -0
- package/src/index.js +204 -0
- package/src/runner.js +102 -0
- package/README.md +0 -3
package/package.json
CHANGED
|
@@ -1,6 +1,25 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@drsamonline/sandbox",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.12.3",
|
|
4
|
+
"description": "Run model-authored code in a contained process: permission model, network namespace, hard limits.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"license": "MIT",
|
|
7
|
+
"main": "./src/index.js",
|
|
8
|
+
"exports": {
|
|
9
|
+
".": "./src/index.js",
|
|
10
|
+
"./src/*": "./src/*"
|
|
11
|
+
},
|
|
12
|
+
"files": [
|
|
13
|
+
"src"
|
|
14
|
+
],
|
|
15
|
+
"repository": {
|
|
16
|
+
"type": "git",
|
|
17
|
+
"url": "git://github.com/drsamonline/sui.git",
|
|
18
|
+
"directory": "packages/sandbox"
|
|
19
|
+
},
|
|
20
|
+
"homepage": "https://github.com/drsamonline/sui#readme",
|
|
21
|
+
"publishConfig": {
|
|
22
|
+
"access": "public",
|
|
23
|
+
"registry": "https://registry.npmjs.org/"
|
|
24
|
+
}
|
|
25
|
+
}
|
package/src/attacks.js
ADDED
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The attack suite (B5.6).
|
|
3
|
+
*
|
|
4
|
+
* Every case is a thing a model-written snippet might do that a sandbox must
|
|
5
|
+
* contain. They are **test fixtures, not exploits**: each one is the simplest
|
|
6
|
+
* form of a class, with no working payload, no target and no obfuscation, because
|
|
7
|
+
* the point is to prove the boundary holds rather than to hand anyone a tool.
|
|
8
|
+
*
|
|
9
|
+
* Each case says what containment looks like: `blocked` (an error, no output),
|
|
10
|
+
* `timeout` (stopped by a clock), or `truncated` (output capped).
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
export const ATTACKS = [
|
|
14
|
+
{
|
|
15
|
+
name: 'read a file outside the work directory',
|
|
16
|
+
why: 'the classic first step out of any sandbox',
|
|
17
|
+
expect: 'blocked',
|
|
18
|
+
code: `const fs = require('node:fs'); console.log(fs.readFileSync('/etc/passwd', 'utf8'));`,
|
|
19
|
+
},
|
|
20
|
+
{
|
|
21
|
+
name: 'import a built-in module dynamically',
|
|
22
|
+
why: 'a dynamic import is the way around a missing `require`',
|
|
23
|
+
// Honest expectation: the context has no module loader, so the import never
|
|
24
|
+
// resolves and nothing is read. The rejection is swallowed inside the
|
|
25
|
+
// context, which means the run reports success — so what is asserted here is
|
|
26
|
+
// that nothing leaked, not that the process failed.
|
|
27
|
+
expect: 'no-leak',
|
|
28
|
+
code: `import('node:fs').then((fs) => console.log(fs.readFileSync('/etc/passwd', 'utf8')));`,
|
|
29
|
+
},
|
|
30
|
+
{
|
|
31
|
+
name: 'spawn a child process',
|
|
32
|
+
why: 'a child inherits the parent\'s reach, not the sandbox\'s',
|
|
33
|
+
expect: 'blocked',
|
|
34
|
+
code: `const cp = require('node:child_process'); console.log(cp.execSync('id').toString());`,
|
|
35
|
+
},
|
|
36
|
+
{
|
|
37
|
+
name: 'eval a string',
|
|
38
|
+
why: 'string code generation turns data into instructions',
|
|
39
|
+
expect: 'blocked',
|
|
40
|
+
code: `console.log(eval('1 + 1'));`,
|
|
41
|
+
},
|
|
42
|
+
{
|
|
43
|
+
name: 'compile a function from a string',
|
|
44
|
+
why: 'the other half of string code generation',
|
|
45
|
+
expect: 'blocked',
|
|
46
|
+
code: `const f = new Function('return 42'); console.log(f());`,
|
|
47
|
+
},
|
|
48
|
+
{
|
|
49
|
+
name: 'compile WASM',
|
|
50
|
+
why: 'WASM is a second instruction set with its own escape surface',
|
|
51
|
+
expect: 'blocked',
|
|
52
|
+
code: `const m = new WebAssembly.Module(new Uint8Array([0,97,115,109,1,0,0,0])); console.log('compiled');`,
|
|
53
|
+
},
|
|
54
|
+
{
|
|
55
|
+
name: 'loop forever',
|
|
56
|
+
why: 'an infinite loop is the cheapest denial of service',
|
|
57
|
+
expect: 'timeout',
|
|
58
|
+
code: `while (true) {}`,
|
|
59
|
+
},
|
|
60
|
+
{
|
|
61
|
+
name: 'recuse until the stack dies',
|
|
62
|
+
why: 'a crash must be the child\'s, not the host\'s',
|
|
63
|
+
expect: 'blocked',
|
|
64
|
+
code: `function f() { return f(); } f();`,
|
|
65
|
+
},
|
|
66
|
+
{
|
|
67
|
+
name: 'allocate until the heap dies',
|
|
68
|
+
why: 'a memory bomb takes the host down with it if the heap is shared',
|
|
69
|
+
expect: 'blocked',
|
|
70
|
+
code: `const a = []; while (true) a.push(new Array(1e6).fill('x'));`,
|
|
71
|
+
},
|
|
72
|
+
{
|
|
73
|
+
name: 'flood the output',
|
|
74
|
+
why: 'a log flood is a denial of service on the reader',
|
|
75
|
+
expect: 'truncated',
|
|
76
|
+
code: `for (let i = 0; i < 200000; i++) console.log('spam spam spam spam spam spam');`,
|
|
77
|
+
},
|
|
78
|
+
{
|
|
79
|
+
name: 'exit the process',
|
|
80
|
+
why: 'a snippet must not decide when the host stops',
|
|
81
|
+
expect: 'blocked',
|
|
82
|
+
code: `process.exit(0);`,
|
|
83
|
+
},
|
|
84
|
+
{
|
|
85
|
+
name: 'read the environment',
|
|
86
|
+
why: 'secrets live in the environment more often than in files',
|
|
87
|
+
expect: 'blocked',
|
|
88
|
+
code: `console.log(JSON.stringify(process.env));`,
|
|
89
|
+
},
|
|
90
|
+
{
|
|
91
|
+
name: 'schedule a callback',
|
|
92
|
+
why: 'an async loop is what a synchronous timeout cannot stop',
|
|
93
|
+
expect: 'blocked',
|
|
94
|
+
code: `setInterval(() => console.log('tick'), 10);`,
|
|
95
|
+
},
|
|
96
|
+
{
|
|
97
|
+
name: 'open a socket',
|
|
98
|
+
why: 'the network is the exfiltration path',
|
|
99
|
+
expect: 'blocked',
|
|
100
|
+
code: `fetch('http://1.1.1.1/').then((r) => console.log('reached', r.status));`,
|
|
101
|
+
},
|
|
102
|
+
];
|
|
103
|
+
|
|
104
|
+
/**
|
|
105
|
+
* Run every case and report whether the boundary held.
|
|
106
|
+
*
|
|
107
|
+
* @param {{runCode: Function, capabilities?: any, limits?: any}} deps
|
|
108
|
+
*/
|
|
109
|
+
export async function runAttackSuite(deps) {
|
|
110
|
+
const results = [];
|
|
111
|
+
for (const attack of ATTACKS) {
|
|
112
|
+
const started = Date.now();
|
|
113
|
+
const result = await deps.runCode({
|
|
114
|
+
code: attack.code,
|
|
115
|
+
capabilities: deps.capabilities,
|
|
116
|
+
limits: { wallMs: 3000, vmTimeoutMs: 1500, heapMb: 96, maxOutputBytes: 8 * 1024, ...(deps.limits ?? {}) },
|
|
117
|
+
});
|
|
118
|
+
|
|
119
|
+
const contained = (() => {
|
|
120
|
+
if (attack.expect === 'timeout') return result.timedOut || result.killed || /timed out/i.test(result.stderr);
|
|
121
|
+
if (attack.expect === 'no-leak') {
|
|
122
|
+
// the only thing that matters: did anything come back?
|
|
123
|
+
return !/root:|\/bin\/|uid=|passwd/.test(result.stdout);
|
|
124
|
+
}
|
|
125
|
+
if (attack.expect === 'truncated') return result.truncated || result.stdout.length >= 8 * 1024;
|
|
126
|
+
// blocked: nothing useful escaped, and the run did not report success.
|
|
127
|
+
// A silent failure counts — what matters is that nothing leaked.
|
|
128
|
+
const leaked = /root:|\/bin\/|uid=|reached 200|compiled|^42$/m.test(result.stdout);
|
|
129
|
+
return !leaked && (result.ok === false || result.exitCode !== 0 || result.stderr.trim().length > 0);
|
|
130
|
+
})();
|
|
131
|
+
|
|
132
|
+
results.push({
|
|
133
|
+
name: attack.name,
|
|
134
|
+
why: attack.why,
|
|
135
|
+
expect: attack.expect,
|
|
136
|
+
contained,
|
|
137
|
+
exitCode: result.exitCode,
|
|
138
|
+
timedOut: Boolean(result.timedOut),
|
|
139
|
+
truncated: Boolean(result.truncated),
|
|
140
|
+
stderr: result.stderr.split('\n')[0].slice(0, 120),
|
|
141
|
+
stdout: result.stdout.slice(0, 120),
|
|
142
|
+
ms: Date.now() - started,
|
|
143
|
+
});
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
const failed = results.filter((r) => !r.contained);
|
|
147
|
+
return { total: results.length, contained: results.length - failed.length, failed: failed.length, results };
|
|
148
|
+
}
|
package/src/index.js
ADDED
|
@@ -0,0 +1,204 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @drsamonline/sandbox — B5.6, running model-authored code without trusting it.
|
|
3
|
+
*
|
|
4
|
+
* The honest starting point: **`node:vm` is not a security boundary.** It stops
|
|
5
|
+
* accidents, not adversaries — a determined escape has been demonstrated many
|
|
6
|
+
* times, and any design that rests on it is a design that will be broken.
|
|
7
|
+
*
|
|
8
|
+
* So the boundary here is a *process*, not a context:
|
|
9
|
+
*
|
|
10
|
+
* 1. a separate `node` child process, so a crash or a hang is containable;
|
|
11
|
+
* 2. Node's permission model — no filesystem outside the work directory, no
|
|
12
|
+
* child processes, no worker threads, no native addons;
|
|
13
|
+
* 3. a **network namespace** via `unshare -n` where the platform allows it, so
|
|
14
|
+
* the code has no interfaces to reach;
|
|
15
|
+
* 4. a stripped environment, so a stray `process.env` reads nothing useful;
|
|
16
|
+
* 5. hard limits: wall clock, heap, output size, and a `vm` timeout inside as
|
|
17
|
+
* defence in depth.
|
|
18
|
+
*
|
|
19
|
+
* What this is **not**: a kernel-level jail. `unshare` needs either root or a
|
|
20
|
+
* user namespace, and where it is unavailable the sandbox says so rather than
|
|
21
|
+
* pretending. `sandboxCapabilities()` reports exactly what is enforced on this
|
|
22
|
+
* machine, and `requireNoNetwork` turns "cannot isolate" into "will not run".
|
|
23
|
+
*/
|
|
24
|
+
|
|
25
|
+
import { spawn } from 'node:child_process';
|
|
26
|
+
import { mkdtempSync, rmSync, writeFileSync, mkdirSync } from 'node:fs';
|
|
27
|
+
import { tmpdir } from 'node:os';
|
|
28
|
+
import { dirname, join } from 'node:path';
|
|
29
|
+
import { fileURLToPath } from 'node:url';
|
|
30
|
+
|
|
31
|
+
const HERE = dirname(fileURLToPath(import.meta.url));
|
|
32
|
+
export const RUNNER = join(HERE, 'runner.js');
|
|
33
|
+
|
|
34
|
+
/** Defaults are deliberately small: this is for a snippet, not a build. */
|
|
35
|
+
export const DEFAULT_LIMITS = {
|
|
36
|
+
wallMs: 5000,
|
|
37
|
+
heapMb: 128,
|
|
38
|
+
maxOutputBytes: 64 * 1024,
|
|
39
|
+
vmTimeoutMs: 4000,
|
|
40
|
+
};
|
|
41
|
+
|
|
42
|
+
/** Environment variables a sandboxed run is allowed to see. */
|
|
43
|
+
const PASSTHROUGH_ENV = ['PATH', 'LANG', 'LC_ALL', 'TZ'];
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* What is actually enforced on this machine. Reported, never assumed.
|
|
47
|
+
*
|
|
48
|
+
* @param {{execPath?: string, probe?: (cmd: string, args: string[]) => Promise<boolean>}} [opts]
|
|
49
|
+
*/
|
|
50
|
+
export async function sandboxCapabilities(opts = {}) {
|
|
51
|
+
const node = opts.execPath ?? process.execPath;
|
|
52
|
+
const probe = opts.probe ?? defaultProbe;
|
|
53
|
+
|
|
54
|
+
const [permissionModel, unshare, userNamespace] = await Promise.all([
|
|
55
|
+
probe(node, ['--experimental-permission', '-e', '0']),
|
|
56
|
+
probe('unshare', ['-n', '-r', 'true']),
|
|
57
|
+
probe('unshare', ['-Ur', 'true']),
|
|
58
|
+
]);
|
|
59
|
+
|
|
60
|
+
return {
|
|
61
|
+
node,
|
|
62
|
+
permissionModel,
|
|
63
|
+
networkNamespace: unshare,
|
|
64
|
+
userNamespace,
|
|
65
|
+
// the network jail needs one of the two unshare forms
|
|
66
|
+
networkIsolated: unshare || userNamespace,
|
|
67
|
+
// a run is only "fully isolated" when both are available
|
|
68
|
+
fullyIsolated: permissionModel && (unshare || userNamespace),
|
|
69
|
+
};
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** @returns {Promise<boolean>} */
|
|
73
|
+
function defaultProbe(cmd, args) {
|
|
74
|
+
return new Promise((resolve) => {
|
|
75
|
+
let child;
|
|
76
|
+
try {
|
|
77
|
+
child = spawn(cmd, args, { stdio: 'ignore' });
|
|
78
|
+
} catch {
|
|
79
|
+
resolve(false);
|
|
80
|
+
return;
|
|
81
|
+
}
|
|
82
|
+
const timer = setTimeout(() => {
|
|
83
|
+
child.kill('SIGKILL');
|
|
84
|
+
resolve(false);
|
|
85
|
+
}, 2000);
|
|
86
|
+
child.on('error', () => {
|
|
87
|
+
clearTimeout(timer);
|
|
88
|
+
resolve(false);
|
|
89
|
+
});
|
|
90
|
+
child.on('exit', (code) => {
|
|
91
|
+
clearTimeout(timer);
|
|
92
|
+
resolve(code === 0);
|
|
93
|
+
});
|
|
94
|
+
});
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/**
|
|
98
|
+
* Run a snippet of JavaScript in a contained process.
|
|
99
|
+
*
|
|
100
|
+
* @param {{code: string, limits?: Partial<typeof DEFAULT_LIMITS>, capabilities?: any, requireNoNetwork?: boolean, env?: NodeJS.ProcessEnv}} input
|
|
101
|
+
*/
|
|
102
|
+
export async function runCode(input) {
|
|
103
|
+
const limits = { ...DEFAULT_LIMITS, ...(input.limits ?? {}) };
|
|
104
|
+
const capabilities = input.capabilities ?? (await sandboxCapabilities());
|
|
105
|
+
|
|
106
|
+
if (input.requireNoNetwork && !capabilities.networkIsolated) {
|
|
107
|
+
return {
|
|
108
|
+
ok: false,
|
|
109
|
+
refused: true,
|
|
110
|
+
reason:
|
|
111
|
+
'This machine cannot create a network namespace (no unshare, or no user namespaces). requireNoNetwork is set, so the code was not run — a sandbox that cannot prove its boundary is not a sandbox.',
|
|
112
|
+
capabilities,
|
|
113
|
+
};
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
const workdir = mkdtempSync(join(tmpdir(), 'sui-sandbox-'));
|
|
117
|
+
const file = join(workdir, 'snippet.mjs');
|
|
118
|
+
writeFileSync(file, String(input.code ?? ''), 'utf8');
|
|
119
|
+
|
|
120
|
+
const nodeArgs = [
|
|
121
|
+
'--max-old-space-size=' + limits.heapMb,
|
|
122
|
+
'--no-warnings',
|
|
123
|
+
...(capabilities.permissionModel
|
|
124
|
+
? [
|
|
125
|
+
'--experimental-permission',
|
|
126
|
+
// the work directory, plus the runner itself: the permission model
|
|
127
|
+
// applies to loading our own script, which is a confusing failure to
|
|
128
|
+
// debug if you meet it as a user
|
|
129
|
+
`--allow-fs-read=${workdir}`,
|
|
130
|
+
`--allow-fs-read=${HERE}`,
|
|
131
|
+
`--allow-fs-write=${workdir}`,
|
|
132
|
+
]
|
|
133
|
+
: []),
|
|
134
|
+
RUNNER,
|
|
135
|
+
file,
|
|
136
|
+
String(limits.vmTimeoutMs),
|
|
137
|
+
String(limits.maxOutputBytes),
|
|
138
|
+
];
|
|
139
|
+
|
|
140
|
+
// the network jail wraps the whole node process, so nothing inside can open a socket
|
|
141
|
+
const command = capabilities.networkIsolated ? 'unshare' : capabilities.node;
|
|
142
|
+
const args = capabilities.networkIsolated ? [...(capabilities.networkNamespace ? ['-n', '-r'] : ['-Ur']), capabilities.node, ...nodeArgs] : nodeArgs;
|
|
143
|
+
|
|
144
|
+
const env = {};
|
|
145
|
+
for (const key of PASSTHROUGH_ENV) if (process.env[key]) env[key] = process.env[key];
|
|
146
|
+
// a stripped environment is the cheapest exfiltration defence there is
|
|
147
|
+
env.HOME = workdir;
|
|
148
|
+
env.TMPDIR = workdir;
|
|
149
|
+
|
|
150
|
+
const started = Date.now();
|
|
151
|
+
const result = await new Promise((resolve) => {
|
|
152
|
+
const child = spawn(command, args, { cwd: workdir, env, stdio: ['ignore', 'pipe', 'pipe'] });
|
|
153
|
+
let stdout = '';
|
|
154
|
+
let stderr = '';
|
|
155
|
+
let killed = false;
|
|
156
|
+
|
|
157
|
+
const killTimer = setTimeout(() => {
|
|
158
|
+
killed = true;
|
|
159
|
+
child.kill('SIGKILL');
|
|
160
|
+
}, limits.wallMs);
|
|
161
|
+
|
|
162
|
+
child.stdout.on('data', (chunk) => {
|
|
163
|
+
if (stdout.length < limits.maxOutputBytes) stdout += chunk;
|
|
164
|
+
});
|
|
165
|
+
child.stderr.on('data', (chunk) => {
|
|
166
|
+
if (stderr.length < limits.maxOutputBytes) stderr += chunk;
|
|
167
|
+
});
|
|
168
|
+
|
|
169
|
+
child.on('error', (err) => {
|
|
170
|
+
clearTimeout(killTimer);
|
|
171
|
+
resolve({ exitCode: null, stdout, stderr: `${stderr}${err.message}`, killed });
|
|
172
|
+
});
|
|
173
|
+
child.on('exit', (code, signal) => {
|
|
174
|
+
clearTimeout(killTimer);
|
|
175
|
+
resolve({ exitCode: code, signal, stdout, stderr, killed });
|
|
176
|
+
});
|
|
177
|
+
});
|
|
178
|
+
|
|
179
|
+
try {
|
|
180
|
+
rmSync(workdir, { recursive: true, force: true });
|
|
181
|
+
} catch {
|
|
182
|
+
/* a leftover temp dir is not worth failing a run over */
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
const truncated = result.stdout.length >= limits.maxOutputBytes;
|
|
186
|
+
return {
|
|
187
|
+
ok: result.exitCode === 0 && !result.killed,
|
|
188
|
+
exitCode: result.exitCode,
|
|
189
|
+
killed: result.killed,
|
|
190
|
+
timedOut: result.killed,
|
|
191
|
+
stdout: result.stdout,
|
|
192
|
+
stderr: result.stderr,
|
|
193
|
+
truncated,
|
|
194
|
+
ms: Date.now() - started,
|
|
195
|
+
limits,
|
|
196
|
+
capabilities: {
|
|
197
|
+
permissionModel: capabilities.permissionModel,
|
|
198
|
+
networkIsolated: capabilities.networkIsolated,
|
|
199
|
+
fullyIsolated: capabilities.fullyIsolated,
|
|
200
|
+
},
|
|
201
|
+
};
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
export { ATTACKS, runAttackSuite } from './attacks.js';
|
package/src/runner.js
ADDED
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The child process entry point.
|
|
3
|
+
*
|
|
4
|
+
* It reads the snippet, evaluates it in a `vm` context with code generation off,
|
|
5
|
+
* and exits. The context is **not** the security boundary — the process and its
|
|
6
|
+
* permission flags are — but it stops the accidents: no `require`, no `process`,
|
|
7
|
+
* no `import`, no `eval` of strings, no WASM.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import { readFileSync } from 'node:fs';
|
|
11
|
+
import vm from 'node:vm';
|
|
12
|
+
|
|
13
|
+
const [, , file, vmTimeoutMs = '4000', maxOutputBytes = '65536'] = process.argv;
|
|
14
|
+
const limit = Number(vmTimeoutMs);
|
|
15
|
+
const outputLimit = Number(maxOutputBytes);
|
|
16
|
+
|
|
17
|
+
const code = readFileSync(file, 'utf8');
|
|
18
|
+
|
|
19
|
+
// A rejected promise must fail the run: a snippet whose async half failed has
|
|
20
|
+
// not succeeded, and exiting 0 would report a silent lie.
|
|
21
|
+
process.on('unhandledRejection', (reason) => {
|
|
22
|
+
process.stderr.write(`UnhandledRejection: ${reason?.message ?? String(reason)}\n`);
|
|
23
|
+
process.exit(1);
|
|
24
|
+
});
|
|
25
|
+
|
|
26
|
+
/** Output is captured, not printed live, so a flood cannot outrun the cap. */
|
|
27
|
+
let out = '';
|
|
28
|
+
const write = (prefix, args) => {
|
|
29
|
+
if (out.length >= outputLimit) return;
|
|
30
|
+
const line = args
|
|
31
|
+
.map((a) => {
|
|
32
|
+
if (typeof a === 'string') return a;
|
|
33
|
+
try {
|
|
34
|
+
return JSON.stringify(a);
|
|
35
|
+
} catch {
|
|
36
|
+
return String(a);
|
|
37
|
+
}
|
|
38
|
+
})
|
|
39
|
+
.join(' ');
|
|
40
|
+
out += `${prefix}${line}\n`;
|
|
41
|
+
};
|
|
42
|
+
|
|
43
|
+
const sandbox = {
|
|
44
|
+
console: {
|
|
45
|
+
log: (...a) => write('', a),
|
|
46
|
+
info: (...a) => write('', a),
|
|
47
|
+
warn: (...a) => write('', a),
|
|
48
|
+
error: (...a) => write('', a),
|
|
49
|
+
debug: () => {},
|
|
50
|
+
},
|
|
51
|
+
// no setTimeout/setInterval: an async loop is what a vm timeout cannot stop
|
|
52
|
+
JSON,
|
|
53
|
+
Math,
|
|
54
|
+
Date,
|
|
55
|
+
String,
|
|
56
|
+
Number,
|
|
57
|
+
Boolean,
|
|
58
|
+
Array,
|
|
59
|
+
Object,
|
|
60
|
+
Map,
|
|
61
|
+
Set,
|
|
62
|
+
Promise,
|
|
63
|
+
Error,
|
|
64
|
+
TypeError,
|
|
65
|
+
RangeError,
|
|
66
|
+
RegExp,
|
|
67
|
+
TextEncoder,
|
|
68
|
+
TextDecoder,
|
|
69
|
+
URL,
|
|
70
|
+
URLSearchParams,
|
|
71
|
+
};
|
|
72
|
+
sandbox.globalThis = sandbox;
|
|
73
|
+
|
|
74
|
+
const context = vm.createContext(sandbox, {
|
|
75
|
+
codeGeneration: { strings: false, wasm: false }, // no eval, no new Function, no WASM
|
|
76
|
+
microtaskMode: 'afterEvaluate',
|
|
77
|
+
});
|
|
78
|
+
|
|
79
|
+
try {
|
|
80
|
+
const script = new vm.Script(code, {
|
|
81
|
+
filename: 'snippet.mjs',
|
|
82
|
+
// dynamic import is the way around a missing `require`; refuse it explicitly
|
|
83
|
+
// rather than letting it reject silently inside the context
|
|
84
|
+
importModuleDynamically: () => {
|
|
85
|
+
throw new Error('Dynamic import is not available in the sandbox.');
|
|
86
|
+
},
|
|
87
|
+
});
|
|
88
|
+
script.runInContext(context, { timeout: limit, breakOnSigint: true });
|
|
89
|
+
// let a top-level promise settle, without letting it run forever
|
|
90
|
+
if (typeof sandbox.__result?.then === 'function') {
|
|
91
|
+
await Promise.race([sandbox.__result, new Promise((r) => setTimeout(r, limit))]);
|
|
92
|
+
}
|
|
93
|
+
if (out) process.stdout.write(out.slice(0, outputLimit));
|
|
94
|
+
process.exit(0);
|
|
95
|
+
} catch (err) {
|
|
96
|
+
if (out) process.stdout.write(out.slice(0, outputLimit));
|
|
97
|
+
const name = err?.name ?? 'Error';
|
|
98
|
+
const message = err?.message ?? String(err);
|
|
99
|
+
process.stderr.write(`${name}: ${message}\n`);
|
|
100
|
+
// 124 is what `timeout(1)` uses for "it ran too long"; keep the convention
|
|
101
|
+
process.exit(name === 'Error' && /Script execution timed out/.test(message) ? 124 : 1);
|
|
102
|
+
}
|
package/README.md
DELETED