@pyrokine/mcp-ssh 1.3.0 → 2.0.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.
@@ -14,12 +14,22 @@ export declare class ForwardManager {
14
14
  private sessions;
15
15
  private dispatchers;
16
16
  private idCounter;
17
- forwardLocal(deps: ForwardDependencies, alias: string, localPort: number, remoteHost: string, remotePort: number, localHost?: string): Promise<string>;
17
+ private readonly idleTimeoutMs;
18
+ private idleSweeper;
19
+ constructor();
20
+ /** 用于测试或停服时手动停止 idle sweeper */
21
+ stopIdleSweeper(): void;
22
+ forwardLocal(deps: ForwardDependencies, alias: string, localPort: number, remoteHost: string, remotePort: number, localHost?: string): Promise<{
23
+ forwardId: string;
24
+ localPort: number;
25
+ }>;
18
26
  forwardRemote(deps: ForwardDependencies, alias: string, remotePort: number, localHost: string, localPort: number, remoteHost?: string): Promise<string>;
19
27
  close(forwardId: string, deps?: ForwardDependencies): boolean;
20
28
  /** 关闭指定 alias 的所有转发(disconnect 时调用,不需要 unforwardIn) */
21
29
  closeByAlias(alias: string): void;
22
30
  list(): PortForwardInfo[];
31
+ private startIdleSweeper;
32
+ private sweepIdle;
23
33
  /**
24
34
  * 确保 SSH session 有共享的 tcp connection dispatcher
25
35
  * 所有 remote forward 共用一个 dispatcher,根据 destIP/destPort 路由
@@ -8,11 +8,37 @@ export class ForwardManager {
8
8
  sessions = new Map();
9
9
  dispatchers = new Map(); // alias → dispatcher
10
10
  idCounter = 0;
11
+ // 默认 idle timeout 1 小时,长时间无连接活动的 forward 自动关闭
12
+ idleTimeoutMs = Number(process.env.SSH_MCP_FORWARD_IDLE_TIMEOUT_MS) || 3600_000;
13
+ idleSweeper = null;
14
+ constructor() {
15
+ this.startIdleSweeper();
16
+ }
17
+ /** 用于测试或停服时手动停止 idle sweeper */
18
+ stopIdleSweeper() {
19
+ if (this.idleSweeper) {
20
+ clearInterval(this.idleSweeper);
21
+ this.idleSweeper = null;
22
+ }
23
+ }
11
24
  async forwardLocal(deps, alias, localPort, remoteHost, remotePort, localHost = '127.0.0.1') {
12
25
  const client = deps.getClient(alias);
13
26
  const forwardId = this.generateId();
14
27
  return new Promise((resolve, reject) => {
28
+ const fwdState = { ref: null };
15
29
  const server = net.createServer((socket) => {
30
+ const fwd = fwdState.ref;
31
+ if (fwd) {
32
+ fwd.activeConnections += 1;
33
+ fwd.lastActivityAt = Date.now();
34
+ }
35
+ const onClose = () => {
36
+ if (fwd) {
37
+ fwd.activeConnections = Math.max(0, fwd.activeConnections - 1);
38
+ fwd.lastActivityAt = Date.now();
39
+ }
40
+ };
41
+ socket.once('close', onClose);
16
42
  client.forwardOut(socket.remoteAddress || '127.0.0.1', socket.remotePort || 0, remoteHost, remotePort, (err, stream) => {
17
43
  if (err) {
18
44
  socket.end();
@@ -25,19 +51,25 @@ export class ForwardManager {
25
51
  reject(new Error(`Local forward failed: ${err.message}`));
26
52
  });
27
53
  server.listen(localPort, localHost, () => {
28
- this.sessions.set(forwardId, {
54
+ const addr = server.address();
55
+ const actualPort = addr && typeof addr === 'object' && typeof addr.port === 'number' ? addr.port : localPort;
56
+ const session = {
29
57
  id: forwardId,
30
58
  alias,
31
59
  type: 'local',
32
60
  localHost,
33
- localPort,
61
+ localPort: actualPort,
34
62
  remoteHost,
35
63
  remotePort,
36
64
  server,
37
65
  createdAt: Date.now(),
38
66
  active: true,
39
- });
40
- resolve(forwardId);
67
+ activeConnections: 0,
68
+ lastActivityAt: Date.now(),
69
+ };
70
+ this.sessions.set(forwardId, session);
71
+ fwdState.ref = session;
72
+ resolve({ forwardId, localPort: actualPort });
41
73
  });
42
74
  });
43
75
  }
@@ -60,6 +92,8 @@ export class ForwardManager {
60
92
  remotePort,
61
93
  createdAt: Date.now(),
62
94
  active: true,
95
+ activeConnections: 0,
96
+ lastActivityAt: Date.now(),
63
97
  });
64
98
  this.ensureTcpDispatcher(alias, client);
65
99
  resolve(forwardId);
@@ -85,7 +119,8 @@ export class ForwardManager {
85
119
  const client = deps.getClient(fwd.alias);
86
120
  client.unforwardIn(fwd.remoteHost, fwd.remotePort);
87
121
  }
88
- catch { /* session 可能已断开 */
122
+ catch {
123
+ /* session 可能已断开 */
89
124
  }
90
125
  this.removeTcpDispatcherIfEmpty(fwd.alias);
91
126
  }
@@ -114,7 +149,8 @@ export class ForwardManager {
114
149
  try {
115
150
  state.client.removeListener('tcp connection', state.handler);
116
151
  }
117
- catch { /* client 可能已关闭 */
152
+ catch {
153
+ /* client 可能已关闭 */
118
154
  }
119
155
  this.dispatchers.delete(alias);
120
156
  }
@@ -136,6 +172,27 @@ export class ForwardManager {
136
172
  }
137
173
  return result;
138
174
  }
175
+ startIdleSweeper() {
176
+ if (this.idleSweeper) {
177
+ return;
178
+ }
179
+ this.idleSweeper = setInterval(() => this.sweepIdle(), 5 * 60_000);
180
+ if (typeof this.idleSweeper.unref === 'function') {
181
+ this.idleSweeper.unref();
182
+ }
183
+ }
184
+ sweepIdle() {
185
+ const now = Date.now();
186
+ for (const [id, fwd] of this.sessions) {
187
+ if (!fwd.active) {
188
+ continue;
189
+ }
190
+ if (fwd.activeConnections === 0 && now - fwd.lastActivityAt > this.idleTimeoutMs) {
191
+ console.warn(`[mcp-ssh] Forward ${id} (${fwd.type}, alias=${fwd.alias}) idle ${Math.round((now - fwd.lastActivityAt) / 1000)}s with 0 connections > ${Math.round(this.idleTimeoutMs / 1000)}s, auto-closing`);
192
+ this.close(id);
193
+ }
194
+ }
195
+ }
139
196
  /**
140
197
  * 确保 SSH session 有共享的 tcp connection dispatcher
141
198
  * 所有 remote forward 共用一个 dispatcher,根据 destIP/destPort 路由
@@ -153,9 +210,22 @@ export class ForwardManager {
153
210
  fwd.remotePort === info.destPort) {
154
211
  const stream = accept();
155
212
  const socket = net.createConnection(fwd.localPort, fwd.localHost);
213
+ fwd.activeConnections += 1;
214
+ fwd.lastActivityAt = Date.now();
215
+ let closed = false;
216
+ const onClose = () => {
217
+ if (closed) {
218
+ return;
219
+ }
220
+ closed = true;
221
+ fwd.activeConnections = Math.max(0, fwd.activeConnections - 1);
222
+ fwd.lastActivityAt = Date.now();
223
+ };
156
224
  socket.pipe(stream).pipe(socket);
157
225
  socket.on('error', () => stream.close());
226
+ socket.once('close', onClose);
158
227
  stream.on('error', () => socket.destroy());
228
+ stream.once('close', onClose);
159
229
  return;
160
230
  }
161
231
  }
package/dist/index.d.ts CHANGED
@@ -5,7 +5,7 @@
5
5
  * A comprehensive SSH MCP Server for Claude Code
6
6
  *
7
7
  * Features:
8
- * - Multiple authentication methods (password, key, agent)
8
+ * - Multiple authentication methods (password, key)
9
9
  * - Connection pooling with keepalive
10
10
  * - Session persistence
11
11
  * - Command execution (exec, sudo, su)
package/dist/index.js CHANGED
@@ -5,7 +5,7 @@
5
5
  * A comprehensive SSH MCP Server for Claude Code
6
6
  *
7
7
  * Features:
8
- * - Multiple authentication methods (password, key, agent)
8
+ * - Multiple authentication methods (password, key)
9
9
  * - Connection pooling with keepalive
10
10
  * - Session persistence
11
11
  * - Command execution (exec, sudo, su)
@@ -15,13 +15,24 @@
15
15
  */
16
16
  import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
17
17
  import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
18
+ import { readFileSync } from 'node:fs';
19
+ import { sessionManager } from './session-manager.js';
18
20
  import { registerConnectionTools, registerExecTools, registerFileTools, registerForwardTools, registerPtyTools, } from './tools/index.js';
19
- const server = new McpServer({ name: 'ssh-mcp-pro', version: '1.2.2' }, { capabilities: { tools: {} } });
21
+ const pkg = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf-8'));
22
+ const server = new McpServer({ name: 'mcp-ssh', version: pkg.version }, { capabilities: { tools: {} } });
20
23
  registerConnectionTools(server);
21
24
  registerExecTools(server);
22
25
  registerFileTools(server);
23
26
  registerPtyTools(server);
24
27
  registerForwardTools(server);
28
+ async function cleanup() {
29
+ try {
30
+ await sessionManager.disconnectAll();
31
+ }
32
+ catch {
33
+ /* 忽略清理错误 */
34
+ }
35
+ }
25
36
  async function main() {
26
37
  // 防止父进程退出后成为孤儿进程持续占用 CPU
27
38
  process.on('uncaughtException', (error) => {
@@ -35,9 +46,25 @@ async function main() {
35
46
  process.exit(1);
36
47
  }
37
48
  });
38
- process.stdin.on('end', () => process.exit(0));
49
+ process.stdin.on('end', async () => {
50
+ await cleanup();
51
+ process.exit(0);
52
+ });
39
53
  process.stdout.on('error', () => process.exit(0));
40
54
  process.stderr.on('error', () => process.exit(0));
55
+ // 优雅退出:SIGINT/SIGTERM 时关闭所有 SSH 会话
56
+ for (const sig of ['SIGINT', 'SIGTERM']) {
57
+ process.on(sig, async () => {
58
+ await cleanup();
59
+ try {
60
+ await server.close();
61
+ }
62
+ catch {
63
+ /* ignore */
64
+ }
65
+ process.exit(0);
66
+ });
67
+ }
41
68
  const transport = new StdioServerTransport();
42
69
  await server.connect(transport);
43
70
  console.error('SSH MCP Pro server started');
@@ -14,6 +14,11 @@ export declare class PtyManager {
14
14
  private sessions;
15
15
  private idCounter;
16
16
  private readonly defaultBufferSize;
17
+ private readonly idleTimeoutMs;
18
+ private idleSweeper;
19
+ constructor();
20
+ /** 用于测试或停服时手动停止 idle sweeper */
21
+ stopIdleSweeper(): void;
17
22
  start(deps: PtyDependencies, alias: string, command: string, options?: PtyOptions): Promise<string>;
18
23
  write(ptyId: string, data: string): boolean;
19
24
  read(ptyId: string, options?: {
@@ -30,6 +35,8 @@ export declare class PtyManager {
30
35
  /** 关闭指定 alias 的所有 PTY 会话 */
31
36
  closeByAlias(alias: string): void;
32
37
  list(): PtySessionInfo[];
38
+ private startIdleSweeper;
39
+ private sweepIdle;
33
40
  private getSession;
34
41
  private generateId;
35
42
  /** 从终端仿真器获取当前屏幕内容 */
@@ -9,6 +9,19 @@ export class PtyManager {
9
9
  sessions = new Map();
10
10
  idCounter = 0;
11
11
  defaultBufferSize = 1024 * 1024; // 1MB
12
+ // 默认 idle timeout 1 小时,超时未读的 pty 自动回收
13
+ idleTimeoutMs = Number(process.env.SSH_MCP_PTY_IDLE_TIMEOUT_MS) || 3600_000;
14
+ idleSweeper = null;
15
+ constructor() {
16
+ this.startIdleSweeper();
17
+ }
18
+ /** 用于测试或停服时手动停止 idle sweeper */
19
+ stopIdleSweeper() {
20
+ if (this.idleSweeper) {
21
+ clearInterval(this.idleSweeper);
22
+ this.idleSweeper = null;
23
+ }
24
+ }
12
25
  async start(deps, alias, command, options = {}) {
13
26
  const ptyId = this.generateId();
14
27
  const rows = options.rows || 24;
@@ -141,6 +154,28 @@ export class PtyManager {
141
154
  }
142
155
  return result;
143
156
  }
157
+ startIdleSweeper() {
158
+ if (this.idleSweeper) {
159
+ return;
160
+ }
161
+ // 每 5 分钟扫一次,关闭超过 idleTimeout 未读的 pty
162
+ this.idleSweeper = setInterval(() => this.sweepIdle(), 5 * 60_000);
163
+ if (typeof this.idleSweeper.unref === 'function') {
164
+ this.idleSweeper.unref();
165
+ }
166
+ }
167
+ sweepIdle() {
168
+ const now = Date.now();
169
+ for (const [id, session] of this.sessions) {
170
+ if (!session.active) {
171
+ continue;
172
+ }
173
+ if (now - session.lastReadAt > this.idleTimeoutMs) {
174
+ console.warn(`[mcp-ssh] PTY ${id} (alias=${session.alias}, command=${session.command}) idle ${Math.round((now - session.lastReadAt) / 1000)}s > ${Math.round(this.idleTimeoutMs / 1000)}s, auto-closing`);
175
+ this.close(id);
176
+ }
177
+ }
178
+ }
144
179
  getSession(ptyId) {
145
180
  const session = this.sessions.get(ptyId);
146
181
  if (!session) {
@@ -154,8 +189,10 @@ export class PtyManager {
154
189
  /** 从终端仿真器获取当前屏幕内容 */
155
190
  getScreenContent(terminal) {
156
191
  const buffer = terminal.buffer.active;
192
+ const start = buffer.viewportY;
193
+ const end = start + terminal.rows;
157
194
  const lines = [];
158
- for (let i = 0; i < terminal.rows; i++) {
195
+ for (let i = start; i < end; i++) {
159
196
  const line = buffer.getLine(i);
160
197
  if (line) {
161
198
  lines.push(line.translateToString(true));
@@ -0,0 +1,24 @@
1
+ /**
2
+ * 路径与文件安全校验
3
+ *
4
+ * 限制 privateKeyPath / configPath 必须位于白名单目录下,
5
+ * 加文件大小上限避免任意大文件被读取,
6
+ * 错误消息脱敏避免 PEM 细节泄露
7
+ */
8
+ /**
9
+ * 校验私钥文件路径在白名单内,且大小不超限
10
+ *
11
+ * 双重校验:原路径(path.resolve 后)和真实路径(realpath 解析所有 symlink 后)都必须在白名单内,
12
+ * 防止"白名单内的 symlink 指向白名单外文件"绕过
13
+ */
14
+ export declare function validateKeyFile(p: string): void;
15
+ /**
16
+ * 校验 SSH config 文件路径在白名单内,且大小不超限
17
+ *
18
+ * 同 validateKeyFile:原路径 + realpath 都必须在白名单
19
+ */
20
+ export declare function validateConfigFile(p: string): void;
21
+ /**
22
+ * 脱敏 ssh2 keyParser 错误,避免 PEM 文件 cipher/kdf 字段被泄露
23
+ */
24
+ export declare function sanitizeKeyError(message: string): string;
@@ -0,0 +1,81 @@
1
+ /**
2
+ * 路径与文件安全校验
3
+ *
4
+ * 限制 privateKeyPath / configPath 必须位于白名单目录下,
5
+ * 加文件大小上限避免任意大文件被读取,
6
+ * 错误消息脱敏避免 PEM 细节泄露
7
+ */
8
+ import * as fs from 'fs';
9
+ import * as os from 'os';
10
+ import * as path from 'path';
11
+ const MAX_KEY_FILE_SIZE = 64 * 1024; // 私钥实际不会超过 64KB
12
+ const MAX_CONFIG_FILE_SIZE = 1024 * 1024; // SSH config 上限 1MB
13
+ function getAllowedDirs() {
14
+ const base = [path.resolve(os.homedir(), '.ssh'), '/etc/ssh'];
15
+ const env = process.env.SSH_MCP_ALLOWED_KEY_DIRS?.split(path.delimiter)
16
+ .map((d) => d.trim())
17
+ .filter(Boolean) ?? [];
18
+ return [...base, ...env.map((d) => path.resolve(d))];
19
+ }
20
+ function isUnderAllowedDir(resolved) {
21
+ const allowed = getAllowedDirs();
22
+ const ok = allowed.some((dir) => resolved === dir || resolved.startsWith(dir + path.sep));
23
+ return { ok, allowed };
24
+ }
25
+ /**
26
+ * 校验私钥文件路径在白名单内,且大小不超限
27
+ *
28
+ * 双重校验:原路径(path.resolve 后)和真实路径(realpath 解析所有 symlink 后)都必须在白名单内,
29
+ * 防止"白名单内的 symlink 指向白名单外文件"绕过
30
+ */
31
+ export function validateKeyFile(p) {
32
+ const resolved = path.resolve(p);
33
+ if (!isUnderAllowedDir(resolved).ok) {
34
+ const { allowed } = isUnderAllowedDir(resolved);
35
+ throw new Error(`Invalid private key path: must be under ${allowed.join(' or ')} ` +
36
+ `(set SSH_MCP_ALLOWED_KEY_DIRS to extend, separated by '${path.delimiter}')`);
37
+ }
38
+ const real = fs.realpathSync(resolved);
39
+ if (!isUnderAllowedDir(real).ok) {
40
+ throw new Error(`Invalid private key path: symlink target falls outside the whitelist`);
41
+ }
42
+ const stats = fs.statSync(real);
43
+ if (stats.size > MAX_KEY_FILE_SIZE) {
44
+ throw new Error(`Private key file too large: ${stats.size} bytes (max ${MAX_KEY_FILE_SIZE})`);
45
+ }
46
+ }
47
+ /**
48
+ * 校验 SSH config 文件路径在白名单内,且大小不超限
49
+ *
50
+ * 同 validateKeyFile:原路径 + realpath 都必须在白名单
51
+ */
52
+ export function validateConfigFile(p) {
53
+ const resolved = path.resolve(p);
54
+ if (!isUnderAllowedDir(resolved).ok) {
55
+ const { allowed } = isUnderAllowedDir(resolved);
56
+ throw new Error(`Invalid config path: must be under ${allowed.join(' or ')} ` +
57
+ `(set SSH_MCP_ALLOWED_KEY_DIRS to extend, separated by '${path.delimiter}')`);
58
+ }
59
+ const real = fs.realpathSync(resolved);
60
+ if (!isUnderAllowedDir(real).ok) {
61
+ throw new Error(`Invalid config path: symlink target falls outside the whitelist`);
62
+ }
63
+ const stats = fs.statSync(real);
64
+ if (stats.size > MAX_CONFIG_FILE_SIZE) {
65
+ throw new Error(`SSH config file too large: ${stats.size} bytes (max ${MAX_CONFIG_FILE_SIZE})`);
66
+ }
67
+ }
68
+ /**
69
+ * 脱敏 ssh2 keyParser 错误,避免 PEM 文件 cipher/kdf 字段被泄露
70
+ */
71
+ export function sanitizeKeyError(message) {
72
+ const lower = message.toLowerCase();
73
+ if (lower.includes('private key') ||
74
+ lower.includes('pem') ||
75
+ lower.includes('encrypted') ||
76
+ lower.includes('passphrase') ||
77
+ lower.includes('cipher')) {
78
+ return 'Invalid private key file';
79
+ }
80
+ return message;
81
+ }
@@ -17,9 +17,13 @@ interface SSHSession {
17
17
  reconnectAttempts: number;
18
18
  connected: boolean;
19
19
  manualClose: boolean;
20
+ /** 当前正在等待的重连定时器,disconnect 时需要清除以防 zombie 重连 */
21
+ reconnectTimer?: NodeJS.Timeout;
20
22
  }
21
23
  export declare class SessionManager {
22
24
  private sessions;
25
+ /** per-alias connect 进行中的 Promise,防止并发 connect 同一 alias 时重复建连 */
26
+ private connectInFlight;
23
27
  private readonly ptyManager;
24
28
  private readonly forwardManager;
25
29
  private readonly persistPath;
@@ -31,7 +35,7 @@ export declare class SessionManager {
31
35
  private reconnectDelay;
32
36
  constructor(persistPath?: string);
33
37
  /**
34
- * 建立 SSH 连接
38
+ * 建立 SSH 连接(per-alias mutex,防止并发 connect 同一 alias 重复建连)
35
39
  */
36
40
  connect(config: SSHConnectionConfig): Promise<string>;
37
41
  /**
@@ -42,6 +46,8 @@ export declare class SessionManager {
42
46
  * 断开连接
43
47
  */
44
48
  disconnect(alias: string): boolean;
49
+ /** 断开所有活跃会话(SIGINT/SIGTERM 时调用) */
50
+ disconnectAll(): Promise<void>;
45
51
  /**
46
52
  * 获取会话
47
53
  */
@@ -57,16 +63,18 @@ export declare class SessionManager {
57
63
  /**
58
64
  * 以其他用户身份执行命令
59
65
  *
60
- * options.loadProfile 控制是否加载用户的 shell 配置(默认 true)。
66
+ * options.loadProfile 控制是否加载用户的 shell 配置(默认 true)
61
67
  * su -c 创建非交互式 shell,不会自动执行 rc 文件,
62
- * 但大多数用户的环境变量设置在 rc 文件中,因此默认加载。
63
- * 支持 bash(.bashrc)、zsh(.zshrc) 及其他 shell(.profile)。
68
+ * 但大多数用户的环境变量设置在 rc 文件中,因此默认加载
69
+ * 支持 bash(.bashrc)、zsh(.zshrc) 及其他 shell(.profile)
64
70
  */
65
71
  execAsUser(alias: string, command: string, targetUser: string, options?: ExecOptions & {
66
72
  loadProfile?: boolean;
67
73
  }): Promise<ExecResult>;
68
74
  /**
69
75
  * 使用 sudo 执行命令
76
+ *
77
+ * 通过 stdin 传递密码,避免密码出现在进程列表和 audit 日志中
70
78
  */
71
79
  execSudo(alias: string, command: string, sudoPassword?: string, options?: ExecOptions): Promise<ExecResult>;
72
80
  /**
@@ -87,10 +95,14 @@ export declare class SessionManager {
87
95
  ptyResize(ptyId: string, rows: number, cols: number): boolean;
88
96
  ptyClose(ptyId: string): boolean;
89
97
  ptyList(): PtySessionInfo[];
90
- forwardLocal(alias: string, localPort: number, remoteHost: string, remotePort: number, localHost?: string): Promise<string>;
98
+ forwardLocal(alias: string, localPort: number, remoteHost: string, remotePort: number, localHost?: string): Promise<{
99
+ forwardId: string;
100
+ localPort: number;
101
+ }>;
91
102
  forwardRemote(alias: string, remotePort: number, localHost: string, localPort: number, remoteHost?: string): Promise<string>;
92
103
  forwardClose(forwardId: string): boolean;
93
104
  forwardList(): PortForwardInfo[];
105
+ private connectInternal;
94
106
  /**
95
107
  * 执行带 PTY 的命令,返回原始 stream(供 PtyManager 使用)
96
108
  */
@@ -117,7 +129,8 @@ export declare class SessionManager {
117
129
  */
118
130
  private diagnoseConnectionError;
119
131
  /**
120
- * 转义 shell 参数(使用单引号方式)
132
+ * 转义 shell 参数(使用单引号方式,防止命令注入)
133
+ * 委托给 tools/utils.ts 的共享实现
121
134
  */
122
135
  private escapeShellArg;
123
136
  /**
@@ -138,7 +151,7 @@ export declare class SessionManager {
138
151
  */
139
152
  private getLoadProfileCommand;
140
153
  /**
141
- * 持久化会话信息
154
+ * 持久化会话信息(异步非阻塞,避免阻塞事件循环)
142
155
  */
143
156
  private persistSessions;
144
157
  }