mcp-ssh-manager 3.4.1 → 3.5.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/src/index.js CHANGED
@@ -160,6 +160,8 @@ import {
160
160
  getConnectionInfo
161
161
  } from './database-manager.js';
162
162
  import { loadToolConfig, isToolEnabled } from './tool-config-manager.js';
163
+ import { evaluatePolicy } from './policy.js';
164
+ import { auditLog } from './audit.js';
163
165
 
164
166
  const __filename = fileURLToPath(import.meta.url);
165
167
  const __dirname = path.dirname(__filename);
@@ -265,6 +267,52 @@ function loadServerConfig() {
265
267
  return servers;
266
268
  }
267
269
 
270
+ // ── Per-server security policy plumbing (v3.5.0+) ──────────────────────────────
271
+ //
272
+ // Wire any handler that mutates remote state (or executes arbitrary commands)
273
+ // through the helpers below. They are *always* safe to call: for any server
274
+ // without a security mode configured (default `unrestricted`), evaluatePolicy()
275
+ // early-returns { allowed: true } and auditLog() is a no-op when AUDIT_LOG is
276
+ // absent — so pre-v3.5.0 configs see zero behavior change.
277
+
278
+ function getServerConfig(serverName) {
279
+ if (!serverName) return null;
280
+ return servers[String(serverName).toLowerCase()] || null;
281
+ }
282
+
283
+ // Apply policy + audit a denial in one shot. Returns null when allowed; returns
284
+ // an MCP error response object when denied (handler should `return` it directly).
285
+ function applyServerPolicy(serverName, toolName, args, command) {
286
+ const serverConfig = getServerConfig(serverName);
287
+ const policy = evaluatePolicy(serverConfig, toolName, command);
288
+ if (!policy.allowed) {
289
+ auditLog(serverConfig, toolName, args, policy);
290
+ return {
291
+ content: [
292
+ {
293
+ type: 'text',
294
+ text: formatJSONResponse({
295
+ server: serverName,
296
+ tool: toolName,
297
+ success: false,
298
+ error: `Policy denied: ${policy.reason}`,
299
+ code: -2,
300
+ }),
301
+ },
302
+ ],
303
+ isError: true,
304
+ };
305
+ }
306
+ return null;
307
+ }
308
+
309
+ // Convenience for the success-path audit: handlers call this after execution to
310
+ // record the outcome. No-op when AUDIT_LOG is not configured.
311
+ function auditOk(serverName, toolName, args, executionResult) {
312
+ const serverConfig = getServerConfig(serverName);
313
+ auditLog(serverConfig, toolName, args, { allowed: true }, executionResult);
314
+ }
315
+
268
316
  // Execute command with timeout - using child_process timeout for real kill
269
317
  async function execCommandWithTimeout(ssh, command, options = {}, timeoutMs = 30000) {
270
318
  // Pass through rawCommand and platform if specified
@@ -617,12 +665,17 @@ registerToolConditional(
617
665
  async ({ server: serverName, command, cwd, timeout = TIMEOUTS.DEFAULT_COMMAND_TIMEOUT }) => {
618
666
  // Cap timeout at maximum allowed
619
667
  const cappedTimeout = Math.min(timeout, TIMEOUTS.MAX_COMMAND_TIMEOUT);
668
+
669
+ // Expand aliases BEFORE policy evaluation so the user can't bypass a DENY
670
+ // regex by hiding a destructive command behind an alias.
671
+ const expandedCommand = expandCommandAlias(command);
672
+
673
+ const denied = applyServerPolicy(serverName, 'ssh_execute', { command, cwd }, expandedCommand);
674
+ if (denied) return denied;
675
+
620
676
  try {
621
677
  const ssh = await getConnection(serverName);
622
678
 
623
- // Expand command aliases
624
- const expandedCommand = expandCommandAlias(command);
625
-
626
679
  // Execute hooks for bench commands
627
680
  if (expandedCommand.includes('bench update')) {
628
681
  await executeHook('pre-bench-update', {
@@ -672,6 +725,11 @@ registerToolConditional(
672
725
  const stdout = truncateOutput(result.stdout);
673
726
  const stderr = truncateOutput(result.stderr);
674
727
 
728
+ auditOk(serverName, 'ssh_execute', { command, cwd }, {
729
+ code: result.code,
730
+ success: result.code === 0,
731
+ });
732
+
675
733
  return {
676
734
  content: [
677
735
  {
@@ -688,6 +746,10 @@ registerToolConditional(
688
746
  ],
689
747
  };
690
748
  } catch (error) {
749
+ auditOk(serverName, 'ssh_execute', { command, cwd }, {
750
+ success: false,
751
+ error: error.message,
752
+ });
691
753
  logger.error('ssh_execute failed', {
692
754
  server: serverName,
693
755
  error: error.message
@@ -722,6 +784,9 @@ registerToolConditional(
722
784
  }
723
785
  },
724
786
  async ({ server: serverName, localPath, remotePath }) => {
787
+ const denied = applyServerPolicy(serverName, 'ssh_upload', { localPath, remotePath });
788
+ if (denied) return denied;
789
+
725
790
  try {
726
791
  const ssh = await getConnection(serverName);
727
792
 
@@ -737,6 +802,8 @@ registerToolConditional(
737
802
  duration: `${Date.now() - startTime}ms`
738
803
  });
739
804
 
805
+ auditOk(serverName, 'ssh_upload', { localPath, remotePath }, { success: true });
806
+
740
807
  return {
741
808
  content: [
742
809
  {
@@ -746,6 +813,10 @@ registerToolConditional(
746
813
  ],
747
814
  };
748
815
  } catch (error) {
816
+ auditOk(serverName, 'ssh_upload', { localPath, remotePath }, {
817
+ success: false,
818
+ error: error.message,
819
+ });
749
820
  logger.logTransfer('upload', serverName, localPath, remotePath, {
750
821
  success: false,
751
822
  error: error.message
@@ -831,6 +902,9 @@ registerToolConditional(
831
902
  }
832
903
  },
833
904
  async ({ server: serverName, source, destination, exclude = [], dryRun = false, delete: deleteFiles = false, compress = true, verbose = false, checksum = false, timeout = 30000 }) => {
905
+ const denied = applyServerPolicy(serverName, 'ssh_sync', { source, destination, dryRun, delete: deleteFiles });
906
+ if (denied) return denied;
907
+
834
908
  try {
835
909
  const ssh = await getConnection(serverName);
836
910
  const servers = loadServerConfig();
@@ -1596,6 +1670,10 @@ registerToolConditional(
1596
1670
  try {
1597
1671
  const session = getSession(sessionId);
1598
1672
 
1673
+ // Resolve the session's underlying server to its policy.
1674
+ const denied = applyServerPolicy(session.serverName, 'ssh_session_send', { session: sessionId, command }, command);
1675
+ if (denied) return denied;
1676
+
1599
1677
  const startTime = Date.now();
1600
1678
  const result = await session.execute(command, { timeout });
1601
1679
  const duration = Date.now() - startTime;
@@ -1826,6 +1904,15 @@ registerToolConditional(
1826
1904
  const result = await executeOnGroup(
1827
1905
  groupName,
1828
1906
  async (serverName) => {
1907
+ // Per-server policy: each server in the group is evaluated independently.
1908
+ // A server in readonly/restricted mode refuses the command; others
1909
+ // execute normally. Refusal is surfaced as a per-server failure rather
1910
+ // than aborting the whole group (group execution is best-effort).
1911
+ const denied = applyServerPolicy(serverName, 'ssh_execute_group', { group: groupName, command, cwd }, command);
1912
+ if (denied) {
1913
+ const errorText = denied.content?.[0]?.text || 'Policy denied';
1914
+ return { stdout: '', stderr: errorText, code: -2, success: false };
1915
+ }
1829
1916
  const ssh = await getConnection(serverName);
1830
1917
 
1831
1918
  // Build full command with cwd if provided.
@@ -2109,6 +2196,12 @@ registerToolConditional(
2109
2196
  }
2110
2197
  },
2111
2198
  async ({ server, files, options = {} }) => {
2199
+ const denied = applyServerPolicy(server, 'ssh_deploy', {
2200
+ files: files.map((f) => ({ local: f.local, remote: f.remote })),
2201
+ options,
2202
+ });
2203
+ if (denied) return denied;
2204
+
2112
2205
  try {
2113
2206
  const ssh = await getConnection(server);
2114
2207
 
@@ -2205,6 +2298,12 @@ registerToolConditional(
2205
2298
  }
2206
2299
  },
2207
2300
  async ({ server, command, password, cwd, timeout = 30000 }) => {
2301
+ // ssh_execute_sudo is in READONLY_BLOCKED_TOOLS, so readonly mode blocks
2302
+ // it at the tool level. In restricted mode the command itself is matched
2303
+ // against ALLOW/DENY patterns.
2304
+ const denied = applyServerPolicy(server, 'ssh_execute_sudo', { command, cwd }, command);
2305
+ if (denied) return denied;
2306
+
2208
2307
  try {
2209
2308
  const ssh = await getConnection(server);
2210
2309
  const servers = loadServerConfig();
@@ -2902,6 +3001,13 @@ registerToolConditional(
2902
3001
  }
2903
3002
  },
2904
3003
  async ({ action, server, autoAccept = false }) => {
3004
+ // Mutating actions (accept, remove) are blocked in readonly mode at the
3005
+ // tool level. Pure-read actions (verify, list, check) are allowed regardless,
3006
+ // so we only gate when the action would modify state.
3007
+ if (server && (action === 'accept' || action === 'remove')) {
3008
+ const denied = applyServerPolicy(server, 'ssh_key_manage', { action, autoAccept });
3009
+ if (denied) return denied;
3010
+ }
2905
3011
  try {
2906
3012
  const servers = loadServerConfig();
2907
3013
  let resolvedName, serverConfig, host, port;
@@ -3258,6 +3364,9 @@ registerToolConditional(
3258
3364
  }
3259
3365
  },
3260
3366
  async ({ server: serverName, type, name, database, dbUser, dbPassword, dbHost, dbPort, paths, exclude, backupDir, retention = 7, compress = true }) => {
3367
+ const denied = applyServerPolicy(serverName, 'ssh_backup_create', { type, name, database, paths });
3368
+ if (denied) return denied;
3369
+
3261
3370
  try {
3262
3371
  const ssh = await getConnection(serverName);
3263
3372
 
@@ -3542,6 +3651,9 @@ registerToolConditional(
3542
3651
  }
3543
3652
  },
3544
3653
  async ({ server: serverName, backupId, database, dbUser, dbPassword, dbHost, dbPort, targetPath, backupDir }) => {
3654
+ const denied = applyServerPolicy(serverName, 'ssh_backup_restore', { backupId, database, targetPath });
3655
+ if (denied) return denied;
3656
+
3545
3657
  try {
3546
3658
  const ssh = await getConnection(serverName);
3547
3659
  const backupDirectory = backupDir || DEFAULT_BACKUP_DIR;
@@ -3658,6 +3770,9 @@ registerToolConditional(
3658
3770
  }
3659
3771
  },
3660
3772
  async ({ server: serverName, schedule, type, name, database, paths, retention = 7 }) => {
3773
+ const denied = applyServerPolicy(serverName, 'ssh_backup_schedule', { schedule, type, name, database, paths });
3774
+ if (denied) return denied;
3775
+
3661
3776
  try {
3662
3777
  const ssh = await getConnection(serverName);
3663
3778
 
@@ -3957,6 +4072,12 @@ registerToolConditional(
3957
4072
  }
3958
4073
  },
3959
4074
  async ({ server: serverName, action, pid, signal = 'TERM', sortBy = 'cpu', limit = 20, filter }) => {
4075
+ // Only the `kill` action mutates remote state — gate just that branch so
4076
+ // operators on readonly servers can still `list` / `info` processes.
4077
+ if (action === 'kill') {
4078
+ const denied = applyServerPolicy(serverName, 'ssh_process_manager', { action, pid, signal });
4079
+ if (denied) return denied;
4080
+ }
3960
4081
  try {
3961
4082
  const ssh = await getConnection(serverName);
3962
4083
 
@@ -4104,6 +4225,11 @@ registerToolConditional(
4104
4225
  }
4105
4226
  },
4106
4227
  async ({ server: serverName, action, cpuThreshold, memoryThreshold, diskThreshold, enabled = true }) => {
4228
+ // `set` writes config on the remote; `get` and `check` are read-only.
4229
+ if (action === 'set') {
4230
+ const denied = applyServerPolicy(serverName, 'ssh_alert_setup', { action, cpuThreshold, memoryThreshold, diskThreshold, enabled });
4231
+ if (denied) return denied;
4232
+ }
4107
4233
  try {
4108
4234
  const ssh = await getConnection(serverName);
4109
4235
  const configPath = '/etc/ssh-manager-alerts.json';
@@ -4288,6 +4414,9 @@ registerToolConditional(
4288
4414
  }
4289
4415
  },
4290
4416
  async ({ server: serverName, type, database, outputFile, dbUser, dbPassword, dbHost, dbPort, compress = true, tables }) => {
4417
+ const denied = applyServerPolicy(serverName, 'ssh_db_dump', { type, database, outputFile, tables });
4418
+ if (denied) return denied;
4419
+
4291
4420
  try {
4292
4421
  const ssh = await getConnection(serverName);
4293
4422
 
@@ -4399,6 +4528,9 @@ registerToolConditional(
4399
4528
  }
4400
4529
  },
4401
4530
  async ({ server: serverName, type, database, inputFile, dbUser, dbPassword, dbHost, dbPort, drop = true }) => {
4531
+ const denied = applyServerPolicy(serverName, 'ssh_db_import', { type, database, inputFile, drop });
4532
+ if (denied) return denied;
4533
+
4402
4534
  try {
4403
4535
  const ssh = await getConnection(serverName);
4404
4536
 
package/src/policy.js ADDED
@@ -0,0 +1,247 @@
1
+ /**
2
+ * Per-server security policy evaluation.
3
+ *
4
+ * Three modes, opt-in per server via config (MODE field):
5
+ * - "unrestricted" (default): no change vs. pre-v3.5.0 behavior. Early-return.
6
+ * - "readonly": blocks mutating tools entirely; for ssh_execute / ssh_execute_sudo /
7
+ * ssh_execute_group / ssh_session_send, blocks commands matching the
8
+ * built-in destructive denylist below.
9
+ * - "restricted": command must match at least one ALLOW_PATTERNS regex AND no
10
+ * DENY_PATTERNS regex. DENY wins over ALLOW.
11
+ *
12
+ * Returns { allowed: boolean, reason?: string } — never throws. Callers translate
13
+ * a refusal into an MCP-level error response.
14
+ */
15
+
16
+ import { logger } from './logger.js';
17
+
18
+ const MODE_UNRESTRICTED = 'unrestricted';
19
+ const MODE_READONLY = 'readonly';
20
+ const MODE_RESTRICTED = 'restricted';
21
+
22
+ export const VALID_MODES = new Set([MODE_UNRESTRICTED, MODE_READONLY, MODE_RESTRICTED]);
23
+
24
+ // Tools that mutate remote state and are unconditionally blocked in readonly mode.
25
+ // Read-only tools (ssh_download, ssh_list_servers, ssh_health_check, ssh_db_query, ssh_tail,
26
+ // ssh_monitor, ssh_history, ssh_*_list, ssh_*_status, ssh_db_list) are not listed and
27
+ // pass through.
28
+ export const READONLY_BLOCKED_TOOLS = new Set([
29
+ 'ssh_upload',
30
+ 'ssh_deploy',
31
+ 'ssh_sync',
32
+ 'ssh_execute_sudo',
33
+ 'ssh_backup_create',
34
+ 'ssh_backup_restore',
35
+ 'ssh_backup_schedule',
36
+ 'ssh_db_import',
37
+ 'ssh_db_dump',
38
+ 'ssh_key_manage',
39
+ 'ssh_alert_setup',
40
+ 'ssh_process_manager',
41
+ ]);
42
+
43
+ // Tools whose command argument we want to filter against the readonly built-in
44
+ // denylist and the restricted ALLOW/DENY regexes.
45
+ export const COMMAND_BEARING_TOOLS = new Set([
46
+ 'ssh_execute',
47
+ 'ssh_execute_sudo',
48
+ 'ssh_execute_group',
49
+ 'ssh_session_send',
50
+ ]);
51
+
52
+ // Built-in destructive command regex denylist applied in readonly mode to any
53
+ // command passed to a COMMAND_BEARING_TOOL. Patterns are intentionally simple
54
+ // substring/word matches — not a security boundary, just a guard rail against
55
+ // accidental destructive commands when an operator opts a server into readonly.
56
+ //
57
+ // The user can layer their own DENY_PATTERNS on top via restricted mode for
58
+ // finer control.
59
+ export const READONLY_DENY_REGEX = [
60
+ /(^|[\s;&|])rm(\s|$)/,
61
+ /(^|[\s;&|])rmdir(\s|$)/,
62
+ /(^|[\s;&|])mv(\s|$)/,
63
+ /(^|[\s;&|])dd(\s|$)/,
64
+ /(^|[\s;&|])mkfs(\.|\s|$)/,
65
+ /(^|[\s;&|])chmod(\s|$)/,
66
+ /(^|[\s;&|])chown(\s|$)/,
67
+ /(^|[\s;&|])truncate(\s|$)/,
68
+ /(^|[\s;&|])tee(\s|$)/,
69
+ /(^|[\s;&|])sudo(\s|$)/,
70
+ /(^|[\s;&|])su(\s|$)/,
71
+ /(^|[\s;&|])kill(\s|$)/,
72
+ /(^|[\s;&|])pkill(\s|$)/,
73
+ /(^|[\s;&|])killall(\s|$)/,
74
+ /(^|[\s;&|])shutdown(\s|$)/,
75
+ /(^|[\s;&|])reboot(\s|$)/,
76
+ /(^|[\s;&|])halt(\s|$)/,
77
+ /(^|[\s;&|])poweroff(\s|$)/,
78
+ /(^|[\s;&|])systemctl\s+(restart|stop|reload|start|enable|disable|mask)/,
79
+ /(^|[\s;&|])service\s+\S+\s+(restart|stop|reload|start)/,
80
+ /(^|[\s;&|])docker\s+(rm|stop|restart|kill|prune|system)/,
81
+ /(^|[\s;&|])apt(-get)?\s+(install|remove|purge|upgrade|update)/,
82
+ /(^|[\s;&|])yum\s+(install|remove|update|upgrade)/,
83
+ /(^|[\s;&|])dnf\s+(install|remove|update|upgrade)/,
84
+ /(^|[\s;&|])pip\s+(install|uninstall)/,
85
+ /(^|[\s;&|])npm\s+(install|uninstall|publish)/,
86
+ /(^|[\s;&|])git\s+(reset\s+--hard|push\s+.*--force|clean\s+-fd?)/,
87
+ />\s*\/(?!dev\/null|dev\/stdout|dev\/stderr|tmp)/, // redirect to non-tmp/non-devnull file
88
+ />>\s*\/(?!dev\/null|tmp)/, // append-redirect to non-tmp file
89
+ /\|\s*sh(\s|$)/,
90
+ /\|\s*bash(\s|$)/,
91
+ /curl\s+[^|]*\|\s*(sh|bash)/,
92
+ /wget\s+[^|]*\|\s*(sh|bash)/,
93
+ ];
94
+
95
+ /**
96
+ * Compile a list of regex source strings into RegExp objects.
97
+ * Invalid regexes are logged and skipped (returned list may be shorter than input).
98
+ *
99
+ * @param {string[]} patterns
100
+ * @param {string} contextLabel - for log messages ("ALLOW" / "DENY")
101
+ * @param {string} serverName
102
+ * @returns {RegExp[]}
103
+ */
104
+ function compilePatterns(patterns, contextLabel, serverName) {
105
+ const compiled = [];
106
+ for (const src of patterns) {
107
+ if (!src || typeof src !== 'string') continue;
108
+ try {
109
+ compiled.push(new RegExp(src));
110
+ } catch (err) {
111
+ logger.warn(
112
+ `Invalid ${contextLabel}_PATTERNS regex for server "${serverName}": /${src}/ — ignored (${err.message})`
113
+ );
114
+ }
115
+ }
116
+ return compiled;
117
+ }
118
+
119
+ // Per-server compiled-regex cache, keyed by server name. Patterns rarely change at runtime
120
+ // (they're loaded once from config), so this avoids recompiling on every tool call.
121
+ const compiledCache = new Map();
122
+
123
+ function getCompiledPatterns(serverConfig) {
124
+ const key = serverConfig.name;
125
+ const cached = compiledCache.get(key);
126
+ // Cache invalidation: if the raw pattern strings change, drop the cached entry.
127
+ if (
128
+ cached &&
129
+ cached.allowSrc === (serverConfig.allowPatterns || []).join('') &&
130
+ cached.denySrc === (serverConfig.denyPatterns || []).join('')
131
+ ) {
132
+ return cached;
133
+ }
134
+ const allow = compilePatterns(serverConfig.allowPatterns || [], 'ALLOW', key);
135
+ const deny = compilePatterns(serverConfig.denyPatterns || [], 'DENY', key);
136
+ const entry = {
137
+ allow,
138
+ deny,
139
+ allowSrc: (serverConfig.allowPatterns || []).join(''),
140
+ denySrc: (serverConfig.denyPatterns || []).join(''),
141
+ };
142
+ compiledCache.set(key, entry);
143
+ return entry;
144
+ }
145
+
146
+ /**
147
+ * Evaluate whether a tool invocation is allowed under the server's policy.
148
+ *
149
+ * Performance: in the common case (mode === 'unrestricted' or undefined), this
150
+ * returns immediately with no allocations beyond the result object.
151
+ *
152
+ * @param {Object} serverConfig - the server config object from config-loader.js
153
+ * @param {string} toolName - MCP tool name (e.g. "ssh_execute")
154
+ * @param {string} [command] - optional command string for COMMAND_BEARING_TOOLS
155
+ * @returns {{ allowed: boolean, reason?: string }}
156
+ */
157
+ export function evaluatePolicy(serverConfig, toolName, command) {
158
+ // Backward-compat fast path: no server config, missing mode, or unrestricted mode
159
+ // → identical behavior to pre-v3.5.0. Not a single regex is compiled or matched.
160
+ const mode = serverConfig && serverConfig.mode;
161
+ if (!mode || mode === MODE_UNRESTRICTED) {
162
+ return { allowed: true };
163
+ }
164
+
165
+ if (mode === MODE_READONLY) {
166
+ if (READONLY_BLOCKED_TOOLS.has(toolName)) {
167
+ return {
168
+ allowed: false,
169
+ reason: `Tool "${toolName}" is disabled on server "${serverConfig.name}" (mode: readonly).`,
170
+ };
171
+ }
172
+ if (COMMAND_BEARING_TOOLS.has(toolName) && typeof command === 'string') {
173
+ for (const re of READONLY_DENY_REGEX) {
174
+ if (re.test(command)) {
175
+ return {
176
+ allowed: false,
177
+ reason: `Command refused on server "${serverConfig.name}" (mode: readonly): matches built-in destructive pattern ${re}.`,
178
+ };
179
+ }
180
+ }
181
+ }
182
+ return { allowed: true };
183
+ }
184
+
185
+ if (mode === MODE_RESTRICTED) {
186
+ const { allow, deny } = getCompiledPatterns(serverConfig);
187
+
188
+ // For non-command-bearing tools in restricted mode, fall back to readonly semantics
189
+ // (block mutating tools, allow read-only tools). This means restricted mode is a
190
+ // strict superset of readonly's tool-level blocks plus command-level allowlisting.
191
+ if (!COMMAND_BEARING_TOOLS.has(toolName)) {
192
+ if (READONLY_BLOCKED_TOOLS.has(toolName)) {
193
+ return {
194
+ allowed: false,
195
+ reason: `Tool "${toolName}" is disabled on server "${serverConfig.name}" (mode: restricted blocks mutating tools by default).`,
196
+ };
197
+ }
198
+ return { allowed: true };
199
+ }
200
+
201
+ if (typeof command !== 'string') {
202
+ // Defensive: command-bearing tool called without a command? Refuse.
203
+ return {
204
+ allowed: false,
205
+ reason: `Tool "${toolName}" requires a command argument under restricted mode.`,
206
+ };
207
+ }
208
+
209
+ for (const re of deny) {
210
+ if (re.test(command)) {
211
+ return {
212
+ allowed: false,
213
+ reason: `Command refused on server "${serverConfig.name}" (mode: restricted): matches DENY pattern ${re}.`,
214
+ };
215
+ }
216
+ }
217
+
218
+ if (allow.length === 0) {
219
+ return {
220
+ allowed: false,
221
+ reason: `Command refused on server "${serverConfig.name}" (mode: restricted): no ALLOW_PATTERNS configured — restricted mode requires an explicit allowlist.`,
222
+ };
223
+ }
224
+
225
+ for (const re of allow) {
226
+ if (re.test(command)) {
227
+ return { allowed: true };
228
+ }
229
+ }
230
+
231
+ return {
232
+ allowed: false,
233
+ reason: `Command refused on server "${serverConfig.name}" (mode: restricted): does not match any ALLOW_PATTERNS.`,
234
+ };
235
+ }
236
+
237
+ // Unknown mode — fail-closed with a clear message rather than silently allowing.
238
+ return {
239
+ allowed: false,
240
+ reason: `Unknown security mode "${mode}" for server "${serverConfig.name}". Valid: ${[...VALID_MODES].join(', ')}.`,
241
+ };
242
+ }
243
+
244
+ // Exposed for tests only.
245
+ export function _clearCompiledCache() {
246
+ compiledCache.clear();
247
+ }
@@ -7,6 +7,22 @@ import { isHostKnown, getCurrentHostKey, addHostKey, updateHostKey } from './ssh
7
7
  import { configLoader } from './config-loader.js';
8
8
  import { logger } from './logger.js';
9
9
 
10
+ // Validate liveness-probe output across shells (bash, cmd.exe, PowerShell).
11
+ // Normalize CRLF, stray quotes/backslashes and case before matching so quoted
12
+ // or escaped variants (e.g. `"ping"`, `\"ping\"\r\n`) still count as alive.
13
+ // `includes` (not strict `===`) is deliberate: a liveness probe should err
14
+ // toward "alive" — a false positive merely lets the next real command
15
+ // reconnect, whereas a false negative needlessly tears down a healthy pooled
16
+ // connection.
17
+ export function isPingAlive(stdout) {
18
+ const normalized = (stdout || '')
19
+ .replace(/[\r\n]+/g, ' ')
20
+ .replace(/["'`\\]/g, '')
21
+ .trim()
22
+ .toLowerCase();
23
+ return normalized.includes('ping');
24
+ }
25
+
10
26
  class SSHManager {
11
27
  constructor(config) {
12
28
  this.config = config;
@@ -509,8 +525,12 @@ class SSHManager {
509
525
 
510
526
  async ping() {
511
527
  try {
512
- const result = await this.execCommand('echo "ping"', { timeout: 5000 });
513
- return result.stdout.trim() === 'ping';
528
+ // Use `echo ping` WITHOUT quotes: cmd.exe echoes surrounding quotes
529
+ // literally (outputs `"ping"`), which broke the strict equality check and
530
+ // marked healthy Windows/OpenSSH sessions as dead. Output handling lives
531
+ // in isPingAlive() so it can be unit-tested without a live connection.
532
+ const result = await this.execCommand('echo ping', { timeout: 5000 });
533
+ return isPingAlive(result.stdout);
514
534
  } catch (error) {
515
535
  return false;
516
536
  }