@fefeding/aicmd 0.1.14 → 0.1.16

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.
Files changed (43) hide show
  1. package/README.md +1 -1
  2. package/README.zh.md +1 -1
  3. package/bin/aicmd.js +19 -1
  4. package/dist/public/rolldown-runtime.js +1 -5
  5. package/dist/public/views.css +253 -253
  6. package/dist/public/views.js +189 -49
  7. package/dist/server/service/ai.service.d.ts +5 -0
  8. package/dist/server/service/ai.service.d.ts.map +1 -1
  9. package/dist/server/service/ai.service.js +69 -2
  10. package/dist/server/service/ai.service.js.map +1 -1
  11. package/dist/server/service/ai.service.ts +66 -2
  12. package/dist/server/service/batch.service.d.ts.map +1 -1
  13. package/dist/server/service/batch.service.js +5 -0
  14. package/dist/server/service/batch.service.js.map +1 -1
  15. package/dist/server/service/batch.service.ts +5 -0
  16. package/dist/server/service/connection.service.d.ts +5 -0
  17. package/dist/server/service/connection.service.d.ts.map +1 -1
  18. package/dist/server/service/connection.service.js +72 -3
  19. package/dist/server/service/connection.service.js.map +1 -1
  20. package/dist/server/service/connection.service.ts +70 -3
  21. package/dist/server/service/monitor.service.d.ts +5 -0
  22. package/dist/server/service/monitor.service.d.ts.map +1 -1
  23. package/dist/server/service/monitor.service.js +100 -3
  24. package/dist/server/service/monitor.service.js.map +1 -1
  25. package/dist/server/service/monitor.service.ts +72 -3
  26. package/dist/server/service/ssh.service.d.ts.map +1 -1
  27. package/dist/server/service/ssh.service.js +3 -2
  28. package/dist/server/service/ssh.service.js.map +1 -1
  29. package/dist/server/service/ssh.service.ts +3 -2
  30. package/dist/server/utils/security.d.ts +15 -0
  31. package/dist/server/utils/security.d.ts.map +1 -0
  32. package/dist/server/utils/security.js +186 -0
  33. package/dist/server/utils/security.js.map +1 -0
  34. package/dist/server/utils/security.ts +133 -0
  35. package/dist/server/utils/shell.d.ts +8 -0
  36. package/dist/server/utils/shell.d.ts.map +1 -0
  37. package/dist/server/utils/shell.js +73 -0
  38. package/dist/server/utils/shell.js.map +1 -0
  39. package/dist/server/utils/shell.ts +43 -0
  40. package/electron/main.js +30 -5
  41. package/electron/preload.js +22 -12
  42. package/package.json +2 -1
  43. package/server.js +113 -21
package/server.js CHANGED
@@ -8,7 +8,19 @@ const WebSocket = require('ws');
8
8
 
9
9
  // 统一数据目录管理(所有写入文件必须通过此模块获取路径)
10
10
  const { ensureDataDir, getDataPath } = require('./dist/server/utils/data-dir');
11
+ const {
12
+ getAccessToken,
13
+ getCookieHeader,
14
+ extractTokenFromHeaders,
15
+ isValidToken,
16
+ isAllowedOrigin,
17
+ requiresToken,
18
+ normalizeUploadName,
19
+ maxUploadBytes,
20
+ } = require('./dist/server/utils/security');
11
21
  const dataDir = ensureDataDir();
22
+ const accessToken = getAccessToken();
23
+ const uploadLimitBytes = maxUploadBytes();
12
24
 
13
25
  // 日志文件路径(写入数据目录,非安装目录)
14
26
  const logFilePath = getDataPath('server.log');
@@ -52,19 +64,54 @@ if (!fs.existsSync(serverIndexPath)) {
52
64
  process.exit(1);
53
65
  }
54
66
 
55
- // 设置 CORS 头
67
+ // 访问控制:默认仅允许同源/本机来源,并要求本地 token
56
68
  app.use((req, res, next) => {
57
- res.setHeader('Access-Control-Allow-Origin', '*');
69
+ const origin = req.headers.origin;
70
+ const host = req.headers.host;
71
+ if (!isAllowedOrigin(origin, host)) {
72
+ res.statusCode = 403;
73
+ res.end('Forbidden origin');
74
+ return;
75
+ }
76
+
77
+ if (origin) res.setHeader('Access-Control-Allow-Origin', origin);
78
+ res.setHeader('Vary', 'Origin');
79
+ res.setHeader('Access-Control-Allow-Credentials', 'true');
58
80
  res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
59
- res.setHeader('Access-Control-Allow-Headers', 'Content-Type, X-Session-Id, X-File-Name');
81
+ res.setHeader('Access-Control-Allow-Headers', 'Content-Type, X-Session-Id, X-File-Name, X-AICmd-Token, Authorization');
60
82
  if (req.method === 'OPTIONS') { res.writeHead(204); res.end(); return; }
83
+
84
+ const requestUrl = new URL(req.url, `http://${host || 'localhost'}`);
85
+ const queryToken = requestUrl.searchParams.get('token');
86
+ if (queryToken && isValidToken(queryToken)) {
87
+ res.setHeader('Set-Cookie', getCookieHeader(queryToken, req.socket.encrypted === true));
88
+ if (requestUrl.pathname === '/') {
89
+ res.writeHead(302, { Location: '/' });
90
+ res.end();
91
+ return;
92
+ }
93
+ }
94
+
95
+ if ((requestUrl.pathname.startsWith('/api/') || requestUrl.pathname.startsWith('/ws/')) && requiresToken(req.headers.origin, req.headers.host) && !isValidToken(extractTokenFromHeaders(req.headers))) {
96
+ res.statusCode = 401;
97
+ res.setHeader('Content-Type', 'application/json');
98
+ res.end(JSON.stringify({ ret: 401, msg: 'Unauthorized' }));
99
+ return;
100
+ }
101
+
61
102
  next();
62
103
  });
63
104
 
64
105
  // HTTP 文件上传端点(绕过 WebSocket,支持大文件)
65
106
  app.post('/api/file-upload', async (req, res) => {
66
107
  const sessionId = req.headers['x-session-id'];
67
- const fileName = req.headers['x-file-name'];
108
+ let fileName;
109
+ try {
110
+ fileName = normalizeUploadName(req.headers['x-file-name']);
111
+ } catch (err) {
112
+ res.status(400).json({ success: false, error: err.message || 'Invalid file name' });
113
+ return;
114
+ }
68
115
  if (!sessionId || !fileName) {
69
116
  res.status(400).json({ success: false, error: 'Missing X-Session-Id or X-File-Name header' });
70
117
  return;
@@ -75,7 +122,13 @@ app.post('/api/file-upload', async (req, res) => {
75
122
  // 收集原始请求体(文件二进制数据)
76
123
  console.log(`[HTTP-Upload] Receiving file: session=${sessionId}, file=${fileName}`);
77
124
  const chunks = [];
125
+ let received = 0;
78
126
  for await (const chunk of req) {
127
+ received += chunk.length;
128
+ if (received > uploadLimitBytes) {
129
+ res.status(413).json({ success: false, error: `File too large, limit ${uploadLimitBytes} bytes`, fileName });
130
+ return;
131
+ }
79
132
  chunks.push(chunk);
80
133
  }
81
134
  const fileBuffer = Buffer.concat(chunks);
@@ -94,7 +147,8 @@ app.use('/api/', async (req, res, next) => {
94
147
  if (req.method === 'POST') {
95
148
  try {
96
149
  const serverModule = require('./dist/server/index.js');
97
- const result = await serverModule.handleRoutes(req.originalUrl, req.body);
150
+ const pathname = new URL(req.originalUrl, `http://${req.headers.host || 'localhost'}`).pathname;
151
+ const result = await serverModule.handleRoutes(pathname, req.body);
98
152
  res.status(200).json({ ret: 0, msg: 'success', data: result });
99
153
  } catch (error) {
100
154
  console.error('API Error:', error);
@@ -118,10 +172,9 @@ app.use((req, res) => {
118
172
  });
119
173
  });
120
174
 
121
- // ========== WebSocket 服务 ==========
122
- // maxPayload 设为 500MB,支持较大文件的 base64 传输(base64 比原文件大 ~33%)
123
- const wss = new WebSocket.Server({ server, path: '/ws/terminal', maxPayload: 500 * 1024 * 1024 });
124
- console.log(`[WS] WebSocket server created on path /ws/terminal (maxPayload: 500MB)`);
175
+ // WebSocket 文件消息限制跟随上传限制,base64 约有 33% 膨胀
176
+ const wss = new WebSocket.Server({ server, path: '/ws/terminal', maxPayload: Math.ceil(uploadLimitBytes * 1.4) });
177
+ console.log(`[WS] WebSocket server created on path /ws/terminal (maxPayload: ${Math.ceil(uploadLimitBytes * 1.4)} bytes)`);
125
178
 
126
179
  // 分块上传缓冲区: uploadId -> { chunks: string[], totalChunks: number, fileName: string, sessionId: string }
127
180
  const pendingUploads = new Map();
@@ -145,6 +198,12 @@ try {
145
198
  }
146
199
 
147
200
  wss.on('connection', async (ws, req) => {
201
+ const requestUrl = new URL(req.url, `http://${req.headers.host || 'localhost'}`);
202
+ const wsToken = requestUrl.searchParams.get('token') || extractTokenFromHeaders(req.headers);
203
+ if (!isAllowedOrigin(req.headers.origin, req.headers.host) || (requiresToken(req.headers.origin, req.headers.host) && !isValidToken(wsToken))) {
204
+ ws.close(1008, 'Unauthorized');
205
+ return;
206
+ }
148
207
  let sessionId = null;
149
208
  console.log(`[WS] Client connected from ${req.socket.remoteAddress}`);
150
209
 
@@ -314,16 +373,28 @@ wss.on('connection', async (ws, req) => {
314
373
  }
315
374
 
316
375
  case 'file-upload': {
317
- // SFTP 文件上传 - 单消息模式(小文件,<50MB base64)
318
- const { fileName, data: fileData } = data || {};
376
+ // SFTP 文件上传 - 单消息模式(小文件,<上传限制)
377
+ let fileName;
378
+ const { data: fileData } = data || {};
379
+ try {
380
+ fileName = normalizeUploadName(data?.fileName);
381
+ } catch (err) {
382
+ ws.send(JSON.stringify({ type: 'file-upload-result', success: false, error: err.message || 'Invalid file name' }));
383
+ break;
384
+ }
319
385
  if (!sid || !fileName || !fileData) {
320
386
  console.error(`[WS] file-upload missing params: sid=${sid}, fileName=${fileName}, hasData=${!!fileData}`);
321
387
  ws.send(JSON.stringify({ type: 'file-upload-result', success: false, error: 'Missing params', fileName }));
322
388
  break;
323
389
  }
390
+ const fileBuffer = Buffer.from(fileData, 'base64');
391
+ if (fileBuffer.length > uploadLimitBytes) {
392
+ ws.send(JSON.stringify({ type: 'file-upload-result', success: false, error: `File too large, limit ${uploadLimitBytes} bytes`, fileName }));
393
+ break;
394
+ }
324
395
  try {
325
- console.log(`[WS] SFTP upload START: session=${sid}, file=${fileName}, b64len=${fileData.length}, wsReady=${ws.readyState}`);
326
- const bytes = await sshService.uploadFileViaSftp(sid, fileName, Buffer.from(fileData, 'base64'));
396
+ console.log(`[WS] SFTP upload START: session=${sid}, file=${fileName}, bytes=${fileBuffer.length}, wsReady=${ws.readyState}`);
397
+ const bytes = await sshService.uploadFileViaSftp(sid, fileName, fileBuffer);
327
398
  console.log(`[WS] SFTP upload DONE: ${fileName}, ${bytes} bytes, wsReady=${ws.readyState}`);
328
399
  if (ws.readyState === WebSocket.OPEN) {
329
400
  ws.send(JSON.stringify({ type: 'file-upload-result', success: true, bytes, fileName }));
@@ -341,13 +412,20 @@ wss.on('connection', async (ws, req) => {
341
412
 
342
413
  case 'file-upload-start': {
343
414
  // 分块上传 - 开始(大文件)
344
- const { uploadId, fileName: startFileName, totalChunks } = data || {};
345
- if (!uploadId || !startFileName || !totalChunks) {
346
- ws.send(JSON.stringify({ type: 'file-upload-result', success: false, error: 'Missing params', fileName: startFileName }));
415
+ const { uploadId, totalChunks } = data || {};
416
+ let startFileName;
417
+ try {
418
+ startFileName = normalizeUploadName(data?.fileName);
419
+ } catch (err) {
420
+ ws.send(JSON.stringify({ type: 'file-upload-result', success: false, error: err.message || 'Invalid file name' }));
421
+ break;
422
+ }
423
+ if (!uploadId || !startFileName || !Number.isInteger(totalChunks) || totalChunks <= 0 || totalChunks > 10000) {
424
+ ws.send(JSON.stringify({ type: 'file-upload-result', success: false, error: 'Invalid upload params', fileName: startFileName }));
347
425
  break;
348
426
  }
349
427
  console.log(`[WS] Chunked upload start: id=${uploadId}, file=${startFileName}, chunks=${totalChunks}`);
350
- pendingUploads.set(uploadId, { chunks: new Array(totalChunks), totalChunks, fileName: startFileName, sessionId: sid, receivedChunks: 0 });
428
+ pendingUploads.set(uploadId, { chunks: new Array(totalChunks), totalChunks, fileName: startFileName, sessionId: sid, receivedChunks: 0, receivedBytes: 0, createdAt: Date.now() });
351
429
  break;
352
430
  }
353
431
 
@@ -359,8 +437,21 @@ wss.on('connection', async (ws, req) => {
359
437
  ws.send(JSON.stringify({ type: 'file-upload-result', success: false, error: 'Upload session not found' }));
360
438
  break;
361
439
  }
440
+ if (!Number.isInteger(chunkIndex) || chunkIndex < 0 || chunkIndex >= upload.totalChunks || typeof chunkData !== 'string') {
441
+ pendingUploads.delete(chunkId);
442
+ ws.send(JSON.stringify({ type: 'file-upload-result', success: false, error: 'Invalid upload chunk', fileName: upload.fileName }));
443
+ break;
444
+ }
445
+ const chunkBytes = Buffer.byteLength(chunkData, 'base64');
446
+ const previousBytes = upload.chunks[chunkIndex] ? Buffer.byteLength(upload.chunks[chunkIndex], 'base64') : 0;
447
+ upload.receivedBytes += chunkBytes - previousBytes;
448
+ if (upload.receivedBytes > uploadLimitBytes) {
449
+ pendingUploads.delete(chunkId);
450
+ ws.send(JSON.stringify({ type: 'file-upload-result', success: false, error: `File too large, limit ${uploadLimitBytes} bytes`, fileName: upload.fileName }));
451
+ break;
452
+ }
453
+ if (upload.chunks[chunkIndex] === undefined) upload.receivedChunks++;
362
454
  upload.chunks[chunkIndex] = chunkData;
363
- upload.receivedChunks++;
364
455
  // 每 10 个 chunk 反馈一次进度
365
456
  if (upload.receivedChunks % 10 === 0 || upload.receivedChunks === upload.totalChunks) {
366
457
  ws.send(JSON.stringify({ type: 'file-upload-progress', uploadId: chunkId, received: upload.receivedChunks, total: upload.totalChunks }));
@@ -469,11 +560,12 @@ function cleanupPid() {
469
560
 
470
561
  // 启动服务器
471
562
  const PORT = portFromArgs || process.env.PORT || 9802;
472
- server.listen(PORT, () => {
563
+ const HOST = process.env.HOST || process.env.AICMD_HOST || '127.0.0.1';
564
+ server.listen(PORT, HOST, () => {
473
565
  fs.writeFileSync(pidFilePath, process.pid.toString());
474
566
  console.log(`PID ${process.pid} written to ${pidFilePath}`);
475
- console.log(`aicmd Server is running on port ${PORT}`);
476
- console.log(`http://localhost:${PORT}`);
567
+ console.log(`aicmd Server is running on ${HOST}:${PORT}`);
568
+ console.log(`http://localhost:${PORT}/?token=${accessToken}`);
477
569
  });
478
570
 
479
571
  // 进程退出处理