@pyrokine/mcp-ssh 1.3.0 → 2.0.1

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/file-ops.ts DELETED
@@ -1,662 +0,0 @@
1
- /**
2
- * SSH File Operations - 文件操作
3
- */
4
-
5
- import {execSync} from 'child_process'
6
- import * as fs from 'fs'
7
- import * as os from 'os'
8
- import * as path from 'path'
9
- import {SFTPWrapper, Stats} from 'ssh2'
10
- import {sessionManager} from './session-manager.js'
11
- import {FileInfo, TransferProgress} from './types.js'
12
-
13
- // 文件类型 mode 常量
14
- const S_IFDIR = 0o40000
15
- const S_IFREG = 0o100000
16
- const S_IFLNK = 0o120000
17
-
18
- /**
19
- * sftp.stat 的 Promise 包装
20
- */
21
- function sftpStat(sftp: SFTPWrapper, remotePath: string): Promise<Stats> {
22
- return new Promise((resolve, reject) => {
23
- sftp.stat(remotePath, (err, stats) => {
24
- if (err) {
25
- reject(err)
26
- } else {
27
- resolve(stats)
28
- }
29
- })
30
- })
31
- }
32
-
33
- /**
34
- * 带进度追踪的流传输
35
- */
36
- function pipeWithProgress(
37
- readStream: NodeJS.ReadableStream,
38
- writeStream: NodeJS.WritableStream,
39
- sftp: SFTPWrapper,
40
- totalSize: number,
41
- onProgress?: (progress: TransferProgress) => void,
42
- ): Promise<{ success: boolean; size: number }> {
43
- return new Promise((resolve, reject) => {
44
- let settled = false
45
-
46
- const cleanup = (err?: Error) => {
47
- if (settled) {
48
- return
49
- }
50
- settled = true
51
- sftp.end()
52
- if (err) {
53
- reject(err)
54
- }
55
- }
56
-
57
- let transferred = 0
58
-
59
- readStream.on('data', (chunk: Buffer) => {
60
- transferred += chunk.length
61
- onProgress?.({
62
- transferred,
63
- total: totalSize,
64
- percent: totalSize > 0 ? Math.round((transferred / totalSize) * 100) : 100,
65
- })
66
- })
67
-
68
- readStream.on('error', (err: Error) => cleanup(err))
69
- writeStream.on('error', (err: Error) => cleanup(err))
70
-
71
- writeStream.on('close', () => {
72
- if (!settled) {
73
- settled = true
74
- sftp.end()
75
- resolve({ success: true, size: totalSize })
76
- }
77
- })
78
-
79
- readStream.pipe(writeStream)
80
- })
81
- }
82
-
83
- /**
84
- * 上传文件
85
- */
86
- export async function uploadFile(
87
- alias: string,
88
- localPath: string,
89
- remotePath: string,
90
- onProgress?: (progress: TransferProgress) => void,
91
- ): Promise<{ success: boolean; size: number }> {
92
- if (!fs.existsSync(localPath)) {
93
- throw new Error(`Local file not found: ${localPath}`)
94
- }
95
-
96
- const sftp = await sessionManager.getSftp(alias)
97
- const totalSize = fs.statSync(localPath).size
98
-
99
- return pipeWithProgress(
100
- fs.createReadStream(localPath),
101
- sftp.createWriteStream(remotePath),
102
- sftp, totalSize, onProgress,
103
- )
104
- }
105
-
106
- /**
107
- * 下载文件
108
- */
109
- export async function downloadFile(
110
- alias: string,
111
- remotePath: string,
112
- localPath: string,
113
- onProgress?: (progress: TransferProgress) => void,
114
- ): Promise<{ success: boolean; size: number }> {
115
- const sftp = await sessionManager.getSftp(alias)
116
- const totalSize = (await sftpStat(sftp, remotePath)).size
117
-
118
- // 确保本地目录存在
119
- const localDir = path.dirname(localPath)
120
- if (!fs.existsSync(localDir)) {
121
- fs.mkdirSync(localDir, { recursive: true })
122
- }
123
-
124
- return pipeWithProgress(
125
- sftp.createReadStream(remotePath),
126
- fs.createWriteStream(localPath),
127
- sftp, totalSize, onProgress,
128
- )
129
- }
130
-
131
- /**
132
- * 读取远程文件内容
133
- */
134
- export async function readFile(
135
- alias: string,
136
- remotePath: string,
137
- maxBytes: number = 1024 * 1024, // 默认最大 1MB
138
- ): Promise<{ content: string; size: number; truncated: boolean }> {
139
- const sftp = await sessionManager.getSftp(alias)
140
- const actualSize = (await sftpStat(sftp, remotePath)).size
141
- const truncated = actualSize > maxBytes
142
-
143
- // 处理空文件
144
- if (actualSize === 0) {
145
- sftp.end()
146
- return { content: '', size: 0, truncated: false }
147
- }
148
-
149
- const readSize = Math.min(actualSize, maxBytes)
150
-
151
- return new Promise((resolve, reject) => {
152
- const chunks: Buffer[] = []
153
-
154
- const readStream = sftp.createReadStream(remotePath, {
155
- start: 0,
156
- end: readSize - 1,
157
- })
158
-
159
- readStream.on('data', (chunk: Buffer) => {
160
- chunks.push(chunk)
161
- })
162
-
163
- readStream.on('end', () => {
164
- sftp.end()
165
- const content = Buffer.concat(chunks).toString('utf-8')
166
- resolve({
167
- content,
168
- size: actualSize,
169
- truncated,
170
- })
171
- })
172
-
173
- readStream.on('error', (err: Error) => {
174
- sftp.end()
175
- reject(err)
176
- })
177
- })
178
- }
179
-
180
- /**
181
- * 写入远程文件
182
- */
183
- export async function writeFile(
184
- alias: string,
185
- remotePath: string,
186
- content: string,
187
- append: boolean = false,
188
- ): Promise<{ success: boolean; size: number }> {
189
- const sftp = await sessionManager.getSftp(alias)
190
- const flags = append ? 'a' : 'w'
191
-
192
- return new Promise((resolve, reject) => {
193
- const writeStream = sftp.createWriteStream(remotePath, { flags })
194
-
195
- writeStream.on('close', () => {
196
- sftp.end()
197
- resolve({ success: true, size: content.length })
198
- })
199
-
200
- writeStream.on('error', (err: Error) => {
201
- sftp.end()
202
- reject(err)
203
- })
204
-
205
- writeStream.write(content)
206
- writeStream.end()
207
- })
208
- }
209
-
210
- /**
211
- * 列出目录内容
212
- */
213
- export async function listDir(
214
- alias: string,
215
- remotePath: string,
216
- showHidden: boolean = false,
217
- ): Promise<FileInfo[]> {
218
- const sftp = await sessionManager.getSftp(alias)
219
-
220
- return new Promise((resolve, reject) => {
221
- sftp.readdir(remotePath, (err, list) => {
222
- if (err) {
223
- sftp.end()
224
- reject(err)
225
- return
226
- }
227
-
228
- const files: FileInfo[] = list
229
- .filter((item) => showHidden || !item.filename.startsWith('.'))
230
- .map((item) => ({
231
- name: item.filename,
232
- path: path.posix.join(remotePath, item.filename),
233
- size: item.attrs.size,
234
- isDirectory: (item.attrs.mode & S_IFDIR) !== 0,
235
- isFile: (item.attrs.mode & S_IFREG) !== 0,
236
- isSymlink: (item.attrs.mode & S_IFLNK) !== 0,
237
- permissions: formatPermissions(item.attrs.mode),
238
- owner: item.attrs.uid,
239
- group: item.attrs.gid,
240
- mtime: new Date(item.attrs.mtime * 1000),
241
- atime: new Date(item.attrs.atime * 1000),
242
- }))
243
- .sort((a, b) => {
244
- // 目录在前
245
- if (a.isDirectory !== b.isDirectory) {
246
- return a.isDirectory ? -1 : 1
247
- }
248
- return a.name.localeCompare(b.name)
249
- })
250
-
251
- sftp.end()
252
- resolve(files)
253
- })
254
- })
255
- }
256
-
257
- /**
258
- * 获取文件信息
259
- */
260
- export async function getFileInfo(
261
- alias: string,
262
- remotePath: string,
263
- ): Promise<FileInfo> {
264
- const sftp = await sessionManager.getSftp(alias)
265
-
266
- return new Promise((resolve, reject) => {
267
- sftp.stat(remotePath, (err, stats) => {
268
- sftp.end()
269
-
270
- if (err) {
271
- reject(err)
272
- return
273
- }
274
-
275
- resolve({
276
- name: path.posix.basename(remotePath),
277
- path: remotePath,
278
- size: stats.size,
279
- isDirectory: (stats.mode & S_IFDIR) !== 0,
280
- isFile: (stats.mode & S_IFREG) !== 0,
281
- isSymlink: (stats.mode & S_IFLNK) !== 0,
282
- permissions: formatPermissions(stats.mode),
283
- owner: stats.uid,
284
- group: stats.gid,
285
- mtime: new Date(stats.mtime * 1000),
286
- atime: new Date(stats.atime * 1000),
287
- })
288
- })
289
- })
290
- }
291
-
292
- /**
293
- * 创建目录
294
- */
295
- export async function mkdir(
296
- alias: string,
297
- remotePath: string,
298
- recursive: boolean = false,
299
- ): Promise<boolean> {
300
- if (recursive) {
301
- // 通过 exec 实现递归创建
302
- const result = await sessionManager.exec(alias, `mkdir -p "${remotePath}"`)
303
- return result.exitCode === 0
304
- }
305
-
306
- const sftp = await sessionManager.getSftp(alias)
307
- return new Promise((resolve, reject) => {
308
- sftp.mkdir(remotePath, (err) => {
309
- sftp.end()
310
- if (err) {
311
- reject(err)
312
- } else {
313
- resolve(true)
314
- }
315
- })
316
- })
317
- }
318
-
319
- /**
320
- * 检查远程是否安装 rsync
321
- */
322
- export async function checkRsync(alias: string): Promise<boolean> {
323
- try {
324
- const result = await sessionManager.exec(alias, 'which rsync')
325
- return result.exitCode === 0 && result.stdout.trim().length > 0
326
- } catch {
327
- return false
328
- }
329
- }
330
-
331
- /**
332
- * 智能文件同步(优先使用 rsync)
333
- *
334
- * @param alias SSH 连接别名
335
- * @param localPath 本地路径
336
- * @param remotePath 远程路径
337
- * @param direction 同步方向:'upload' 或 'download'
338
- * @param options 同步选项
339
- */
340
- export async function syncFiles(
341
- alias: string,
342
- localPath: string,
343
- remotePath: string,
344
- direction: 'upload' | 'download',
345
- options: {
346
- delete?: boolean; // 删除目标端多余文件
347
- dryRun?: boolean; // 仅显示将执行的操作
348
- exclude?: string[]; // 排除模式
349
- recursive?: boolean; // 递归同步目录
350
- } = {},
351
- ): Promise<SyncResult> {
352
- const hasRsync = await checkRsync(alias)
353
-
354
- if (hasRsync) {
355
- return syncWithRsync(alias, localPath, remotePath, direction, options)
356
- }
357
- return syncWithSftp(alias, localPath, remotePath, direction, options)
358
- }
359
-
360
- /**
361
- * 转义 shell 路径参数
362
- */
363
- function escapeShellPath(p: string): string {
364
- return `'${p.replace(/'/g, '\'\\\'\'')}'`
365
- }
366
-
367
- /**
368
- * 使用 rsync 同步文件
369
- * 通过本地执行 rsync 连接到远程(需要密钥认证或 ssh-agent)
370
- */
371
- async function syncWithRsync(
372
- alias: string,
373
- localPath: string,
374
- remotePath: string,
375
- direction: 'upload' | 'download',
376
- options: {
377
- delete?: boolean;
378
- dryRun?: boolean;
379
- exclude?: string[];
380
- recursive?: boolean;
381
- },
382
- ): Promise<SyncResult> {
383
- // 检查本地是否有 rsync
384
- let hasLocalRsync = false
385
- try {
386
- const cmd = os.platform() === 'win32' ? 'where rsync' : 'which rsync'
387
- execSync(cmd, { stdio: 'pipe' })
388
- hasLocalRsync = true
389
- } catch {
390
- }
391
-
392
- if (!hasLocalRsync) {
393
- // 本地没有 rsync,回退到 SFTP
394
- return syncWithSftp(alias, localPath, remotePath, direction, options)
395
- }
396
-
397
- // 获取会话信息以构建 rsync 命令
398
- const sessions = sessionManager.listSessions()
399
- const sessionInfo = sessions.find(s => s.alias === alias)
400
- if (!sessionInfo) {
401
- throw new Error(`Session '${alias}' not found`)
402
- }
403
-
404
- // 构建 rsync 参数
405
- const args: string[] = ['-avz', '--progress']
406
-
407
- if (options.delete) {
408
- args.push('--delete')
409
- }
410
- if (options.dryRun) {
411
- args.push('--dry-run')
412
- }
413
- if (options.recursive === false) {
414
- args.push('--dirs') // 不递归,只传输目录本身
415
- }
416
- if (options.exclude) {
417
- for (const pattern of options.exclude) {
418
- args.push(`--exclude=${escapeShellPath(pattern)}`)
419
- }
420
- }
421
-
422
- // 构建 rsync 命令(本地执行)
423
- // 注意:这需要密钥认证或 ssh-agent,密码认证不支持
424
- const sshCmd = `ssh -p ${sessionInfo.port} -o StrictHostKeyChecking=no -o BatchMode=yes`
425
- const remoteSpec = `${sessionInfo.username}@${sessionInfo.host}:${escapeShellPath(remotePath)}`
426
- const rsyncCmd = direction === 'upload'
427
- ? `rsync ${args.join(' ')} -e "${sshCmd}" ${escapeShellPath(localPath)} ${remoteSpec}`
428
- : `rsync ${args.join(' ')} -e "${sshCmd}" ${remoteSpec} ${escapeShellPath(localPath)}`
429
-
430
- try {
431
- const result = execSync(rsyncCmd, {
432
- encoding: 'utf-8',
433
- timeout: 600000, // 10 分钟超时
434
- stdio: ['pipe', 'pipe', 'pipe'],
435
- })
436
-
437
- // 解析 rsync 输出统计文件数
438
- const lines = result.split('\n')
439
- let filesTransferred = 0
440
- for (const line of lines) {
441
- if (line.trim() &&
442
- !line.startsWith('sending') &&
443
- !line.startsWith('receiving') &&
444
- !line.startsWith('total')) {
445
- filesTransferred++
446
- }
447
- }
448
-
449
- return {
450
- success: true,
451
- method: 'rsync',
452
- filesTransferred,
453
- output: result,
454
- }
455
- } catch {
456
- // rsync 失败(可能是密码认证),回退到 SFTP
457
- return syncWithSftp(alias, localPath, remotePath, direction, options)
458
- }
459
- }
460
-
461
- /**
462
- * 使用 SFTP 同步文件
463
- */
464
- type SyncResult = {
465
- success: boolean;
466
- method: 'rsync' | 'sftp';
467
- filesTransferred?: number;
468
- bytesTransferred?: number;
469
- output?: string;
470
- }
471
-
472
- function buildSyncResult(
473
- fileCount: number,
474
- totalSize: number,
475
- warnings: string[],
476
- ): SyncResult {
477
- return {
478
- success: true,
479
- method: 'sftp',
480
- filesTransferred: fileCount,
481
- bytesTransferred: totalSize,
482
- output: warnings.length ? `Warning: ${warnings.join('; ')}` : undefined,
483
- }
484
- }
485
-
486
- async function syncWithSftp(
487
- alias: string,
488
- localPath: string,
489
- remotePath: string,
490
- direction: 'upload' | 'download',
491
- options: {
492
- delete?: boolean;
493
- dryRun?: boolean;
494
- exclude?: string[];
495
- recursive?: boolean;
496
- },
497
- ): Promise<SyncResult> {
498
- const warnings: string[] = []
499
- if (options.delete) {
500
- warnings.push('delete option is not supported in SFTP mode (requires rsync)')
501
- }
502
-
503
- if (options.dryRun) {
504
- return {
505
- success: true,
506
- method: 'sftp',
507
- output: 'Dry run mode: would transfer files via SFTP' +
508
- (warnings.length ? `. Warning: ${warnings.join('; ')}` : ''),
509
- }
510
- }
511
-
512
- try {
513
- if (direction === 'upload') {
514
- const stats = fs.statSync(localPath)
515
- if (stats.isDirectory() && options.recursive !== false) {
516
- const { fileCount, totalSize } = await uploadDirectory(alias, localPath, remotePath, options.exclude)
517
- return buildSyncResult(fileCount, totalSize, warnings)
518
- }
519
- const { size } = await uploadFile(alias, localPath, remotePath)
520
- return buildSyncResult(1, size, warnings)
521
- }
522
-
523
- // download
524
- const info = await getFileInfo(alias, remotePath)
525
- if (info.isDirectory && options.recursive !== false) {
526
- const { fileCount, totalSize } = await downloadDirectory(alias, remotePath, localPath, options.exclude)
527
- return buildSyncResult(fileCount, totalSize, warnings)
528
- }
529
- const { size } = await downloadFile(alias, remotePath, localPath)
530
- return buildSyncResult(1, size, warnings)
531
- } catch (err: any) {
532
- return {
533
- success: false,
534
- method: 'sftp',
535
- output: err.message,
536
- }
537
- }
538
- }
539
-
540
- /**
541
- * 递归上传目录
542
- */
543
- async function uploadDirectory(
544
- alias: string,
545
- localPath: string,
546
- remotePath: string,
547
- exclude?: string[],
548
- ): Promise<{ fileCount: number; totalSize: number }> {
549
- let fileCount = 0
550
- let totalSize = 0
551
-
552
- // 确保远程目录存在
553
- await mkdir(alias, remotePath, true)
554
-
555
- const items = fs.readdirSync(localPath)
556
- for (const item of items) {
557
- // 检查排除模式
558
- if (exclude && exclude.some(pattern => matchPattern(item, pattern))) {
559
- continue
560
- }
561
-
562
- const itemLocalPath = path.join(localPath, item)
563
- const itemRemotePath = path.posix.join(remotePath, item)
564
- const stats = fs.statSync(itemLocalPath)
565
-
566
- if (stats.isDirectory()) {
567
- const result = await uploadDirectory(alias, itemLocalPath, itemRemotePath, exclude)
568
- fileCount += result.fileCount
569
- totalSize += result.totalSize
570
- } else if (stats.isFile()) {
571
- await uploadFile(alias, itemLocalPath, itemRemotePath)
572
- fileCount++
573
- totalSize += stats.size
574
- }
575
- }
576
-
577
- return { fileCount, totalSize }
578
- }
579
-
580
- /**
581
- * 递归下载目录
582
- */
583
- async function downloadDirectory(
584
- alias: string,
585
- remotePath: string,
586
- localPath: string,
587
- exclude?: string[],
588
- ): Promise<{ fileCount: number; totalSize: number }> {
589
- let fileCount = 0
590
- let totalSize = 0
591
-
592
- // 确保本地目录存在
593
- if (!fs.existsSync(localPath)) {
594
- fs.mkdirSync(localPath, { recursive: true })
595
- }
596
-
597
- const items = await listDir(alias, remotePath, true)
598
- for (const item of items) {
599
- // 检查排除模式
600
- if (exclude && exclude.some(pattern => matchPattern(item.name, pattern))) {
601
- continue
602
- }
603
-
604
- const itemLocalPath = path.join(localPath, item.name)
605
-
606
- if (item.isDirectory) {
607
- const result = await downloadDirectory(alias, item.path, itemLocalPath, exclude)
608
- fileCount += result.fileCount
609
- totalSize += result.totalSize
610
- } else if (item.isFile) {
611
- await downloadFile(alias, item.path, itemLocalPath)
612
- fileCount++
613
- totalSize += item.size
614
- }
615
- }
616
-
617
- return { fileCount, totalSize }
618
- }
619
-
620
- /**
621
- * 简单的模式匹配(支持 * 和 ?)
622
- */
623
- function matchPattern(name: string, pattern: string): boolean {
624
- const regexPattern = pattern
625
- .replace(/[.+^${}()|[\]\\]/g, '\\$&') // 转义特殊字符
626
- .replace(/\*/g, '.*')
627
- .replace(/\?/g, '.')
628
- return new RegExp(`^${regexPattern}$`).test(name)
629
- }
630
-
631
- /**
632
- * 格式化权限字符串
633
- */
634
- function formatPermissions(mode: number): string {
635
- const types: [number, string][] = [
636
- [S_IFDIR, 'd'],
637
- [S_IFLNK, 'l'],
638
- [S_IFREG, '-'],
639
- ]
640
-
641
- let type = '-'
642
- for (const [mask, char] of types) {
643
- if ((mode & mask) !== 0) {
644
- type = char
645
- break
646
- }
647
- }
648
-
649
- const perms = [
650
- (mode & 0o400) ? 'r' : '-',
651
- (mode & 0o200) ? 'w' : '-',
652
- (mode & 0o100) ? 'x' : '-',
653
- (mode & 0o040) ? 'r' : '-',
654
- (mode & 0o020) ? 'w' : '-',
655
- (mode & 0o010) ? 'x' : '-',
656
- (mode & 0o004) ? 'r' : '-',
657
- (mode & 0o002) ? 'w' : '-',
658
- (mode & 0o001) ? 'x' : '-',
659
- ]
660
-
661
- return type + perms.join('')
662
- }