@pyrokine/mcp-ssh 1.1.2 → 1.2.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.
Files changed (43) hide show
  1. package/README.md +3 -1
  2. package/README_zh.md +3 -1
  3. package/dist/file-ops.d.ts +7 -10
  4. package/dist/file-ops.js +74 -172
  5. package/dist/forward-manager.d.ts +33 -0
  6. package/dist/forward-manager.js +185 -0
  7. package/dist/index.js +8 -953
  8. package/dist/pty-manager.d.ts +37 -0
  9. package/dist/pty-manager.js +169 -0
  10. package/dist/session-manager.d.ts +28 -86
  11. package/dist/session-manager.js +131 -441
  12. package/dist/ssh-config.d.ts +0 -4
  13. package/dist/ssh-config.js +1 -8
  14. package/dist/tools/connection.d.ts +7 -0
  15. package/dist/tools/connection.js +215 -0
  16. package/dist/tools/exec.d.ts +8 -0
  17. package/dist/tools/exec.js +221 -0
  18. package/dist/tools/file.d.ts +8 -0
  19. package/dist/tools/file.js +192 -0
  20. package/dist/tools/forward.d.ts +7 -0
  21. package/dist/tools/forward.js +116 -0
  22. package/dist/tools/index.d.ts +8 -0
  23. package/dist/tools/index.js +8 -0
  24. package/dist/tools/pty.d.ts +7 -0
  25. package/dist/tools/pty.js +178 -0
  26. package/dist/tools/utils.d.ts +22 -0
  27. package/dist/tools/utils.js +21 -0
  28. package/dist/types.d.ts +0 -7
  29. package/package.json +3 -2
  30. package/src/file-ops.ts +117 -212
  31. package/src/forward-manager.ts +257 -0
  32. package/src/index.ts +17 -1099
  33. package/src/pty-manager.ts +220 -0
  34. package/src/session-manager.ts +166 -532
  35. package/src/ssh-config.ts +1 -8
  36. package/src/tools/connection.ts +240 -0
  37. package/src/tools/exec.ts +260 -0
  38. package/src/tools/file.ts +219 -0
  39. package/src/tools/forward.ts +141 -0
  40. package/src/tools/index.ts +9 -0
  41. package/src/tools/pty.ts +203 -0
  42. package/src/tools/utils.ts +23 -0
  43. package/src/types.ts +0 -9
package/src/file-ops.ts CHANGED
@@ -5,31 +5,42 @@
5
5
  import {execSync} from 'child_process'
6
6
  import * as fs from 'fs'
7
7
  import * as path from 'path'
8
- import {Stats} from 'ssh2'
8
+ import {SFTPWrapper, Stats} from 'ssh2'
9
9
  import {sessionManager} from './session-manager.js'
10
10
  import {FileInfo, TransferProgress} from './types.js'
11
11
 
12
+ // 文件类型 mode 常量
13
+ const S_IFDIR = 0o40000
14
+ const S_IFREG = 0o100000
15
+ const S_IFLNK = 0o120000
16
+
12
17
  /**
13
- * 上传文件
18
+ * sftp.stat 的 Promise 包装
14
19
  */
15
- export async function uploadFile(
16
- alias: string,
17
- localPath: string,
18
- remotePath: string,
20
+ function sftpStat(sftp: SFTPWrapper, remotePath: string): Promise<Stats> {
21
+ return new Promise((resolve, reject) => {
22
+ sftp.stat(remotePath, (err, stats) => {
23
+ if (err) {
24
+ reject(err)
25
+ } else {
26
+ resolve(stats)
27
+ }
28
+ })
29
+ })
30
+ }
31
+
32
+ /**
33
+ * 带进度追踪的流传输
34
+ */
35
+ function pipeWithProgress(
36
+ readStream: NodeJS.ReadableStream,
37
+ writeStream: NodeJS.WritableStream,
38
+ sftp: SFTPWrapper,
39
+ totalSize: number,
19
40
  onProgress?: (progress: TransferProgress) => void,
20
41
  ): Promise<{ success: boolean; size: number }> {
21
- if (!fs.existsSync(localPath)) {
22
- throw new Error(`Local file not found: ${localPath}`)
23
- }
24
-
25
- const sftp = await sessionManager.getSftp(alias)
26
- const stats = fs.statSync(localPath)
27
- const totalSize = stats.size
28
-
29
42
  return new Promise((resolve, reject) => {
30
- const readStream = fs.createReadStream(localPath)
31
- const writeStream = sftp.createWriteStream(remotePath)
32
- let settled = false
43
+ let settled = false
33
44
 
34
45
  const cleanup = (err?: Error) => {
35
46
  if (settled) {
@@ -46,13 +57,11 @@ export async function uploadFile(
46
57
 
47
58
  readStream.on('data', (chunk: Buffer) => {
48
59
  transferred += chunk.length
49
- if (onProgress) {
50
- onProgress({
51
- transferred,
52
- total: totalSize,
53
- percent: totalSize > 0 ? Math.round((transferred / totalSize) * 100) : 100,
54
- })
55
- }
60
+ onProgress?.({
61
+ transferred,
62
+ total: totalSize,
63
+ percent: totalSize > 0 ? Math.round((transferred / totalSize) * 100) : 100,
64
+ })
56
65
  })
57
66
 
58
67
  readStream.on('error', (err: Error) => cleanup(err))
@@ -70,6 +79,29 @@ export async function uploadFile(
70
79
  })
71
80
  }
72
81
 
82
+ /**
83
+ * 上传文件
84
+ */
85
+ export async function uploadFile(
86
+ alias: string,
87
+ localPath: string,
88
+ remotePath: string,
89
+ onProgress?: (progress: TransferProgress) => void,
90
+ ): Promise<{ success: boolean; size: number }> {
91
+ if (!fs.existsSync(localPath)) {
92
+ throw new Error(`Local file not found: ${localPath}`)
93
+ }
94
+
95
+ const sftp = await sessionManager.getSftp(alias)
96
+ const totalSize = fs.statSync(localPath).size
97
+
98
+ return pipeWithProgress(
99
+ fs.createReadStream(localPath),
100
+ sftp.createWriteStream(remotePath),
101
+ sftp, totalSize, onProgress,
102
+ )
103
+ }
104
+
73
105
  /**
74
106
  * 下载文件
75
107
  */
@@ -79,19 +111,8 @@ export async function downloadFile(
79
111
  localPath: string,
80
112
  onProgress?: (progress: TransferProgress) => void,
81
113
  ): Promise<{ success: boolean; size: number }> {
82
- const sftp = await sessionManager.getSftp(alias)
83
-
84
- // 获取远程文件大小
85
- const stats = await new Promise<Stats>((resolve, reject) => {
86
- sftp.stat(remotePath, (err, stats) => {
87
- if (err) {
88
- reject(err)
89
- } else {
90
- resolve(stats)
91
- }
92
- })
93
- })
94
- const totalSize = stats.size
114
+ const sftp = await sessionManager.getSftp(alias)
115
+ const totalSize = (await sftpStat(sftp, remotePath)).size
95
116
 
96
117
  // 确保本地目录存在
97
118
  const localDir = path.dirname(localPath)
@@ -99,48 +120,11 @@ export async function downloadFile(
99
120
  fs.mkdirSync(localDir, {recursive: true})
100
121
  }
101
122
 
102
- return new Promise((resolve, reject) => {
103
- const readStream = sftp.createReadStream(remotePath)
104
- const writeStream = fs.createWriteStream(localPath)
105
- let settled = false
106
-
107
- const cleanup = (err?: Error) => {
108
- if (settled) {
109
- return
110
- }
111
- settled = true
112
- sftp.end()
113
- if (err) {
114
- reject(err)
115
- }
116
- }
117
-
118
- let transferred = 0
119
-
120
- readStream.on('data', (chunk: Buffer) => {
121
- transferred += chunk.length
122
- if (onProgress) {
123
- onProgress({
124
- transferred,
125
- total: totalSize,
126
- percent: totalSize > 0 ? Math.round((transferred / totalSize) * 100) : 100,
127
- })
128
- }
129
- })
130
-
131
- readStream.on('error', (err: Error) => cleanup(err))
132
- writeStream.on('error', (err: Error) => cleanup(err))
133
-
134
- writeStream.on('close', () => {
135
- if (!settled) {
136
- settled = true
137
- sftp.end()
138
- resolve({success: true, size: totalSize})
139
- }
140
- })
141
-
142
- readStream.pipe(writeStream)
143
- })
123
+ return pipeWithProgress(
124
+ sftp.createReadStream(remotePath),
125
+ fs.createWriteStream(localPath),
126
+ sftp, totalSize, onProgress,
127
+ )
144
128
  }
145
129
 
146
130
  /**
@@ -151,20 +135,8 @@ export async function readFile(
151
135
  remotePath: string,
152
136
  maxBytes: number = 1024 * 1024, // 默认最大 1MB
153
137
  ): Promise<{ content: string; size: number; truncated: boolean }> {
154
- const sftp = await sessionManager.getSftp(alias)
155
-
156
- // 获取文件大小
157
- const stats = await new Promise<Stats>((resolve, reject) => {
158
- sftp.stat(remotePath, (err, stats) => {
159
- if (err) {
160
- reject(err)
161
- } else {
162
- resolve(stats)
163
- }
164
- })
165
- })
166
-
167
- const actualSize = stats.size
138
+ const sftp = await sessionManager.getSftp(alias)
139
+ const actualSize = (await sftpStat(sftp, remotePath)).size
168
140
  const truncated = actualSize > maxBytes
169
141
 
170
142
  // 处理空文件
@@ -258,9 +230,9 @@ export async function listDir(
258
230
  name: item.filename,
259
231
  path: path.posix.join(remotePath, item.filename),
260
232
  size: item.attrs.size,
261
- isDirectory: (item.attrs.mode & 0o40000) !== 0,
262
- isFile: (item.attrs.mode & 0o100000) !== 0,
263
- isSymlink: (item.attrs.mode & 0o120000) !== 0,
233
+ isDirectory: (item.attrs.mode & S_IFDIR) !== 0,
234
+ isFile: (item.attrs.mode & S_IFREG) !== 0,
235
+ isSymlink: (item.attrs.mode & S_IFLNK) !== 0,
264
236
  permissions: formatPermissions(item.attrs.mode),
265
237
  owner: item.attrs.uid,
266
238
  group: item.attrs.gid,
@@ -303,9 +275,9 @@ export async function getFileInfo(
303
275
  name: path.posix.basename(remotePath),
304
276
  path: remotePath,
305
277
  size: stats.size,
306
- isDirectory: (stats.mode & 0o40000) !== 0,
307
- isFile: (stats.mode & 0o100000) !== 0,
308
- isSymlink: (stats.mode & 0o120000) !== 0,
278
+ isDirectory: (stats.mode & S_IFDIR) !== 0,
279
+ isFile: (stats.mode & S_IFREG) !== 0,
280
+ isSymlink: (stats.mode & S_IFLNK) !== 0,
309
281
  permissions: formatPermissions(stats.mode),
310
282
  owner: stats.uid,
311
283
  group: stats.gid,
@@ -316,23 +288,6 @@ export async function getFileInfo(
316
288
  })
317
289
  }
318
290
 
319
- /**
320
- * 检查文件是否存在
321
- */
322
- export async function fileExists(
323
- alias: string,
324
- remotePath: string,
325
- ): Promise<boolean> {
326
- const sftp = await sessionManager.getSftp(alias)
327
-
328
- return new Promise((resolve) => {
329
- sftp.stat(remotePath, (err) => {
330
- sftp.end()
331
- resolve(!err)
332
- })
333
- })
334
- }
335
-
336
291
  /**
337
292
  * 创建目录
338
293
  */
@@ -360,26 +315,6 @@ export async function mkdir(
360
315
  })
361
316
  }
362
317
 
363
- /**
364
- * 删除文件
365
- */
366
- export async function removeFile(
367
- alias: string,
368
- remotePath: string,
369
- ): Promise<boolean> {
370
- const sftp = await sessionManager.getSftp(alias)
371
- return new Promise((resolve, reject) => {
372
- sftp.unlink(remotePath, (err) => {
373
- sftp.end()
374
- if (err) {
375
- reject(err)
376
- } else {
377
- resolve(true)
378
- }
379
- })
380
- })
381
- }
382
-
383
318
  /**
384
319
  * 检查远程是否安装 rsync
385
320
  */
@@ -412,23 +347,13 @@ export async function syncFiles(
412
347
  exclude?: string[]; // 排除模式
413
348
  recursive?: boolean; // 递归同步目录
414
349
  } = {},
415
- ): Promise<{
416
- success: boolean;
417
- method: 'rsync' | 'sftp';
418
- filesTransferred?: number;
419
- bytesTransferred?: number;
420
- output?: string;
421
- }> {
422
- // 检查远程 rsync
350
+ ): Promise<SyncResult> {
423
351
  const hasRsync = await checkRsync(alias)
424
352
 
425
353
  if (hasRsync) {
426
- // 使用 rsync(通过远程端执行)
427
354
  return syncWithRsync(alias, localPath, remotePath, direction, options)
428
- } else {
429
- // 回退到 SFTP
430
- return syncWithSftp(alias, localPath, remotePath, direction, options)
431
355
  }
356
+ return syncWithSftp(alias, localPath, remotePath, direction, options)
432
357
  }
433
358
 
434
359
  /**
@@ -453,13 +378,7 @@ async function syncWithRsync(
453
378
  exclude?: string[];
454
379
  recursive?: boolean;
455
380
  },
456
- ): Promise<{
457
- success: boolean;
458
- method: 'rsync' | 'sftp';
459
- filesTransferred?: number;
460
- bytesTransferred?: number;
461
- output?: string;
462
- }> {
381
+ ): Promise<SyncResult> {
463
382
  // 检查本地是否有 rsync
464
383
  let hasLocalRsync = false
465
384
  try {
@@ -540,6 +459,28 @@ async function syncWithRsync(
540
459
  /**
541
460
  * 使用 SFTP 同步文件
542
461
  */
462
+ type SyncResult = {
463
+ success: boolean;
464
+ method: 'rsync' | 'sftp';
465
+ filesTransferred?: number;
466
+ bytesTransferred?: number;
467
+ output?: string;
468
+ }
469
+
470
+ function buildSyncResult(
471
+ fileCount: number,
472
+ totalSize: number,
473
+ warnings: string[],
474
+ ): SyncResult {
475
+ return {
476
+ success: true,
477
+ method: 'sftp',
478
+ filesTransferred: fileCount,
479
+ bytesTransferred: totalSize,
480
+ output: warnings.length ? `Warning: ${warnings.join('; ')}` : undefined,
481
+ }
482
+ }
483
+
543
484
  async function syncWithSftp(
544
485
  alias: string,
545
486
  localPath: string,
@@ -551,14 +492,7 @@ async function syncWithSftp(
551
492
  exclude?: string[];
552
493
  recursive?: boolean;
553
494
  },
554
- ): Promise<{
555
- success: boolean;
556
- method: 'rsync' | 'sftp';
557
- filesTransferred?: number;
558
- bytesTransferred?: number;
559
- output?: string;
560
- }> {
561
- // SFTP 模式不支持 delete 选项
495
+ ): Promise<SyncResult> {
562
496
  const warnings: string[] = []
563
497
  if (options.delete) {
564
498
  warnings.push('delete option is not supported in SFTP mode (requires rsync)')
@@ -574,53 +508,24 @@ async function syncWithSftp(
574
508
  }
575
509
 
576
510
  try {
577
- let result: { fileCount: number; totalSize: number } | { success: boolean; size: number }
578
-
579
511
  if (direction === 'upload') {
580
- // 检查是否是目录
581
512
  const stats = fs.statSync(localPath)
582
513
  if (stats.isDirectory() && options.recursive !== false) {
583
- result = await uploadDirectory(alias, localPath, remotePath, options.exclude)
584
- return {
585
- success: true,
586
- method: 'sftp',
587
- filesTransferred: result.fileCount,
588
- bytesTransferred: result.totalSize,
589
- output: warnings.length ? `Warning: ${warnings.join('; ')}` : undefined,
590
- }
591
- } else {
592
- result = await uploadFile(alias, localPath, remotePath)
593
- return {
594
- success: result.success,
595
- method: 'sftp',
596
- filesTransferred: 1,
597
- bytesTransferred: result.size,
598
- output: warnings.length ? `Warning: ${warnings.join('; ')}` : undefined,
599
- }
600
- }
601
- } else {
602
- // 下载
603
- const info = await getFileInfo(alias, remotePath)
604
- if (info.isDirectory && options.recursive !== false) {
605
- result = await downloadDirectory(alias, remotePath, localPath, options.exclude)
606
- return {
607
- success: true,
608
- method: 'sftp',
609
- filesTransferred: result.fileCount,
610
- bytesTransferred: result.totalSize,
611
- output: warnings.length ? `Warning: ${warnings.join('; ')}` : undefined,
612
- }
613
- } else {
614
- result = await downloadFile(alias, remotePath, localPath)
615
- return {
616
- success: result.success,
617
- method: 'sftp',
618
- filesTransferred: 1,
619
- bytesTransferred: result.size,
620
- output: warnings.length ? `Warning: ${warnings.join('; ')}` : undefined,
621
- }
514
+ const {fileCount, totalSize} = await uploadDirectory(alias, localPath, remotePath, options.exclude)
515
+ return buildSyncResult(fileCount, totalSize, warnings)
622
516
  }
517
+ const {size} = await uploadFile(alias, localPath, remotePath)
518
+ return buildSyncResult(1, size, warnings)
519
+ }
520
+
521
+ // download
522
+ const info = await getFileInfo(alias, remotePath)
523
+ if (info.isDirectory && options.recursive !== false) {
524
+ const {fileCount, totalSize} = await downloadDirectory(alias, remotePath, localPath, options.exclude)
525
+ return buildSyncResult(fileCount, totalSize, warnings)
623
526
  }
527
+ const {size} = await downloadFile(alias, remotePath, localPath)
528
+ return buildSyncResult(1, size, warnings)
624
529
  } catch (err: any) {
625
530
  return {
626
531
  success: false,
@@ -725,15 +630,15 @@ function matchPattern(name: string, pattern: string): boolean {
725
630
  * 格式化权限字符串
726
631
  */
727
632
  function formatPermissions(mode: number): string {
728
- const types: Record<number, string> = {
729
- 0o40000: 'd',
730
- 0o120000: 'l',
731
- 0o100000: '-',
732
- }
633
+ const types: [number, string][] = [
634
+ [S_IFDIR, 'd'],
635
+ [S_IFLNK, 'l'],
636
+ [S_IFREG, '-'],
637
+ ]
733
638
 
734
639
  let type = '-'
735
- for (const [mask, char] of Object.entries(types)) {
736
- if ((mode & parseInt(mask)) !== 0) {
640
+ for (const [mask, char] of types) {
641
+ if ((mode & mask) !== 0) {
737
642
  type = char
738
643
  break
739
644
  }