mcp-ssh-manager 3.6.7 → 3.8.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.
@@ -21,19 +21,69 @@ const EXECUTION_STRATEGIES = {
21
21
  ROLLING: 'rolling' // Execute with delay between servers
22
22
  };
23
23
 
24
- class ServerGroups {
25
- constructor() {
24
+ export class ServerGroups {
25
+ constructor(options = {}) {
26
+ // Both options exist so this class can be instantiated in isolation (tests,
27
+ // embedding). The exported singleton below keeps the historical defaults.
28
+ this.groupsFile = options.groupsFile || GROUPS_FILE;
29
+ this.serverConfigProvider = typeof options.serverConfigProvider === 'function'
30
+ ? options.serverConfigProvider
31
+ : null;
26
32
  this.groups = this.loadGroups();
27
33
  }
28
34
 
35
+ /**
36
+ * Inject an accessor to the loaded SSH server configuration.
37
+ * Without it this module can only see servers declared in the environment,
38
+ * which misses every TOML-defined server.
39
+ */
40
+ setServerConfigProvider(provider) {
41
+ this.serverConfigProvider = typeof provider === 'function' ? provider : null;
42
+ }
43
+
44
+ /**
45
+ * Current SSH server configurations, keyed by server name.
46
+ * Empty when no provider has been injected.
47
+ */
48
+ getServerConfigs() {
49
+ if (!this.serverConfigProvider) return {};
50
+
51
+ try {
52
+ return this.serverConfigProvider() || {};
53
+ } catch (error) {
54
+ logger.warn('Failed to read SSH server configuration for groups', { error: error.message });
55
+ return {};
56
+ }
57
+ }
58
+
59
+ /**
60
+ * Built-in groups whose membership is computed, never stored.
61
+ */
62
+ getDynamicGroups() {
63
+ return {
64
+ all: {
65
+ description: 'All configured servers',
66
+ servers: [],
67
+ dynamic: true // Will be populated from server config
68
+ }
69
+ };
70
+ }
71
+
29
72
  /**
30
73
  * Load groups from file
31
74
  */
32
75
  loadGroups() {
33
76
  try {
34
- if (fs.existsSync(GROUPS_FILE)) {
35
- const data = fs.readFileSync(GROUPS_FILE, 'utf8');
36
- return JSON.parse(data);
77
+ if (fs.existsSync(this.groupsFile)) {
78
+ const data = fs.readFileSync(this.groupsFile, 'utf8');
79
+ const stored = JSON.parse(data);
80
+
81
+ // Dynamic groups are deliberately never persisted (see saveGroups), so
82
+ // they are missing from every file written after the first group edit.
83
+ // Re-inject them, otherwise 'all' disappears for good the moment a user
84
+ // creates a group. They cannot be deleted on purpose either, so nothing
85
+ // the user did is being undone here.
86
+ return { ...this.getDynamicGroups(), ...stored };
37
87
  }
38
88
  } catch (error) {
39
89
  logger.warn('Failed to load server groups', { error: error.message });
@@ -41,11 +91,7 @@ class ServerGroups {
41
91
 
42
92
  // Return default groups
43
93
  return {
44
- all: {
45
- description: 'All configured servers',
46
- servers: [],
47
- dynamic: true // Will be populated from server config
48
- },
94
+ ...this.getDynamicGroups(),
49
95
  production: {
50
96
  description: 'Production servers',
51
97
  servers: [],
@@ -78,7 +124,7 @@ class ServerGroups {
78
124
  }
79
125
  }
80
126
 
81
- fs.writeFileSync(GROUPS_FILE, JSON.stringify(groupsToSave, null, 2));
127
+ fs.writeFileSync(this.groupsFile, JSON.stringify(groupsToSave, null, 2));
82
128
  logger.info('Server groups saved', { count: Object.keys(groupsToSave).length });
83
129
  return true;
84
130
  } catch (error) {
@@ -87,24 +133,111 @@ class ServerGroups {
87
133
  }
88
134
  }
89
135
 
136
+ /**
137
+ * Groups derived from the per-server `group` field of the SSH configuration.
138
+ * Returns a Map of group name -> server names. Group names are lowercased, so
139
+ * `group = "Production"` and `group = "production"` land in the same group.
140
+ */
141
+ getConfigGroups() {
142
+ const derived = new Map();
143
+
144
+ for (const [name, config] of Object.entries(this.getServerConfigs())) {
145
+ const label = typeof config?.group === 'string' ? config.group.trim() : '';
146
+ if (!label) continue;
147
+
148
+ const groupName = label.toLowerCase();
149
+ const serverName = String(config.name || name).toLowerCase();
150
+ const members = derived.get(groupName) || [];
151
+ if (!members.includes(serverName)) members.push(serverName);
152
+ derived.set(groupName, members);
153
+ }
154
+
155
+ return derived;
156
+ }
157
+
158
+ /**
159
+ * Members of a group, merging the explicit `.server-groups.json` list with
160
+ * every server whose config carries a matching `group` field. Membership is a
161
+ * union: tagging a server in the SSH config adds it to the group without
162
+ * touching the stored list, and the stored list keeps working on its own.
163
+ */
164
+ resolveMembers(groupName, explicitServers = [], derived = this.getConfigGroups()) {
165
+ const members = [];
166
+
167
+ for (const server of [...explicitServers, ...(derived.get(groupName) || [])]) {
168
+ const normalized = String(server).toLowerCase();
169
+ if (!members.includes(normalized)) members.push(normalized);
170
+ }
171
+
172
+ return members;
173
+ }
174
+
90
175
  /**
91
176
  * Get a group by name
92
177
  */
93
178
  getGroup(name) {
94
- const group = this.groups[name.toLowerCase()];
179
+ const groupName = name.toLowerCase();
180
+ const group = this.groups[groupName];
181
+ const derived = this.getConfigGroups();
182
+ const derivedMembers = derived.get(groupName) || [];
95
183
 
96
184
  if (!group) {
97
- throw new Error(`Group '${name}' not found`);
185
+ // Group declared only through the `group` field of the SSH configuration.
186
+ if (derivedMembers.length === 0) {
187
+ throw new Error(`Group '${name}' not found`);
188
+ }
189
+
190
+ return {
191
+ description: `Servers configured with group = "${groupName}"`,
192
+ servers: derivedMembers,
193
+ strategy: EXECUTION_STRATEGIES.PARALLEL,
194
+ dynamic: true,
195
+ fromConfig: true
196
+ };
98
197
  }
99
198
 
100
199
  // For 'all' group, return all configured servers
101
- if (name.toLowerCase() === 'all' && group.dynamic) {
200
+ if (groupName === 'all' && group.dynamic) {
102
201
  return {
103
202
  ...group,
104
203
  servers: this.getAllServers()
105
204
  };
106
205
  }
107
206
 
207
+ if (derivedMembers.length === 0) {
208
+ return group;
209
+ }
210
+
211
+ return {
212
+ ...group,
213
+ servers: this.resolveMembers(groupName, group.servers, derived),
214
+ fromConfig: true
215
+ };
216
+ }
217
+
218
+ /**
219
+ * Resolve a group for mutation, rejecting the ones that are not editable.
220
+ * `verb` only shapes the error message ("Cannot update dynamic group ...").
221
+ */
222
+ getMutableGroup(name, verb) {
223
+ const groupName = name.toLowerCase();
224
+ const group = this.groups[groupName];
225
+
226
+ if (!group) {
227
+ if (this.getConfigGroups().has(groupName)) {
228
+ throw new Error(
229
+ `Group '${name}' comes from the 'group' field of your SSH server configuration and cannot be edited here. ` +
230
+ 'Change the group of the servers themselves in your .env/TOML config, or use a different group name.'
231
+ );
232
+ }
233
+
234
+ throw new Error(`Group '${name}' not found`);
235
+ }
236
+
237
+ if (group.dynamic) {
238
+ throw new Error(`Cannot ${verb} dynamic group '${name}'`);
239
+ }
240
+
108
241
  return group;
109
242
  }
110
243
 
@@ -112,7 +245,13 @@ class ServerGroups {
112
245
  * Get all configured servers
113
246
  */
114
247
  getAllServers() {
115
- // This will be populated from the main server config
248
+ const configured = Object.keys(this.getServerConfigs());
249
+ if (configured.length > 0) {
250
+ return configured.map(name => name.toLowerCase());
251
+ }
252
+
253
+ // No provider injected: fall back to scanning the environment. This only
254
+ // sees .env servers, never TOML ones — hence the provider.
116
255
  const servers = [];
117
256
 
118
257
  for (const key of Object.keys(process.env)) {
@@ -160,15 +299,7 @@ class ServerGroups {
160
299
  */
161
300
  updateGroup(name, updates) {
162
301
  const groupName = name.toLowerCase();
163
- const group = this.groups[groupName];
164
-
165
- if (!group) {
166
- throw new Error(`Group '${name}' not found`);
167
- }
168
-
169
- if (group.dynamic) {
170
- throw new Error(`Cannot update dynamic group '${name}'`);
171
- }
302
+ const group = this.getMutableGroup(name, 'update');
172
303
 
173
304
  // Update group properties
174
305
  if (updates.servers !== undefined) {
@@ -204,15 +335,7 @@ class ServerGroups {
204
335
  */
205
336
  deleteGroup(name) {
206
337
  const groupName = name.toLowerCase();
207
- const group = this.groups[groupName];
208
-
209
- if (!group) {
210
- throw new Error(`Group '${name}' not found`);
211
- }
212
-
213
- if (group.dynamic) {
214
- throw new Error(`Cannot delete dynamic group '${name}'`);
215
- }
338
+ this.getMutableGroup(name, 'delete');
216
339
 
217
340
  delete this.groups[groupName];
218
341
  this.saveGroups();
@@ -227,15 +350,7 @@ class ServerGroups {
227
350
  */
228
351
  addServers(name, servers) {
229
352
  const groupName = name.toLowerCase();
230
- const group = this.groups[groupName];
231
-
232
- if (!group) {
233
- throw new Error(`Group '${name}' not found`);
234
- }
235
-
236
- if (group.dynamic) {
237
- throw new Error(`Cannot modify dynamic group '${name}'`);
238
- }
353
+ const group = this.getMutableGroup(name, 'modify');
239
354
 
240
355
  // Add servers (avoid duplicates)
241
356
  const currentServers = new Set(group.servers);
@@ -258,15 +373,7 @@ class ServerGroups {
258
373
  */
259
374
  removeServers(name, servers) {
260
375
  const groupName = name.toLowerCase();
261
- const group = this.groups[groupName];
262
-
263
- if (!group) {
264
- throw new Error(`Group '${name}' not found`);
265
- }
266
-
267
- if (group.dynamic) {
268
- throw new Error(`Cannot modify dynamic group '${name}'`);
269
- }
376
+ const group = this.getMutableGroup(name, 'modify');
270
377
 
271
378
  // Remove servers
272
379
  const toRemove = new Set(servers.map(s => s.toLowerCase()));
@@ -287,18 +394,36 @@ class ServerGroups {
287
394
  * List all groups
288
395
  */
289
396
  listGroups() {
397
+ const derived = this.getConfigGroups();
290
398
  const groups = [];
291
399
 
292
400
  for (const [name, group] of Object.entries(this.groups)) {
293
401
  // Populate dynamic groups
294
- if (group.dynamic && name === 'all') {
295
- group.servers = this.getAllServers();
296
- }
402
+ const servers = group.dynamic && name === 'all'
403
+ ? this.getAllServers()
404
+ : this.resolveMembers(name, group.servers, derived);
297
405
 
298
406
  groups.push({
299
407
  name,
300
408
  ...group,
301
- serverCount: group.servers.length
409
+ servers,
410
+ serverCount: servers.length,
411
+ ...((derived.get(name) || []).length > 0 ? { fromConfig: true } : {})
412
+ });
413
+ }
414
+
415
+ // Groups that exist only through the `group` field of the SSH configuration
416
+ for (const [name, servers] of derived) {
417
+ if (this.groups[name]) continue;
418
+
419
+ groups.push({
420
+ name,
421
+ description: `Servers configured with group = "${name}"`,
422
+ servers,
423
+ serverCount: servers.length,
424
+ strategy: EXECUTION_STRATEGIES.PARALLEL,
425
+ dynamic: true,
426
+ fromConfig: true
302
427
  });
303
428
  }
304
429
 
@@ -398,6 +523,8 @@ class ServerGroups {
398
523
  const serverGroups = new ServerGroups();
399
524
 
400
525
  // Export convenience functions
526
+ export const setServerConfigProvider = (provider) => serverGroups.setServerConfigProvider(provider);
527
+ export const getGroup = (name) => serverGroups.getGroup(name);
401
528
  export const createGroup = (name, servers, options) => serverGroups.createGroup(name, servers, options);
402
529
  export const updateGroup = (name, updates) => serverGroups.updateGroup(name, updates);
403
530
  export const deleteGroup = (name) => serverGroups.deleteGroup(name);
@@ -3,14 +3,14 @@
3
3
  * Manages persistent SSH sessions with state and context
4
4
  */
5
5
 
6
- import { v4 as uuidv4 } from 'uuid';
6
+ import { randomUUID } from 'node:crypto';
7
7
  import { logger } from './logger.js';
8
8
 
9
9
  // Map to store active sessions
10
10
  const sessions = new Map();
11
11
 
12
12
  function generateMarker(prefix) {
13
- return `${prefix}_${uuidv4().replace(/-/g, '')}`;
13
+ return `${prefix}_${randomUUID().replace(/-/g, '')}`;
14
14
  }
15
15
 
16
16
  // Session states
@@ -289,7 +289,7 @@ class SSHSession {
289
289
  * Create a new SSH session
290
290
  */
291
291
  export async function createSession(serverName, ssh) {
292
- const sessionId = `ssh_${Date.now()}_${uuidv4().substring(0, 8)}`;
292
+ const sessionId = `ssh_${Date.now()}_${randomUUID().substring(0, 8)}`;
293
293
 
294
294
  const session = new SSHSession(sessionId, serverName, ssh);
295
295
  sessions.set(sessionId, session);
@@ -32,6 +32,7 @@ class SSHManager {
32
32
  this.jumpConnection = null;
33
33
  }
34
34
 
35
+ /** @returns {Promise<void>} */
35
36
  async connect(options = {}) {
36
37
  return new Promise((resolve, reject) => {
37
38
  this.client.on('ready', () => {
@@ -152,6 +153,13 @@ class SSHManager {
152
153
  // Use ssh-agent if available (handles passphrase-protected keys transparently)
153
154
  if (process.env.SSH_AUTH_SOCK) {
154
155
  connConfig.agent = process.env.SSH_AUTH_SOCK;
156
+ // Opt-in per-server agent forwarding. ssh2 requires `agent` to be set,
157
+ // so we only enable it inside this block — otherwise ssh2 throws at
158
+ // connect. With allowAgentFwd on, every exec/shell channel forwards the
159
+ // agent automatically, so no per-command change is needed.
160
+ if (this.config.forwardAgent) {
161
+ connConfig.agentForward = true;
162
+ }
155
163
  }
156
164
 
157
165
  // Add authentication (support both keyPath and keypath for compatibility)
@@ -438,9 +446,9 @@ class SSHManager {
438
446
  return;
439
447
  }
440
448
 
441
- sftp.fastPut(localPath, resolvedRemotePath, (err) => {
449
+ sftp.fastPut(localPath, resolvedRemotePath, (/** @type {Error|undefined} */ err) => {
442
450
  if (err) reject(err);
443
- else resolve();
451
+ else resolve(undefined);
444
452
  });
445
453
  });
446
454
  }
@@ -469,9 +477,9 @@ class SSHManager {
469
477
 
470
478
  const sftp = await this.getSFTP();
471
479
  return new Promise((resolve, reject) => {
472
- sftp.fastGet(resolvedRemotePath, localPath, (err) => {
480
+ sftp.fastGet(resolvedRemotePath, localPath, (/** @type {Error|undefined} */ err) => {
473
481
  if (err) reject(err);
474
- else resolve();
482
+ else resolve(undefined);
475
483
  });
476
484
  });
477
485
  }
@@ -3,13 +3,45 @@
3
3
  * Manages SSH port forwarding and SOCKS proxy tunnels
4
4
  */
5
5
 
6
- import { v4 as uuidv4 } from 'uuid';
6
+ import { randomUUID } from 'node:crypto';
7
7
  import net from 'net';
8
8
  import { logger } from './logger.js';
9
9
 
10
10
  // Map to store active tunnels
11
11
  const tunnels = new Map();
12
12
 
13
+ /**
14
+ * Bind a local server, rejecting when the bind fails.
15
+ *
16
+ * `net.Server#listen` does NOT pass an error to its callback — the callback
17
+ * only ever fires on success. A failed bind (EADDRINUSE, the common case when
18
+ * the requested tunnel port is already taken) surfaces as an `'error'` event
19
+ * instead. With no listener for it, Node rethrows as an uncaught exception:
20
+ * that used to kill the whole MCP server process, while the awaited promise
21
+ * never settled either way.
22
+ *
23
+ * @param {import('net').Server} server
24
+ * @param {number} port
25
+ * @param {string} host
26
+ * @returns {Promise<void>}
27
+ */
28
+ export function listenOrReject(server, port, host) {
29
+ return new Promise((resolve, reject) => {
30
+ const onError = (error) => {
31
+ server.removeListener('listening', onListening);
32
+ reject(error);
33
+ };
34
+ const onListening = () => {
35
+ server.removeListener('error', onError);
36
+ resolve();
37
+ };
38
+
39
+ server.once('error', onError);
40
+ server.once('listening', onListening);
41
+ server.listen(port, host);
42
+ });
43
+ }
44
+
13
45
  // Tunnel types
14
46
  const TUNNEL_TYPES = {
15
47
  LOCAL: 'local', // Local port forwarding (access remote service locally)
@@ -154,12 +186,7 @@ class SSHTunnel {
154
186
  });
155
187
 
156
188
  // Start listening
157
- await new Promise((resolve, reject) => {
158
- this.server.listen(localPort, localHost, (err) => {
159
- if (err) reject(err);
160
- else resolve();
161
- });
162
- });
189
+ await listenOrReject(this.server, localPort, localHost);
163
190
 
164
191
  logger.info('Local forwarding established', {
165
192
  local: `${localHost}:${localPort}`,
@@ -174,12 +201,14 @@ class SSHTunnel {
174
201
  const { localHost, localPort, remoteHost, remotePort } = this.config;
175
202
 
176
203
  // Request remote forwarding from SSH server
177
- await new Promise((resolve, reject) => {
204
+ /** @type {Promise<void>} */
205
+ const forwarded = new Promise((resolve, reject) => {
178
206
  this.ssh.forwardIn(remoteHost, remotePort, (err) => {
179
207
  if (err) reject(err);
180
208
  else resolve();
181
209
  });
182
210
  });
211
+ await forwarded;
183
212
 
184
213
  // Handle incoming connections from remote
185
214
  this.ssh.on('tcp connection', (info, accept) => {
@@ -258,7 +287,7 @@ class SSHTunnel {
258
287
  // Send auth method response
259
288
  localSocket.write(Buffer.from([0x05, 0x00]));
260
289
 
261
- localSocket.once('data', async (chunk2) => {
290
+ localSocket.once('data', async (/** @type {Buffer} */ chunk2) => {
262
291
  // Parse connection request
263
292
  if (chunk2[0] === 0x05 && chunk2[1] === 0x01) { // CONNECT
264
293
  const addrType = chunk2[3];
@@ -338,12 +367,7 @@ class SSHTunnel {
338
367
  });
339
368
 
340
369
  // Start listening
341
- await new Promise((resolve, reject) => {
342
- this.server.listen(localPort, localHost, (err) => {
343
- if (err) reject(err);
344
- else resolve();
345
- });
346
- });
370
+ await listenOrReject(this.server, localPort, localHost);
347
371
 
348
372
  logger.info('SOCKS proxy established', {
349
373
  local: `${localHost}:${localPort}`
@@ -439,7 +463,7 @@ class SSHTunnel {
439
463
  * Create a new SSH tunnel
440
464
  */
441
465
  export async function createTunnel(serverName, ssh, config) {
442
- const tunnelId = `tunnel_${Date.now()}_${uuidv4().substring(0, 8)}`;
466
+ const tunnelId = `tunnel_${Date.now()}_${randomUUID().substring(0, 8)}`;
443
467
 
444
468
  // Validate config
445
469
  if (!config.type || !Object.values(TUNNEL_TYPES).includes(config.type)) {
package/tsconfig.json ADDED
@@ -0,0 +1,36 @@
1
+ {
2
+ "//": [
3
+ "Type-checking only — this project ships plain JavaScript and is published",
4
+ "straight from src/, with no build step. TypeScript is used purely as a",
5
+ "static checker over JSDoc annotations (`npm run typecheck`), so nothing",
6
+ "here ever emits a file or changes what users install.",
7
+ "",
8
+ "Strictness is deliberately moderate: the goal is catching the mistakes that",
9
+ "actually bit this project (reading a config field that does not exist — see",
10
+ "issue #49 — wrong argument counts, typos on typed objects), not converting",
11
+ "the codebase to TypeScript."
12
+ ],
13
+ "compilerOptions": {
14
+ "target": "ES2022",
15
+ "module": "NodeNext",
16
+ "moduleResolution": "NodeNext",
17
+ "lib": ["ES2022"],
18
+ "types": ["node"],
19
+
20
+ "allowJs": true,
21
+ "checkJs": true,
22
+ "noEmit": true,
23
+
24
+ "strict": false,
25
+ "noImplicitAny": false,
26
+ "strictNullChecks": false,
27
+ "noImplicitThis": true,
28
+ "alwaysStrict": true,
29
+
30
+ "skipLibCheck": true,
31
+ "forceConsistentCasingInFileNames": true,
32
+ "resolveJsonModule": true
33
+ },
34
+ "include": ["src/**/*.js"],
35
+ "exclude": ["node_modules", "src/index.js.bak"]
36
+ }