@pyrokine/mcp-ssh 2.3.1 → 2.4.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 +103 -21
- package/README_zh.md +73 -20
- package/dist/command-risk.d.ts +7 -0
- package/dist/command-risk.js +106 -0
- package/dist/directory-verification.d.ts +43 -0
- package/dist/directory-verification.js +485 -0
- package/dist/file-ops.d.ts +56 -13
- package/dist/file-ops.js +531 -145
- package/dist/forward-manager.d.ts +5 -2
- package/dist/forward-manager.js +133 -19
- package/dist/index.js +2 -1
- package/dist/operation-manager.d.ts +52 -0
- package/dist/operation-manager.js +402 -0
- package/dist/pty-manager.d.ts +1 -0
- package/dist/pty-manager.js +11 -7
- package/dist/session-manager.d.ts +21 -10
- package/dist/session-manager.js +328 -75
- package/dist/tools/connection.js +48 -8
- package/dist/tools/exec.js +7 -66
- package/dist/tools/file.js +455 -81
- package/dist/tools/forward.js +12 -4
- package/dist/tools/index.d.ts +1 -0
- package/dist/tools/index.js +1 -0
- package/dist/tools/operation.d.ts +2 -0
- package/dist/tools/operation.js +126 -0
- package/dist/tools/utils.d.ts +2 -2
- package/dist/transfer-outcome.d.ts +12 -0
- package/dist/transfer-outcome.js +72 -0
- package/dist/types.d.ts +94 -6
- package/package.json +11 -9
package/dist/session-manager.js
CHANGED
|
@@ -13,6 +13,7 @@ import * as path from 'path';
|
|
|
13
13
|
import { Client } from 'ssh2';
|
|
14
14
|
import { clearRsyncCache } from './file-ops.js';
|
|
15
15
|
import { ForwardManager } from './forward-manager.js';
|
|
16
|
+
import { OperationManager } from './operation-manager.js';
|
|
16
17
|
import { PtyManager } from './pty-manager.js';
|
|
17
18
|
import { sanitizeKeyError, validateKeyFile } from './security.js';
|
|
18
19
|
import { escapeShellArg, expandTilde } from './tools/utils.js';
|
|
@@ -26,12 +27,21 @@ class CommandError extends Error {
|
|
|
26
27
|
this.name = 'CommandError';
|
|
27
28
|
}
|
|
28
29
|
}
|
|
30
|
+
class ConnectionError extends Error {
|
|
31
|
+
details;
|
|
32
|
+
constructor(message, details) {
|
|
33
|
+
super(message);
|
|
34
|
+
this.details = details;
|
|
35
|
+
this.name = 'ConnectionError';
|
|
36
|
+
}
|
|
37
|
+
}
|
|
29
38
|
export class SessionManager {
|
|
30
39
|
sessions = new Map();
|
|
31
40
|
/** per-alias connect 进行中的 Promise,防止并发 connect 同一 alias 时重复建连 */
|
|
32
41
|
connectInFlight = new Map();
|
|
33
42
|
ptyManager = new PtyManager();
|
|
34
43
|
forwardManager = new ForwardManager();
|
|
44
|
+
operationManager;
|
|
35
45
|
persistPath;
|
|
36
46
|
defaultKeepaliveInterval = 30000; // 30秒
|
|
37
47
|
defaultKeepaliveCountMax = 3;
|
|
@@ -41,6 +51,10 @@ export class SessionManager {
|
|
|
41
51
|
reconnectDelay = 5000; // 5秒
|
|
42
52
|
constructor(persistPath) {
|
|
43
53
|
this.persistPath = persistPath || path.join(os.homedir(), '.ssh-mcp-pro', 'sessions.json');
|
|
54
|
+
this.operationManager = new OperationManager({
|
|
55
|
+
openStream: (alias, command, marker, options) => this.openOperationStream(alias, command, marker, options),
|
|
56
|
+
cancelRemote: (alias, pid, marker, processGroup, options) => this.cancelRemoteOperation(alias, pid, marker, processGroup, options),
|
|
57
|
+
});
|
|
44
58
|
this.ensurePersistDir();
|
|
45
59
|
}
|
|
46
60
|
/**
|
|
@@ -89,7 +103,8 @@ export class SessionManager {
|
|
|
89
103
|
clearTimeout(session.reconnectTimer);
|
|
90
104
|
session.reconnectTimer = undefined;
|
|
91
105
|
}
|
|
92
|
-
//
|
|
106
|
+
// 清理关联资源;tracked operation 的远端状态在连接断开后无法继续证明
|
|
107
|
+
this.operationManager.markAliasDisconnected(alias);
|
|
93
108
|
this.ptyManager.closeByAlias(alias);
|
|
94
109
|
this.forwardManager.closeByAlias(alias);
|
|
95
110
|
// 清理 file-ops 中的 rsync 可用性缓存,防止重连到不同主机后读到旧判断
|
|
@@ -127,33 +142,78 @@ export class SessionManager {
|
|
|
127
142
|
session.lastUsedAt = Date.now();
|
|
128
143
|
return session;
|
|
129
144
|
}
|
|
130
|
-
/**
|
|
131
|
-
* 列出所有会话
|
|
132
|
-
*/
|
|
133
145
|
listSessions() {
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
146
|
+
return Array.from(this.sessions, ([alias, session]) => ({
|
|
147
|
+
alias,
|
|
148
|
+
identity: this.sessionIdentity(session),
|
|
149
|
+
runAs: session.config.runAs,
|
|
150
|
+
connected: this.isAlive(session),
|
|
151
|
+
lastUsedAt: session.lastUsedAt,
|
|
152
|
+
}));
|
|
153
|
+
}
|
|
154
|
+
listSessionDetails() {
|
|
155
|
+
return Array.from(this.sessions, ([alias, session]) => ({
|
|
156
|
+
alias,
|
|
157
|
+
identity: this.sessionIdentity(session),
|
|
158
|
+
host: session.config.host,
|
|
159
|
+
port: session.config.port || 22,
|
|
160
|
+
username: session.config.username,
|
|
161
|
+
runAs: session.config.runAs,
|
|
162
|
+
authMethod: session.config.privateKeyPath
|
|
137
163
|
? 'key'
|
|
138
|
-
: session.config.
|
|
164
|
+
: session.config.privateKey
|
|
165
|
+
? 'inline-key'
|
|
166
|
+
: session.config.password
|
|
167
|
+
? 'password'
|
|
168
|
+
: 'agent',
|
|
169
|
+
connected: this.isAlive(session),
|
|
170
|
+
connectedAt: session.connectedAt,
|
|
171
|
+
lastUsedAt: session.lastUsedAt,
|
|
172
|
+
hasJumpHost: Boolean(session.config.jumpHost),
|
|
173
|
+
}));
|
|
174
|
+
}
|
|
175
|
+
getExternalTransferCapability(alias) {
|
|
176
|
+
const session = this.getSession(alias);
|
|
177
|
+
const config = session.config;
|
|
178
|
+
const authMethod = config.privateKeyPath
|
|
179
|
+
? 'key-path'
|
|
180
|
+
: config.privateKey
|
|
181
|
+
? 'inline-key'
|
|
182
|
+
: config.password
|
|
139
183
|
? 'password'
|
|
140
184
|
: 'agent';
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
185
|
+
const hasJumpHost = Boolean(config.jumpHost);
|
|
186
|
+
const routeSafeForOpenSsh = !hasJumpHost;
|
|
187
|
+
const expandedKeyPath = config.privateKeyPath ? expandTilde(config.privateKeyPath) : undefined;
|
|
188
|
+
const keyPathUsable = authMethod === 'key-path' && this.isOpenSshKeyPathUsable(expandedKeyPath);
|
|
189
|
+
const agentAvailable = authMethod === 'agent' && this.isSshAgentAvailable();
|
|
190
|
+
const rsyncEligible = routeSafeForOpenSsh && (keyPathUsable || agentAvailable);
|
|
191
|
+
const decisionReason = hasJumpHost
|
|
192
|
+
? 'jump_host_route_requires_live_ssh_session'
|
|
193
|
+
: authMethod === 'password'
|
|
194
|
+
? 'password_not_forwarded_to_openssh'
|
|
195
|
+
: authMethod === 'inline-key'
|
|
196
|
+
? 'inline_private_key_not_written_to_disk'
|
|
197
|
+
: authMethod === 'key-path'
|
|
198
|
+
? keyPathUsable
|
|
199
|
+
? 'direct_openssh_compatible_key_path'
|
|
200
|
+
: 'key_path_not_openssh_compatible'
|
|
201
|
+
: agentAvailable
|
|
202
|
+
? 'direct_ssh_agent_socket'
|
|
203
|
+
: 'ssh_agent_socket_unavailable';
|
|
204
|
+
return {
|
|
205
|
+
alias,
|
|
206
|
+
identity: this.sessionIdentity(session),
|
|
207
|
+
host: config.host,
|
|
208
|
+
port: config.port || 22,
|
|
209
|
+
username: config.username,
|
|
210
|
+
authMethod,
|
|
211
|
+
keyPath: keyPathUsable ? expandedKeyPath : undefined,
|
|
212
|
+
hasJumpHost,
|
|
213
|
+
routeSafeForOpenSsh,
|
|
214
|
+
rsyncEligible,
|
|
215
|
+
decisionReason,
|
|
216
|
+
};
|
|
157
217
|
}
|
|
158
218
|
/**
|
|
159
219
|
* 执行命令
|
|
@@ -166,6 +226,21 @@ export class SessionManager {
|
|
|
166
226
|
}
|
|
167
227
|
return this.execDirect(alias, command, options, { cwd: options.cwd });
|
|
168
228
|
}
|
|
229
|
+
operationStart(alias, command, options = {}) {
|
|
230
|
+
return this.operationManager.start(alias, command, options);
|
|
231
|
+
}
|
|
232
|
+
operationStatus(operationId) {
|
|
233
|
+
return this.operationManager.status(operationId);
|
|
234
|
+
}
|
|
235
|
+
operationRead(operationId, options = {}) {
|
|
236
|
+
return this.operationManager.read(operationId, options);
|
|
237
|
+
}
|
|
238
|
+
operationCancel(operationId) {
|
|
239
|
+
return this.operationManager.cancel(operationId);
|
|
240
|
+
}
|
|
241
|
+
operationList(alias) {
|
|
242
|
+
return this.operationManager.list(alias);
|
|
243
|
+
}
|
|
169
244
|
/**
|
|
170
245
|
* 以其他用户身份执行命令
|
|
171
246
|
*
|
|
@@ -347,14 +422,45 @@ export class SessionManager {
|
|
|
347
422
|
async forwardRemote(alias, remotePort, localHost, localPort, remoteHost = '127.0.0.1') {
|
|
348
423
|
return this.forwardManager.forwardRemote({ getClient: (a) => this.getSession(a).client }, alias, remotePort, localHost, localPort, remoteHost);
|
|
349
424
|
}
|
|
350
|
-
forwardClose(forwardId) {
|
|
425
|
+
forwardClose(forwardId, options = {}) {
|
|
351
426
|
return this.forwardManager.close(forwardId, {
|
|
352
427
|
getClient: (a) => this.getSession(a).client,
|
|
353
|
-
});
|
|
428
|
+
}, options);
|
|
354
429
|
}
|
|
355
430
|
forwardList() {
|
|
356
431
|
return this.forwardManager.list();
|
|
357
432
|
}
|
|
433
|
+
isSshAgentAvailable() {
|
|
434
|
+
const socketPath = process.env.SSH_AUTH_SOCK;
|
|
435
|
+
if (!socketPath) {
|
|
436
|
+
return false;
|
|
437
|
+
}
|
|
438
|
+
if (process.platform === 'win32') {
|
|
439
|
+
return true;
|
|
440
|
+
}
|
|
441
|
+
try {
|
|
442
|
+
return fs.statSync(socketPath).isSocket();
|
|
443
|
+
}
|
|
444
|
+
catch {
|
|
445
|
+
return false;
|
|
446
|
+
}
|
|
447
|
+
}
|
|
448
|
+
isOpenSshKeyPathUsable(keyPath) {
|
|
449
|
+
try {
|
|
450
|
+
const stats = fs.statSync(keyPath);
|
|
451
|
+
if (!stats.isFile()) {
|
|
452
|
+
return false;
|
|
453
|
+
}
|
|
454
|
+
if (process.platform !== 'win32' && (stats.mode & 0o077) !== 0) {
|
|
455
|
+
return false;
|
|
456
|
+
}
|
|
457
|
+
const currentUid = process.getuid?.();
|
|
458
|
+
return currentUid === undefined || stats.uid === currentUid;
|
|
459
|
+
}
|
|
460
|
+
catch {
|
|
461
|
+
return false;
|
|
462
|
+
}
|
|
463
|
+
}
|
|
358
464
|
sessionIdentity(session) {
|
|
359
465
|
return this.configIdentity(session.config);
|
|
360
466
|
}
|
|
@@ -421,6 +527,64 @@ export class SessionManager {
|
|
|
421
527
|
}
|
|
422
528
|
return maxOutputSize;
|
|
423
529
|
}
|
|
530
|
+
async openOperationStream(alias, command, marker, options) {
|
|
531
|
+
const session = this.getSession(alias);
|
|
532
|
+
const markerEnv = `MCP_SSH_OPERATION_MARKER=${this.escapeShellArg(marker)}`;
|
|
533
|
+
const markerLine = `__MCP_SSH_OPERATION__:${marker}:%s:%s\\n`;
|
|
534
|
+
const operationScript = this.escapeShellArg(`printf ${this.escapeShellArg(markerLine)} "$$" "$1" >&2; exec sh -c ${this.escapeShellArg(command)}`);
|
|
535
|
+
const wrappedCommand = `if command -v setsid >/dev/null 2>&1; then ` +
|
|
536
|
+
`exec env ${markerEnv} setsid sh -c ${operationScript} sh 1; ` +
|
|
537
|
+
`else exec env ${markerEnv} sh -c ${operationScript} sh 0; fi`;
|
|
538
|
+
const runAs = options.useLoginUser ? undefined : (options.runAs ?? session.config.runAs);
|
|
539
|
+
let fullCommand;
|
|
540
|
+
if (runAs) {
|
|
541
|
+
if (!this.isValidUsername(runAs)) {
|
|
542
|
+
throw new Error(`Invalid username: ${runAs}`);
|
|
543
|
+
}
|
|
544
|
+
const loadProfile = options.loadProfile ?? true;
|
|
545
|
+
const targetCommand = this.buildCommand(`${loadProfile ? this.getLoadProfileCommand() : ''}${wrappedCommand}`, session, options);
|
|
546
|
+
fullCommand = `su - ${runAs} -c ${this.escapeShellArg(targetCommand)}`;
|
|
547
|
+
}
|
|
548
|
+
else {
|
|
549
|
+
fullCommand = this.buildCommand(wrappedCommand, session, options);
|
|
550
|
+
}
|
|
551
|
+
return new Promise((resolve, reject) => {
|
|
552
|
+
session.client.exec(fullCommand, {}, (error, stream) => {
|
|
553
|
+
if (error) {
|
|
554
|
+
reject(new Error(`Operation start failed: ${error.message}`));
|
|
555
|
+
}
|
|
556
|
+
else {
|
|
557
|
+
resolve(stream);
|
|
558
|
+
}
|
|
559
|
+
});
|
|
560
|
+
});
|
|
561
|
+
}
|
|
562
|
+
async cancelRemoteOperation(alias, pid, marker, processGroup, options) {
|
|
563
|
+
const expectedMarker = `MCP_SSH_OPERATION_MARKER=${marker}`;
|
|
564
|
+
const signalTarget = processGroup ? `-${pid}` : `${pid}`;
|
|
565
|
+
const command = [
|
|
566
|
+
`pid=${pid}`,
|
|
567
|
+
`expected=${this.escapeShellArg(expectedMarker)}`,
|
|
568
|
+
'if [ ! -r "/proc/$pid/environ" ]; then printf "operation marker unavailable" >&2; exit 3; fi',
|
|
569
|
+
'if ! tr "\\000" "\\n" < "/proc/$pid/environ" | grep -Fqx -- "$expected"; then printf "operation marker mismatch" >&2; exit 4; fi',
|
|
570
|
+
`kill -TERM -- ${signalTarget}`,
|
|
571
|
+
].join('; ');
|
|
572
|
+
try {
|
|
573
|
+
const result = await this.exec(alias, command, {
|
|
574
|
+
runAs: options.runAs,
|
|
575
|
+
useLoginUser: options.useLoginUser,
|
|
576
|
+
loadProfile: false,
|
|
577
|
+
timeout: 5000,
|
|
578
|
+
maxOutputSize: 4096,
|
|
579
|
+
});
|
|
580
|
+
return result.success
|
|
581
|
+
? { success: true }
|
|
582
|
+
: { success: false, error: result.stderr || `Remote cancel exited with code ${result.exitCode}` };
|
|
583
|
+
}
|
|
584
|
+
catch (error) {
|
|
585
|
+
return { success: false, error: error instanceof Error ? error.message : String(error) };
|
|
586
|
+
}
|
|
587
|
+
}
|
|
424
588
|
async execDirect(alias, command, options = {}, context = {}) {
|
|
425
589
|
const session = this.getSession(alias);
|
|
426
590
|
const startTime = Date.now();
|
|
@@ -555,42 +719,79 @@ export class SessionManager {
|
|
|
555
719
|
return alias;
|
|
556
720
|
}
|
|
557
721
|
const client = new Client();
|
|
558
|
-
|
|
722
|
+
const readyTimeout = config.readyTimeout ?? this.defaultTimeout;
|
|
559
723
|
const connectConfig = {
|
|
560
724
|
host: config.host,
|
|
561
725
|
port: config.port ?? 22,
|
|
562
726
|
username: config.username,
|
|
563
|
-
readyTimeout
|
|
727
|
+
readyTimeout,
|
|
564
728
|
keepaliveInterval: config.keepaliveInterval ?? this.defaultKeepaliveInterval,
|
|
565
729
|
keepaliveCountMax: config.keepaliveCountMax ?? this.defaultKeepaliveCountMax,
|
|
566
730
|
};
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
|
|
731
|
+
try {
|
|
732
|
+
if (config.password) {
|
|
733
|
+
connectConfig.password = config.password;
|
|
734
|
+
}
|
|
735
|
+
if (config.privateKeyPath) {
|
|
736
|
+
const keyPath = expandTilde(config.privateKeyPath);
|
|
737
|
+
// 路径白名单 + 大小上限校验,避免任意文件读取
|
|
738
|
+
validateKeyFile(keyPath);
|
|
739
|
+
connectConfig.privateKey = fs.readFileSync(keyPath);
|
|
740
|
+
}
|
|
741
|
+
if (config.privateKey) {
|
|
742
|
+
connectConfig.privateKey = config.privateKey;
|
|
743
|
+
}
|
|
744
|
+
if (config.passphrase) {
|
|
745
|
+
connectConfig.passphrase = config.passphrase;
|
|
746
|
+
}
|
|
579
747
|
}
|
|
580
|
-
|
|
581
|
-
|
|
748
|
+
catch (error) {
|
|
749
|
+
throw this.createConnectionError(error, config, readyTimeout, 'key_read');
|
|
582
750
|
}
|
|
583
|
-
// 跳板机支持
|
|
584
751
|
if (config.jumpHost) {
|
|
585
|
-
const
|
|
752
|
+
const jumpConfig = {
|
|
753
|
+
...config.jumpHost,
|
|
754
|
+
readyTimeout: config.jumpHost.readyTimeout ?? readyTimeout,
|
|
755
|
+
};
|
|
756
|
+
let jumpAlias;
|
|
757
|
+
try {
|
|
758
|
+
jumpAlias = await this.connect(jumpConfig);
|
|
759
|
+
}
|
|
760
|
+
catch (error) {
|
|
761
|
+
if (error instanceof ConnectionError) {
|
|
762
|
+
throw new ConnectionError(error.message, {
|
|
763
|
+
...error.details,
|
|
764
|
+
connectionStep: 'jump_connect',
|
|
765
|
+
});
|
|
766
|
+
}
|
|
767
|
+
throw this.createConnectionError(error, jumpConfig, jumpConfig.readyTimeout, 'jump_connect');
|
|
768
|
+
}
|
|
586
769
|
const jumpSession = this.sessions.get(jumpAlias);
|
|
587
|
-
if (jumpSession) {
|
|
588
|
-
|
|
589
|
-
|
|
770
|
+
if (!jumpSession || !this.isAlive(jumpSession)) {
|
|
771
|
+
throw new ConnectionError(`Jump host session '${jumpAlias}' is unavailable`, {
|
|
772
|
+
failureStage: 'transport_or_handshake',
|
|
773
|
+
connectionStep: 'jump_connect',
|
|
774
|
+
retryable: true,
|
|
775
|
+
suggestion: '重新连接跳板机,或检查 jumpHost 配置和网络路径',
|
|
776
|
+
});
|
|
590
777
|
}
|
|
778
|
+
connectConfig.sock = await this.forwardConnection(jumpSession.client, config.host, config.port || 22, readyTimeout);
|
|
591
779
|
}
|
|
592
780
|
return new Promise((resolve, reject) => {
|
|
781
|
+
let settled = false;
|
|
782
|
+
const rejectConnection = (error) => {
|
|
783
|
+
if (settled) {
|
|
784
|
+
return;
|
|
785
|
+
}
|
|
786
|
+
settled = true;
|
|
787
|
+
reject(this.createConnectionError(error, config, readyTimeout, 'target_connect'));
|
|
788
|
+
};
|
|
593
789
|
client.on('ready', () => {
|
|
790
|
+
if (settled) {
|
|
791
|
+
client.end();
|
|
792
|
+
return;
|
|
793
|
+
}
|
|
794
|
+
settled = true;
|
|
594
795
|
const session = {
|
|
595
796
|
client,
|
|
596
797
|
config,
|
|
@@ -604,21 +805,19 @@ export class SessionManager {
|
|
|
604
805
|
this.persistSessions();
|
|
605
806
|
resolve(alias);
|
|
606
807
|
});
|
|
607
|
-
client.on('error', (
|
|
808
|
+
client.on('error', (error) => {
|
|
608
809
|
const session = this.sessions.get(alias);
|
|
609
810
|
if (session && session.client === client) {
|
|
610
811
|
session.connected = false;
|
|
611
812
|
}
|
|
612
|
-
|
|
613
|
-
const safeMessage = sanitizeKeyError(err.message);
|
|
614
|
-
const suggestion = this.diagnoseConnectionError(err);
|
|
615
|
-
reject(new Error(`SSH connection to ${target} failed: ${safeMessage}${suggestion ? ` (${suggestion})` : ''}`));
|
|
813
|
+
rejectConnection(error);
|
|
616
814
|
});
|
|
617
815
|
client.on('close', () => {
|
|
618
816
|
const session = this.sessions.get(alias);
|
|
619
817
|
if (session && session.client === client) {
|
|
620
818
|
session.connected = false;
|
|
621
|
-
// 清理绑定旧 client
|
|
819
|
+
// 清理绑定旧 client 的资源;tracked operation 状态已无法继续证明
|
|
820
|
+
this.operationManager.markAliasDisconnected(alias);
|
|
622
821
|
this.forwardManager.closeByAlias(alias);
|
|
623
822
|
this.ptyManager.closeByAlias(alias);
|
|
624
823
|
if (!session.manualClose) {
|
|
@@ -626,7 +825,12 @@ export class SessionManager {
|
|
|
626
825
|
}
|
|
627
826
|
}
|
|
628
827
|
});
|
|
629
|
-
|
|
828
|
+
try {
|
|
829
|
+
client.connect(connectConfig);
|
|
830
|
+
}
|
|
831
|
+
catch (error) {
|
|
832
|
+
rejectConnection(error);
|
|
833
|
+
}
|
|
630
834
|
});
|
|
631
835
|
}
|
|
632
836
|
/**
|
|
@@ -667,11 +871,35 @@ export class SessionManager {
|
|
|
667
871
|
/**
|
|
668
872
|
* 通过跳板机转发连接
|
|
669
873
|
*/
|
|
670
|
-
forwardConnection(jumpClient, targetHost, targetPort) {
|
|
874
|
+
forwardConnection(jumpClient, targetHost, targetPort, timeout) {
|
|
671
875
|
return new Promise((resolve, reject) => {
|
|
672
|
-
|
|
673
|
-
|
|
674
|
-
|
|
876
|
+
let settled = false;
|
|
877
|
+
const timer = setTimeout(() => {
|
|
878
|
+
if (settled) {
|
|
879
|
+
return;
|
|
880
|
+
}
|
|
881
|
+
settled = true;
|
|
882
|
+
reject(new ConnectionError(`Jump host forwarding to ${targetHost}:${targetPort} timed out`, {
|
|
883
|
+
failureStage: 'ready_timeout',
|
|
884
|
+
connectionStep: 'jump_forward',
|
|
885
|
+
retryable: true,
|
|
886
|
+
suggestion: '检查跳板机到目标地址的网络路径,必要时提高 readyTimeout',
|
|
887
|
+
}));
|
|
888
|
+
}, timeout);
|
|
889
|
+
jumpClient.forwardOut('127.0.0.1', 0, targetHost, targetPort, (error, stream) => {
|
|
890
|
+
if (settled) {
|
|
891
|
+
stream?.close();
|
|
892
|
+
return;
|
|
893
|
+
}
|
|
894
|
+
settled = true;
|
|
895
|
+
clearTimeout(timer);
|
|
896
|
+
if (error) {
|
|
897
|
+
reject(new ConnectionError(`Jump host forwarding to ${targetHost}:${targetPort} failed`, {
|
|
898
|
+
failureStage: 'transport_or_handshake',
|
|
899
|
+
connectionStep: 'jump_forward',
|
|
900
|
+
retryable: true,
|
|
901
|
+
suggestion: '检查跳板机到目标地址的网络路径、目标端口和防火墙',
|
|
902
|
+
}));
|
|
675
903
|
}
|
|
676
904
|
else {
|
|
677
905
|
resolve(stream);
|
|
@@ -744,28 +972,53 @@ export class SessionManager {
|
|
|
744
972
|
],
|
|
745
973
|
});
|
|
746
974
|
}
|
|
747
|
-
|
|
748
|
-
|
|
749
|
-
|
|
750
|
-
|
|
751
|
-
|
|
752
|
-
|
|
753
|
-
if (code === 'ECONNREFUSED' || msg.includes('ECONNREFUSED')) {
|
|
754
|
-
return 'check if SSH service is running on the target host';
|
|
975
|
+
createConnectionError(error, config, readyTimeout, connectionStep) {
|
|
976
|
+
if (error instanceof ConnectionError) {
|
|
977
|
+
return new ConnectionError(error.message, {
|
|
978
|
+
...error.details,
|
|
979
|
+
connectionStep: error.details.connectionStep ?? connectionStep,
|
|
980
|
+
});
|
|
755
981
|
}
|
|
756
|
-
|
|
757
|
-
|
|
982
|
+
const err = error instanceof Error ? error : new Error(String(error));
|
|
983
|
+
const target = `${config.username}@${config.host}:${config.port || 22}`;
|
|
984
|
+
return new ConnectionError(`SSH connection to ${target} failed: ${sanitizeKeyError(err.message)}`, {
|
|
985
|
+
...this.classifyConnectionError(err, readyTimeout),
|
|
986
|
+
connectionStep,
|
|
987
|
+
});
|
|
988
|
+
}
|
|
989
|
+
classifyConnectionError(err, readyTimeout) {
|
|
990
|
+
const message = err.message || '';
|
|
991
|
+
const code = err.code || '';
|
|
992
|
+
if (message.includes('All configured authentication methods failed') || err.level === 'client-authentication') {
|
|
993
|
+
return {
|
|
994
|
+
failureStage: 'authentication',
|
|
995
|
+
retryable: false,
|
|
996
|
+
suggestion: '检查用户名、密码、keyPath、passphrase 和远端 authorized_keys',
|
|
997
|
+
};
|
|
758
998
|
}
|
|
759
|
-
if (
|
|
760
|
-
|
|
999
|
+
if (message.includes('Timed out while waiting for handshake') ||
|
|
1000
|
+
message.includes(`Timed out after ${readyTimeout}`)) {
|
|
1001
|
+
return {
|
|
1002
|
+
failureStage: 'ready_timeout',
|
|
1003
|
+
retryable: true,
|
|
1004
|
+
suggestion: '检查网络路径、跳板机和服务端握手延迟,必要时提高 readyTimeout',
|
|
1005
|
+
};
|
|
761
1006
|
}
|
|
762
|
-
if (
|
|
763
|
-
return '
|
|
1007
|
+
if (code === 'ENOTFOUND' || message.includes('getaddrinfo')) {
|
|
1008
|
+
return { failureStage: 'preflight', retryable: false, suggestion: '检查 host 或 DNS 配置' };
|
|
764
1009
|
}
|
|
765
|
-
if (
|
|
766
|
-
|
|
1010
|
+
if (code === 'ECONNREFUSED' ||
|
|
1011
|
+
code === 'ECONNRESET' ||
|
|
1012
|
+
code === 'ETIMEDOUT' ||
|
|
1013
|
+
message.includes('handshake') ||
|
|
1014
|
+
message.includes('ECONN')) {
|
|
1015
|
+
return {
|
|
1016
|
+
failureStage: 'transport_or_handshake',
|
|
1017
|
+
retryable: code !== 'ECONNREFUSED',
|
|
1018
|
+
suggestion: '检查目标端口、防火墙、ProxyJump 和 SSH 服务状态',
|
|
1019
|
+
};
|
|
767
1020
|
}
|
|
768
|
-
return '';
|
|
1021
|
+
return { failureStage: 'unknown', retryable: false };
|
|
769
1022
|
}
|
|
770
1023
|
/**
|
|
771
1024
|
* 转义 shell 参数(使用单引号方式,防止命令注入)
|
package/dist/tools/connection.js
CHANGED
|
@@ -54,7 +54,14 @@ const connectSchema = z.object({
|
|
|
54
54
|
env: z.record(z.string(), z.string()).optional().describe('环境变量'),
|
|
55
55
|
defaultEnv: z.record(z.string(), z.string()).optional().describe('连接级默认环境变量'),
|
|
56
56
|
runAs: z.string().optional().describe('连接级默认执行用户,后续 ssh_exec 默认以该用户执行'),
|
|
57
|
-
keepaliveInterval: z.number().optional().describe('心跳间隔(毫秒),默认 30000'),
|
|
57
|
+
keepaliveInterval: z.number().int().positive().optional().describe('心跳间隔(毫秒),默认 30000'),
|
|
58
|
+
readyTimeout: z
|
|
59
|
+
.number()
|
|
60
|
+
.int()
|
|
61
|
+
.positive()
|
|
62
|
+
.max(600000)
|
|
63
|
+
.optional()
|
|
64
|
+
.describe('等待 SSH ready 的超时(毫秒),默认 30000'),
|
|
58
65
|
jumpHost: z
|
|
59
66
|
.object({
|
|
60
67
|
host: z.string().describe('跳板机地址'),
|
|
@@ -62,6 +69,13 @@ const connectSchema = z.object({
|
|
|
62
69
|
password: z.string().optional().describe('跳板机密码'),
|
|
63
70
|
keyPath: z.string().optional().describe('跳板机私钥路径'),
|
|
64
71
|
port: z.number().optional().describe('跳板机端口,默认 22'),
|
|
72
|
+
readyTimeout: z
|
|
73
|
+
.number()
|
|
74
|
+
.int()
|
|
75
|
+
.positive()
|
|
76
|
+
.max(600000)
|
|
77
|
+
.optional()
|
|
78
|
+
.describe('跳板机等待 SSH ready 的超时(毫秒),默认继承顶层 readyTimeout'),
|
|
65
79
|
})
|
|
66
80
|
.optional()
|
|
67
81
|
.describe('跳板机配置'),
|
|
@@ -69,7 +83,23 @@ const connectSchema = z.object({
|
|
|
69
83
|
const disconnectSchema = z.object({
|
|
70
84
|
alias: z.string().describe('连接别名'),
|
|
71
85
|
});
|
|
72
|
-
const
|
|
86
|
+
const sessionFieldSchema = z.enum([
|
|
87
|
+
'alias',
|
|
88
|
+
'identity',
|
|
89
|
+
'runAs',
|
|
90
|
+
'connected',
|
|
91
|
+
'lastUsedAt',
|
|
92
|
+
'host',
|
|
93
|
+
'port',
|
|
94
|
+
'username',
|
|
95
|
+
'authMethod',
|
|
96
|
+
'connectedAt',
|
|
97
|
+
'hasJumpHost',
|
|
98
|
+
]);
|
|
99
|
+
const listSessionsSchema = z.object({
|
|
100
|
+
detail: z.boolean().optional().describe('返回不含 keyPath 的连接详情'),
|
|
101
|
+
fields: z.array(sessionFieldSchema).max(12).optional().describe('只返回指定字段;任何模式都不返回 keyPath'),
|
|
102
|
+
});
|
|
73
103
|
const reconnectSchema = z.object({
|
|
74
104
|
alias: z.string().describe('连接别名'),
|
|
75
105
|
});
|
|
@@ -91,6 +121,7 @@ async function handleConnect(args) {
|
|
|
91
121
|
const defaultEnv = mergeEnv(template.defaultEnv, args.defaultEnv);
|
|
92
122
|
const env = mergeEnv(template.env, args.env);
|
|
93
123
|
const keepaliveInterval = args.keepaliveInterval ?? template.keepaliveInterval;
|
|
124
|
+
const readyTimeout = args.readyTimeout ?? template.readyTimeout;
|
|
94
125
|
let jumpHostResolved;
|
|
95
126
|
if (configHost) {
|
|
96
127
|
const allHosts = parseSSHConfig(args.configPath);
|
|
@@ -163,12 +194,13 @@ async function handleConnect(args) {
|
|
|
163
194
|
username: args.jumpHost.user,
|
|
164
195
|
password: args.jumpHost.password,
|
|
165
196
|
privateKeyPath: args.jumpHost.keyPath,
|
|
197
|
+
readyTimeout: args.jumpHost.readyTimeout ?? readyTimeout,
|
|
166
198
|
}
|
|
167
199
|
: jumpHostResolved;
|
|
168
200
|
const finalPort = port || 22;
|
|
169
201
|
const finalAlias = requestedAlias || `${user}@${host}:${finalPort}`;
|
|
170
202
|
const identity = `${user}@${host}:${finalPort}`;
|
|
171
|
-
const sessionsBeforeConnect = sessionManager.
|
|
203
|
+
const sessionsBeforeConnect = sessionManager.listSessionDetails();
|
|
172
204
|
const reused = sessionsBeforeConnect.some((session) => session.alias === finalAlias && session.connected);
|
|
173
205
|
const reusableSessions = sessionsBeforeConnect
|
|
174
206
|
.filter((session) => session.identity === identity && session.alias !== finalAlias && session.connected)
|
|
@@ -185,6 +217,7 @@ async function handleConnect(args) {
|
|
|
185
217
|
defaultEnv,
|
|
186
218
|
env,
|
|
187
219
|
keepaliveInterval,
|
|
220
|
+
readyTimeout,
|
|
188
221
|
jumpHost,
|
|
189
222
|
});
|
|
190
223
|
return formatResult({
|
|
@@ -221,13 +254,20 @@ async function handleDisconnect(args) {
|
|
|
221
254
|
return formatError(error);
|
|
222
255
|
}
|
|
223
256
|
}
|
|
224
|
-
async function handleListSessions() {
|
|
257
|
+
async function handleListSessions(args) {
|
|
225
258
|
try {
|
|
226
|
-
const sessions = sessionManager.listSessions();
|
|
259
|
+
const sessions = args.detail || args.fields ? sessionManager.listSessionDetails() : sessionManager.listSessions();
|
|
260
|
+
const selected = args.fields
|
|
261
|
+
? sessions.map((session) => {
|
|
262
|
+
const record = session;
|
|
263
|
+
return Object.fromEntries(args.fields.filter((field) => field in record).map((field) => [field, record[field]]));
|
|
264
|
+
})
|
|
265
|
+
: sessions;
|
|
227
266
|
return formatResult({
|
|
228
267
|
success: true,
|
|
229
|
-
count:
|
|
230
|
-
|
|
268
|
+
count: selected.length,
|
|
269
|
+
detail: args.detail === true || args.fields !== undefined,
|
|
270
|
+
sessions: selected,
|
|
231
271
|
});
|
|
232
272
|
}
|
|
233
273
|
catch (error) {
|
|
@@ -286,7 +326,7 @@ export function registerConnectionTools(server) {
|
|
|
286
326
|
server.registerTool('ssh_list_sessions', {
|
|
287
327
|
description: '列出所有活跃的 SSH 会话',
|
|
288
328
|
inputSchema: listSessionsSchema,
|
|
289
|
-
}, () => handleListSessions());
|
|
329
|
+
}, (args) => handleListSessions(args));
|
|
290
330
|
server.registerTool('ssh_reconnect', {
|
|
291
331
|
description: '重新连接已断开的会话',
|
|
292
332
|
inputSchema: reconnectSchema,
|