@glodon-aiot/workspace-sandbox 0.0.0-stage → 0.2.0-alpha.0

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.
@@ -0,0 +1,50 @@
1
+ #!/usr/bin/env node
2
+ import { manifest, selfCheck } from '../src/check.mjs';
3
+ import { handleRequest, PROTOCOL } from '../src/request.mjs';
4
+ import { runServe } from '../src/serve.mjs';
5
+
6
+ function readStdin() {
7
+ return new Promise((resolve, reject) => {
8
+ let body = '';
9
+ process.stdin.setEncoding('utf8');
10
+ process.stdin.on('data', (chunk) => {
11
+ body += chunk;
12
+ });
13
+ process.stdin.on('end', () => resolve(body));
14
+ process.stdin.on('error', reject);
15
+ });
16
+ }
17
+
18
+ function optionValue(name) {
19
+ const index = process.argv.indexOf(name);
20
+ return index > 0 ? process.argv[index + 1] : undefined;
21
+ }
22
+
23
+ let response;
24
+ if (process.argv.includes('--serve')) {
25
+ await runServe();
26
+ process.exit(0);
27
+ } else if (process.argv.includes('--manifest')) {
28
+ response = manifest();
29
+ } else if (process.argv.includes('--check')) {
30
+ const report = await selfCheck({ python: optionValue('--python') });
31
+ process.exitCode = report.ok ? 0 : 1;
32
+ if (!process.argv.includes('--json')) {
33
+ const lines = report.checks.map((check) => (check.ok ? `✓ ${check.name}` : `✗ ${check.name}:${check.detail}`));
34
+ if (report.ok) lines.push('沙箱已运行:sandbox-ok');
35
+ process.stdout.write(`${lines.join('\n')}\n`);
36
+ process.exit();
37
+ }
38
+ response = report;
39
+ } else {
40
+ let request;
41
+ try {
42
+ request = JSON.parse((await readStdin()) || '{}');
43
+ } catch {
44
+ request = undefined;
45
+ }
46
+ response = request
47
+ ? await handleRequest(request)
48
+ : { protocol: PROTOCOL, ok: false, name: 'TypeError', message: '请求不是合法的 JSON。' };
49
+ }
50
+ process.stdout.write(JSON.stringify(response));
package/package.json CHANGED
@@ -1,6 +1,26 @@
1
1
  {
2
2
  "name": "@glodon-aiot/workspace-sandbox",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.0-alpha.0",
4
+ "description": "供端侧宿主调用:在工程目录内读写文件,并在 Microsoft Execution Containers 里执行命令和脚本。",
5
+ "license": "MIT",
6
+ "type": "module",
7
+ "bin": "./bin/workspace-sandbox.mjs",
8
+ "files": [
9
+ "bin",
10
+ "src"
11
+ ],
12
+ "engines": {
13
+ "node": ">=24.0.0"
14
+ },
15
+ "scripts": {
16
+ "test": "node --test \"test/*.test.mjs\"",
17
+ "bundle": "node scripts/bundle.mjs"
18
+ },
19
+ "dependencies": {
20
+ "@microsoft/mxc-sdk": "1.0.1"
21
+ },
22
+ "publishConfig": {
23
+ "access": "public",
24
+ "registry": "https://registry.npmjs.org/"
25
+ }
26
+ }
package/src/check.mjs ADDED
@@ -0,0 +1,58 @@
1
+ import { mkdtempSync, readFileSync, realpathSync, rmSync } from 'node:fs';
2
+ import { tmpdir } from 'node:os';
3
+ import { join } from 'node:path';
4
+ import { PROTOCOL, handleRequest } from './request.mjs';
5
+ import { removeView } from './view.mjs';
6
+
7
+ const pkg = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8'));
8
+
9
+ export function manifest() {
10
+ return {
11
+ name: pkg.name,
12
+ version: pkg.version,
13
+ protocol: PROTOCOL,
14
+ platform: `${process.platform}-${process.arch}`,
15
+ node: process.versions.node,
16
+ };
17
+ }
18
+
19
+ const PROBES = [
20
+ { name: 'shell', command: 'echo ok > check.txt && cat check.txt && ls', expect: /ok\ncheck\.txt/ },
21
+ { name: 'python', command: 'python3 -c "print(6*7)"', expect: /^42$/m },
22
+ { name: 'node', command: 'node -e "console.log(6*7)"', expect: /^42$/m },
23
+ {
24
+ name: 'network-denied',
25
+ command:
26
+ 'node -e "require(\'net\').connect(443,\'1.1.1.1\').on(\'connect\',()=>process.exit(3)).on(\'error\',()=>console.log(\'denied\'))"',
27
+ expect: /^denied$/m,
28
+ },
29
+ ];
30
+
31
+ /** 在临时工程里跑一遍 shell、python、node 和断网检查,宿主据此决定是否声明 sandbox-exec。 */
32
+ export async function selfCheck({ python } = {}) {
33
+ const root = realpathSync(mkdtempSync(join(tmpdir(), 'glodon-sandbox-check-')));
34
+ try {
35
+ const checks = [];
36
+ for (const probe of PROBES) {
37
+ const response = await handleRequest({
38
+ protocol: PROTOCOL,
39
+ op: 'exec',
40
+ root,
41
+ cwd: '.',
42
+ command: probe.command,
43
+ timeoutMs: 20_000,
44
+ ...(python ? { python } : {}),
45
+ });
46
+ const passed = response.ok && response.exitCode === 0 && probe.expect.test(response.stdout);
47
+ checks.push({
48
+ name: probe.name,
49
+ ok: passed,
50
+ ...(passed ? {} : { detail: response.ok ? `${response.stdout}${response.stderr}`.trim() : response.message }),
51
+ });
52
+ }
53
+ return { ...manifest(), ok: checks.every((check) => check.ok), checks };
54
+ } finally {
55
+ removeView(root);
56
+ rmSync(root, { recursive: true, force: true });
57
+ }
58
+ }
@@ -0,0 +1,27 @@
1
+ import { delimiter, join } from 'node:path';
2
+
3
+ const POSIX_PATH = ['/usr/bin', '/bin', '/usr/sbin', '/sbin'];
4
+
5
+ /** 子进程只拿到这里列出的变量,宿主自己的 PATH 和密钥都不传进去。 */
6
+ export function sandboxEnvironment({ tmp, pathDirs = [], extra = {} }) {
7
+ const system =
8
+ process.platform === 'win32' && process.env.SystemRoot
9
+ ? [join(process.env.SystemRoot, 'System32'), process.env.SystemRoot]
10
+ : POSIX_PATH;
11
+ const path = [...new Set([...pathDirs, ...system])].join(delimiter);
12
+ const environment = {
13
+ PATH: path,
14
+ HOME: tmp,
15
+ TMPDIR: tmp,
16
+ TEMP: tmp,
17
+ TMP: tmp,
18
+ LANG: process.platform === 'darwin' ? 'en_US.UTF-8' : 'C.UTF-8',
19
+ PYTHONUTF8: '1',
20
+ PYTHONDONTWRITEBYTECODE: '1',
21
+ ...(process.platform === 'win32' && process.env.SystemRoot
22
+ ? { SystemRoot: process.env.SystemRoot, LOCALAPPDATA: tmp, USERPROFILE: tmp }
23
+ : {}),
24
+ ...extra,
25
+ };
26
+ return Object.fromEntries(Object.entries(environment).filter(([, value]) => value !== undefined));
27
+ }
package/src/exec.mjs ADDED
@@ -0,0 +1,140 @@
1
+ import { randomBytes } from 'node:crypto';
2
+ import { existsSync, mkdirSync, mkdtempSync, realpathSync, rmSync, statSync, symlinkSync, writeFileSync } from 'node:fs';
3
+ import { tmpdir } from 'node:os';
4
+ import { dirname, join } from 'node:path';
5
+ import { sandboxEnvironment } from './environment.mjs';
6
+ import { contained, selectContainment } from './mxc.mjs';
7
+ import { defaultPython, installFailureResponse, preparePython } from './python.mjs';
8
+ import {
9
+ isSyntheticCwd,
10
+ mentionsSyntheticDir,
11
+ quoteArg,
12
+ resolveInside,
13
+ SANDBOX_REQUIREMENTS_FILE,
14
+ sandboxError,
15
+ shellQuote,
16
+ SYNTHETIC_DIR_MESSAGE,
17
+ truncateOutput,
18
+ } from './policy.mjs';
19
+ import { ensureView, outputMappings, toRealCommand, toVirtualCwd, toVirtualText } from './view.mjs';
20
+
21
+ const PROGRAMS = new Set(['python3', 'node', 'sh']);
22
+
23
+ function shellPath() {
24
+ return existsSync('/bin/bash') ? '/bin/bash' : '/bin/sh';
25
+ }
26
+
27
+ const NO_PIP = `#!/bin/sh
28
+ echo '沙箱不能联网安装依赖。把包名写进工程根目录的 ${SANDBOX_REQUIREMENTS_FILE},下次执行前会自动安装。' >&2
29
+ exit 1
30
+ `;
31
+
32
+ function makeBin(tmp, python) {
33
+ const bin = join(tmp, 'bin');
34
+ mkdirSync(bin);
35
+ symlinkSync(process.execPath, join(bin, 'node'));
36
+ for (const name of ['pip', 'pip3']) writeFileSync(join(bin, name), NO_PIP, { mode: 0o755 });
37
+ if (python) {
38
+ symlinkSync(python, join(bin, 'python3'));
39
+ symlinkSync(python, join(bin, 'python'));
40
+ }
41
+ return bin;
42
+ }
43
+
44
+ /** 脚本路径换成视图路径,命令文本里不出现工程真实路径。 */
45
+ function scriptPath(request, view) {
46
+ const real = resolveInside(request.rootReal, request.argv[1]);
47
+ if (!statSync(real).isFile()) throw sandboxError('TypeMismatchError', '脚本不是文件。');
48
+ return join(view, request.argv[1]);
49
+ }
50
+
51
+ function commandScript(request, view) {
52
+ if (request.command !== undefined) return `${toRealCommand(request.command, view)}\n`;
53
+ const [program, , ...args] = request.argv;
54
+ return `${[program, scriptPath(request, view), ...args].map(shellQuote).join(' ')}\n`;
55
+ }
56
+
57
+ /**
58
+ * run.sh 先进入视图里的工作目录,再在同一个 shell 里执行命令,最后把 $PWD 带着随机标记写到 stderr,
59
+ * 用来回传 cd 之后的目录。
60
+ */
61
+ function runnerScript({ cwdPath, fallbackPath, commandFile, marker }) {
62
+ return [
63
+ 'exec </dev/null',
64
+ `cd -- ${shellQuote(cwdPath)} 2>/dev/null || cd -- ${shellQuote(fallbackPath)} || exit 1`,
65
+ `. ${shellQuote(commandFile)}`,
66
+ '__glodon_status=$?',
67
+ `printf '\\n%s%s\\n' ${shellQuote(marker)} "$PWD" >&2`,
68
+ 'exit $__glodon_status',
69
+ '',
70
+ ].join('\n');
71
+ }
72
+
73
+ function splitMarker(stderr, marker) {
74
+ const index = stderr.lastIndexOf(marker);
75
+ if (index < 0) return { stderr, pwd: undefined };
76
+ const pwd = stderr.slice(index + marker.length).split('\n')[0];
77
+ const before = stderr.slice(0, index);
78
+ return { stderr: before.endsWith('\n') ? before.slice(0, -1) : before, pwd };
79
+ }
80
+
81
+ export async function runExec(request) {
82
+ const script = request.argv?.[1];
83
+ if (isSyntheticCwd(request.cwd) || mentionsSyntheticDir(request.command) || mentionsSyntheticDir(script)) {
84
+ return { exitCode: 1, timedOut: false, stdout: '', stderr: `${SYNTHETIC_DIR_MESSAGE}\n` };
85
+ }
86
+ if (process.platform === 'win32') throw sandboxError('NotAllowedError', 'Windows 宿主暂不支持执行 shell 命令。');
87
+ if (request.argv && !PROGRAMS.has(request.argv[0])) {
88
+ throw sandboxError('NotAllowedError', '只能用 python3、node 或 sh 执行脚本。');
89
+ }
90
+ const containment = await selectContainment();
91
+ const view = ensureView(request.rootReal);
92
+ const tmp = realpathSync(mkdtempSync(join(tmpdir(), 'glodon-sandbox-')));
93
+ try {
94
+ const pythonPath = request.python ?? defaultPython();
95
+ const python = pythonPath
96
+ ? await preparePython({ containment, rootReal: request.rootReal, python: pythonPath, tmp })
97
+ : undefined;
98
+ if (python?.failure) return installFailureResponse(python.failure);
99
+ const venv = python?.venv === true;
100
+ const bin = makeBin(tmp, venv ? undefined : python?.python);
101
+ const marker = `__glodon_cwd_${randomBytes(8).toString('hex')}__`;
102
+ const commandFile = join(tmp, 'command.sh');
103
+ const runner = join(tmp, 'run.sh');
104
+ writeFileSync(commandFile, commandScript(request, view));
105
+ writeFileSync(
106
+ runner,
107
+ runnerScript({
108
+ cwdPath: request.cwd === '.' ? view : join(view, request.cwd),
109
+ fallbackPath: view,
110
+ commandFile,
111
+ marker,
112
+ })
113
+ );
114
+ const result = await contained(containment, [shellPath(), runner].map(quoteArg).join(' '), {
115
+ filesystem: {
116
+ readonlyPaths: [view, dirname(dirname(process.execPath)), ...(python?.readonlyPaths ?? [])],
117
+ readwritePaths: [request.rootReal, tmp],
118
+ },
119
+ network: { egress: { default: 'deny' } },
120
+ environment: sandboxEnvironment({
121
+ tmp,
122
+ pathDirs: [bin, ...(venv ? [dirname(python.python)] : [])],
123
+ }),
124
+ timeoutMs: request.timeoutMs,
125
+ workingDirectory: view,
126
+ });
127
+ const mappings = outputMappings({ view, rootReal: request.rootReal, rootGiven: request.root });
128
+ const { stderr, pwd } = splitMarker(result.stderr || '', marker);
129
+ const cwd = pwd === undefined ? undefined : toVirtualCwd(pwd, { view, rootReal: request.rootReal });
130
+ return {
131
+ exitCode: result.exitCode ?? 1,
132
+ timedOut: Boolean(result.timedOut),
133
+ stdout: truncateOutput(toVirtualText(result.stdout, mappings)),
134
+ stderr: truncateOutput(toVirtualText(`${python?.note ?? ''}${stderr}`, mappings)),
135
+ ...(cwd ? { cwd } : {}),
136
+ };
137
+ } finally {
138
+ rmSync(tmp, { recursive: true, force: true });
139
+ }
140
+ }
package/src/files.mjs ADDED
@@ -0,0 +1,289 @@
1
+ import { randomBytes } from 'node:crypto';
2
+ import { lstat, mkdir, readdir, readFile, realpath, rename, rm, stat, unlink, writeFile } from 'node:fs/promises';
3
+ import { basename, dirname, isAbsolute, join, relative, sep } from 'node:path';
4
+ import { isSyntheticCwd, sandboxError, SYNTHETIC_DIR_MESSAGE } from './policy.mjs';
5
+
6
+ /** 与页面约定一致:单文件不超过 50 MB。 */
7
+ export const MAX_FILE_BYTES = 50 * 1024 * 1024;
8
+
9
+ const DOM_ERROR = /^[A-Z][A-Za-z]+Error$/;
10
+
11
+ export function assertWithinQuota(byteLength, limit = MAX_FILE_BYTES) {
12
+ if (byteLength > limit) throw sandboxError('QuotaExceededError', '文件超过 50 MB。');
13
+ }
14
+
15
+ /** 页面传来的相对路径。空路径是工程根。拒绝绝对路径、盘符、反斜杠和 `..`。 */
16
+ export function splitWorkspacePath(path) {
17
+ let rel = String(path ?? '').trim();
18
+ if (rel === '.') rel = '';
19
+ while (rel.startsWith('./')) rel = rel.slice(2);
20
+ if (rel.startsWith('/') || rel.includes(':') || rel.includes('\\') || rel.includes('\0')) {
21
+ throw sandboxError('SecurityError', '路径必须是工程内的相对路径。');
22
+ }
23
+ const parts = rel.split('/').filter((part) => part.length > 0);
24
+ if (parts.some((part) => part === '.' || part === '..')) {
25
+ throw sandboxError('SecurityError', '路径必须是工程内的相对路径。');
26
+ }
27
+ if (parts.length > 0 && isSyntheticCwd(parts[0])) {
28
+ throw sandboxError('NotAllowedError', SYNTHETIC_DIR_MESSAGE);
29
+ }
30
+ return parts;
31
+ }
32
+
33
+ function escapesRoot(rootReal, real) {
34
+ const fromRoot = relative(rootReal, real);
35
+ if (fromRoot === '') return false;
36
+ if (isAbsolute(fromRoot)) return true;
37
+ return fromRoot.split(sep).includes('..');
38
+ }
39
+
40
+ function asFileError(error) {
41
+ if (error?.code && DOM_ERROR.test(error.code)) return error;
42
+ if (error?.code === 'ENOENT') return sandboxError('NotFoundError', '目标不存在。');
43
+ if (error?.code === 'ENOTDIR' || error?.code === 'EEXIST') return sandboxError('TypeMismatchError', '路径中有同名文件。');
44
+ if (error?.code === 'ENOTEMPTY') return sandboxError('InvalidModificationError', '目录不为空。');
45
+ if (error?.code === 'EACCES' || error?.code === 'EPERM') return sandboxError('NotAllowedError', '文件打不开。');
46
+ return sandboxError('NoModificationAllowedError', '操作没有完成。');
47
+ }
48
+
49
+ /**
50
+ * 逐段 realpath。已经存在的前缀必须落在工程根里,符号链接指向根外则拒绝。
51
+ * 还不存在的部分接在最近的真实祖先后面,供写入和建目录使用。
52
+ */
53
+ export async function resolveWorkspacePath(rootReal, path) {
54
+ const parts = splitWorkspacePath(path);
55
+ let ancestor = rootReal;
56
+ const missing = [];
57
+ for (let index = 0; index < parts.length; index += 1) {
58
+ let real;
59
+ try {
60
+ real = await realpath(join(ancestor, parts[index]));
61
+ } catch (error) {
62
+ if (error?.code !== 'ENOENT') throw error;
63
+ missing.push(...parts.slice(index));
64
+ break;
65
+ }
66
+ if (escapesRoot(rootReal, real)) throw sandboxError('SecurityError', '路径不在工程目录内。');
67
+ ancestor = real;
68
+ }
69
+ return missing.length === 0 ? ancestor : join(ancestor, ...missing);
70
+ }
71
+
72
+ /** 删除和移动作用在最后一段本身,不跟随这一段上的符号链接。 */
73
+ async function resolveEntryPath(rootReal, path) {
74
+ const parts = splitWorkspacePath(path);
75
+ const name = parts.pop();
76
+ if (!name) throw sandboxError('InvalidModificationError', '不能改动工程根目录。');
77
+ const parent = await resolveWorkspacePath(rootReal, parts.join('/'));
78
+ let parentReal;
79
+ try {
80
+ parentReal = await realpath(parent);
81
+ } catch (error) {
82
+ if (error?.code === 'ENOENT') throw sandboxError('NotFoundError', '父目录不存在。');
83
+ throw error;
84
+ }
85
+ if (escapesRoot(rootReal, parentReal)) throw sandboxError('SecurityError', '路径不在工程目录内。');
86
+ const parentStat = await stat(parentReal);
87
+ if (!parentStat.isDirectory()) throw sandboxError('NotFoundError', '父目录不存在。');
88
+ return join(parentReal, name);
89
+ }
90
+
91
+ function entryFor(name, info) {
92
+ if (info.isDirectory()) return { name, kind: 'directory' };
93
+ return { name, kind: 'file', size: info.size, lastModified: Math.trunc(info.mtimeMs) };
94
+ }
95
+
96
+ async function statOp(request) {
97
+ const real = await resolveWorkspacePath(request.rootReal, request.path);
98
+ let info;
99
+ try {
100
+ info = await stat(real);
101
+ } catch (error) {
102
+ if (error?.code === 'ENOENT') throw sandboxError('NotFoundError', '目标不存在。');
103
+ throw error;
104
+ }
105
+ return { entry: entryFor(basename(real), info) };
106
+ }
107
+
108
+ async function listOp(request) {
109
+ const real = await resolveWorkspacePath(request.rootReal, request.path);
110
+ let info;
111
+ try {
112
+ info = await stat(real);
113
+ } catch (error) {
114
+ if (error?.code === 'ENOENT') throw sandboxError('NotFoundError', '目标不存在。');
115
+ throw error;
116
+ }
117
+ if (!info.isDirectory()) throw sandboxError('TypeMismatchError', '不是目录。');
118
+ const children = await readdir(real, { withFileTypes: true });
119
+ const entries = [];
120
+ for (const child of children) {
121
+ const childPath = join(real, child.name);
122
+ let realChild;
123
+ try {
124
+ realChild = await realpath(childPath);
125
+ } catch {
126
+ entries.push({ name: child.name, kind: 'file' });
127
+ continue;
128
+ }
129
+ if (escapesRoot(request.rootReal, realChild)) continue;
130
+ let childInfo;
131
+ try {
132
+ childInfo = await stat(realChild);
133
+ } catch {
134
+ entries.push({ name: child.name, kind: 'file' });
135
+ continue;
136
+ }
137
+ entries.push(entryFor(child.name, childInfo));
138
+ }
139
+ entries.sort((left, right) => (left.name < right.name ? -1 : left.name > right.name ? 1 : 0));
140
+ return { entries };
141
+ }
142
+
143
+ async function readOp(request, maxBytes) {
144
+ const real = await resolveWorkspacePath(request.rootReal, request.path);
145
+ let info;
146
+ try {
147
+ info = await stat(real);
148
+ } catch (error) {
149
+ if (error?.code === 'ENOENT') throw sandboxError('NotFoundError', '目标不存在。');
150
+ throw error;
151
+ }
152
+ if (info.isDirectory()) throw sandboxError('TypeMismatchError', '不是文件。');
153
+ assertWithinQuota(info.size, maxBytes);
154
+ const bytes = await readFile(real);
155
+ return { contentBase64: Buffer.from(bytes).toString('base64') };
156
+ }
157
+
158
+ async function ensureParent(real, createDirectories) {
159
+ const parent = dirname(real);
160
+ let info;
161
+ try {
162
+ info = await stat(parent);
163
+ } catch (error) {
164
+ if (error?.code !== 'ENOENT') throw error;
165
+ }
166
+ if (info?.isDirectory()) return parent;
167
+ if (info || !createDirectories) throw sandboxError('NotFoundError', '父目录不存在。');
168
+ await mkdir(parent, { recursive: true });
169
+ return parent;
170
+ }
171
+
172
+ async function writeOp(request, maxBytes) {
173
+ if (request.contentBase64 !== undefined && typeof request.contentBase64 !== 'string') {
174
+ throw sandboxError('TypeError', 'contentBase64 必须是字符串。');
175
+ }
176
+ const real = await resolveWorkspacePath(request.rootReal, request.path);
177
+ let existing;
178
+ try {
179
+ existing = await stat(real);
180
+ } catch (error) {
181
+ if (error?.code !== 'ENOENT') throw error;
182
+ }
183
+ if (existing?.isDirectory()) throw sandboxError('TypeMismatchError', '不能把目录当文件写。');
184
+ const parent = await ensureParent(real, request.createDirectories === true);
185
+ const bytes = Buffer.from(request.contentBase64 ?? '', 'base64');
186
+ assertWithinQuota(bytes.length, maxBytes);
187
+ const temporary = join(parent, `.${basename(real)}.${randomBytes(6).toString('hex')}.tmp`);
188
+ try {
189
+ await writeFile(temporary, bytes);
190
+ await rename(temporary, real);
191
+ } catch (error) {
192
+ await unlink(temporary).catch(() => undefined);
193
+ throw error;
194
+ }
195
+ return {};
196
+ }
197
+
198
+ async function mkdirOp(request) {
199
+ const real = await resolveWorkspacePath(request.rootReal, request.path);
200
+ try {
201
+ const info = await stat(real);
202
+ if (!info.isDirectory()) throw sandboxError('TypeMismatchError', '同名文件已存在。');
203
+ return {};
204
+ } catch (error) {
205
+ if (error?.code && DOM_ERROR.test(error.code)) throw error;
206
+ if (error?.code !== 'ENOENT') throw error;
207
+ }
208
+ await mkdir(real, { recursive: true });
209
+ return {};
210
+ }
211
+
212
+ async function removeOp(request) {
213
+ const target = await resolveEntryPath(request.rootReal, request.path);
214
+ let info;
215
+ try {
216
+ info = await lstat(target);
217
+ } catch (error) {
218
+ if (error?.code === 'ENOENT') throw sandboxError('NotFoundError', '目标不存在。');
219
+ throw error;
220
+ }
221
+ if (info.isSymbolicLink() || !info.isDirectory()) {
222
+ await unlink(target);
223
+ return {};
224
+ }
225
+ const children = await readdir(target);
226
+ if (children.length > 0 && request.recursive !== true) {
227
+ throw sandboxError('InvalidModificationError', '目录不为空。');
228
+ }
229
+ await rm(target, { recursive: true });
230
+ return {};
231
+ }
232
+
233
+ async function moveOp(request) {
234
+ const from = await resolveEntryPath(request.rootReal, request.from);
235
+ const to = await resolveEntryPath(request.rootReal, request.to);
236
+ let source;
237
+ try {
238
+ source = await lstat(from);
239
+ } catch (error) {
240
+ if (error?.code === 'ENOENT') throw sandboxError('NotFoundError', '目标不存在。');
241
+ throw error;
242
+ }
243
+ let parentInfo;
244
+ try {
245
+ parentInfo = await stat(dirname(to));
246
+ } catch (error) {
247
+ if (error?.code === 'ENOENT') throw sandboxError('NotFoundError', '父目录不存在。');
248
+ throw error;
249
+ }
250
+ if (!parentInfo.isDirectory()) throw sandboxError('NotFoundError', '父目录不存在。');
251
+ let destination;
252
+ try {
253
+ destination = await lstat(to);
254
+ } catch (error) {
255
+ if (error?.code !== 'ENOENT') throw error;
256
+ }
257
+ const sourceIsDirectory = source.isDirectory() && !source.isSymbolicLink();
258
+ const destinationIsDirectory = Boolean(destination?.isDirectory() && !destination.isSymbolicLink());
259
+ if (to === from || to.startsWith(`${from}${sep}`) || (destination && (sourceIsDirectory || destinationIsDirectory))) {
260
+ throw sandboxError('InvalidModificationError', '不能这样移动。');
261
+ }
262
+ if (destination) await unlink(to);
263
+ await rename(from, to);
264
+ return {};
265
+ }
266
+
267
+ const OPERATIONS = {
268
+ stat: statOp,
269
+ list: listOp,
270
+ read: readOp,
271
+ write: writeOp,
272
+ mkdir: mkdirOp,
273
+ remove: removeOp,
274
+ move: moveOp,
275
+ };
276
+
277
+ /**
278
+ * 工程目录内的文件操作。不进入 MXC,由调用方保证 rootReal 是真实工程根。
279
+ * limits 只给测试收紧配额,协议请求里没有这个字段。
280
+ */
281
+ export async function runFileOp(request, limits = {}) {
282
+ const operation = OPERATIONS[request.op];
283
+ if (!operation) throw sandboxError('NotSupportedError', `不支持的操作 ${String(request.op)}。`);
284
+ try {
285
+ return await operation(request, limits.maxBytes ?? MAX_FILE_BYTES);
286
+ } catch (error) {
287
+ throw asFileError(error);
288
+ }
289
+ }
package/src/mxc.mjs ADDED
@@ -0,0 +1,63 @@
1
+ import { existsSync } from 'node:fs';
2
+ import { sandboxError } from './policy.mjs';
3
+
4
+ export const DENIED_PATHS = ['/etc/passwd', '/etc/group', '/private/etc/passwd', '/private/etc/group'];
5
+
6
+ /** bubblewrap 只挂载列出的目录,系统目录要显式只读。Seatbelt 默认可读。 */
7
+ const LINUX_SYSTEM_PATHS = ['/usr', '/bin', '/sbin', '/lib', '/lib64', '/etc'];
8
+
9
+ let loaded;
10
+
11
+ async function loadMxc() {
12
+ loaded ??= import('@microsoft/mxc-sdk/v1');
13
+ return loaded;
14
+ }
15
+
16
+ export async function selectContainment() {
17
+ const mxc = await loadMxc();
18
+ const support = mxc.getPlatformSupport();
19
+ const methods = support.availableMethods ?? [];
20
+ const containment =
21
+ process.platform === 'darwin' && methods.includes('seatbelt')
22
+ ? { type: 'seatbelt', config: { nestedPty: false, guiAccess: false, keychainAccess: false } }
23
+ : process.platform === 'win32' && methods.includes('processcontainer')
24
+ ? { type: 'processcontainer' }
25
+ : process.platform === 'linux' && methods.includes('bubblewrap')
26
+ ? { type: 'bubblewrap' }
27
+ : null;
28
+ if (!support.isSupported || !containment) {
29
+ throw sandboxError('NotAllowedError', support.reason || '当前系统没有可用的 MXC 沙箱。');
30
+ }
31
+ return containment;
32
+ }
33
+
34
+ export function systemReadonlyPaths() {
35
+ return process.platform === 'linux' ? LINUX_SYSTEM_PATHS.filter((dir) => existsSync(dir)) : [];
36
+ }
37
+
38
+ /** command 会被 MXC 按 shell 规则拆分,调用方负责引号。 */
39
+ export async function contained(containment, command, { filesystem, network, environment, timeoutMs, workingDirectory }) {
40
+ const mxc = await loadMxc();
41
+ 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
+ });
56
+ } 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 || '沙箱启动失败。');
62
+ }
63
+ }