@glodon-aiot/workspace-sandbox 0.2.0-alpha.1 → 0.2.0-alpha.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/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
  }
package/src/runPython.mjs CHANGED
@@ -7,7 +7,7 @@ import { mentionsSyntheticDir, quoteArg, resolvePythonRun, SYNTHETIC_DIR_MESSAGE
7
7
  import { defaultPython, installFailureResponse, preparePython } from './python.mjs';
8
8
  import { outputMappings, toVirtualText } from './view.mjs';
9
9
 
10
- /** 旧的 run_python 请求:在工程根目录用宿主指定的 Python 跑一个 .py 脚本。 */
10
+ /** 在工程根目录用宿主指定的 Python 跑一个 .py 脚本。 */
11
11
  export async function runPython(request) {
12
12
  if (mentionsSyntheticDir(request.script)) {
13
13
  return { exitCode: 1, timedOut: false, stdout: '', stderr: `${SYNTHETIC_DIR_MESSAGE}\n` };
package/src/request.mjs DELETED
@@ -1,112 +0,0 @@
1
- import { realpathSync, statSync } from 'node:fs';
2
- import { isAbsolute } from 'node:path';
3
- import { runExec } from './exec.mjs';
4
- import { runFileOp } from './files.mjs';
5
- import { clampTimeout, isSafeRelative, sandboxError } from './policy.mjs';
6
- import { runPython } from './runPython.mjs';
7
- import { outputMappings, toVirtualText } from './view.mjs';
8
-
9
- export const PROTOCOL = 1;
10
- const MAX_COMMAND_CHARS = 64 * 1024;
11
- const MAX_ARGV = 64;
12
-
13
- function requireRoot(root) {
14
- if (typeof root !== 'string' || !isAbsolute(root)) throw sandboxError('NotAllowedError', '缺少工程目录。');
15
- let real;
16
- try {
17
- real = realpathSync(root);
18
- } catch {
19
- throw sandboxError('NotFoundError', '工程目录不存在。');
20
- }
21
- if (!statSync(real).isDirectory()) throw sandboxError('TypeMismatchError', '工程目录不是文件夹。');
22
- return real;
23
- }
24
-
25
- function requireText(value, label) {
26
- if (typeof value !== 'string' || value.includes('\0')) throw sandboxError('TypeError', `${label}必须是字符串。`);
27
- return value;
28
- }
29
-
30
- function parseExec(raw) {
31
- const hasCommand = raw.command !== undefined;
32
- const hasArgv = raw.argv !== undefined;
33
- if (hasCommand === hasArgv) throw sandboxError('TypeError', 'command 和 argv 必须二选一。');
34
- const cwd = raw.cwd === undefined || raw.cwd === '' || raw.cwd === '.' ? '.' : requireText(raw.cwd, 'cwd ');
35
- if (cwd !== '.' && !isSafeRelative(cwd)) {
36
- throw sandboxError('SecurityError', 'cwd 必须是工程内的相对路径。');
37
- }
38
- if (raw.python !== undefined && (typeof raw.python !== 'string' || !isAbsolute(raw.python))) {
39
- throw sandboxError('NotAllowedError', 'python 必须是绝对路径。');
40
- }
41
- const request = { op: 'exec', cwd, python: raw.python };
42
- if (hasCommand) {
43
- const command = requireText(raw.command, 'command ');
44
- if (!command.trim()) throw sandboxError('TypeError', 'command 不能为空。');
45
- if (command.length > MAX_COMMAND_CHARS) throw sandboxError('QuotaExceededError', 'command 过长。');
46
- return { ...request, command };
47
- }
48
- if (!Array.isArray(raw.argv) || raw.argv.length < 2 || raw.argv.length > MAX_ARGV) {
49
- throw sandboxError('TypeError', `argv 需要程序和脚本,最多 ${MAX_ARGV} 项。`);
50
- }
51
- const argv = raw.argv.map((item) => requireText(item, 'argv 每一项'));
52
- if (argv.join('').length > MAX_COMMAND_CHARS) throw sandboxError('QuotaExceededError', 'argv 过长。');
53
- if (!isSafeRelative(argv[1])) throw sandboxError('SecurityError', '脚本必须是工程内的相对路径。');
54
- return { ...request, argv };
55
- }
56
-
57
- const FILE_OPS = new Set(['stat', 'list', 'read', 'write', 'mkdir', 'remove', 'move']);
58
-
59
- function parseFile(raw, op) {
60
- const request = { op, root: raw.root, rootReal: requireRoot(raw.root) };
61
- if (op === 'move') {
62
- request.from = raw.from ?? '';
63
- request.to = raw.to ?? '';
64
- return request;
65
- }
66
- request.path = raw.path ?? '';
67
- if (op === 'write') {
68
- if (raw.contentBase64 !== undefined && typeof raw.contentBase64 !== 'string') {
69
- throw sandboxError('TypeError', 'contentBase64 必须是字符串。');
70
- }
71
- request.contentBase64 = typeof raw.contentBase64 === 'string' ? raw.contentBase64 : '';
72
- request.createDirectories = raw.createDirectories === true;
73
- }
74
- if (op === 'remove') request.recursive = raw.recursive === true;
75
- return request;
76
- }
77
-
78
- export function parseRequest(raw) {
79
- if (!raw || typeof raw !== 'object' || Array.isArray(raw)) throw sandboxError('TypeError', '请求必须是 JSON 对象。');
80
- if (raw.protocol !== undefined && raw.protocol !== PROTOCOL) {
81
- throw sandboxError('NotSupportedError', `沙箱协议 ${raw.protocol} 不支持,当前为 ${PROTOCOL}。`);
82
- }
83
- const op = raw.op ?? 'run_python';
84
- if (FILE_OPS.has(op)) return parseFile(raw, op);
85
- const base = { root: raw.root, rootReal: requireRoot(raw.root), timeoutMs: clampTimeout(raw.timeoutMs) };
86
- if (op === 'exec') return { ...base, ...parseExec(raw) };
87
- if (op === 'run_python') return { ...base, op, script: raw.script, args: raw.args, python: raw.python };
88
- throw sandboxError('NotSupportedError', `不支持的操作 ${String(op)}。`);
89
- }
90
-
91
- export async function handleRequest(raw) {
92
- try {
93
- const request = parseRequest(raw);
94
- const result =
95
- request.op === 'exec' ? await runExec(request) : request.op === 'run_python' ? await runPython(request) : await runFileOp(request);
96
- return { protocol: PROTOCOL, ok: true, ...result };
97
- } catch (error) {
98
- let rootReal;
99
- try {
100
- rootReal = realpathSync(raw.root);
101
- } catch {
102
- rootReal = undefined;
103
- }
104
- const mappings = outputMappings({ rootReal, rootGiven: typeof raw?.root === 'string' ? raw.root : undefined });
105
- return {
106
- protocol: PROTOCOL,
107
- ok: false,
108
- name: error?.code && /^[A-Z][A-Za-z]+Error$/.test(error.code) ? error.code : 'NotAllowedError',
109
- message: toVirtualText(error?.message || '沙箱执行失败。', mappings),
110
- };
111
- }
112
- }
package/src/serve.mjs DELETED
@@ -1,65 +0,0 @@
1
- import { createInterface } from 'node:readline';
2
- import { handleRequest, PROTOCOL } from './request.mjs';
3
-
4
- function isCommand(raw) {
5
- if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return false;
6
- const op = raw.op ?? 'run_python';
7
- return op === 'exec' || op === 'run_python';
8
- }
9
-
10
- /**
11
- * 常驻进程:stdin 每行一个 JSON 请求,stdout 每行一个 JSON 响应,用 id 对应。
12
- * 文件操作可以同时进行。命令仍是一次一个,第二个直接返回 AbortError。
13
- */
14
- export function runServe(input = process.stdin, output = process.stdout) {
15
- return new Promise((resolve, reject) => {
16
- const lines = createInterface({ input, crlfDelay: Infinity });
17
- let pending = 0;
18
- let closed = false;
19
- let commandBusy = false;
20
- const finish = () => {
21
- if (closed && pending === 0) resolve();
22
- };
23
- const respond = (raw, response) => {
24
- const id = raw && typeof raw === 'object' && typeof raw.id === 'string' ? raw.id : undefined;
25
- output.write(`${JSON.stringify(id === undefined ? response : { id, ...response })}\n`);
26
- };
27
- lines.on('line', (line) => {
28
- const text = line.trim();
29
- if (!text) return;
30
- pending += 1;
31
- let raw;
32
- try {
33
- raw = JSON.parse(text);
34
- } catch {
35
- raw = undefined;
36
- }
37
- const command = isCommand(raw);
38
- if (command && commandBusy) {
39
- respond(raw, { protocol: PROTOCOL, ok: false, name: 'AbortError', message: '已有一个命令在运行。' });
40
- pending -= 1;
41
- finish();
42
- return;
43
- }
44
- if (command) commandBusy = true;
45
- const task = raw
46
- ? handleRequest(raw)
47
- : Promise.resolve({ protocol: PROTOCOL, ok: false, name: 'TypeError', message: '请求不是合法的 JSON。' });
48
- task
49
- .then(
50
- (response) => respond(raw, response),
51
- () => respond(raw, { protocol: PROTOCOL, ok: false, name: 'NotAllowedError', message: '沙箱执行失败。' })
52
- )
53
- .finally(() => {
54
- if (command) commandBusy = false;
55
- pending -= 1;
56
- finish();
57
- });
58
- });
59
- lines.on('close', () => {
60
- closed = true;
61
- finish();
62
- });
63
- input.on?.('error', reject);
64
- });
65
- }