@glodon-aiot/workspace-sandbox 0.2.0-alpha.1 → 0.2.0-alpha.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.
package/README.md CHANGED
@@ -2,11 +2,43 @@
2
2
 
3
3
  供端侧宿主调用:在工程目录内读写文件,并在 Microsoft Execution Containers 里执行命令和脚本。
4
4
 
5
- 需要 Node.js 24。宿主启动本进程并转发请求。页面协议里没有本地绝对路径。
5
+ 需要 Node.js 24。页面用 WebSocket 直连本进程,宿主只负责启动、关闭和转发就绪信息。页面协议里没有本地绝对路径。只使用 `ws://127.0.0.1`,不提供 `wss://`。
6
+
7
+ ## 直连
8
+
9
+ 宿主启动时绑定系统分配的回环端口,并把页面来源放进允许列表:
10
+
11
+ ```bash
12
+ workspace-sandbox --listen --root /path/to/project --origin https://app.example
13
+ ```
14
+
15
+ stdout 第一行是 `ready`(`url`、`token`、`pid`)或 `fatal`(`reason`、不含路径的 `message`)。之后 stdout 只写 `status` 和 `bye`。令牌不写进 URL、日志和 stderr。
16
+
17
+ 页面连上后,第一帧必须是 `{ "protocol": 2, "op": "auth", "token": "..." }`。文件读写用文本帧加二进制分片(最大 1 MB)。命令的 stdout / stderr 按 32 KB 或 50 ms 合并成文本帧,结束时发 `exit`。超过 16000 字符的输出另写 `tmp/sandbox-exec/<id>.log`,最多 8 MB。
18
+
19
+ stdin 只接受 `{"op":"status"}` 和 `{"op":"shutdown"}`。WebSocket 上不能关机、改根目录或改来源。
20
+
21
+ ## 运行环境
22
+
23
+ 帧格式是普通 WebSocket,不调用某一种 WebView 的接口。Qt WebEngine、WebView2 或其他内核,只要下面的条件成立,就能连上。
24
+
25
+ 本进程:
26
+
27
+ - Node.js 24 或更新版本。
28
+ - 能在 `127.0.0.1` 上绑定系统分配的临时端口。只监听这个地址,不提供 `wss://`。
29
+ - 命令隔离依赖当前系统的容器能力:macOS 用 Seatbelt,Windows 用 ProcessContainer,Linux 用 Bubblewrap。Windows 上 `exec` 暂不可用。
30
+
31
+ 发起连接的页面:
32
+
33
+ - 提供 `WebSocket`,并且 HTTPS 页面可以连接 `ws://127.0.0.1`。Chromium(Qt WebEngine、WebView2)不把回环地址当成混合内容。
34
+ - 浏览器会带上 `Origin`。这个值必须与启动时的某个 `--origin` 完全一致,例如 `https://app.example`。`file://` 的来源是 `null`,只有调试时加上 `--allow-null-origin` 才接受。
35
+ - 公网来源访问回环地址时,嵌入环境要放行这次本地网络访问。沙箱只对匹配的来源返回 `Access-Control-Allow-Private-Network: true`。
36
+ - 页面 CSP 的 `connect-src` 放行 `ws://127.0.0.1:*`。
37
+ - 令牌放在页面内存里,同一页面的脚本可以读到。页面本身应是可信来源。
6
38
 
7
39
  ## 启动
8
40
 
9
- 常驻模式。stdin 每行一个 JSON 请求,stdout 每行一个 JSON 响应,用 `id` 对应。不监听端口。
41
+ 旧的行协议仍可用于单次请求和测试。stdin 每行一个 JSON 请求,stdout 每行一个 JSON 响应,用 `id` 对应。不监听端口。
10
42
 
11
43
  ```bash
12
44
  workspace-sandbox --serve
@@ -1,5 +1,6 @@
1
1
  #!/usr/bin/env node
2
2
  import { manifest, selfCheck } from '../src/check.mjs';
3
+ import { fatalLine, runListen } from '../src/listen.mjs';
3
4
  import { handleRequest, PROTOCOL } from '../src/request.mjs';
4
5
  import { runServe } from '../src/serve.mjs';
5
6
 
@@ -20,8 +21,37 @@ function optionValue(name) {
20
21
  return index > 0 ? process.argv[index + 1] : undefined;
21
22
  }
22
23
 
24
+ function optionValues(name) {
25
+ const values = [];
26
+ for (let index = 0; index < process.argv.length; index += 1) {
27
+ if (process.argv[index] === name && process.argv[index + 1]) values.push(process.argv[index + 1]);
28
+ }
29
+ return values;
30
+ }
31
+
23
32
  let response;
24
- if (process.argv.includes('--serve')) {
33
+ if (process.argv.includes('--listen')) {
34
+ process.on('uncaughtException', () => {
35
+ process.stdout.write(`${JSON.stringify({ protocol: 2, op: 'bye', reason: 'fatal' })}\n`);
36
+ process.exit(1);
37
+ });
38
+ const root = optionValue('--root');
39
+ const origins = optionValues('--origin');
40
+ if (!root || origins.length === 0) {
41
+ process.stdout.write(`${JSON.stringify(fatalLine('invalid-config'))}\n`);
42
+ process.exit(1);
43
+ }
44
+ try {
45
+ const code = await runListen({
46
+ root,
47
+ origins,
48
+ allowNullOrigin: process.argv.includes('--allow-null-origin'),
49
+ });
50
+ process.exit(code || 0);
51
+ } catch {
52
+ process.exit(1);
53
+ }
54
+ } else if (process.argv.includes('--serve')) {
25
55
  await runServe();
26
56
  process.exit(0);
27
57
  } else if (process.argv.includes('--manifest')) {
package/package.json CHANGED
@@ -1,12 +1,10 @@
1
1
  {
2
2
  "name": "@glodon-aiot/workspace-sandbox",
3
- "version": "0.2.0-alpha.1",
3
+ "version": "0.2.0-alpha.2",
4
4
  "description": "供端侧宿主调用:在工程目录内读写文件,并在 Microsoft Execution Containers 里执行命令和脚本。",
5
5
  "license": "MIT",
6
6
  "type": "module",
7
- "bin": {
8
- "workspace-sandbox": "./bin/workspace-sandbox.mjs"
9
- },
7
+ "bin": "./bin/workspace-sandbox.mjs",
10
8
  "files": [
11
9
  "bin",
12
10
  "src"
@@ -19,7 +17,8 @@
19
17
  "bundle": "node scripts/bundle.mjs"
20
18
  },
21
19
  "dependencies": {
22
- "@microsoft/mxc-sdk": "1.0.1"
20
+ "@microsoft/mxc-sdk": "1.0.1",
21
+ "ws": "8.18.3"
23
22
  },
24
23
  "publishConfig": {
25
24
  "access": "public",
package/src/exec.mjs CHANGED
@@ -3,7 +3,7 @@ import { existsSync, mkdirSync, mkdtempSync, realpathSync, rmSync, statSync, sym
3
3
  import { tmpdir } from 'node:os';
4
4
  import { dirname, join } from 'node:path';
5
5
  import { sandboxEnvironment } from './environment.mjs';
6
- import { contained, selectContainment } from './mxc.mjs';
6
+ import { contained, selectContainment, spawnContained } from './mxc.mjs';
7
7
  import { defaultPython, installFailureResponse, preparePython } from './python.mjs';
8
8
  import {
9
9
  isSyntheticCwd,
@@ -19,6 +19,9 @@ import {
19
19
  import { ensureView, outputMappings, toRealCommand, toVirtualCwd, toVirtualText } from './view.mjs';
20
20
 
21
21
  const PROGRAMS = new Set(['python3', 'node', 'sh']);
22
+ const OUTPUT_CHUNK = 32 * 1024;
23
+ const OUTPUT_DELAY_MS = 50;
24
+ const STDERR_HOLDBACK = 4096;
22
25
 
23
26
  function shellPath() {
24
27
  return existsSync('/bin/bash') ? '/bin/bash' : '/bin/sh';
@@ -70,6 +73,99 @@ function runnerScript({ cwdPath, fallbackPath, commandFile, marker }) {
70
73
  ].join('\n');
71
74
  }
72
75
 
76
+ async function emitCoalesced(stream, onChunk) {
77
+ if (!stream) return '';
78
+ let pending = '';
79
+ let full = '';
80
+ let last = Date.now();
81
+ let timer;
82
+ let chain = Promise.resolve();
83
+ const flush = () => {
84
+ if (!pending) return;
85
+ last = Date.now();
86
+ const text = pending;
87
+ pending = '';
88
+ chain = chain.then(async () => {
89
+ for (let index = 0; index < text.length; index += OUTPUT_CHUNK) {
90
+ const piece = text.slice(index, index + OUTPUT_CHUNK);
91
+ full += piece;
92
+ await onChunk(piece);
93
+ }
94
+ });
95
+ };
96
+ const arm = () => {
97
+ if (timer || !pending) return;
98
+ timer = setTimeout(() => {
99
+ timer = undefined;
100
+ flush();
101
+ arm();
102
+ }, OUTPUT_DELAY_MS);
103
+ };
104
+ try {
105
+ for await (const chunk of stream) {
106
+ pending += Buffer.isBuffer(chunk) ? chunk.toString('utf8') : String(chunk);
107
+ if (pending.length >= OUTPUT_CHUNK || Date.now() - last >= OUTPUT_DELAY_MS) {
108
+ if (timer) clearTimeout(timer);
109
+ timer = undefined;
110
+ flush();
111
+ } else arm();
112
+ }
113
+ } finally {
114
+ if (timer) clearTimeout(timer);
115
+ }
116
+ flush();
117
+ await chain;
118
+ return full;
119
+ }
120
+
121
+ async function streamExec({ containment, command, launch, request, mappings, marker, note }) {
122
+ const child = await spawnContained(containment, command, launch);
123
+ const abort = () => {
124
+ try {
125
+ child.kill();
126
+ } catch {
127
+ /* 进程已经结束。 */
128
+ }
129
+ };
130
+ if (request.signal?.aborted) abort();
131
+ else request.signal?.addEventListener('abort', abort, { once: true });
132
+ try {
133
+ child.standardInput?.end();
134
+ if (note) await request.onOutput('stderr', note);
135
+ const stdoutStream = child.standardOutput;
136
+ const stderrStream = child.standardError;
137
+ let held = '';
138
+ const [stdoutRaw, stderrRaw] = await Promise.all([
139
+ emitCoalesced(stdoutStream, (text) => request.onOutput('stdout', toVirtualText(text, mappings))),
140
+ emitCoalesced(stderrStream, async (text) => {
141
+ held += text;
142
+ if (held.length <= STDERR_HOLDBACK) return;
143
+ const emit = held.slice(0, held.length - STDERR_HOLDBACK);
144
+ held = held.slice(-STDERR_HOLDBACK);
145
+ await request.onOutput('stderr', toVirtualText(emit, mappings));
146
+ }),
147
+ ]);
148
+ const waited = await child.wait();
149
+ const { stderr: tail, pwd } = splitMarker(held, marker);
150
+ if (tail) await request.onOutput('stderr', toVirtualText(tail, mappings));
151
+ const { stderr } = splitMarker(stderrRaw, marker);
152
+ const cwd = pwd === undefined ? undefined : toVirtualCwd(pwd, { view: launch.workingDirectory, rootReal: request.rootReal });
153
+ return {
154
+ exitCode: waited.exitCode ?? 1,
155
+ timedOut: Boolean(waited.timedOut),
156
+ stdout: toVirtualText(stdoutRaw, mappings),
157
+ stderr: toVirtualText(`${note}${stderr}`, mappings),
158
+ ...(cwd ? { cwd } : {}),
159
+ };
160
+ } catch (error) {
161
+ abort();
162
+ if (request.signal?.aborted) throw sandboxError('AbortError', '已取消。');
163
+ throw error;
164
+ } finally {
165
+ request.signal?.removeEventListener('abort', abort);
166
+ }
167
+ }
168
+
73
169
  function splitMarker(stderr, marker) {
74
170
  const index = stderr.lastIndexOf(marker);
75
171
  if (index < 0) return { stderr, pwd: undefined };
@@ -111,7 +207,7 @@ export async function runExec(request) {
111
207
  marker,
112
208
  })
113
209
  );
114
- const result = await contained(containment, [shellPath(), runner].map(quoteArg).join(' '), {
210
+ const launch = {
115
211
  filesystem: {
116
212
  readonlyPaths: [view, dirname(dirname(process.execPath)), ...(python?.readonlyPaths ?? [])],
117
213
  readwritePaths: [request.rootReal, tmp],
@@ -123,8 +219,13 @@ export async function runExec(request) {
123
219
  }),
124
220
  timeoutMs: request.timeoutMs,
125
221
  workingDirectory: view,
126
- });
222
+ };
223
+ const command = [shellPath(), runner].map(quoteArg).join(' ');
127
224
  const mappings = outputMappings({ view, rootReal: request.rootReal, rootGiven: request.root });
225
+ if (typeof request.onOutput === 'function') {
226
+ return await streamExec({ containment, command, launch, request, mappings, marker, note: python?.note ?? '' });
227
+ }
228
+ const result = await contained(containment, command, launch);
128
229
  const { stderr, pwd } = splitMarker(result.stderr || '', marker);
129
230
  const cwd = pwd === undefined ? undefined : toVirtualCwd(pwd, { view, rootReal: request.rootReal });
130
231
  return {
package/src/files.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  import { randomBytes } from 'node:crypto';
2
- import { lstat, mkdir, readdir, readFile, realpath, rename, rm, stat, unlink, writeFile } from 'node:fs/promises';
2
+ import { lstat, mkdir, open, opendir, readFile, readdir, realpath, rename, rm, stat, unlink, writeFile } from 'node:fs/promises';
3
3
  import { basename, dirname, isAbsolute, join, relative, sep } from 'node:path';
4
4
  import { isSyntheticCwd, sandboxError, SYNTHETIC_DIR_MESSAGE } from './policy.mjs';
5
5
 
@@ -13,7 +13,7 @@ export function assertWithinQuota(byteLength, limit = MAX_FILE_BYTES) {
13
13
  }
14
14
 
15
15
  /** 页面传来的相对路径。空路径是工程根。拒绝绝对路径、盘符、反斜杠和 `..`。 */
16
- export function splitWorkspacePath(path) {
16
+ export function splitWorkspacePath(path, options = {}) {
17
17
  let rel = String(path ?? '').trim();
18
18
  if (rel === '.') rel = '';
19
19
  while (rel.startsWith('./')) rel = rel.slice(2);
@@ -25,7 +25,8 @@ export function splitWorkspacePath(path) {
25
25
  throw sandboxError('SecurityError', '路径必须是工程内的相对路径。');
26
26
  }
27
27
  if (parts.length > 0 && isSyntheticCwd(parts[0])) {
28
- throw sandboxError('NotAllowedError', SYNTHETIC_DIR_MESSAGE);
28
+ const execLog = options.allowExecLog === true && parts[0] === 'tmp' && parts[1] === 'sandbox-exec' && parts.length >= 3;
29
+ if (!execLog) throw sandboxError('NotAllowedError', SYNTHETIC_DIR_MESSAGE);
29
30
  }
30
31
  return parts;
31
32
  }
@@ -50,8 +51,8 @@ function asFileError(error) {
50
51
  * 逐段 realpath。已经存在的前缀必须落在工程根里,符号链接指向根外则拒绝。
51
52
  * 还不存在的部分接在最近的真实祖先后面,供写入和建目录使用。
52
53
  */
53
- export async function resolveWorkspacePath(rootReal, path) {
54
- const parts = splitWorkspacePath(path);
54
+ export async function resolveWorkspacePath(rootReal, path, options) {
55
+ const parts = splitWorkspacePath(path, options);
55
56
  let ancestor = rootReal;
56
57
  const missing = [];
57
58
  for (let index = 0; index < parts.length; index += 1) {
@@ -264,6 +265,100 @@ async function moveOp(request) {
264
265
  return {};
265
266
  }
266
267
 
268
+ const LOG_PATH = { allowExecLog: true };
269
+ const READ_RETRY_MS = [0, 20, 50, 100];
270
+
271
+ function sleep(ms) {
272
+ return new Promise((resolve) => setTimeout(resolve, ms));
273
+ }
274
+
275
+ export function isSharingConflict(error) {
276
+ return error?.code === 'EBUSY' || error?.code === 'ETXTBSY' || error?.code === 'EAGAIN';
277
+ }
278
+
279
+ /** 按偏移读取窗口,不把整个文件读进一个缓冲区。文件在读取期间变化时最多再试 3 次。 */
280
+ export async function readFileWindow(rootReal, path, offset, maxBytes) {
281
+ if (!Number.isInteger(offset) || offset < 0) throw sandboxError('TypeError', 'offset 必须是非负整数。');
282
+ if (!Number.isInteger(maxBytes) || maxBytes < 0) throw sandboxError('TypeError', 'maxBytes 必须是非负整数。');
283
+ if (maxBytes > MAX_FILE_BYTES) throw sandboxError('QuotaExceededError', '文件超过 50 MB。');
284
+ const real = await resolveWorkspacePath(rootReal, path, LOG_PATH);
285
+ for (let attempt = 0; attempt < READ_RETRY_MS.length; attempt += 1) {
286
+ if (READ_RETRY_MS[attempt] > 0) await sleep(READ_RETRY_MS[attempt]);
287
+ let before;
288
+ try {
289
+ before = await stat(real);
290
+ } catch (error) {
291
+ if (error?.code === 'ENOENT') throw sandboxError('NotFoundError', '目标不存在。');
292
+ if (isSharingConflict(error)) throw sandboxError('NoModificationAllowedError', '文件正在被其他程序修改。');
293
+ throw error;
294
+ }
295
+ if (before.isDirectory()) throw sandboxError('TypeMismatchError', '不是文件。');
296
+ const length = Math.min(maxBytes, Math.max(0, before.size - offset));
297
+ const handle = await open(real, 'r');
298
+ let bytes;
299
+ try {
300
+ bytes = Buffer.alloc(length);
301
+ if (length > 0) await handle.read(bytes, 0, length, offset);
302
+ } finally {
303
+ await handle.close();
304
+ }
305
+ const after = await stat(real);
306
+ if (before.size === after.size && before.mtimeMs === after.mtimeMs) {
307
+ return { bytes, size: after.size, offset, returned: bytes.length };
308
+ }
309
+ }
310
+ throw sandboxError('NoModificationAllowedError', '文件正在被其他程序修改。');
311
+ }
312
+
313
+ /** 目录流最多取 limit 项。超出时不再 stat 其余条目。 */
314
+ export async function listLimited(rootReal, path, limit = 2000) {
315
+ const real = await resolveWorkspacePath(rootReal, path);
316
+ let info;
317
+ try {
318
+ info = await stat(real);
319
+ } catch (error) {
320
+ if (error?.code === 'ENOENT') throw sandboxError('NotFoundError', '目标不存在。');
321
+ throw error;
322
+ }
323
+ if (!info.isDirectory()) throw sandboxError('TypeMismatchError', '不是目录。');
324
+ const dir = await opendir(real);
325
+ const names = [];
326
+ let truncated = false;
327
+ try {
328
+ for await (const child of dir) {
329
+ if (names.length === limit) {
330
+ truncated = true;
331
+ break;
332
+ }
333
+ names.push(child.name);
334
+ }
335
+ } finally {
336
+ await dir.close().catch(() => undefined);
337
+ }
338
+ names.sort((left, right) => (left < right ? -1 : left > right ? 1 : 0));
339
+ const entries = [];
340
+ for (const name of names) {
341
+ const childPath = join(real, name);
342
+ let realChild;
343
+ try {
344
+ realChild = await realpath(childPath);
345
+ } catch {
346
+ entries.push({ name, kind: 'file' });
347
+ continue;
348
+ }
349
+ if (escapesRoot(rootReal, realChild)) continue;
350
+ let childInfo;
351
+ try {
352
+ childInfo = await stat(realChild);
353
+ } catch {
354
+ entries.push({ name, kind: 'file' });
355
+ continue;
356
+ }
357
+ entries.push(entryFor(name, childInfo));
358
+ }
359
+ return truncated ? { entries, truncated: true } : { entries };
360
+ }
361
+
267
362
  const OPERATIONS = {
268
363
  stat: statOp,
269
364
  list: listOp,
package/src/frames.mjs ADDED
@@ -0,0 +1,31 @@
1
+ export const MAX_BINARY_PAYLOAD = 1024 * 1024;
2
+
3
+ export function encodeBinaryFrame({ id, offset, eof, payload }) {
4
+ const idBytes = Buffer.from(id);
5
+ if (idBytes.length > 0xffff) throw new Error('id 过长。');
6
+ const body = Buffer.isBuffer(payload) ? payload : Buffer.from(payload);
7
+ if (body.length > MAX_BINARY_PAYLOAD) throw new Error('分片超过 1 MB。');
8
+ const header = Buffer.alloc(4 + idBytes.length + 8);
9
+ header.writeUInt8(1, 0);
10
+ header.writeUInt8(eof ? 1 : 0, 1);
11
+ header.writeUInt16BE(idBytes.length, 2);
12
+ idBytes.copy(header, 4);
13
+ header.writeBigUInt64BE(BigInt(offset), 4 + idBytes.length);
14
+ return Buffer.concat([header, body]);
15
+ }
16
+
17
+ export function decodeBinaryFrame(data) {
18
+ const bytes = Buffer.isBuffer(data) ? data : Buffer.from(data);
19
+ if (bytes.length < 12) throw Object.assign(new Error('分片过短。'), { code: 'TypeError' });
20
+ const version = bytes.readUInt8(0);
21
+ if (version !== 1) throw Object.assign(new Error('分片版本不支持。'), { code: 'NotSupportedError' });
22
+ const eof = (bytes.readUInt8(1) & 1) === 1;
23
+ const idLen = bytes.readUInt16BE(2);
24
+ const offsetAt = 4 + idLen;
25
+ if (bytes.length < offsetAt + 8) throw Object.assign(new Error('分片过短。'), { code: 'TypeError' });
26
+ const id = bytes.toString('utf8', 4, offsetAt);
27
+ const offset = Number(bytes.readBigUInt64BE(offsetAt));
28
+ const payload = bytes.subarray(offsetAt + 8);
29
+ if (payload.length > MAX_BINARY_PAYLOAD) throw Object.assign(new Error('分片超过 1 MB。'), { code: 'QuotaExceededError' });
30
+ return { id, offset, eof, payload };
31
+ }
package/src/listen.mjs ADDED
@@ -0,0 +1,638 @@
1
+ import { randomBytes } from 'node:crypto';
2
+ import { createServer } from 'node:http';
3
+ import { realpathSync, statSync } from 'node:fs';
4
+ import { mkdir, readFile, readdir, rename, stat, unlink, writeFile } from 'node:fs/promises';
5
+ import { createInterface } from 'node:readline';
6
+ import { dirname, join } from 'node:path';
7
+ import { WebSocketServer } from 'ws';
8
+ import { decodeBinaryFrame, encodeBinaryFrame } from './frames.mjs';
9
+ import {
10
+ isSharingConflict,
11
+ listLimited,
12
+ MAX_FILE_BYTES,
13
+ readFileWindow,
14
+ resolveWorkspacePath,
15
+ runFileOp,
16
+ splitWorkspacePath,
17
+ } from './files.mjs';
18
+ import { sandboxError } from './policy.mjs';
19
+ import { runExec } from './exec.mjs';
20
+ import { runPython } from './runPython.mjs';
21
+ import { cacheBase, rootHash } from './view.mjs';
22
+
23
+ export const LISTEN_PROTOCOL = 2;
24
+ const MAX_TEXT = 256 * 1024;
25
+ const MAX_FRAME = 1024 * 1024;
26
+ const HIGH_WATER = 4 * 1024 * 1024;
27
+ const LOW_WATER = 1024 * 1024;
28
+ const CHUNK = 32 * 1024;
29
+ const LOG_MAX = 8 * 1024 * 1024;
30
+ const OBSERVE_CHARS = 16_000;
31
+ const FILE_OP_LIMIT = 8;
32
+ const LIST_LIMIT = 2000;
33
+ const WRITE_IDLE_MS = 30_000;
34
+ const AUTH_MS = 5_000;
35
+ const PING_MS = 30_000;
36
+ const PONG_MS = 90_000;
37
+
38
+ const FATAL_MESSAGE = {
39
+ 'listen-failed': '沙箱没有监听到端口。',
40
+ 'invalid-config': '沙箱启动参数不正确。',
41
+ };
42
+
43
+ export function untilDrained(getAmount, aborted = () => false) {
44
+ if (getAmount() <= HIGH_WATER) return Promise.resolve();
45
+ return new Promise((resolve) => {
46
+ const timer = setInterval(() => {
47
+ if (aborted() || getAmount() <= LOW_WATER) {
48
+ clearInterval(timer);
49
+ resolve();
50
+ }
51
+ }, 10);
52
+ });
53
+ }
54
+
55
+ export function fatalLine(reason, code) {
56
+ return {
57
+ protocol: LISTEN_PROTOCOL,
58
+ op: 'fatal',
59
+ reason,
60
+ ...(code ? { code } : {}),
61
+ message: FATAL_MESSAGE[reason] || FATAL_MESSAGE['invalid-config'],
62
+ };
63
+ }
64
+
65
+ function writeLine(output, value) {
66
+ output.write(`${JSON.stringify(value)}\n`);
67
+ }
68
+
69
+ function failure(error) {
70
+ const name = error?.code && /^[A-Z][A-Za-z]+Error$/.test(error.code) ? error.code : 'NotAllowedError';
71
+ return { protocol: LISTEN_PROTOCOL, ok: false, name, message: error?.message || '沙箱执行失败。' };
72
+ }
73
+
74
+ function originAllowed(origin, origins, allowNullOrigin) {
75
+ if (origin == null || origin === '' || origin === 'null') return allowNullOrigin === true && origin === 'null';
76
+ return origins.includes(origin);
77
+ }
78
+
79
+ function hostAllowed(host, port) {
80
+ const value = String(host || '').replace(/:\d+$/, (suffix) => suffix);
81
+ return value === `127.0.0.1:${port}` || value === `localhost:${port}`;
82
+ }
83
+
84
+ async function cleanupPartials(rootReal) {
85
+ const file = join(cacheBase(), rootHash(rootReal), 'partials.json');
86
+ let paths = [];
87
+ try {
88
+ paths = JSON.parse(await readFileText(file));
89
+ } catch {
90
+ return;
91
+ }
92
+ await Promise.all(paths.map((path) => unlink(path).catch(() => undefined)));
93
+ await writeFile(file, '[]');
94
+ }
95
+
96
+ function readFileText(file) {
97
+ return readFile(file, 'utf8');
98
+ }
99
+
100
+ async function rememberPartial(rootReal, path) {
101
+ const dir = join(cacheBase(), rootHash(rootReal));
102
+ await mkdir(dir, { recursive: true });
103
+ const file = join(dir, 'partials.json');
104
+ let paths = [];
105
+ try {
106
+ paths = JSON.parse(await readFileText(file));
107
+ } catch {
108
+ paths = [];
109
+ }
110
+ paths.push(path);
111
+ await writeFile(file, JSON.stringify(paths));
112
+ return async () => {
113
+ const current = JSON.parse(await readFileText(file).catch(() => '[]'));
114
+ await writeFile(file, JSON.stringify(current.filter((item) => item !== path)));
115
+ };
116
+ }
117
+
118
+ async function pruneLogs(rootReal) {
119
+ const dir = join(rootReal, 'tmp', 'sandbox-exec');
120
+ let names = [];
121
+ try {
122
+ names = await readdir(dir);
123
+ } catch {
124
+ return;
125
+ }
126
+ const cutoff = Date.now() - 24 * 60 * 60 * 1000;
127
+ await Promise.all(
128
+ names.map(async (name) => {
129
+ const path = join(dir, name);
130
+ const info = await stat(path).catch(() => undefined);
131
+ if (info && info.mtimeMs < cutoff) await unlink(path).catch(() => undefined);
132
+ })
133
+ );
134
+ }
135
+
136
+ function logName(id) {
137
+ return /^[A-Za-z0-9._-]+$/.test(id) ? id : 'exec';
138
+ }
139
+
140
+ async function writeExecLog(rootReal, id, text) {
141
+ const dir = join(rootReal, 'tmp', 'sandbox-exec');
142
+ await mkdir(dir, { recursive: true });
143
+ const path = join(dir, `${logName(id)}.log`);
144
+ const body = Buffer.from(text);
145
+ const truncated = body.length > LOG_MAX;
146
+ await writeFile(path, truncated ? body.subarray(0, LOG_MAX) : body);
147
+ return { logPath: `tmp/sandbox-exec/${logName(id)}.log`, logTruncated: truncated };
148
+ }
149
+
150
+ /**
151
+ * 在 127.0.0.1 上提供协议 2 的 WebSocket。stdout 只写 ready、fatal、status、bye。
152
+ * execute / runPythonCommand 可在测试里替换,默认走 MXC。
153
+ */
154
+ export function runListen({
155
+ root,
156
+ origins,
157
+ allowNullOrigin = false,
158
+ input = process.stdin,
159
+ output = process.stdout,
160
+ signals = true,
161
+ execute = runExec,
162
+ runPythonCommand = runPython,
163
+ runFile = runFileOp,
164
+ renameFile = rename,
165
+ }) {
166
+ if (typeof root !== 'string' || origins?.length < 1) {
167
+ writeLine(output, fatalLine('invalid-config'));
168
+ return Promise.reject(Object.assign(new Error('invalid-config'), { fatal: true }));
169
+ }
170
+
171
+ return new Promise((resolve, reject) => {
172
+ let token = '';
173
+ let rootReal;
174
+ try {
175
+ rootReal = splitCheck(root);
176
+ } catch {
177
+ writeLine(output, fatalLine('invalid-config'));
178
+ reject(Object.assign(new Error('invalid-config'), { fatal: true }));
179
+ return;
180
+ }
181
+
182
+ const http = createServer((request, response) => {
183
+ if (request.method !== 'OPTIONS') {
184
+ response.writeHead(404);
185
+ response.end();
186
+ return;
187
+ }
188
+ const origin = request.headers.origin;
189
+ if (!originAllowed(origin, origins, allowNullOrigin)) {
190
+ response.writeHead(403);
191
+ response.end();
192
+ return;
193
+ }
194
+ response.writeHead(204, {
195
+ 'Access-Control-Allow-Origin': origin,
196
+ 'Access-Control-Allow-Private-Network': 'true',
197
+ 'Access-Control-Allow-Methods': 'GET, OPTIONS',
198
+ 'Access-Control-Allow-Headers': 'Content-Type',
199
+ Vary: 'Origin',
200
+ });
201
+ response.end();
202
+ });
203
+ const sockets = new WebSocketServer({ noServer: true, maxPayload: MAX_FRAME });
204
+ let unauthenticated = 0;
205
+ let authenticated;
206
+ let command;
207
+ let fileOps = 0;
208
+ let writeActive = false;
209
+ let stopped = false;
210
+
211
+ const finish = (code) => {
212
+ if (stopped) return;
213
+ stopped = true;
214
+ clearInterval(pingTimer);
215
+ input?.pause?.();
216
+ for (const client of sockets.clients) client.terminate();
217
+ sockets.close();
218
+ http.close(() => resolve(code));
219
+ };
220
+
221
+ const sendBye = async (reason, code) => {
222
+ command?.abort();
223
+ const frame = { protocol: LISTEN_PROTOCOL, op: 'bye', reason };
224
+ if (authenticated?.readyState === 1) {
225
+ try {
226
+ authenticated.send(JSON.stringify(frame));
227
+ } catch {
228
+ /* 连接已经不可用。 */
229
+ }
230
+ }
231
+ writeLine(output, { ...frame, ...(code === undefined ? {} : {}) });
232
+ authenticated?.close();
233
+ finish(code);
234
+ };
235
+
236
+ http.on('upgrade', (request, socket, head) => {
237
+ const address = http.address();
238
+ const port = typeof address === 'object' && address ? address.port : 0;
239
+ if (!hostAllowed(request.headers.host, port) || !originAllowed(request.headers.origin, origins, allowNullOrigin)) {
240
+ socket.destroy();
241
+ return;
242
+ }
243
+ if (unauthenticated >= 4) {
244
+ socket.destroy();
245
+ return;
246
+ }
247
+ sockets.handleUpgrade(request, socket, head, (ws) => sockets.emit('connection', ws, request));
248
+ });
249
+
250
+ sockets.on('connection', (ws) => {
251
+ unauthenticated += 1;
252
+ let authed = false;
253
+ let lastPong = Date.now();
254
+ const writes = new Map();
255
+ const earlyFrames = new Map();
256
+ const authTimer = setTimeout(() => {
257
+ if (!authed) ws.close(1008);
258
+ }, AUTH_MS);
259
+ ws.lastPong = Date.now();
260
+ ws.on('pong', () => {
261
+ lastPong = Date.now();
262
+ ws.lastPong = lastPong;
263
+ });
264
+ ws.on('close', () => {
265
+ clearTimeout(authTimer);
266
+ if (!authed) unauthenticated = Math.max(0, unauthenticated - 1);
267
+ if (authenticated === ws) {
268
+ command?.abort();
269
+ authenticated = undefined;
270
+ }
271
+ earlyFrames.clear();
272
+ for (const pending of writes.values()) pending.fail(sandboxError('AbortError', '连接已关闭。'));
273
+ });
274
+ let chain = Promise.resolve();
275
+ ws.on('message', (data, isBinary) => {
276
+ chain = chain.then(() => onMessage(data, isBinary)).catch((error) => {
277
+ if (ws.readyState === 1) ws.send(JSON.stringify({ protocol: LISTEN_PROTOCOL, ...failure(error) }));
278
+ });
279
+ });
280
+
281
+ async function onMessage(data, isBinary) {
282
+ if (!authed) {
283
+ let text;
284
+ try {
285
+ text = JSON.parse(data.toString());
286
+ } catch {
287
+ text = undefined;
288
+ }
289
+ if (!text || text.op !== 'auth' || text.protocol !== LISTEN_PROTOCOL || text.token !== token) {
290
+ ws.close(1008);
291
+ return;
292
+ }
293
+ authed = true;
294
+ unauthenticated = Math.max(0, unauthenticated - 1);
295
+ clearTimeout(authTimer);
296
+ if (authenticated && authenticated !== ws) {
297
+ authenticated.send(JSON.stringify({ protocol: LISTEN_PROTOCOL, ok: false, name: 'AbortError', message: '连接已被替换。' }));
298
+ authenticated.close();
299
+ }
300
+ authenticated = ws;
301
+ ws.send(JSON.stringify({ protocol: LISTEN_PROTOCOL, op: 'auth', ok: true }));
302
+ return;
303
+ }
304
+ await handleMessage(ws, data, isBinary, writes);
305
+ }
306
+
307
+ async function handleMessage(socket, data, isBinary, pendingWrites) {
308
+ if (isBinary) {
309
+ const frame = decodeBinaryFrame(data);
310
+ const pending = pendingWrites.get(frame.id);
311
+ if (!pending) {
312
+ const queued = earlyFrames.get(frame.id) ?? [];
313
+ queued.push(frame);
314
+ earlyFrames.set(frame.id, queued);
315
+ return;
316
+ }
317
+ pending.enqueue(frame);
318
+ return;
319
+ }
320
+ if (data.length > MAX_TEXT) {
321
+ socket.send(JSON.stringify({ protocol: LISTEN_PROTOCOL, ...failure(sandboxError('QuotaExceededError', '文本帧超过 256 KB。')) }));
322
+ return;
323
+ }
324
+ let message;
325
+ try {
326
+ message = JSON.parse(data.toString());
327
+ } catch {
328
+ socket.send(JSON.stringify({ protocol: LISTEN_PROTOCOL, ...failure(sandboxError('TypeError', '请求不是合法的 JSON。')) }));
329
+ return;
330
+ }
331
+ if (message.root !== undefined || message.op === 'shutdown' || message.op === 'setRoot' || message.op === 'setOrigin') {
332
+ socket.send(JSON.stringify({ protocol: LISTEN_PROTOCOL, id: message.id, ...failure(sandboxError('SecurityError', '不能通过连接改变沙箱。')) }));
333
+ return;
334
+ }
335
+ if (message.op === 'cancel') {
336
+ if (command?.id === message.id) command.abort();
337
+ return;
338
+ }
339
+ if (message.op === 'write') {
340
+ await beginWrite(socket, message, pendingWrites);
341
+ return;
342
+ }
343
+ if (message.op === 'exec' || message.op === 'run_python') {
344
+ void beginCommand(socket, message);
345
+ return;
346
+ }
347
+ void beginFile(socket, message);
348
+ }
349
+ });
350
+
351
+ const pingTimer = setInterval(() => {
352
+ const now = Date.now();
353
+ const busy = Boolean(command) || fileOps > 0 || writeActive;
354
+ for (const client of sockets.clients) {
355
+ if (!busy && now - lastPongOf(client) > PONG_MS) client.close();
356
+ else client.ping();
357
+ }
358
+ }, PING_MS);
359
+
360
+ function lastPongOf(client) {
361
+ return client.lastPong || Date.now();
362
+ }
363
+
364
+ async function sendJson(socket, value) {
365
+ await waitForRoom(socket);
366
+ if (socket.readyState !== 1) return;
367
+ socket.send(JSON.stringify(value));
368
+ }
369
+
370
+ function waitForRoom(socket) {
371
+ return untilDrained(() => socket.bufferedAmount || 0, () => socket.readyState !== 1);
372
+ }
373
+
374
+ async function beginFile(socket, message) {
375
+ if (fileOps >= FILE_OP_LIMIT) {
376
+ await sendJson(socket, { protocol: LISTEN_PROTOCOL, id: message.id, ...failure(sandboxError('QuotaExceededError', '请求过多。')) });
377
+ return;
378
+ }
379
+ fileOps += 1;
380
+ try {
381
+ if (message.op === 'list') {
382
+ const result = await listLimited(rootReal, message.path ?? '', LIST_LIMIT);
383
+ await sendJson(socket, { protocol: LISTEN_PROTOCOL, id: message.id, ok: true, ...result });
384
+ return;
385
+ }
386
+ if (message.op === 'read') {
387
+ const window = await readFileWindow(rootReal, message.path ?? '', message.offset ?? 0, message.maxBytes ?? MAX_FILE_BYTES);
388
+ let sent = 0;
389
+ while (sent < window.bytes.length) {
390
+ const payload = window.bytes.subarray(sent, sent + MAX_FRAME);
391
+ const eof = sent + payload.length >= window.bytes.length;
392
+ await waitForRoom(socket);
393
+ socket.send(encodeBinaryFrame({ id: message.id, offset: sent, eof, payload }));
394
+ sent += payload.length;
395
+ }
396
+ await sendJson(socket, {
397
+ protocol: LISTEN_PROTOCOL,
398
+ id: message.id,
399
+ ok: true,
400
+ size: window.size,
401
+ offset: window.offset,
402
+ returned: window.returned,
403
+ });
404
+ return;
405
+ }
406
+ const result = await runFile(fileRequest(message));
407
+ await sendJson(socket, { protocol: LISTEN_PROTOCOL, id: message.id, ok: true, ...result });
408
+ } catch (error) {
409
+ await sendJson(socket, { protocol: LISTEN_PROTOCOL, id: message.id, ...failure(error) });
410
+ } finally {
411
+ fileOps -= 1;
412
+ }
413
+ }
414
+
415
+ function fileRequest(message) {
416
+ const request = { op: message.op, root, rootReal, path: message.path ?? '' };
417
+ if (message.op === 'move') {
418
+ request.from = message.from ?? '';
419
+ request.to = message.to ?? '';
420
+ }
421
+ if (message.op === 'remove') request.recursive = message.recursive === true;
422
+ if (message.op === 'mkdir') request.path = message.path ?? '';
423
+ try {
424
+ splitWorkspacePath(request.path || request.from || '');
425
+ } catch (error) {
426
+ throw error;
427
+ }
428
+ return request;
429
+ }
430
+
431
+ async function beginWrite(socket, message, pendingWrites) {
432
+ if (fileOps >= FILE_OP_LIMIT || writeActive) {
433
+ await sendJson(socket, { protocol: LISTEN_PROTOCOL, id: message.id, ...failure(sandboxError('QuotaExceededError', '请求过多。')) });
434
+ return;
435
+ }
436
+ const size = message.size;
437
+ if (!Number.isInteger(size) || size < 0 || size > MAX_FILE_BYTES) {
438
+ await sendJson(socket, { protocol: LISTEN_PROTOCOL, id: message.id, ...failure(sandboxError('QuotaExceededError', '文件超过 50 MB。')) });
439
+ return;
440
+ }
441
+ let real;
442
+ try {
443
+ real = await resolveWorkspacePath(rootReal, message.path ?? '');
444
+ splitWorkspacePath(message.path ?? '');
445
+ } catch (error) {
446
+ await sendJson(socket, { protocol: LISTEN_PROTOCOL, id: message.id, ...failure(error) });
447
+ return;
448
+ }
449
+ if (message.createDirectories === true) await mkdir(dirname(real), { recursive: true });
450
+ fileOps += 1;
451
+ writeActive = true;
452
+ let settled = false;
453
+ const temporary = `${real}.${randomBytes(6).toString('hex')}.partial`;
454
+ const forget = await rememberPartial(rootReal, temporary);
455
+ let received = 0;
456
+ let timer;
457
+ const fail = async (error) => {
458
+ if (settled) return;
459
+ settled = true;
460
+ clearTimeout(timer);
461
+ pendingWrites.delete(message.id);
462
+ await unlink(temporary).catch(() => undefined);
463
+ await forget();
464
+ fileOps -= 1;
465
+ writeActive = false;
466
+ await sendJson(socket, { protocol: LISTEN_PROTOCOL, id: message.id, ...failure(error) });
467
+ };
468
+ let chunkChain = Promise.resolve();
469
+ const pending = {
470
+ fail,
471
+ enqueue(frame) {
472
+ chunkChain = chunkChain.then(() => pending.chunk(frame)).catch((error) => fail(error));
473
+ },
474
+ chunk: async (frame) => {
475
+ if (frame.offset !== received) {
476
+ await fail(sandboxError('QuotaExceededError', '分片偏移不连续。'));
477
+ return;
478
+ }
479
+ received += frame.payload.length;
480
+ await writeFile(temporary, frame.payload, { flag: received === frame.payload.length ? 'w' : 'a' });
481
+ clearTimeout(timer);
482
+ timer = setTimeout(() => fail(sandboxError('AbortError', '写入超时。')), WRITE_IDLE_MS);
483
+ if ((socket.bufferedAmount || 0) + frame.payload.length >= HIGH_WATER) socket.pause?.();
484
+ await sendJson(socket, { protocol: LISTEN_PROTOCOL, id: message.id, op: 'ack', offset: received });
485
+ socket.resume?.();
486
+ if (!frame.eof) return;
487
+ if (received !== size) {
488
+ await fail(sandboxError('QuotaExceededError', '写入长度与 size 不一致。'));
489
+ return;
490
+ }
491
+ try {
492
+ await renameFile(temporary, real);
493
+ } catch (error) {
494
+ await fail(
495
+ isSharingConflict(error)
496
+ ? sandboxError('NoModificationAllowedError', '文件正在被占用,没有写入。')
497
+ : error
498
+ );
499
+ return;
500
+ }
501
+ if (settled) return;
502
+ settled = true;
503
+ clearTimeout(timer);
504
+ pendingWrites.delete(message.id);
505
+ await forget();
506
+ fileOps -= 1;
507
+ writeActive = false;
508
+ await sendJson(socket, { protocol: LISTEN_PROTOCOL, id: message.id, ok: true });
509
+ },
510
+ };
511
+ pendingWrites.set(message.id, pending);
512
+ timer = setTimeout(() => fail(sandboxError('AbortError', '写入超时。')), WRITE_IDLE_MS);
513
+ const queued = earlyFrames.get(message.id) ?? [];
514
+ earlyFrames.delete(message.id);
515
+ for (const frame of queued) pending.enqueue(frame);
516
+ if (size === 0) pending.enqueue({ id: message.id, offset: 0, eof: true, payload: Buffer.alloc(0) });
517
+ }
518
+
519
+ async function beginCommand(socket, message) {
520
+ if (command) {
521
+ await sendJson(socket, {
522
+ protocol: LISTEN_PROTOCOL,
523
+ id: message.id,
524
+ ...failure(sandboxError('AbortError', '已有一个命令在运行。')),
525
+ });
526
+ return;
527
+ }
528
+ const controller = new AbortController();
529
+ command = { id: message.id, abort: () => controller.abort() };
530
+ try {
531
+ await pruneLogs(rootReal);
532
+ let streamed = false;
533
+ const request = {
534
+ ...message,
535
+ root,
536
+ rootReal,
537
+ op: message.op,
538
+ signal: controller.signal,
539
+ onOutput: async (kind, text) => {
540
+ streamed = true;
541
+ if (!text) return;
542
+ await sendJson(socket, { protocol: LISTEN_PROTOCOL, id: message.id, op: kind, text });
543
+ },
544
+ };
545
+ const result = controller.signal.aborted
546
+ ? null
547
+ : message.op === 'run_python'
548
+ ? await runPythonCommand(request)
549
+ : await execute(request);
550
+ if (controller.signal.aborted || !result) {
551
+ await sendJson(socket, { protocol: LISTEN_PROTOCOL, id: message.id, ...failure(sandboxError('AbortError', '已取消。')) });
552
+ return;
553
+ }
554
+ const stdout = result.stdout || '';
555
+ const stderr = result.stderr || '';
556
+ if (!streamed) {
557
+ for (let index = 0; index < stdout.length; index += CHUNK) {
558
+ await sendJson(socket, { protocol: LISTEN_PROTOCOL, id: message.id, op: 'stdout', text: stdout.slice(index, index + CHUNK) });
559
+ }
560
+ for (let index = 0; index < stderr.length; index += CHUNK) {
561
+ await sendJson(socket, { protocol: LISTEN_PROTOCOL, id: message.id, op: 'stderr', text: stderr.slice(index, index + CHUNK) });
562
+ }
563
+ }
564
+ const combined = `${stdout}${stderr}`;
565
+ const logged = combined.length > OBSERVE_CHARS ? await writeExecLog(rootReal, message.id, combined) : {};
566
+ await sendJson(socket, {
567
+ protocol: LISTEN_PROTOCOL,
568
+ id: message.id,
569
+ op: 'exit',
570
+ exitCode: result.exitCode ?? 1,
571
+ timedOut: result.timedOut === true,
572
+ ...(result.cwd ? { cwd: result.cwd } : {}),
573
+ ...logged,
574
+ });
575
+ } catch (error) {
576
+ await sendJson(socket, { protocol: LISTEN_PROTOCOL, id: message.id, ...failure(error) });
577
+ } finally {
578
+ if (command?.id === message.id) command = undefined;
579
+ }
580
+ }
581
+
582
+ const lines = input ? createInterface({ input, crlfDelay: Infinity }) : undefined;
583
+ lines?.on('line', (line) => {
584
+ let message;
585
+ try {
586
+ message = JSON.parse(line);
587
+ } catch {
588
+ return;
589
+ }
590
+ if (message.op === 'status') {
591
+ writeLine(output, {
592
+ protocol: LISTEN_PROTOCOL,
593
+ op: 'status',
594
+ state: 'ready',
595
+ execBusy: Boolean(command),
596
+ connections: authenticated ? 1 : 0,
597
+ });
598
+ } else if (message.op === 'shutdown') {
599
+ void sendBye('shutdown', 0);
600
+ }
601
+ });
602
+
603
+ if (signals) {
604
+ process.once('SIGTERM', () => void sendBye('shutdown', 0));
605
+ }
606
+
607
+ cleanupPartials(rootReal)
608
+ .then(
609
+ () =>
610
+ new Promise((ok, bad) => {
611
+ http.once('error', bad);
612
+ http.listen(0, '127.0.0.1', ok);
613
+ })
614
+ )
615
+ .then(() => {
616
+ const address = http.address();
617
+ const port = typeof address === 'object' && address ? address.port : 0;
618
+ token = randomBytes(32).toString('hex');
619
+ writeLine(output, {
620
+ protocol: LISTEN_PROTOCOL,
621
+ op: 'ready',
622
+ url: `ws://127.0.0.1:${port}`,
623
+ token,
624
+ pid: process.pid,
625
+ });
626
+ })
627
+ .catch((error) => {
628
+ writeLine(output, fatalLine(error?.code === 'EADDRINUSE' || error?.code === 'EACCES' ? 'listen-failed' : 'invalid-config', error?.code));
629
+ finish(1);
630
+ });
631
+ });
632
+ }
633
+
634
+ function splitCheck(root) {
635
+ const real = realpathSync(root);
636
+ if (!statSync(real).isDirectory()) throw new Error('invalid-config');
637
+ return real;
638
+ }
package/src/mxc.mjs CHANGED
@@ -35,29 +35,47 @@ export function systemReadonlyPaths() {
35
35
  return process.platform === 'linux' ? LINUX_SYSTEM_PATHS.filter((dir) => existsSync(dir)) : [];
36
36
  }
37
37
 
38
+ function containerRequest(containment, command, { filesystem, network, environment, timeoutMs, workingDirectory }) {
39
+ return {
40
+ command,
41
+ containment,
42
+ inheritDefaultEnvironment: false,
43
+ filesystem: {
44
+ ...filesystem,
45
+ readonlyPaths: [...systemReadonlyPaths(), ...(filesystem.readonlyPaths ?? [])],
46
+ deniedPaths: [...DENIED_PATHS, ...(filesystem.deniedPaths ?? [])],
47
+ },
48
+ network: network ?? { egress: { default: 'deny' } },
49
+ environment,
50
+ timeoutMs,
51
+ workingDirectory,
52
+ };
53
+ }
54
+
55
+ function asSandboxError(mxc, error) {
56
+ const message =
57
+ error instanceof mxc.MxcError
58
+ ? `${error.message}${error.remediation ? `\n${error.remediation}` : ''}`
59
+ : error?.message;
60
+ return sandboxError('NotAllowedError', message || '沙箱启动失败。');
61
+ }
62
+
38
63
  /** command 会被 MXC 按 shell 规则拆分,调用方负责引号。 */
39
- export async function contained(containment, command, { filesystem, network, environment, timeoutMs, workingDirectory }) {
64
+ export async function contained(containment, command, options) {
65
+ const mxc = await loadMxc();
66
+ try {
67
+ return await mxc.run(containerRequest(containment, command, options));
68
+ } catch (error) {
69
+ throw asSandboxError(mxc, error);
70
+ }
71
+ }
72
+
73
+ /** 流式执行。调用方在 wait 之前取走 stdout / stderr,取消时 kill。 */
74
+ export async function spawnContained(containment, command, options) {
40
75
  const mxc = await loadMxc();
41
76
  try {
42
- return await mxc.run({
43
- command,
44
- containment,
45
- inheritDefaultEnvironment: false,
46
- filesystem: {
47
- ...filesystem,
48
- readonlyPaths: [...systemReadonlyPaths(), ...(filesystem.readonlyPaths ?? [])],
49
- deniedPaths: [...DENIED_PATHS, ...(filesystem.deniedPaths ?? [])],
50
- },
51
- network: network ?? { egress: { default: 'deny' } },
52
- environment,
53
- timeoutMs,
54
- workingDirectory,
55
- });
77
+ return await mxc.spawn(containerRequest(containment, command, options));
56
78
  } catch (error) {
57
- const message =
58
- error instanceof mxc.MxcError
59
- ? `${error.message}${error.remediation ? `\n${error.remediation}` : ''}`
60
- : error?.message;
61
- throw sandboxError('NotAllowedError', message || '沙箱启动失败。');
79
+ throw asSandboxError(mxc, error);
62
80
  }
63
81
  }