@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/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
+ }