@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.
- package/README.md +3 -1
- package/README_zh.md +3 -1
- package/dist/file-ops.d.ts +7 -10
- package/dist/file-ops.js +74 -172
- package/dist/forward-manager.d.ts +33 -0
- package/dist/forward-manager.js +185 -0
- package/dist/index.js +8 -953
- package/dist/pty-manager.d.ts +37 -0
- package/dist/pty-manager.js +169 -0
- package/dist/session-manager.d.ts +28 -86
- package/dist/session-manager.js +131 -441
- package/dist/ssh-config.d.ts +0 -4
- package/dist/ssh-config.js +1 -8
- package/dist/tools/connection.d.ts +7 -0
- package/dist/tools/connection.js +215 -0
- package/dist/tools/exec.d.ts +8 -0
- package/dist/tools/exec.js +221 -0
- package/dist/tools/file.d.ts +8 -0
- package/dist/tools/file.js +192 -0
- package/dist/tools/forward.d.ts +7 -0
- package/dist/tools/forward.js +116 -0
- package/dist/tools/index.d.ts +8 -0
- package/dist/tools/index.js +8 -0
- package/dist/tools/pty.d.ts +7 -0
- package/dist/tools/pty.js +178 -0
- package/dist/tools/utils.d.ts +22 -0
- package/dist/tools/utils.js +21 -0
- package/dist/types.d.ts +0 -7
- package/package.json +3 -2
- package/src/file-ops.ts +117 -212
- package/src/forward-manager.ts +257 -0
- package/src/index.ts +17 -1099
- package/src/pty-manager.ts +220 -0
- package/src/session-manager.ts +166 -532
- package/src/ssh-config.ts +1 -8
- package/src/tools/connection.ts +240 -0
- package/src/tools/exec.ts +260 -0
- package/src/tools/file.ts +219 -0
- package/src/tools/forward.ts +141 -0
- package/src/tools/index.ts +9 -0
- package/src/tools/pty.ts +203 -0
- package/src/tools/utils.ts +23 -0
- package/src/types.ts +0 -9
package/README.md
CHANGED
package/README_zh.md
CHANGED
package/dist/file-ops.d.ts
CHANGED
|
@@ -39,18 +39,10 @@ export declare function listDir(alias: string, remotePath: string, showHidden?:
|
|
|
39
39
|
* 获取文件信息
|
|
40
40
|
*/
|
|
41
41
|
export declare function getFileInfo(alias: string, remotePath: string): Promise<FileInfo>;
|
|
42
|
-
/**
|
|
43
|
-
* 检查文件是否存在
|
|
44
|
-
*/
|
|
45
|
-
export declare function fileExists(alias: string, remotePath: string): Promise<boolean>;
|
|
46
42
|
/**
|
|
47
43
|
* 创建目录
|
|
48
44
|
*/
|
|
49
45
|
export declare function mkdir(alias: string, remotePath: string, recursive?: boolean): Promise<boolean>;
|
|
50
|
-
/**
|
|
51
|
-
* 删除文件
|
|
52
|
-
*/
|
|
53
|
-
export declare function removeFile(alias: string, remotePath: string): Promise<boolean>;
|
|
54
46
|
/**
|
|
55
47
|
* 检查远程是否安装 rsync
|
|
56
48
|
*/
|
|
@@ -69,10 +61,15 @@ export declare function syncFiles(alias: string, localPath: string, remotePath:
|
|
|
69
61
|
dryRun?: boolean;
|
|
70
62
|
exclude?: string[];
|
|
71
63
|
recursive?: boolean;
|
|
72
|
-
}): Promise<
|
|
64
|
+
}): Promise<SyncResult>;
|
|
65
|
+
/**
|
|
66
|
+
* 使用 SFTP 同步文件
|
|
67
|
+
*/
|
|
68
|
+
type SyncResult = {
|
|
73
69
|
success: boolean;
|
|
74
70
|
method: 'rsync' | 'sftp';
|
|
75
71
|
filesTransferred?: number;
|
|
76
72
|
bytesTransferred?: number;
|
|
77
73
|
output?: string;
|
|
78
|
-
}
|
|
74
|
+
};
|
|
75
|
+
export {};
|
package/dist/file-ops.js
CHANGED
|
@@ -5,19 +5,30 @@ import { execSync } from 'child_process';
|
|
|
5
5
|
import * as fs from 'fs';
|
|
6
6
|
import * as path from 'path';
|
|
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
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
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
34
|
if (settled) {
|
|
@@ -32,13 +43,11 @@ export async function uploadFile(alias, localPath, remotePath, onProgress) {
|
|
|
32
43
|
let transferred = 0;
|
|
33
44
|
readStream.on('data', (chunk) => {
|
|
34
45
|
transferred += chunk.length;
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
});
|
|
41
|
-
}
|
|
46
|
+
onProgress?.({
|
|
47
|
+
transferred,
|
|
48
|
+
total: totalSize,
|
|
49
|
+
percent: totalSize > 0 ? Math.round((transferred / totalSize) * 100) : 100,
|
|
50
|
+
});
|
|
42
51
|
});
|
|
43
52
|
readStream.on('error', (err) => cleanup(err));
|
|
44
53
|
writeStream.on('error', (err) => cleanup(err));
|
|
@@ -52,82 +61,36 @@ export async function uploadFile(alias, localPath, remotePath, onProgress) {
|
|
|
52
61
|
readStream.pipe(writeStream);
|
|
53
62
|
});
|
|
54
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
|
+
}
|
|
55
75
|
/**
|
|
56
76
|
* 下载文件
|
|
57
77
|
*/
|
|
58
78
|
export async function downloadFile(alias, remotePath, localPath, onProgress) {
|
|
59
79
|
const sftp = await sessionManager.getSftp(alias);
|
|
60
|
-
|
|
61
|
-
const stats = await new Promise((resolve, reject) => {
|
|
62
|
-
sftp.stat(remotePath, (err, stats) => {
|
|
63
|
-
if (err) {
|
|
64
|
-
reject(err);
|
|
65
|
-
}
|
|
66
|
-
else {
|
|
67
|
-
resolve(stats);
|
|
68
|
-
}
|
|
69
|
-
});
|
|
70
|
-
});
|
|
71
|
-
const totalSize = stats.size;
|
|
80
|
+
const totalSize = (await sftpStat(sftp, remotePath)).size;
|
|
72
81
|
// 确保本地目录存在
|
|
73
82
|
const localDir = path.dirname(localPath);
|
|
74
83
|
if (!fs.existsSync(localDir)) {
|
|
75
84
|
fs.mkdirSync(localDir, { recursive: true });
|
|
76
85
|
}
|
|
77
|
-
return
|
|
78
|
-
const readStream = sftp.createReadStream(remotePath);
|
|
79
|
-
const writeStream = fs.createWriteStream(localPath);
|
|
80
|
-
let settled = false;
|
|
81
|
-
const cleanup = (err) => {
|
|
82
|
-
if (settled) {
|
|
83
|
-
return;
|
|
84
|
-
}
|
|
85
|
-
settled = true;
|
|
86
|
-
sftp.end();
|
|
87
|
-
if (err) {
|
|
88
|
-
reject(err);
|
|
89
|
-
}
|
|
90
|
-
};
|
|
91
|
-
let transferred = 0;
|
|
92
|
-
readStream.on('data', (chunk) => {
|
|
93
|
-
transferred += chunk.length;
|
|
94
|
-
if (onProgress) {
|
|
95
|
-
onProgress({
|
|
96
|
-
transferred,
|
|
97
|
-
total: totalSize,
|
|
98
|
-
percent: totalSize > 0 ? Math.round((transferred / totalSize) * 100) : 100,
|
|
99
|
-
});
|
|
100
|
-
}
|
|
101
|
-
});
|
|
102
|
-
readStream.on('error', (err) => cleanup(err));
|
|
103
|
-
writeStream.on('error', (err) => cleanup(err));
|
|
104
|
-
writeStream.on('close', () => {
|
|
105
|
-
if (!settled) {
|
|
106
|
-
settled = true;
|
|
107
|
-
sftp.end();
|
|
108
|
-
resolve({ success: true, size: totalSize });
|
|
109
|
-
}
|
|
110
|
-
});
|
|
111
|
-
readStream.pipe(writeStream);
|
|
112
|
-
});
|
|
86
|
+
return pipeWithProgress(sftp.createReadStream(remotePath), fs.createWriteStream(localPath), sftp, totalSize, onProgress);
|
|
113
87
|
}
|
|
114
88
|
/**
|
|
115
89
|
* 读取远程文件内容
|
|
116
90
|
*/
|
|
117
91
|
export async function readFile(alias, remotePath, maxBytes = 1024 * 1024) {
|
|
118
92
|
const sftp = await sessionManager.getSftp(alias);
|
|
119
|
-
|
|
120
|
-
const stats = await new Promise((resolve, reject) => {
|
|
121
|
-
sftp.stat(remotePath, (err, stats) => {
|
|
122
|
-
if (err) {
|
|
123
|
-
reject(err);
|
|
124
|
-
}
|
|
125
|
-
else {
|
|
126
|
-
resolve(stats);
|
|
127
|
-
}
|
|
128
|
-
});
|
|
129
|
-
});
|
|
130
|
-
const actualSize = stats.size;
|
|
93
|
+
const actualSize = (await sftpStat(sftp, remotePath)).size;
|
|
131
94
|
const truncated = actualSize > maxBytes;
|
|
132
95
|
// 处理空文件
|
|
133
96
|
if (actualSize === 0) {
|
|
@@ -197,9 +160,9 @@ export async function listDir(alias, remotePath, showHidden = false) {
|
|
|
197
160
|
name: item.filename,
|
|
198
161
|
path: path.posix.join(remotePath, item.filename),
|
|
199
162
|
size: item.attrs.size,
|
|
200
|
-
isDirectory: (item.attrs.mode &
|
|
201
|
-
isFile: (item.attrs.mode &
|
|
202
|
-
isSymlink: (item.attrs.mode &
|
|
163
|
+
isDirectory: (item.attrs.mode & S_IFDIR) !== 0,
|
|
164
|
+
isFile: (item.attrs.mode & S_IFREG) !== 0,
|
|
165
|
+
isSymlink: (item.attrs.mode & S_IFLNK) !== 0,
|
|
203
166
|
permissions: formatPermissions(item.attrs.mode),
|
|
204
167
|
owner: item.attrs.uid,
|
|
205
168
|
group: item.attrs.gid,
|
|
@@ -234,9 +197,9 @@ export async function getFileInfo(alias, remotePath) {
|
|
|
234
197
|
name: path.posix.basename(remotePath),
|
|
235
198
|
path: remotePath,
|
|
236
199
|
size: stats.size,
|
|
237
|
-
isDirectory: (stats.mode &
|
|
238
|
-
isFile: (stats.mode &
|
|
239
|
-
isSymlink: (stats.mode &
|
|
200
|
+
isDirectory: (stats.mode & S_IFDIR) !== 0,
|
|
201
|
+
isFile: (stats.mode & S_IFREG) !== 0,
|
|
202
|
+
isSymlink: (stats.mode & S_IFLNK) !== 0,
|
|
240
203
|
permissions: formatPermissions(stats.mode),
|
|
241
204
|
owner: stats.uid,
|
|
242
205
|
group: stats.gid,
|
|
@@ -246,18 +209,6 @@ export async function getFileInfo(alias, remotePath) {
|
|
|
246
209
|
});
|
|
247
210
|
});
|
|
248
211
|
}
|
|
249
|
-
/**
|
|
250
|
-
* 检查文件是否存在
|
|
251
|
-
*/
|
|
252
|
-
export async function fileExists(alias, remotePath) {
|
|
253
|
-
const sftp = await sessionManager.getSftp(alias);
|
|
254
|
-
return new Promise((resolve) => {
|
|
255
|
-
sftp.stat(remotePath, (err) => {
|
|
256
|
-
sftp.end();
|
|
257
|
-
resolve(!err);
|
|
258
|
-
});
|
|
259
|
-
});
|
|
260
|
-
}
|
|
261
212
|
/**
|
|
262
213
|
* 创建目录
|
|
263
214
|
*/
|
|
@@ -280,23 +231,6 @@ export async function mkdir(alias, remotePath, recursive = false) {
|
|
|
280
231
|
});
|
|
281
232
|
});
|
|
282
233
|
}
|
|
283
|
-
/**
|
|
284
|
-
* 删除文件
|
|
285
|
-
*/
|
|
286
|
-
export async function removeFile(alias, remotePath) {
|
|
287
|
-
const sftp = await sessionManager.getSftp(alias);
|
|
288
|
-
return new Promise((resolve, reject) => {
|
|
289
|
-
sftp.unlink(remotePath, (err) => {
|
|
290
|
-
sftp.end();
|
|
291
|
-
if (err) {
|
|
292
|
-
reject(err);
|
|
293
|
-
}
|
|
294
|
-
else {
|
|
295
|
-
resolve(true);
|
|
296
|
-
}
|
|
297
|
-
});
|
|
298
|
-
});
|
|
299
|
-
}
|
|
300
234
|
/**
|
|
301
235
|
* 检查远程是否安装 rsync
|
|
302
236
|
*/
|
|
@@ -319,16 +253,11 @@ export async function checkRsync(alias) {
|
|
|
319
253
|
* @param options 同步选项
|
|
320
254
|
*/
|
|
321
255
|
export async function syncFiles(alias, localPath, remotePath, direction, options = {}) {
|
|
322
|
-
// 检查远程 rsync
|
|
323
256
|
const hasRsync = await checkRsync(alias);
|
|
324
257
|
if (hasRsync) {
|
|
325
|
-
// 使用 rsync(通过远程端执行)
|
|
326
258
|
return syncWithRsync(alias, localPath, remotePath, direction, options);
|
|
327
259
|
}
|
|
328
|
-
|
|
329
|
-
// 回退到 SFTP
|
|
330
|
-
return syncWithSftp(alias, localPath, remotePath, direction, options);
|
|
331
|
-
}
|
|
260
|
+
return syncWithSftp(alias, localPath, remotePath, direction, options);
|
|
332
261
|
}
|
|
333
262
|
/**
|
|
334
263
|
* 转义 shell 路径参数
|
|
@@ -411,11 +340,16 @@ async function syncWithRsync(alias, localPath, remotePath, direction, options) {
|
|
|
411
340
|
return syncWithSftp(alias, localPath, remotePath, direction, options);
|
|
412
341
|
}
|
|
413
342
|
}
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
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
|
+
}
|
|
417
352
|
async function syncWithSftp(alias, localPath, remotePath, direction, options) {
|
|
418
|
-
// SFTP 模式不支持 delete 选项
|
|
419
353
|
const warnings = [];
|
|
420
354
|
if (options.delete) {
|
|
421
355
|
warnings.push('delete option is not supported in SFTP mode (requires rsync)');
|
|
@@ -429,55 +363,23 @@ async function syncWithSftp(alias, localPath, remotePath, direction, options) {
|
|
|
429
363
|
};
|
|
430
364
|
}
|
|
431
365
|
try {
|
|
432
|
-
let result;
|
|
433
366
|
if (direction === 'upload') {
|
|
434
|
-
// 检查是否是目录
|
|
435
367
|
const stats = fs.statSync(localPath);
|
|
436
368
|
if (stats.isDirectory() && options.recursive !== false) {
|
|
437
|
-
|
|
438
|
-
return
|
|
439
|
-
success: true,
|
|
440
|
-
method: 'sftp',
|
|
441
|
-
filesTransferred: result.fileCount,
|
|
442
|
-
bytesTransferred: result.totalSize,
|
|
443
|
-
output: warnings.length ? `Warning: ${warnings.join('; ')}` : undefined,
|
|
444
|
-
};
|
|
445
|
-
}
|
|
446
|
-
else {
|
|
447
|
-
result = await uploadFile(alias, localPath, remotePath);
|
|
448
|
-
return {
|
|
449
|
-
success: result.success,
|
|
450
|
-
method: 'sftp',
|
|
451
|
-
filesTransferred: 1,
|
|
452
|
-
bytesTransferred: result.size,
|
|
453
|
-
output: warnings.length ? `Warning: ${warnings.join('; ')}` : undefined,
|
|
454
|
-
};
|
|
369
|
+
const { fileCount, totalSize } = await uploadDirectory(alias, localPath, remotePath, options.exclude);
|
|
370
|
+
return buildSyncResult(fileCount, totalSize, warnings);
|
|
455
371
|
}
|
|
372
|
+
const { size } = await uploadFile(alias, localPath, remotePath);
|
|
373
|
+
return buildSyncResult(1, size, warnings);
|
|
456
374
|
}
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
return {
|
|
463
|
-
success: true,
|
|
464
|
-
method: 'sftp',
|
|
465
|
-
filesTransferred: result.fileCount,
|
|
466
|
-
bytesTransferred: result.totalSize,
|
|
467
|
-
output: warnings.length ? `Warning: ${warnings.join('; ')}` : undefined,
|
|
468
|
-
};
|
|
469
|
-
}
|
|
470
|
-
else {
|
|
471
|
-
result = await downloadFile(alias, remotePath, localPath);
|
|
472
|
-
return {
|
|
473
|
-
success: result.success,
|
|
474
|
-
method: 'sftp',
|
|
475
|
-
filesTransferred: 1,
|
|
476
|
-
bytesTransferred: result.size,
|
|
477
|
-
output: warnings.length ? `Warning: ${warnings.join('; ')}` : undefined,
|
|
478
|
-
};
|
|
479
|
-
}
|
|
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);
|
|
480
380
|
}
|
|
381
|
+
const { size } = await downloadFile(alias, remotePath, localPath);
|
|
382
|
+
return buildSyncResult(1, size, warnings);
|
|
481
383
|
}
|
|
482
384
|
catch (err) {
|
|
483
385
|
return {
|
|
@@ -561,14 +463,14 @@ function matchPattern(name, pattern) {
|
|
|
561
463
|
* 格式化权限字符串
|
|
562
464
|
*/
|
|
563
465
|
function formatPermissions(mode) {
|
|
564
|
-
const types =
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
466
|
+
const types = [
|
|
467
|
+
[S_IFDIR, 'd'],
|
|
468
|
+
[S_IFLNK, 'l'],
|
|
469
|
+
[S_IFREG, '-'],
|
|
470
|
+
];
|
|
569
471
|
let type = '-';
|
|
570
|
-
for (const [mask, char] of
|
|
571
|
-
if ((mode &
|
|
472
|
+
for (const [mask, char] of types) {
|
|
473
|
+
if ((mode & mask) !== 0) {
|
|
572
474
|
type = char;
|
|
573
475
|
break;
|
|
574
476
|
}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 端口转发管理器
|
|
3
|
+
*
|
|
4
|
+
* 负责本地/远程端口转发的完整生命周期
|
|
5
|
+
*/
|
|
6
|
+
import type { Client } from 'ssh2';
|
|
7
|
+
import type { PortForwardInfo } from './types.js';
|
|
8
|
+
/** 端口转发所需的外部依赖 */
|
|
9
|
+
export interface ForwardDependencies {
|
|
10
|
+
/** 获取 SSH client */
|
|
11
|
+
getClient(alias: string): Client;
|
|
12
|
+
}
|
|
13
|
+
export declare class ForwardManager {
|
|
14
|
+
private sessions;
|
|
15
|
+
private dispatchers;
|
|
16
|
+
private idCounter;
|
|
17
|
+
forwardLocal(deps: ForwardDependencies, alias: string, localPort: number, remoteHost: string, remotePort: number, localHost?: string): Promise<string>;
|
|
18
|
+
forwardRemote(deps: ForwardDependencies, alias: string, remotePort: number, localHost: string, localPort: number, remoteHost?: string): Promise<string>;
|
|
19
|
+
close(forwardId: string, deps?: ForwardDependencies): boolean;
|
|
20
|
+
/** 关闭指定 alias 的所有转发(disconnect 时调用,不需要 unforwardIn) */
|
|
21
|
+
closeByAlias(alias: string): void;
|
|
22
|
+
list(): PortForwardInfo[];
|
|
23
|
+
/**
|
|
24
|
+
* 确保 SSH session 有共享的 tcp connection dispatcher
|
|
25
|
+
* 所有 remote forward 共用一个 dispatcher,根据 destIP/destPort 路由
|
|
26
|
+
*/
|
|
27
|
+
private ensureTcpDispatcher;
|
|
28
|
+
/**
|
|
29
|
+
* 移除 dispatcher(当没有活跃的 remote forward 时)
|
|
30
|
+
*/
|
|
31
|
+
private removeTcpDispatcherIfEmpty;
|
|
32
|
+
private generateId;
|
|
33
|
+
}
|
|
@@ -0,0 +1,185 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 端口转发管理器
|
|
3
|
+
*
|
|
4
|
+
* 负责本地/远程端口转发的完整生命周期
|
|
5
|
+
*/
|
|
6
|
+
import * as net from 'net';
|
|
7
|
+
export class ForwardManager {
|
|
8
|
+
sessions = new Map();
|
|
9
|
+
dispatchers = new Map(); // alias → dispatcher
|
|
10
|
+
idCounter = 0;
|
|
11
|
+
async forwardLocal(deps, alias, localPort, remoteHost, remotePort, localHost = '127.0.0.1') {
|
|
12
|
+
const client = deps.getClient(alias);
|
|
13
|
+
const forwardId = this.generateId();
|
|
14
|
+
return new Promise((resolve, reject) => {
|
|
15
|
+
const server = net.createServer((socket) => {
|
|
16
|
+
client.forwardOut(socket.remoteAddress || '127.0.0.1', socket.remotePort || 0, remoteHost, remotePort, (err, stream) => {
|
|
17
|
+
if (err) {
|
|
18
|
+
socket.end();
|
|
19
|
+
return;
|
|
20
|
+
}
|
|
21
|
+
socket.pipe(stream).pipe(socket);
|
|
22
|
+
});
|
|
23
|
+
});
|
|
24
|
+
server.on('error', (err) => {
|
|
25
|
+
reject(new Error(`Local forward failed: ${err.message}`));
|
|
26
|
+
});
|
|
27
|
+
server.listen(localPort, localHost, () => {
|
|
28
|
+
this.sessions.set(forwardId, {
|
|
29
|
+
id: forwardId,
|
|
30
|
+
alias,
|
|
31
|
+
type: 'local',
|
|
32
|
+
localHost,
|
|
33
|
+
localPort,
|
|
34
|
+
remoteHost,
|
|
35
|
+
remotePort,
|
|
36
|
+
server,
|
|
37
|
+
createdAt: Date.now(),
|
|
38
|
+
active: true,
|
|
39
|
+
});
|
|
40
|
+
resolve(forwardId);
|
|
41
|
+
});
|
|
42
|
+
});
|
|
43
|
+
}
|
|
44
|
+
async forwardRemote(deps, alias, remotePort, localHost, localPort, remoteHost = '127.0.0.1') {
|
|
45
|
+
const client = deps.getClient(alias);
|
|
46
|
+
const forwardId = this.generateId();
|
|
47
|
+
return new Promise((resolve, reject) => {
|
|
48
|
+
client.forwardIn(remoteHost, remotePort, (err) => {
|
|
49
|
+
if (err) {
|
|
50
|
+
reject(new Error(`Remote forward failed: ${err.message}`));
|
|
51
|
+
return;
|
|
52
|
+
}
|
|
53
|
+
this.sessions.set(forwardId, {
|
|
54
|
+
id: forwardId,
|
|
55
|
+
alias,
|
|
56
|
+
type: 'remote',
|
|
57
|
+
localHost,
|
|
58
|
+
localPort,
|
|
59
|
+
remoteHost,
|
|
60
|
+
remotePort,
|
|
61
|
+
createdAt: Date.now(),
|
|
62
|
+
active: true,
|
|
63
|
+
});
|
|
64
|
+
this.ensureTcpDispatcher(alias, client);
|
|
65
|
+
resolve(forwardId);
|
|
66
|
+
});
|
|
67
|
+
});
|
|
68
|
+
}
|
|
69
|
+
close(forwardId, deps) {
|
|
70
|
+
const fwd = this.sessions.get(forwardId);
|
|
71
|
+
if (!fwd) {
|
|
72
|
+
return false;
|
|
73
|
+
}
|
|
74
|
+
fwd.active = false;
|
|
75
|
+
if (fwd.type === 'local' && fwd.server) {
|
|
76
|
+
try {
|
|
77
|
+
fwd.server.close();
|
|
78
|
+
}
|
|
79
|
+
catch (e) {
|
|
80
|
+
console.warn(`Forward ${forwardId} server close failed:`, e.message);
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
else if (fwd.type === 'remote' && deps) {
|
|
84
|
+
try {
|
|
85
|
+
const client = deps.getClient(fwd.alias);
|
|
86
|
+
client.unforwardIn(fwd.remoteHost, fwd.remotePort);
|
|
87
|
+
}
|
|
88
|
+
catch { /* session 可能已断开 */
|
|
89
|
+
}
|
|
90
|
+
this.removeTcpDispatcherIfEmpty(fwd.alias);
|
|
91
|
+
}
|
|
92
|
+
this.sessions.delete(forwardId);
|
|
93
|
+
return true;
|
|
94
|
+
}
|
|
95
|
+
/** 关闭指定 alias 的所有转发(disconnect 时调用,不需要 unforwardIn) */
|
|
96
|
+
closeByAlias(alias) {
|
|
97
|
+
for (const [id, fwd] of this.sessions) {
|
|
98
|
+
if (fwd.alias === alias) {
|
|
99
|
+
fwd.active = false;
|
|
100
|
+
if (fwd.type === 'local' && fwd.server) {
|
|
101
|
+
try {
|
|
102
|
+
fwd.server.close();
|
|
103
|
+
}
|
|
104
|
+
catch (e) {
|
|
105
|
+
console.warn(`Forward ${id} server close failed:`, e.message);
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
this.sessions.delete(id);
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
// 清理该 alias 的 dispatcher
|
|
112
|
+
const state = this.dispatchers.get(alias);
|
|
113
|
+
if (state) {
|
|
114
|
+
try {
|
|
115
|
+
state.client.removeListener('tcp connection', state.handler);
|
|
116
|
+
}
|
|
117
|
+
catch { /* client 可能已关闭 */ }
|
|
118
|
+
this.dispatchers.delete(alias);
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
list() {
|
|
122
|
+
const result = [];
|
|
123
|
+
for (const [id, fwd] of this.sessions) {
|
|
124
|
+
result.push({
|
|
125
|
+
id,
|
|
126
|
+
alias: fwd.alias,
|
|
127
|
+
type: fwd.type,
|
|
128
|
+
localHost: fwd.localHost,
|
|
129
|
+
localPort: fwd.localPort,
|
|
130
|
+
remoteHost: fwd.remoteHost,
|
|
131
|
+
remotePort: fwd.remotePort,
|
|
132
|
+
createdAt: fwd.createdAt,
|
|
133
|
+
active: fwd.active,
|
|
134
|
+
});
|
|
135
|
+
}
|
|
136
|
+
return result;
|
|
137
|
+
}
|
|
138
|
+
/**
|
|
139
|
+
* 确保 SSH session 有共享的 tcp connection dispatcher
|
|
140
|
+
* 所有 remote forward 共用一个 dispatcher,根据 destIP/destPort 路由
|
|
141
|
+
*/
|
|
142
|
+
ensureTcpDispatcher(alias, client) {
|
|
143
|
+
if (this.dispatchers.has(alias)) {
|
|
144
|
+
return;
|
|
145
|
+
}
|
|
146
|
+
const handler = (info, accept, rejectConn) => {
|
|
147
|
+
for (const fwd of this.sessions.values()) {
|
|
148
|
+
if (fwd.type === 'remote' &&
|
|
149
|
+
fwd.active &&
|
|
150
|
+
fwd.alias === alias &&
|
|
151
|
+
fwd.remoteHost === info.destIP &&
|
|
152
|
+
fwd.remotePort === info.destPort) {
|
|
153
|
+
const stream = accept();
|
|
154
|
+
const socket = net.createConnection(fwd.localPort, fwd.localHost);
|
|
155
|
+
socket.pipe(stream).pipe(socket);
|
|
156
|
+
socket.on('error', () => stream.close());
|
|
157
|
+
stream.on('error', () => socket.destroy());
|
|
158
|
+
return;
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
rejectConn();
|
|
162
|
+
};
|
|
163
|
+
this.dispatchers.set(alias, { handler, client });
|
|
164
|
+
client.on('tcp connection', handler);
|
|
165
|
+
}
|
|
166
|
+
/**
|
|
167
|
+
* 移除 dispatcher(当没有活跃的 remote forward 时)
|
|
168
|
+
*/
|
|
169
|
+
removeTcpDispatcherIfEmpty(alias) {
|
|
170
|
+
const state = this.dispatchers.get(alias);
|
|
171
|
+
if (!state) {
|
|
172
|
+
return;
|
|
173
|
+
}
|
|
174
|
+
for (const fwd of this.sessions.values()) {
|
|
175
|
+
if (fwd.type === 'remote' && fwd.alias === alias && fwd.active) {
|
|
176
|
+
return; // 还有活跃的 remote forward
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
state.client.removeListener('tcp connection', state.handler);
|
|
180
|
+
this.dispatchers.delete(alias);
|
|
181
|
+
}
|
|
182
|
+
generateId() {
|
|
183
|
+
return `fwd_${++this.idCounter}_${Date.now()}`;
|
|
184
|
+
}
|
|
185
|
+
}
|