@pyrokine/mcp-ssh 1.1.0 → 1.1.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/dist/file-ops.js CHANGED
@@ -1,42 +1,53 @@
1
1
  /**
2
2
  * SSH File Operations - 文件操作
3
3
  */
4
+ import { execSync } from 'child_process';
4
5
  import * as fs from 'fs';
5
6
  import * as path from 'path';
6
- import { execSync } from 'child_process';
7
7
  import { sessionManager } from './session-manager.js';
8
+ // 文件类型 mode 常量
9
+ const S_IFDIR = 0o40000;
10
+ const S_IFREG = 0o100000;
11
+ const S_IFLNK = 0o120000;
8
12
  /**
9
- * 上传文件
13
+ * sftp.stat 的 Promise 包装
10
14
  */
11
- export async function uploadFile(alias, localPath, remotePath, onProgress) {
12
- if (!fs.existsSync(localPath)) {
13
- throw new Error(`Local file not found: ${localPath}`);
14
- }
15
- const sftp = await sessionManager.getSftp(alias);
16
- const stats = fs.statSync(localPath);
17
- const totalSize = stats.size;
15
+ function sftpStat(sftp, remotePath) {
16
+ return new Promise((resolve, reject) => {
17
+ sftp.stat(remotePath, (err, stats) => {
18
+ if (err) {
19
+ reject(err);
20
+ }
21
+ else {
22
+ resolve(stats);
23
+ }
24
+ });
25
+ });
26
+ }
27
+ /**
28
+ * 带进度追踪的流传输
29
+ */
30
+ function pipeWithProgress(readStream, writeStream, sftp, totalSize, onProgress) {
18
31
  return new Promise((resolve, reject) => {
19
- const readStream = fs.createReadStream(localPath);
20
- const writeStream = sftp.createWriteStream(remotePath);
21
32
  let settled = false;
22
33
  const cleanup = (err) => {
23
- if (settled)
34
+ if (settled) {
24
35
  return;
36
+ }
25
37
  settled = true;
26
38
  sftp.end();
27
- if (err)
39
+ if (err) {
28
40
  reject(err);
41
+ }
29
42
  };
30
43
  let transferred = 0;
31
44
  readStream.on('data', (chunk) => {
32
45
  transferred += chunk.length;
33
- if (onProgress) {
34
- onProgress({
35
- transferred,
36
- total: totalSize,
37
- percent: totalSize > 0 ? Math.round((transferred / totalSize) * 100) : 100,
38
- });
39
- }
46
+ onProgress?.({
47
+ transferred,
48
+ total: totalSize,
49
+ percent: totalSize > 0 ? Math.round((transferred / totalSize) * 100) : 100,
50
+ });
40
51
  });
41
52
  readStream.on('error', (err) => cleanup(err));
42
53
  writeStream.on('error', (err) => cleanup(err));
@@ -50,77 +61,36 @@ export async function uploadFile(alias, localPath, remotePath, onProgress) {
50
61
  readStream.pipe(writeStream);
51
62
  });
52
63
  }
64
+ /**
65
+ * 上传文件
66
+ */
67
+ export async function uploadFile(alias, localPath, remotePath, onProgress) {
68
+ if (!fs.existsSync(localPath)) {
69
+ throw new Error(`Local file not found: ${localPath}`);
70
+ }
71
+ const sftp = await sessionManager.getSftp(alias);
72
+ const totalSize = fs.statSync(localPath).size;
73
+ return pipeWithProgress(fs.createReadStream(localPath), sftp.createWriteStream(remotePath), sftp, totalSize, onProgress);
74
+ }
53
75
  /**
54
76
  * 下载文件
55
77
  */
56
78
  export async function downloadFile(alias, remotePath, localPath, onProgress) {
57
79
  const sftp = await sessionManager.getSftp(alias);
58
- // 获取远程文件大小
59
- const stats = await new Promise((resolve, reject) => {
60
- sftp.stat(remotePath, (err, stats) => {
61
- if (err)
62
- reject(err);
63
- else
64
- resolve(stats);
65
- });
66
- });
67
- const totalSize = stats.size;
80
+ const totalSize = (await sftpStat(sftp, remotePath)).size;
68
81
  // 确保本地目录存在
69
82
  const localDir = path.dirname(localPath);
70
83
  if (!fs.existsSync(localDir)) {
71
84
  fs.mkdirSync(localDir, { recursive: true });
72
85
  }
73
- return new Promise((resolve, reject) => {
74
- const readStream = sftp.createReadStream(remotePath);
75
- const writeStream = fs.createWriteStream(localPath);
76
- let settled = false;
77
- const cleanup = (err) => {
78
- if (settled)
79
- return;
80
- settled = true;
81
- sftp.end();
82
- if (err)
83
- reject(err);
84
- };
85
- let transferred = 0;
86
- readStream.on('data', (chunk) => {
87
- transferred += chunk.length;
88
- if (onProgress) {
89
- onProgress({
90
- transferred,
91
- total: totalSize,
92
- percent: totalSize > 0 ? Math.round((transferred / totalSize) * 100) : 100,
93
- });
94
- }
95
- });
96
- readStream.on('error', (err) => cleanup(err));
97
- writeStream.on('error', (err) => cleanup(err));
98
- writeStream.on('close', () => {
99
- if (!settled) {
100
- settled = true;
101
- sftp.end();
102
- resolve({ success: true, size: totalSize });
103
- }
104
- });
105
- readStream.pipe(writeStream);
106
- });
86
+ return pipeWithProgress(sftp.createReadStream(remotePath), fs.createWriteStream(localPath), sftp, totalSize, onProgress);
107
87
  }
108
88
  /**
109
89
  * 读取远程文件内容
110
90
  */
111
- export async function readFile(alias, remotePath, maxBytes = 1024 * 1024 // 默认最大 1MB
112
- ) {
91
+ export async function readFile(alias, remotePath, maxBytes = 1024 * 1024) {
113
92
  const sftp = await sessionManager.getSftp(alias);
114
- // 获取文件大小
115
- const stats = await new Promise((resolve, reject) => {
116
- sftp.stat(remotePath, (err, stats) => {
117
- if (err)
118
- reject(err);
119
- else
120
- resolve(stats);
121
- });
122
- });
123
- const actualSize = stats.size;
93
+ const actualSize = (await sftpStat(sftp, remotePath)).size;
124
94
  const truncated = actualSize > maxBytes;
125
95
  // 处理空文件
126
96
  if (actualSize === 0) {
@@ -190,9 +160,9 @@ export async function listDir(alias, remotePath, showHidden = false) {
190
160
  name: item.filename,
191
161
  path: path.posix.join(remotePath, item.filename),
192
162
  size: item.attrs.size,
193
- isDirectory: (item.attrs.mode & 0o40000) !== 0,
194
- isFile: (item.attrs.mode & 0o100000) !== 0,
195
- isSymlink: (item.attrs.mode & 0o120000) !== 0,
163
+ isDirectory: (item.attrs.mode & S_IFDIR) !== 0,
164
+ isFile: (item.attrs.mode & S_IFREG) !== 0,
165
+ isSymlink: (item.attrs.mode & S_IFLNK) !== 0,
196
166
  permissions: formatPermissions(item.attrs.mode),
197
167
  owner: item.attrs.uid,
198
168
  group: item.attrs.gid,
@@ -227,9 +197,9 @@ export async function getFileInfo(alias, remotePath) {
227
197
  name: path.posix.basename(remotePath),
228
198
  path: remotePath,
229
199
  size: stats.size,
230
- isDirectory: (stats.mode & 0o40000) !== 0,
231
- isFile: (stats.mode & 0o100000) !== 0,
232
- isSymlink: (stats.mode & 0o120000) !== 0,
200
+ isDirectory: (stats.mode & S_IFDIR) !== 0,
201
+ isFile: (stats.mode & S_IFREG) !== 0,
202
+ isSymlink: (stats.mode & S_IFLNK) !== 0,
233
203
  permissions: formatPermissions(stats.mode),
234
204
  owner: stats.uid,
235
205
  group: stats.gid,
@@ -239,18 +209,6 @@ export async function getFileInfo(alias, remotePath) {
239
209
  });
240
210
  });
241
211
  }
242
- /**
243
- * 检查文件是否存在
244
- */
245
- export async function fileExists(alias, remotePath) {
246
- const sftp = await sessionManager.getSftp(alias);
247
- return new Promise((resolve) => {
248
- sftp.stat(remotePath, (err) => {
249
- sftp.end();
250
- resolve(!err);
251
- });
252
- });
253
- }
254
212
  /**
255
213
  * 创建目录
256
214
  */
@@ -264,25 +222,12 @@ export async function mkdir(alias, remotePath, recursive = false) {
264
222
  return new Promise((resolve, reject) => {
265
223
  sftp.mkdir(remotePath, (err) => {
266
224
  sftp.end();
267
- if (err)
268
- reject(err);
269
- else
270
- resolve(true);
271
- });
272
- });
273
- }
274
- /**
275
- * 删除文件
276
- */
277
- export async function removeFile(alias, remotePath) {
278
- const sftp = await sessionManager.getSftp(alias);
279
- return new Promise((resolve, reject) => {
280
- sftp.unlink(remotePath, (err) => {
281
- sftp.end();
282
- if (err)
225
+ if (err) {
283
226
  reject(err);
284
- else
227
+ }
228
+ else {
285
229
  resolve(true);
230
+ }
286
231
  });
287
232
  });
288
233
  }
@@ -308,22 +253,17 @@ export async function checkRsync(alias) {
308
253
  * @param options 同步选项
309
254
  */
310
255
  export async function syncFiles(alias, localPath, remotePath, direction, options = {}) {
311
- // 检查远程 rsync
312
256
  const hasRsync = await checkRsync(alias);
313
257
  if (hasRsync) {
314
- // 使用 rsync(通过远程端执行)
315
258
  return syncWithRsync(alias, localPath, remotePath, direction, options);
316
259
  }
317
- else {
318
- // 回退到 SFTP
319
- return syncWithSftp(alias, localPath, remotePath, direction, options);
320
- }
260
+ return syncWithSftp(alias, localPath, remotePath, direction, options);
321
261
  }
322
262
  /**
323
263
  * 转义 shell 路径参数
324
264
  */
325
265
  function escapeShellPath(p) {
326
- return `'${p.replace(/'/g, "'\\''")}'`;
266
+ return `'${p.replace(/'/g, '\'\\\'\'')}'`;
327
267
  }
328
268
  /**
329
269
  * 使用 rsync 同步文件
@@ -336,7 +276,8 @@ async function syncWithRsync(alias, localPath, remotePath, direction, options) {
336
276
  execSync('which rsync', { stdio: 'pipe' });
337
277
  hasLocalRsync = true;
338
278
  }
339
- catch { }
279
+ catch {
280
+ }
340
281
  if (!hasLocalRsync) {
341
282
  // 本地没有 rsync,回退到 SFTP
342
283
  return syncWithSftp(alias, localPath, remotePath, direction, options);
@@ -374,13 +315,16 @@ async function syncWithRsync(alias, localPath, remotePath, direction, options) {
374
315
  const result = execSync(rsyncCmd, {
375
316
  encoding: 'utf-8',
376
317
  timeout: 600000, // 10 分钟超时
377
- stdio: ['pipe', 'pipe', 'pipe']
318
+ stdio: ['pipe', 'pipe', 'pipe'],
378
319
  });
379
320
  // 解析 rsync 输出统计文件数
380
321
  const lines = result.split('\n');
381
322
  let filesTransferred = 0;
382
323
  for (const line of lines) {
383
- if (line.trim() && !line.startsWith('sending') && !line.startsWith('receiving') && !line.startsWith('total')) {
324
+ if (line.trim() &&
325
+ !line.startsWith('sending') &&
326
+ !line.startsWith('receiving') &&
327
+ !line.startsWith('total')) {
384
328
  filesTransferred++;
385
329
  }
386
330
  }
@@ -396,11 +340,16 @@ async function syncWithRsync(alias, localPath, remotePath, direction, options) {
396
340
  return syncWithSftp(alias, localPath, remotePath, direction, options);
397
341
  }
398
342
  }
399
- /**
400
- * 使用 SFTP 同步文件
401
- */
343
+ function buildSyncResult(fileCount, totalSize, warnings) {
344
+ return {
345
+ success: true,
346
+ method: 'sftp',
347
+ filesTransferred: fileCount,
348
+ bytesTransferred: totalSize,
349
+ output: warnings.length ? `Warning: ${warnings.join('; ')}` : undefined,
350
+ };
351
+ }
402
352
  async function syncWithSftp(alias, localPath, remotePath, direction, options) {
403
- // SFTP 模式不支持 delete 选项
404
353
  const warnings = [];
405
354
  if (options.delete) {
406
355
  warnings.push('delete option is not supported in SFTP mode (requires rsync)');
@@ -409,59 +358,28 @@ async function syncWithSftp(alias, localPath, remotePath, direction, options) {
409
358
  return {
410
359
  success: true,
411
360
  method: 'sftp',
412
- output: 'Dry run mode: would transfer files via SFTP' + (warnings.length ? `. Warning: ${warnings.join('; ')}` : ''),
361
+ output: 'Dry run mode: would transfer files via SFTP' +
362
+ (warnings.length ? `. Warning: ${warnings.join('; ')}` : ''),
413
363
  };
414
364
  }
415
365
  try {
416
- let result;
417
366
  if (direction === 'upload') {
418
- // 检查是否是目录
419
367
  const stats = fs.statSync(localPath);
420
368
  if (stats.isDirectory() && options.recursive !== false) {
421
- result = await uploadDirectory(alias, localPath, remotePath, options.exclude);
422
- return {
423
- success: true,
424
- method: 'sftp',
425
- filesTransferred: result.fileCount,
426
- bytesTransferred: result.totalSize,
427
- output: warnings.length ? `Warning: ${warnings.join('; ')}` : undefined,
428
- };
429
- }
430
- else {
431
- result = await uploadFile(alias, localPath, remotePath);
432
- return {
433
- success: result.success,
434
- method: 'sftp',
435
- filesTransferred: 1,
436
- bytesTransferred: result.size,
437
- output: warnings.length ? `Warning: ${warnings.join('; ')}` : undefined,
438
- };
369
+ const { fileCount, totalSize } = await uploadDirectory(alias, localPath, remotePath, options.exclude);
370
+ return buildSyncResult(fileCount, totalSize, warnings);
439
371
  }
372
+ const { size } = await uploadFile(alias, localPath, remotePath);
373
+ return buildSyncResult(1, size, warnings);
440
374
  }
441
- else {
442
- // 下载
443
- const info = await getFileInfo(alias, remotePath);
444
- if (info.isDirectory && options.recursive !== false) {
445
- result = await downloadDirectory(alias, remotePath, localPath, options.exclude);
446
- return {
447
- success: true,
448
- method: 'sftp',
449
- filesTransferred: result.fileCount,
450
- bytesTransferred: result.totalSize,
451
- output: warnings.length ? `Warning: ${warnings.join('; ')}` : undefined,
452
- };
453
- }
454
- else {
455
- result = await downloadFile(alias, remotePath, localPath);
456
- return {
457
- success: result.success,
458
- method: 'sftp',
459
- filesTransferred: 1,
460
- bytesTransferred: result.size,
461
- output: warnings.length ? `Warning: ${warnings.join('; ')}` : undefined,
462
- };
463
- }
375
+ // download
376
+ const info = await getFileInfo(alias, remotePath);
377
+ if (info.isDirectory && options.recursive !== false) {
378
+ const { fileCount, totalSize } = await downloadDirectory(alias, remotePath, localPath, options.exclude);
379
+ return buildSyncResult(fileCount, totalSize, warnings);
464
380
  }
381
+ const { size } = await downloadFile(alias, remotePath, localPath);
382
+ return buildSyncResult(1, size, warnings);
465
383
  }
466
384
  catch (err) {
467
385
  return {
@@ -545,14 +463,14 @@ function matchPattern(name, pattern) {
545
463
  * 格式化权限字符串
546
464
  */
547
465
  function formatPermissions(mode) {
548
- const types = {
549
- 0o40000: 'd',
550
- 0o120000: 'l',
551
- 0o100000: '-',
552
- };
466
+ const types = [
467
+ [S_IFDIR, 'd'],
468
+ [S_IFLNK, 'l'],
469
+ [S_IFREG, '-'],
470
+ ];
553
471
  let type = '-';
554
- for (const [mask, char] of Object.entries(types)) {
555
- if ((mode & parseInt(mask)) !== 0) {
472
+ for (const [mask, char] of types) {
473
+ if ((mode & mask) !== 0) {
556
474
  type = char;
557
475
  break;
558
476
  }