mcp-ssh-manager 3.8.7 → 4.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/.eslintignore +5 -0
- package/.gitattributes +5 -0
- package/CHANGELOG.md +371 -6
- package/CLAUDE.md +6 -0
- package/CODE_OF_CONDUCT.md +18 -0
- package/CONTRIBUTING.md +30 -0
- package/Formula/ssh-manager.rb +60 -0
- package/README.md +484 -964
- package/ROADMAP-V4.md +451 -0
- package/brand/README.md +43 -0
- package/brand/icon.svg +32 -0
- package/brand/mark.svg +18 -0
- package/brand/wordmark.svg +30 -0
- package/cli/app.js +230 -0
- package/cli/control.js +116 -0
- package/cli/lib/colors.sh +15 -0
- package/cli/lib/menu.sh +145 -96
- package/cli/portability.js +186 -0
- package/cli/ssh-manager +197 -91
- package/cli/ssh-manager.js +14 -0
- package/cli/style.js +17 -0
- package/cli/vault.js +411 -0
- package/desktop/ControlPlaneApp.swift +219 -0
- package/desktop/build.sh +58 -0
- package/desktop/electron/after-pack.cjs +39 -0
- package/desktop/electron/electron-builder.yml +148 -0
- package/desktop/electron/finalize-artifacts.mjs +83 -0
- package/desktop/electron/main.js +815 -0
- package/desktop/electron/package-lock.json +3656 -0
- package/desktop/electron/package.json +30 -0
- package/desktop/electron/prepare-engine.mjs +84 -0
- package/desktop/electron/resources/entitlements.mac.plist +22 -0
- package/desktop/electron/resources/icon.png +0 -0
- package/desktop/electron/resources/trayTemplate.png +0 -0
- package/desktop/electron/resources/trayTemplate@2x.png +0 -0
- package/desktop/electron/smoke-test.mjs +184 -0
- package/dist/ui/app.css +1 -0
- package/dist/ui/app.js +501 -0
- package/dist/ui/assets/Forum-Regular.woff2 +0 -0
- package/dist/ui/assets/JetBrainsMono-Bold.woff2 +0 -0
- package/dist/ui/assets/JetBrainsMono-Regular.woff2 +0 -0
- package/dist/ui/assets/Karla-Variable.woff2 +0 -0
- package/dist/ui/index.html +16 -0
- package/docs/DISTRIBUTION.md +136 -0
- package/docs/FINAL-TEST-V4.md +209 -0
- package/docs/MIGRATION.md +334 -0
- package/docs/TESTING-V4.md +119 -0
- package/docs/superpowers/specs/2026-10-08-desktop-from-npm-and-cli-design.md +187 -0
- package/docs/videos/control-plane.mp4 +0 -0
- package/package.json +61 -30
- package/scripts/build-interface.mjs +73 -0
- package/scripts/capture-screenshots.mjs +191 -0
- package/scripts/demo-env.mjs +461 -0
- package/scripts/frame-screenshots.py +176 -0
- package/scripts/macbook-mockup.py +296 -0
- package/scripts/make-tray-icon.py +61 -0
- package/scripts/preview-candidate.mjs +291 -0
- package/scripts/publish-desktop.mjs +46 -0
- package/scripts/record-demo.mjs +229 -0
- package/scripts/release-version.mjs +32 -0
- package/scripts/render-cli-menu.py +157 -0
- package/scripts/requirements-dev.in +12 -0
- package/scripts/requirements-dev.txt +424 -0
- package/scripts/run-ui-regression.mjs +48 -0
- package/scripts/setup-hooks.sh +7 -13
- package/scripts/smoke-desktop.mjs +80 -0
- package/scripts/test-drag-and-drop.mjs +114 -0
- package/scripts/test-first-run.mjs +5 -0
- package/scripts/test-import-ui.mjs +5 -0
- package/scripts/test-preferences-persist.mjs +5 -0
- package/scripts/test-upgrade-from-published.mjs +226 -0
- package/scripts/verify-mac-build.sh +153 -0
- package/scripts/verify-windows-build.ps1 +15 -0
- package/server.json +3 -3
- package/skills/README.md +42 -0
- package/skills/ssh-incident/SKILL.md +55 -0
- package/skills/ssh-operations/SKILL.md +62 -0
- package/skills/ssh-restricted/SKILL.md +57 -0
- package/src/agent-clients.js +482 -0
- package/src/approval.js +291 -0
- package/src/audit.js +11 -1
- package/src/command-log.js +162 -0
- package/src/config-loader.js +119 -4
- package/src/config-paths.js +101 -0
- package/src/control-plane.js +2730 -0
- package/src/desktop-install.js +747 -0
- package/src/index.js +179 -213
- package/src/live-stream.js +261 -0
- package/src/saved-commands.js +150 -0
- package/src/secret-store.js +573 -0
- package/src/server-aliases.js +8 -7
- package/src/server-config-manager.js +33 -7
- package/src/server-export.js +106 -0
- package/src/server-groups.js +82 -21
- package/src/server-import.js +477 -0
- package/src/shell-quote.js +9 -2
- package/src/ssh-connection.js +155 -0
- package/src/ssh-manager.js +186 -13
- package/src/tunnel-manager.js +79 -0
- package/src/vault-recovery.js +206 -0
- package/src/xlsx.js +322 -0
- package/docs/images/social-preview.png +0 -0
- package/docs/images/social-preview@2x.png +0 -0
- package/docs/images/ssh-manager-cli-menu.png +0 -0
package/src/index.js
CHANGED
|
@@ -3,11 +3,14 @@
|
|
|
3
3
|
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
|
|
4
4
|
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
|
|
5
5
|
import { z } from 'zod';
|
|
6
|
-
import SSHManager from './ssh-manager.js';
|
|
6
|
+
import SSHManager, { rsyncAgentAnnouncement } from './ssh-manager.js';
|
|
7
|
+
import { connectSSH, connectServer } from './ssh-connection.js';
|
|
7
8
|
import * as dotenv from 'dotenv';
|
|
8
9
|
import fs from 'fs';
|
|
9
10
|
import path from 'path';
|
|
10
|
-
import
|
|
11
|
+
import { AsyncLocalStorage } from 'node:async_hooks';
|
|
12
|
+
import { isDeepStrictEqual } from 'node:util';
|
|
13
|
+
import { envFileChoice, envFileProblem, expandHomePath } from './config-paths.js';
|
|
11
14
|
import { fileURLToPath } from 'url';
|
|
12
15
|
import { ServerConfigManager } from './server-config-manager.js';
|
|
13
16
|
import {
|
|
@@ -147,38 +150,19 @@ import {
|
|
|
147
150
|
} from './database-manager.js';
|
|
148
151
|
import { loadToolConfig, isToolEnabled } from './tool-config-manager.js';
|
|
149
152
|
import { evaluatePolicy } from './policy.js';
|
|
153
|
+
import { needsApproval, isControlPlaneListening, requestDecision, buildRequest, isApprovalExempt, isReadOnlyAction, HANDLER_GATED_TOOLS } from './approval.js';
|
|
150
154
|
import { shellQuote, shellPath, safeInteger } from './shell-quote.js';
|
|
151
|
-
import {
|
|
155
|
+
import { openStream } from './live-stream.js';
|
|
156
|
+
import { auditLog, sanitize } from './audit.js';
|
|
152
157
|
|
|
153
158
|
const __filename = fileURLToPath(import.meta.url);
|
|
154
159
|
const __dirname = path.dirname(__filename);
|
|
155
160
|
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
//
|
|
159
|
-
//
|
|
160
|
-
|
|
161
|
-
// 5. __dirname/../.env (backward compat for local installs)
|
|
162
|
-
function resolveEnvFilePath() {
|
|
163
|
-
if (process.env.SSH_ENV_PATH) {
|
|
164
|
-
return process.env.SSH_ENV_PATH;
|
|
165
|
-
}
|
|
166
|
-
const sshManagerHome = process.env.SSH_MANAGER_HOME || path.join(os.homedir(), '.ssh-manager');
|
|
167
|
-
const candidates = [
|
|
168
|
-
path.join(sshManagerHome, '.env'),
|
|
169
|
-
path.join(process.cwd(), '.env'),
|
|
170
|
-
path.join(os.homedir(), '.env'),
|
|
171
|
-
path.join(__dirname, '..', '.env'),
|
|
172
|
-
];
|
|
173
|
-
for (const candidate of candidates) {
|
|
174
|
-
if (fs.existsSync(candidate)) {
|
|
175
|
-
return candidate;
|
|
176
|
-
}
|
|
177
|
-
}
|
|
178
|
-
return path.join(process.cwd(), '.env');
|
|
179
|
-
}
|
|
180
|
-
|
|
181
|
-
const envFilePath = resolveEnvFilePath();
|
|
161
|
+
const envChoice = envFileChoice({ projectRoot: path.join(__dirname, '..') });
|
|
162
|
+
const envFilePath = envChoice.path;
|
|
163
|
+
// Said at startup and repeated wherever a missing server would otherwise be
|
|
164
|
+
// the only clue: an empty configuration used to fail without a word (#90).
|
|
165
|
+
const envProblem = envFileProblem(envChoice);
|
|
182
166
|
const envFile = dotenv.config({ path: envFilePath, processEnv: {} });
|
|
183
167
|
const envFileValues = envFile.parsed || {};
|
|
184
168
|
|
|
@@ -193,6 +177,8 @@ logger.info('MCP SSH Manager starting', {
|
|
|
193
177
|
envFilePath
|
|
194
178
|
});
|
|
195
179
|
|
|
180
|
+
if (envProblem) logger.warn(envProblem);
|
|
181
|
+
|
|
196
182
|
// Load SSH server configuration
|
|
197
183
|
const serverConfigManager = new ServerConfigManager({
|
|
198
184
|
envPath: envFilePath,
|
|
@@ -254,10 +240,16 @@ const WRAPPED_COMMAND_TIMEOUT_GRACE_MS = 5000;
|
|
|
254
240
|
// Map to track proxy jump dependencies (target -> jump server)
|
|
255
241
|
const jumpDependencies = new Map();
|
|
256
242
|
|
|
257
|
-
//
|
|
243
|
+
// Tunnels own independent transports. Retain their original configuration for
|
|
244
|
+
// local lookup and disposal even if the vault is removed or becomes unreadable.
|
|
245
|
+
const tunnelConnections = new Map();
|
|
246
|
+
|
|
247
|
+
// One immutable configuration snapshot per tool invocation: a vault edit while
|
|
248
|
+
// a decision is pending must not redirect the approved action to another host.
|
|
249
|
+
const toolContext = new AsyncLocalStorage();
|
|
250
|
+
|
|
258
251
|
async function loadServerConfig() {
|
|
259
|
-
|
|
260
|
-
return serverConfigManager.getServers();
|
|
252
|
+
return toolContext.getStore()?.servers || serverConfigManager.getServers();
|
|
261
253
|
}
|
|
262
254
|
|
|
263
255
|
// ── Per-server security policy plumbing (v3.5.0+) ──────────────────────────────
|
|
@@ -269,22 +261,20 @@ async function loadServerConfig() {
|
|
|
269
261
|
// absent — so pre-v3.5.0 configs see zero behavior change.
|
|
270
262
|
|
|
271
263
|
async function getServerConfig(serverName) {
|
|
272
|
-
if (!serverName) return null;
|
|
273
264
|
const servers = await loadServerConfig();
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
const name = resolveServerName(String(serverName), servers);
|
|
280
|
-
return (name && servers[String(name).toLowerCase()]) || null;
|
|
265
|
+
const name = serverName && resolveServerName(String(serverName), servers);
|
|
266
|
+
if (!name) {
|
|
267
|
+
throw new Error(`Server "${serverName}" not found${envProblem && !Object.keys(servers).length ? ` (${envProblem})` : ''}`);
|
|
268
|
+
}
|
|
269
|
+
return servers[name];
|
|
281
270
|
}
|
|
282
271
|
|
|
283
272
|
// Apply policy + audit a denial in one shot. Returns null when allowed; returns
|
|
284
273
|
// an MCP error response object when denied (handler should `return` it directly).
|
|
285
274
|
async function applyServerPolicy(serverName, toolName, args, command) {
|
|
286
275
|
const serverConfig = await getServerConfig(serverName);
|
|
287
|
-
const
|
|
276
|
+
const readOnlyAction = isReadOnlyAction(toolName, args);
|
|
277
|
+
const policy = evaluatePolicy(serverConfig, readOnlyAction ? `${toolName}:read` : toolName, command);
|
|
288
278
|
if (!policy.allowed) {
|
|
289
279
|
auditLog(serverConfig, toolName, args, policy);
|
|
290
280
|
return {
|
|
@@ -303,6 +293,28 @@ async function applyServerPolicy(serverName, toolName, args, command) {
|
|
|
303
293
|
isError: true,
|
|
304
294
|
};
|
|
305
295
|
}
|
|
296
|
+
|
|
297
|
+
// Servers without approval retain the headless v3 path. Once approval is
|
|
298
|
+
// enabled, an unavailable interface cannot count as the operator saying yes.
|
|
299
|
+
if (needsApproval(serverConfig, readOnlyAction ? `${toolName}:read` : toolName, command)) {
|
|
300
|
+
const decision = isControlPlaneListening()
|
|
301
|
+
? await requestDecision(buildRequest(serverConfig, toolName, sanitize(args), command))
|
|
302
|
+
: { decision: 'deny', source: 'unavailable', reason: 'Approval is required; start ssh-manager control or the desktop app' };
|
|
303
|
+
auditLog(serverConfig, toolName, args, {
|
|
304
|
+
allowed: decision.decision === 'allow',
|
|
305
|
+
reason: `approval ${decision.decision} (${decision.source})${decision.reason ? `: ${decision.reason}` : ''}`,
|
|
306
|
+
});
|
|
307
|
+
if (decision.decision !== 'allow') {
|
|
308
|
+
return {
|
|
309
|
+
content: [{ type: 'text', text: formatJSONResponse({
|
|
310
|
+
server: serverConfig.name, tool: toolName, success: false,
|
|
311
|
+
error: `Approval denied${decision.reason ? `: ${decision.reason}` : ''}`, code: -3,
|
|
312
|
+
}) }],
|
|
313
|
+
isError: true,
|
|
314
|
+
};
|
|
315
|
+
}
|
|
316
|
+
}
|
|
317
|
+
|
|
306
318
|
return null;
|
|
307
319
|
}
|
|
308
320
|
|
|
@@ -322,7 +334,10 @@ async function auditOk(serverName, toolName, args, executionResult) {
|
|
|
322
334
|
* @param {number} [timeoutMs]
|
|
323
335
|
*/
|
|
324
336
|
async function execCommandWithTimeout(ssh, command, options = {}, timeoutMs = 30000) {
|
|
325
|
-
// Pass through rawCommand and platform if specified
|
|
337
|
+
// Pass through rawCommand and platform if specified. onStdout/onStderr ride
|
|
338
|
+
// along in otherOptions to SSHManager.execCommand, which calls them as output
|
|
339
|
+
// arrives — that is what makes live streaming possible without a second
|
|
340
|
+
// execution path.
|
|
326
341
|
const { rawCommand, platform = 'linux', ...otherOptions } = options;
|
|
327
342
|
|
|
328
343
|
// Windows targets: encode the command as PowerShell -EncodedCommand (UTF-16
|
|
@@ -438,6 +453,14 @@ function setupKeepalive(serverName, ssh) {
|
|
|
438
453
|
function closeConnection(serverName) {
|
|
439
454
|
const normalizedName = serverName.toLowerCase();
|
|
440
455
|
|
|
456
|
+
// Dependants and interactive sessions hold the old transport too.
|
|
457
|
+
for (const [dependent, jump] of [...jumpDependencies]) {
|
|
458
|
+
if (jump === normalizedName) closeConnection(dependent);
|
|
459
|
+
}
|
|
460
|
+
for (const session of listSessions()) {
|
|
461
|
+
if (session.server === normalizedName) closeSession(session.id);
|
|
462
|
+
}
|
|
463
|
+
|
|
441
464
|
// Clear keepalive interval
|
|
442
465
|
if (keepaliveIntervals.has(normalizedName)) {
|
|
443
466
|
clearInterval(keepaliveIntervals.get(normalizedName));
|
|
@@ -460,6 +483,17 @@ function closeConnection(serverName) {
|
|
|
460
483
|
logger.logConnection(serverName, 'closed');
|
|
461
484
|
}
|
|
462
485
|
|
|
486
|
+
function openTunnelServers() {
|
|
487
|
+
return Object.fromEntries(listTunnels().map(tunnel =>
|
|
488
|
+
[tunnel.server, tunnelConnections.get(tunnel.id)?.config || {}]));
|
|
489
|
+
}
|
|
490
|
+
|
|
491
|
+
function disposeTunnelConnection(tunnelId) {
|
|
492
|
+
const ssh = tunnelConnections.get(tunnelId);
|
|
493
|
+
tunnelConnections.delete(tunnelId);
|
|
494
|
+
ssh?.dispose();
|
|
495
|
+
}
|
|
496
|
+
|
|
463
497
|
// Clean up old connections
|
|
464
498
|
function cleanupOldConnections() {
|
|
465
499
|
const now = Date.now();
|
|
@@ -471,56 +505,13 @@ function cleanupOldConnections() {
|
|
|
471
505
|
}
|
|
472
506
|
}
|
|
473
507
|
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
const
|
|
480
|
-
|
|
481
|
-
const cmd = proxyCommand.replace(/%h/g, host).replace(/%p/g, port.toString());
|
|
482
|
-
|
|
483
|
-
return new Promise((resolve, reject) => {
|
|
484
|
-
const child = spawn(cmd, {
|
|
485
|
-
shell: true,
|
|
486
|
-
stdio: ['pipe', 'pipe', 'pipe']
|
|
487
|
-
});
|
|
488
|
-
|
|
489
|
-
// Cast: Node accepts a {readable, writable} pair here, but the bundled
|
|
490
|
-
// types only model the stream/iterable overloads.
|
|
491
|
-
const socket = Duplex.from(/** @type {any} */ ({
|
|
492
|
-
readable: child.stdout,
|
|
493
|
-
writable: child.stdin,
|
|
494
|
-
allowHalfOpen: false
|
|
495
|
-
}));
|
|
496
|
-
|
|
497
|
-
// Forward proxy stderr to the MCP server's stderr for debugging
|
|
498
|
-
child.stderr.on('data', (chunk) => {
|
|
499
|
-
process.stderr.write(`[proxy-command] ${chunk}`);
|
|
500
|
-
});
|
|
501
|
-
|
|
502
|
-
let settled = false;
|
|
503
|
-
const settle = (fn, arg) => {
|
|
504
|
-
if (settled) return;
|
|
505
|
-
settled = true;
|
|
506
|
-
fn(arg);
|
|
507
|
-
};
|
|
508
|
-
|
|
509
|
-
socket.on('close', () => {
|
|
510
|
-
if (!child.killed) child.kill();
|
|
511
|
-
});
|
|
512
|
-
|
|
513
|
-
child.on('error', (err) => settle(reject, err));
|
|
514
|
-
child.on('spawn', () => settle(resolve, socket));
|
|
515
|
-
child.on('exit', (code, signal) => {
|
|
516
|
-
// Only surface unexpected exits — a kill() after a successful connection is normal.
|
|
517
|
-
if (!settled && code !== 0) {
|
|
518
|
-
settle(reject, new Error(`Proxy command exited with code ${code}${signal ? ` (${signal})` : ''}`));
|
|
519
|
-
} else if (settled && code !== 0 && !signal && !socket.destroyed) {
|
|
520
|
-
socket.destroy(new Error(`Proxy command exited with code ${code}`));
|
|
521
|
-
}
|
|
522
|
-
});
|
|
523
|
-
});
|
|
508
|
+
function connectionMatchesConfig(name, servers, seen = new Set()) {
|
|
509
|
+
if (seen.has(name)) return false;
|
|
510
|
+
seen.add(name);
|
|
511
|
+
const ssh = connections.get(name);
|
|
512
|
+
if (!ssh || !isDeepStrictEqual(ssh.config, servers[name])) return false;
|
|
513
|
+
const jump = jumpDependencies.get(name);
|
|
514
|
+
return !jump || connectionMatchesConfig(jump, servers, seen);
|
|
524
515
|
}
|
|
525
516
|
|
|
526
517
|
// Get or create SSH connection with reconnection support
|
|
@@ -544,6 +535,13 @@ async function getConnection(serverName) {
|
|
|
544
535
|
}
|
|
545
536
|
|
|
546
537
|
const normalizedName = resolvedName;
|
|
538
|
+
const serverConfig = servers[normalizedName];
|
|
539
|
+
|
|
540
|
+
// A renamed host, credential, or jump configuration invalidates the pool.
|
|
541
|
+
// Compare objects, never print or persist a credential-bearing signature.
|
|
542
|
+
if (connections.has(normalizedName) && !connectionMatchesConfig(normalizedName, servers)) {
|
|
543
|
+
closeConnection(normalizedName);
|
|
544
|
+
}
|
|
547
545
|
|
|
548
546
|
// Check if we have an existing connection
|
|
549
547
|
if (connections.has(normalizedName)) {
|
|
@@ -564,56 +562,11 @@ async function getConnection(serverName) {
|
|
|
564
562
|
}
|
|
565
563
|
|
|
566
564
|
// Create new connection
|
|
567
|
-
const serverConfig = servers[normalizedName];
|
|
568
565
|
const ssh = new SSHManager(serverConfig);
|
|
569
566
|
|
|
570
567
|
try {
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
// Validate jump server exists
|
|
575
|
-
if (!servers[jumpServerName]) {
|
|
576
|
-
throw new Error(
|
|
577
|
-
`Proxy jump server "${serverConfig.proxyJump}" not found. ` +
|
|
578
|
-
`Available servers: ${Object.keys(servers).join(', ')}`
|
|
579
|
-
);
|
|
580
|
-
}
|
|
581
|
-
|
|
582
|
-
// Detect circular proxy jumps
|
|
583
|
-
const visited = new Set([normalizedName]);
|
|
584
|
-
let current = jumpServerName;
|
|
585
|
-
while (current) {
|
|
586
|
-
if (visited.has(current)) {
|
|
587
|
-
throw new Error(`Circular proxy jump detected: ${[...visited, current].join(' -> ')}`);
|
|
588
|
-
}
|
|
589
|
-
visited.add(current);
|
|
590
|
-
current = servers[current]?.proxyJump?.toLowerCase() || null;
|
|
591
|
-
}
|
|
592
|
-
|
|
593
|
-
// Connect to jump server (recursive — handles chained jumps)
|
|
594
|
-
const jumpSSH = await getConnection(serverConfig.proxyJump);
|
|
595
|
-
|
|
596
|
-
// Create forwarded stream through the jump server
|
|
597
|
-
const stream = await jumpSSH.forwardOut(
|
|
598
|
-
'127.0.0.1', 0,
|
|
599
|
-
serverConfig.host, serverConfig.port || 22
|
|
600
|
-
);
|
|
601
|
-
|
|
602
|
-
// Connect target through the forwarded stream
|
|
603
|
-
await ssh.connect({ sock: stream });
|
|
604
|
-
jumpDependencies.set(normalizedName, jumpServerName);
|
|
605
|
-
ssh.jumpConnection = jumpSSH;
|
|
606
|
-
} else if (serverConfig.proxyCommand) {
|
|
607
|
-
// Create socket via proxy command (e.g., SOCKS5 proxy)
|
|
608
|
-
const socket = await createProxyCommandSocket(
|
|
609
|
-
serverConfig.proxyCommand,
|
|
610
|
-
serverConfig.host,
|
|
611
|
-
serverConfig.port || 22
|
|
612
|
-
);
|
|
613
|
-
await ssh.connect({ sock: socket });
|
|
614
|
-
} else {
|
|
615
|
-
await ssh.connect();
|
|
616
|
-
}
|
|
568
|
+
const jumpName = await connectSSH(ssh, servers, { resolveJump: getConnection });
|
|
569
|
+
if (jumpName) jumpDependencies.set(normalizedName, jumpName);
|
|
617
570
|
|
|
618
571
|
connections.set(normalizedName, ssh);
|
|
619
572
|
connectionTimestamps.set(normalizedName, Date.now());
|
|
@@ -674,9 +627,33 @@ logger.info('MCP Server initialized', { version: serverVersion });
|
|
|
674
627
|
*/
|
|
675
628
|
function registerToolConditional(toolName, schema, handler) {
|
|
676
629
|
if (isToolEnabled(toolName)) {
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
|
|
630
|
+
const guarded = async (args, extra) => {
|
|
631
|
+
// These handlers inspect local state or release existing resources. They
|
|
632
|
+
// must remain usable during vault recovery; handlers that actually read
|
|
633
|
+
// configuration (such as server listing) still load it explicitly.
|
|
634
|
+
if (isApprovalExempt(toolName, args)) return handler(args, extra);
|
|
635
|
+
const servers = await serverConfigManager.getServers();
|
|
636
|
+
return toolContext.run({ servers }, async () => {
|
|
637
|
+
if (HANDLER_GATED_TOOLS.has(toolName)) {
|
|
638
|
+
return handler(args, extra);
|
|
639
|
+
}
|
|
640
|
+
// Fail closed for newly added remote tools with an unresolved target.
|
|
641
|
+
// Local tools must be explicitly exempted above.
|
|
642
|
+
try {
|
|
643
|
+
const config = await getServerConfig(args.server);
|
|
644
|
+
const canonicalArgs = { ...args, server: config.name };
|
|
645
|
+
const command = toolName === 'ssh_execute'
|
|
646
|
+
? expandCommandAlias(args.command) : args.command;
|
|
647
|
+
const denied = await applyServerPolicy(config.name, toolName, canonicalArgs, command);
|
|
648
|
+
if (denied) return denied;
|
|
649
|
+
return handler(canonicalArgs, extra);
|
|
650
|
+
} catch (error) {
|
|
651
|
+
return { isError: true, content: [{ type: 'text', text: error.message }] };
|
|
652
|
+
}
|
|
653
|
+
});
|
|
654
|
+
};
|
|
655
|
+
// The runtime zod schema validates args before this shared guard runs.
|
|
656
|
+
server.registerTool(toolName, schema, /** @type {any} */ (guarded));
|
|
680
657
|
logger.debug(`Registered tool: ${toolName}`);
|
|
681
658
|
} else {
|
|
682
659
|
logger.debug(`Skipped disabled tool: ${toolName}`);
|
|
@@ -703,8 +680,6 @@ registerToolConditional(
|
|
|
703
680
|
// regex by hiding a destructive command behind an alias.
|
|
704
681
|
const expandedCommand = expandCommandAlias(command);
|
|
705
682
|
|
|
706
|
-
const denied = await applyServerPolicy(serverName, 'ssh_execute', { command, cwd }, expandedCommand);
|
|
707
|
-
if (denied) return denied;
|
|
708
683
|
|
|
709
684
|
try {
|
|
710
685
|
const ssh = await getConnection(serverName);
|
|
@@ -740,7 +715,21 @@ registerToolConditional(
|
|
|
740
715
|
// Log command execution
|
|
741
716
|
const startTime = logger.logCommand(serverName, fullCommand, workingDir);
|
|
742
717
|
|
|
743
|
-
|
|
718
|
+
// Mirror the command to the control plane while it runs, when one is
|
|
719
|
+
// watching. openStream returns null otherwise, and every call below is
|
|
720
|
+
// optional-chained — so this costs one stat() when nobody is looking.
|
|
721
|
+
const live = openStream(serverName, fullCommand);
|
|
722
|
+
const result = await execCommandWithTimeout(
|
|
723
|
+
ssh,
|
|
724
|
+
fullCommand,
|
|
725
|
+
{
|
|
726
|
+
platform,
|
|
727
|
+
onStdout: live ? chunk => live.write('stdout', chunk) : undefined,
|
|
728
|
+
onStderr: live ? chunk => live.write('stderr', chunk) : undefined,
|
|
729
|
+
},
|
|
730
|
+
cappedTimeout
|
|
731
|
+
);
|
|
732
|
+
live?.end(result.code ?? null);
|
|
744
733
|
|
|
745
734
|
// Log command result
|
|
746
735
|
logger.logCommandResult(serverName, fullCommand, startTime, result);
|
|
@@ -817,8 +806,6 @@ registerToolConditional(
|
|
|
817
806
|
}
|
|
818
807
|
},
|
|
819
808
|
async ({ server: serverName, localPath, remotePath }) => {
|
|
820
|
-
const denied = await applyServerPolicy(serverName, 'ssh_upload', { localPath, remotePath });
|
|
821
|
-
if (denied) return denied;
|
|
822
809
|
|
|
823
810
|
try {
|
|
824
811
|
const ssh = await getConnection(serverName);
|
|
@@ -935,8 +922,6 @@ registerToolConditional(
|
|
|
935
922
|
}
|
|
936
923
|
},
|
|
937
924
|
async ({ server: serverName, source, destination, exclude = [], dryRun = false, delete: deleteFiles = false, compress = true, verbose = false, checksum = false, timeout = 30000 }) => {
|
|
938
|
-
const denied = await applyServerPolicy(serverName, 'ssh_sync', { source, destination, dryRun, delete: deleteFiles });
|
|
939
|
-
if (denied) return denied;
|
|
940
925
|
|
|
941
926
|
try {
|
|
942
927
|
await getConnection(serverName);
|
|
@@ -1035,7 +1020,7 @@ registerToolConditional(
|
|
|
1035
1020
|
sshOptions.push('-o StrictHostKeyChecking=accept-new'); // Accept new keys, reject changed ones
|
|
1036
1021
|
sshOptions.push('-o ConnectTimeout=10'); // Connection timeout
|
|
1037
1022
|
|
|
1038
|
-
const keyPath = serverConfig.keyPath
|
|
1023
|
+
const keyPath = expandHomePath(serverConfig.keyPath);
|
|
1039
1024
|
sshOptions.push(`-i ${keyPath}`);
|
|
1040
1025
|
} else {
|
|
1041
1026
|
// With sshpass, we don't use BatchMode
|
|
@@ -1045,6 +1030,11 @@ registerToolConditional(
|
|
|
1045
1030
|
|
|
1046
1031
|
// port is a number (ConfigLoader parseInt's it), so comparing against the
|
|
1047
1032
|
// string '22' never matched and every server got an explicit -p 22.
|
|
1033
|
+
// Announce the agent to this host when asked to, as the ssh2 channels
|
|
1034
|
+
// do; see rsyncAgentAnnouncement() for why this is SendEnv.
|
|
1035
|
+
const agentAnnouncement = rsyncAgentAnnouncement(serverConfig);
|
|
1036
|
+
sshOptions.push(...agentAnnouncement.sshOptions);
|
|
1037
|
+
|
|
1048
1038
|
if (serverConfig.port && serverConfig.port !== 22) {
|
|
1049
1039
|
sshOptions.push(`-p ${serverConfig.port}`);
|
|
1050
1040
|
}
|
|
@@ -1070,7 +1060,7 @@ registerToolConditional(
|
|
|
1070
1060
|
// Build command based on authentication method
|
|
1071
1061
|
let rsyncCommand;
|
|
1072
1062
|
let rsyncArgs = [];
|
|
1073
|
-
let processEnv = { ...process.env };
|
|
1063
|
+
let processEnv = { ...process.env, ...agentAnnouncement.env };
|
|
1074
1064
|
|
|
1075
1065
|
if (serverConfig.password) {
|
|
1076
1066
|
// Use sshpass for password authentication
|
|
@@ -1272,8 +1262,6 @@ registerToolConditional(
|
|
|
1272
1262
|
// mode, which is exactly why it must consult the policy layer: without this
|
|
1273
1263
|
// it was a way to run commands on a server the operator locked down
|
|
1274
1264
|
// (GHSA-m793-whw6-f537).
|
|
1275
|
-
const denied = await applyServerPolicy(serverName, 'ssh_tail', { file, lines, follow, grep });
|
|
1276
|
-
if (denied) return denied;
|
|
1277
1265
|
|
|
1278
1266
|
try {
|
|
1279
1267
|
const ssh = await getConnection(serverName);
|
|
@@ -1707,6 +1695,11 @@ registerToolConditional(
|
|
|
1707
1695
|
async ({ session: sessionId, command, timeout = 30000 }) => {
|
|
1708
1696
|
try {
|
|
1709
1697
|
const session = getSession(sessionId);
|
|
1698
|
+
const currentConfig = await getServerConfig(session.serverName);
|
|
1699
|
+
if (!isDeepStrictEqual(session.ssh.config, currentConfig)) {
|
|
1700
|
+
closeSession(sessionId);
|
|
1701
|
+
throw new Error('Server configuration changed; start a new session');
|
|
1702
|
+
}
|
|
1710
1703
|
|
|
1711
1704
|
// Resolve the session's underlying server to its policy.
|
|
1712
1705
|
const denied = await applyServerPolicy(session.serverName, 'ssh_session_send', { session: sessionId, command }, command);
|
|
@@ -1947,6 +1940,7 @@ registerToolConditional(
|
|
|
1947
1940
|
const result = await executeOnGroup(
|
|
1948
1941
|
groupName,
|
|
1949
1942
|
async (serverName) => {
|
|
1943
|
+
serverName = (await getServerConfig(serverName)).name;
|
|
1950
1944
|
// Per-server policy: each server in the group is evaluated independently.
|
|
1951
1945
|
// A server in readonly/restricted mode refuses the command; others
|
|
1952
1946
|
// execute normally. Refusal is surfaced as a per-server failure rather
|
|
@@ -2234,14 +2228,15 @@ registerToolConditional(
|
|
|
2234
2228
|
description: config.description || ''
|
|
2235
2229
|
}));
|
|
2236
2230
|
|
|
2237
|
-
|
|
2238
|
-
|
|
2239
|
-
|
|
2240
|
-
|
|
2241
|
-
|
|
2242
|
-
|
|
2243
|
-
|
|
2244
|
-
};
|
|
2231
|
+
const content = [
|
|
2232
|
+
{
|
|
2233
|
+
type: 'text',
|
|
2234
|
+
text: JSON.stringify(serverInfo, null, 2),
|
|
2235
|
+
},
|
|
2236
|
+
];
|
|
2237
|
+
// The list stays the first item, unchanged, for anything that parses it.
|
|
2238
|
+
if (envProblem && !serverInfo.length) content.push({ type: 'text', text: `No server loaded: ${envProblem}.` });
|
|
2239
|
+
return { content };
|
|
2245
2240
|
}
|
|
2246
2241
|
);
|
|
2247
2242
|
|
|
@@ -2266,11 +2261,6 @@ registerToolConditional(
|
|
|
2266
2261
|
}
|
|
2267
2262
|
},
|
|
2268
2263
|
async ({ server, files, options = {} }) => {
|
|
2269
|
-
const denied = await applyServerPolicy(server, 'ssh_deploy', {
|
|
2270
|
-
files: files.map((f) => ({ local: f.local, remote: f.remote })),
|
|
2271
|
-
options,
|
|
2272
|
-
});
|
|
2273
|
-
if (denied) return denied;
|
|
2274
2264
|
|
|
2275
2265
|
try {
|
|
2276
2266
|
const ssh = await getConnection(server);
|
|
@@ -2378,8 +2368,6 @@ registerToolConditional(
|
|
|
2378
2368
|
// ssh_execute_sudo is in READONLY_BLOCKED_TOOLS, so readonly mode blocks
|
|
2379
2369
|
// it at the tool level. In restricted mode the command itself is matched
|
|
2380
2370
|
// against ALLOW/DENY patterns.
|
|
2381
|
-
const denied = await applyServerPolicy(server, 'ssh_execute_sudo', { command, cwd }, command);
|
|
2382
|
-
if (denied) return denied;
|
|
2383
2371
|
|
|
2384
2372
|
try {
|
|
2385
2373
|
const ssh = await getConnection(server);
|
|
@@ -2751,7 +2739,7 @@ registerToolConditional(
|
|
|
2751
2739
|
for (const [serverName, ssh] of connections.entries()) {
|
|
2752
2740
|
const timestamp = connectionTimestamps.get(serverName);
|
|
2753
2741
|
const ageMinutes = Math.floor((now - timestamp) / 1000 / 60);
|
|
2754
|
-
const isValid =
|
|
2742
|
+
const isValid = ssh.connected;
|
|
2755
2743
|
|
|
2756
2744
|
activeConnections.push({
|
|
2757
2745
|
server: serverName,
|
|
@@ -2801,7 +2789,8 @@ registerToolConditional(
|
|
|
2801
2789
|
throw new Error('Server name is required for disconnect action');
|
|
2802
2790
|
}
|
|
2803
2791
|
|
|
2804
|
-
|
|
2792
|
+
const openServers = Object.fromEntries([...connections].map(([name, ssh]) => [name, ssh.config]));
|
|
2793
|
+
closeConnection(resolveServerName(server, openServers) || server.toLowerCase());
|
|
2805
2794
|
return {
|
|
2806
2795
|
content: [
|
|
2807
2796
|
{
|
|
@@ -2818,7 +2807,7 @@ registerToolConditional(
|
|
|
2818
2807
|
|
|
2819
2808
|
// Also check and remove dead connections
|
|
2820
2809
|
for (const [serverName, ssh] of connections.entries()) {
|
|
2821
|
-
const isValid =
|
|
2810
|
+
const isValid = ssh.connected;
|
|
2822
2811
|
if (!isValid) {
|
|
2823
2812
|
closeConnection(serverName);
|
|
2824
2813
|
}
|
|
@@ -2871,9 +2860,7 @@ registerToolConditional(
|
|
|
2871
2860
|
throw new Error(`Server "${server}" not found`);
|
|
2872
2861
|
}
|
|
2873
2862
|
|
|
2874
|
-
const
|
|
2875
|
-
const ssh = new SSHManager(serverConfig);
|
|
2876
|
-
await ssh.connect();
|
|
2863
|
+
const ssh = await connectServer(resolvedName, servers);
|
|
2877
2864
|
|
|
2878
2865
|
const config = {
|
|
2879
2866
|
type,
|
|
@@ -2883,7 +2870,14 @@ registerToolConditional(
|
|
|
2883
2870
|
remotePort
|
|
2884
2871
|
};
|
|
2885
2872
|
|
|
2886
|
-
|
|
2873
|
+
let tunnel;
|
|
2874
|
+
try {
|
|
2875
|
+
tunnel = await createTunnel(resolvedName, ssh, config);
|
|
2876
|
+
} catch (error) {
|
|
2877
|
+
ssh.dispose();
|
|
2878
|
+
throw error;
|
|
2879
|
+
}
|
|
2880
|
+
tunnelConnections.set(tunnel.id, ssh);
|
|
2887
2881
|
|
|
2888
2882
|
let output = '✅ SSH tunnel created\n';
|
|
2889
2883
|
output += `ID: ${tunnel.id}\n`;
|
|
@@ -2942,11 +2936,10 @@ registerToolConditional(
|
|
|
2942
2936
|
},
|
|
2943
2937
|
async ({ server }) => {
|
|
2944
2938
|
try {
|
|
2945
|
-
const servers = await loadServerConfig();
|
|
2946
2939
|
let resolvedName = null;
|
|
2947
2940
|
|
|
2948
2941
|
if (server) {
|
|
2949
|
-
resolvedName = resolveServerName(server,
|
|
2942
|
+
resolvedName = resolveServerName(server, openTunnelServers());
|
|
2950
2943
|
if (!resolvedName) {
|
|
2951
2944
|
throw new Error(`Server "${server}" not found`);
|
|
2952
2945
|
}
|
|
@@ -3034,19 +3027,21 @@ registerToolConditional(
|
|
|
3034
3027
|
if (tunnelId) {
|
|
3035
3028
|
// Close specific tunnel
|
|
3036
3029
|
closeTunnel(tunnelId);
|
|
3030
|
+
disposeTunnelConnection(tunnelId);
|
|
3037
3031
|
output = `✅ Tunnel ${tunnelId} closed`;
|
|
3038
3032
|
|
|
3039
3033
|
logger.info('SSH tunnel closed', { id: tunnelId });
|
|
3040
3034
|
} else if (server) {
|
|
3041
3035
|
// Close all tunnels for server
|
|
3042
|
-
const
|
|
3043
|
-
const resolvedName = resolveServerName(server, servers);
|
|
3036
|
+
const resolvedName = resolveServerName(server, openTunnelServers());
|
|
3044
3037
|
|
|
3045
3038
|
if (!resolvedName) {
|
|
3046
3039
|
throw new Error(`Server "${server}" not found`);
|
|
3047
3040
|
}
|
|
3048
3041
|
|
|
3042
|
+
const open = listTunnels(resolvedName);
|
|
3049
3043
|
const count = closeServerTunnels(resolvedName);
|
|
3044
|
+
for (const tunnel of open) disposeTunnelConnection(tunnel.id);
|
|
3050
3045
|
output = `✅ Closed ${count} tunnel(s) for server ${resolvedName}`;
|
|
3051
3046
|
|
|
3052
3047
|
logger.info('Server tunnels closed', {
|
|
@@ -3088,20 +3083,13 @@ registerToolConditional(
|
|
|
3088
3083
|
autoAccept: z.boolean().optional().describe('Automatically accept new keys (use with caution)')
|
|
3089
3084
|
}
|
|
3090
3085
|
},
|
|
3091
|
-
async ({ action, server
|
|
3092
|
-
// Mutating actions (accept, remove) are blocked in readonly mode at the
|
|
3093
|
-
// tool level. Pure-read actions (verify, list, check) are allowed regardless,
|
|
3094
|
-
// so we only gate when the action would modify state.
|
|
3095
|
-
if (server && (action === 'accept' || action === 'remove')) {
|
|
3096
|
-
const denied = await applyServerPolicy(server, 'ssh_key_manage', { action, autoAccept });
|
|
3097
|
-
if (denied) return denied;
|
|
3098
|
-
}
|
|
3086
|
+
async ({ action, server }) => {
|
|
3099
3087
|
try {
|
|
3100
|
-
const servers = await loadServerConfig();
|
|
3101
3088
|
let resolvedName, serverConfig, host, port;
|
|
3102
3089
|
|
|
3103
3090
|
// Resolve server details for actions that need them
|
|
3104
3091
|
if (server && action !== 'list') {
|
|
3092
|
+
const servers = await loadServerConfig();
|
|
3105
3093
|
resolvedName = resolveServerName(server, servers);
|
|
3106
3094
|
if (!resolvedName) {
|
|
3107
3095
|
throw new Error(`Server "${server}" not found`);
|
|
@@ -3278,9 +3266,10 @@ registerToolConditional(
|
|
|
3278
3266
|
if (knownHosts.length === 0) {
|
|
3279
3267
|
output += 'No hosts in known_hosts file\n';
|
|
3280
3268
|
} else {
|
|
3281
|
-
//
|
|
3269
|
+
// Names are optional labels from the last loaded snapshot. Reading
|
|
3270
|
+
// known_hosts must not require unlocking or repairing the vault.
|
|
3282
3271
|
const serverMap = new Map();
|
|
3283
|
-
for (const [name, config] of Object.entries(servers)) {
|
|
3272
|
+
for (const [name, config] of Object.entries(serverConfigManager.servers)) {
|
|
3284
3273
|
const key = `${config.host}:${config.port || 22}`;
|
|
3285
3274
|
serverMap.set(key, name);
|
|
3286
3275
|
}
|
|
@@ -3454,8 +3443,6 @@ registerToolConditional(
|
|
|
3454
3443
|
}
|
|
3455
3444
|
},
|
|
3456
3445
|
async ({ server: serverName, type, name, database, dbUser, dbPassword, dbHost, dbPort, paths, exclude, backupDir, retention = 7, compress = true }) => {
|
|
3457
|
-
const denied = await applyServerPolicy(serverName, 'ssh_backup_create', { type, name, database, paths });
|
|
3458
|
-
if (denied) return denied;
|
|
3459
3446
|
|
|
3460
3447
|
try {
|
|
3461
3448
|
const ssh = await getConnection(serverName);
|
|
@@ -3741,8 +3728,6 @@ registerToolConditional(
|
|
|
3741
3728
|
}
|
|
3742
3729
|
},
|
|
3743
3730
|
async ({ server: serverName, backupId, database, dbUser, dbPassword, dbHost, dbPort, targetPath, backupDir }) => {
|
|
3744
|
-
const denied = await applyServerPolicy(serverName, 'ssh_backup_restore', { backupId, database, targetPath });
|
|
3745
|
-
if (denied) return denied;
|
|
3746
3731
|
|
|
3747
3732
|
try {
|
|
3748
3733
|
// Checked before anything connects: an ID that is not a plain file name
|
|
@@ -3862,8 +3847,6 @@ registerToolConditional(
|
|
|
3862
3847
|
}
|
|
3863
3848
|
},
|
|
3864
3849
|
async ({ server: serverName, schedule, type, name, database, paths, retention = 7 }) => {
|
|
3865
|
-
const denied = await applyServerPolicy(serverName, 'ssh_backup_schedule', { schedule, type, name, database, paths });
|
|
3866
|
-
if (denied) return denied;
|
|
3867
3850
|
|
|
3868
3851
|
try {
|
|
3869
3852
|
// The name becomes a file name, a cron comment and a find pattern, and
|
|
@@ -4089,8 +4072,6 @@ registerToolConditional(
|
|
|
4089
4072
|
async ({ server: serverName, services }) => {
|
|
4090
4073
|
// Read-only tools stay enabled under readonly/restricted, so they are the
|
|
4091
4074
|
// ones that most need the policy check (GHSA-m793-whw6-f537).
|
|
4092
|
-
const denied = await applyServerPolicy(serverName, 'ssh_service_status', { services });
|
|
4093
|
-
if (denied) return denied;
|
|
4094
4075
|
|
|
4095
4076
|
try {
|
|
4096
4077
|
const ssh = await getConnection(serverName);
|
|
@@ -4181,12 +4162,6 @@ registerToolConditional(
|
|
|
4181
4162
|
}
|
|
4182
4163
|
},
|
|
4183
4164
|
async ({ server: serverName, action, pid, signal = 'TERM', sortBy = 'cpu', limit = 20, filter }) => {
|
|
4184
|
-
// Only the `kill` action mutates remote state — gate just that branch so
|
|
4185
|
-
// operators on readonly servers can still `list` / `info` processes.
|
|
4186
|
-
if (action === 'kill') {
|
|
4187
|
-
const denied = await applyServerPolicy(serverName, 'ssh_process_manager', { action, pid, signal });
|
|
4188
|
-
if (denied) return denied;
|
|
4189
|
-
}
|
|
4190
4165
|
try {
|
|
4191
4166
|
const ssh = await getConnection(serverName);
|
|
4192
4167
|
|
|
@@ -4334,11 +4309,6 @@ registerToolConditional(
|
|
|
4334
4309
|
}
|
|
4335
4310
|
},
|
|
4336
4311
|
async ({ server: serverName, action, cpuThreshold, memoryThreshold, diskThreshold, enabled = true }) => {
|
|
4337
|
-
// `set` writes config on the remote; `get` and `check` are read-only.
|
|
4338
|
-
if (action === 'set') {
|
|
4339
|
-
const denied = await applyServerPolicy(serverName, 'ssh_alert_setup', { action, cpuThreshold, memoryThreshold, diskThreshold, enabled });
|
|
4340
|
-
if (denied) return denied;
|
|
4341
|
-
}
|
|
4342
4312
|
try {
|
|
4343
4313
|
const ssh = await getConnection(serverName);
|
|
4344
4314
|
const configPath = '/etc/ssh-manager-alerts.json';
|
|
@@ -4523,8 +4493,6 @@ registerToolConditional(
|
|
|
4523
4493
|
}
|
|
4524
4494
|
},
|
|
4525
4495
|
async ({ server: serverName, type, database, outputFile, dbUser, dbPassword, dbHost, dbPort, compress = true, tables }) => {
|
|
4526
|
-
const denied = await applyServerPolicy(serverName, 'ssh_db_dump', { type, database, outputFile, tables });
|
|
4527
|
-
if (denied) return denied;
|
|
4528
4496
|
|
|
4529
4497
|
try {
|
|
4530
4498
|
const ssh = await getConnection(serverName);
|
|
@@ -4637,8 +4605,6 @@ registerToolConditional(
|
|
|
4637
4605
|
}
|
|
4638
4606
|
},
|
|
4639
4607
|
async ({ server: serverName, type, database, inputFile, dbUser, dbPassword, dbHost, dbPort, drop = true }) => {
|
|
4640
|
-
const denied = await applyServerPolicy(serverName, 'ssh_db_import', { type, database, inputFile, drop });
|
|
4641
|
-
if (denied) return denied;
|
|
4642
4608
|
|
|
4643
4609
|
try {
|
|
4644
4610
|
const ssh = await getConnection(serverName);
|