mcp-ssh-manager 3.8.3 → 3.8.5

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.
@@ -9,22 +9,32 @@ echo ""
9
9
 
10
10
  ERRORS=0
11
11
 
12
- # Check JavaScript syntax
13
- echo "📋 Checking JavaScript syntax..."
14
- if node --check src/index.js 2>/dev/null; then
15
- echo " ✅ JavaScript syntax is valid"
12
+ # Check JavaScript syntax across every tracked .js file.
13
+ # Previously this checked only src/index.js and src/ssh-manager.js, which is how
14
+ # examples/backup-workflow.js sat broken: a cron expression (*/6) inside a block
15
+ # comment closed it early, so the file never parsed. Examples are code people
16
+ # copy — they get checked too.
17
+ echo "📋 Checking JavaScript syntax (all tracked .js files)..."
18
+ JS_ERRORS=0
19
+ JS_COUNT=0
20
+ if git rev-parse --git-dir >/dev/null 2>&1; then
21
+ JS_FILES=$(git ls-files '*.js' | grep -v node_modules)
16
22
  else
17
- echo " ❌ JavaScript syntax error!"
18
- ERRORS=$((ERRORS + 1))
23
+ JS_FILES=$(find src cli tests examples debug -name '*.js' 2>/dev/null)
19
24
  fi
20
-
21
- # Check SSH Manager syntax
22
- echo "📋 Checking SSH Manager syntax..."
23
- if node --check src/ssh-manager.js 2>/dev/null; then
24
- echo " ✅ SSH Manager syntax is valid"
25
+ for f in $JS_FILES; do
26
+ [ -f "$f" ] || continue
27
+ JS_COUNT=$((JS_COUNT + 1))
28
+ if ! node --check "$f" 2>/dev/null; then
29
+ echo " ❌ syntax error: $f"
30
+ JS_ERRORS=$((JS_ERRORS + 1))
31
+ fi
32
+ done
33
+ if [ $JS_ERRORS -eq 0 ]; then
34
+ echo " ✅ JavaScript syntax is valid ($JS_COUNT files)"
25
35
  else
26
- echo " ❌ SSH Manager syntax error!"
27
- ERRORS=$((ERRORS + 1))
36
+ echo " ❌ $JS_ERRORS file(s) with syntax errors"
37
+ ERRORS=$((ERRORS + JS_ERRORS))
28
38
  fi
29
39
 
30
40
  # Check for .env in git
package/server.json CHANGED
@@ -6,12 +6,12 @@
6
6
  "url": "https://github.com/bvisible/mcp-ssh-manager",
7
7
  "source": "github"
8
8
  },
9
- "version": "3.8.3",
9
+ "version": "3.8.5",
10
10
  "packages": [
11
11
  {
12
12
  "registryType": "npm",
13
13
  "identifier": "mcp-ssh-manager",
14
- "version": "3.8.3",
14
+ "version": "3.8.5",
15
15
  "transport": {
16
16
  "type": "stdio"
17
17
  },
@@ -7,6 +7,7 @@
7
7
  import path from 'path';
8
8
  import crypto from 'crypto';
9
9
  import { logger } from './logger.js';
10
+ import { shellQuote, safeInteger } from './shell-quote.js';
10
11
 
11
12
  // Backup types
12
13
  export const BACKUP_TYPES = {
@@ -61,23 +62,23 @@ export function buildMySQLDumpCommand(options) {
61
62
  let command = 'mysqldump';
62
63
 
63
64
  // Connection parameters
64
- if (user) command += ` -u${user}`;
65
- if (password) command += ` -p'${password}'`;
66
- if (host) command += ` -h ${host}`;
67
- if (port) command += ` -P ${port}`;
65
+ if (user) command += ` -u${shellQuote(user)}`;
66
+ if (password) command += ` -p${shellQuote(password)}`;
67
+ if (host) command += ` -h ${shellQuote(host)}`;
68
+ if (port) command += ` -P ${safeInteger(port, 3306)}`;
68
69
 
69
70
  // Dump options
70
71
  if (singleTransaction) command += ' --single-transaction';
71
72
  command += ' --routines --triggers';
72
73
 
73
74
  // Database name
74
- command += ` ${database}`;
75
+ command += ` ${shellQuote(database)}`;
75
76
 
76
77
  // Output handling
77
78
  if (compress) {
78
- command += ` | gzip > "${outputFile}"`;
79
+ command += ` | gzip > ${shellQuote(outputFile)}`;
79
80
  } else {
80
- command += ` > "${outputFile}"`;
81
+ command += ` > ${shellQuote(outputFile)}`;
81
82
  }
82
83
 
83
84
  return command;
@@ -100,27 +101,27 @@ export function buildPostgreSQLDumpCommand(options) {
100
101
  // PostgreSQL uses PGPASSWORD environment variable
101
102
  let command = '';
102
103
  if (password) {
103
- command = `PGPASSWORD='${password}' `;
104
+ command = `PGPASSWORD=${shellQuote(password)} `;
104
105
  }
105
106
 
106
107
  command += 'pg_dump';
107
108
 
108
109
  // Connection parameters
109
- if (user) command += ` -U ${user}`;
110
- if (host) command += ` -h ${host}`;
111
- if (port) command += ` -p ${port}`;
110
+ if (user) command += ` -U ${shellQuote(user)}`;
111
+ if (host) command += ` -h ${shellQuote(host)}`;
112
+ if (port) command += ` -p ${safeInteger(port, 5432)}`;
112
113
 
113
114
  // Dump options
114
115
  command += ' --format=custom --clean --if-exists';
115
116
 
116
117
  // Database name
117
- command += ` ${database}`;
118
+ command += ` ${shellQuote(database)}`;
118
119
 
119
120
  // Output handling
120
121
  if (compress) {
121
- command += ` | gzip > "${outputFile}"`;
122
+ command += ` | gzip > ${shellQuote(outputFile)}`;
122
123
  } else {
123
- command += ` > "${outputFile}"`;
124
+ command += ` > ${shellQuote(outputFile)}`;
124
125
  }
125
126
 
126
127
  return command;
@@ -143,22 +144,24 @@ export function buildMongoDBDumpCommand(options) {
143
144
  let command = 'mongodump';
144
145
 
145
146
  // Connection parameters
146
- if (host) command += ` --host ${host}`;
147
- if (port) command += ` --port ${port}`;
148
- if (user) command += ` --username ${user}`;
149
- if (password) command += ` --password '${password}'`;
147
+ if (host) command += ` --host ${shellQuote(host)}`;
148
+ if (port) command += ` --port ${safeInteger(port, 27017)}`;
149
+ if (user) command += ` --username ${shellQuote(user)}`;
150
+ if (password) command += ` --password ${shellQuote(password)}`;
150
151
 
151
152
  // Database selection
152
- if (database) command += ` --db ${database}`;
153
+ if (database) command += ` --db ${shellQuote(database)}`;
153
154
 
154
155
  // Output directory
155
- command += ` --out "${outputDir}"`;
156
+ command += ` --out ${shellQuote(outputDir)}`;
156
157
 
157
158
  // Compress the output directory
158
159
  if (compress) {
159
160
  const archiveName = `${outputDir}.tar.gz`;
160
- command += ` && tar -czf "${archiveName}" -C "$(dirname ${outputDir})" "$(basename ${outputDir})"`;
161
- command += ` && rm -rf "${outputDir}"`;
161
+ // dirname/basename receive the quoted value, so the substitution itself
162
+ // cannot be steered by the caller.
163
+ command += ` && tar -czf ${shellQuote(archiveName)} -C "$(dirname ${shellQuote(outputDir)})" "$(basename ${shellQuote(outputDir)})"`;
164
+ command += ` && rm -rf ${shellQuote(outputDir)}`;
162
165
  }
163
166
 
164
167
  return command;
@@ -189,15 +192,15 @@ export function buildFilesBackupCommand(options) {
189
192
  }
190
193
 
191
194
  // Output file
192
- command += ` "${outputFile}"`;
195
+ command += ` ${shellQuote(outputFile)}`;
193
196
 
194
197
  // Exclude patterns
195
198
  for (const pattern of exclude) {
196
- command += ` --exclude="${pattern}"`;
199
+ command += ` --exclude=${shellQuote(pattern)}`;
197
200
  }
198
201
 
199
202
  // Paths to backup
200
- command += ` ${paths.map(p => `"${p}"`).join(' ')}`;
203
+ command += ` ${paths.map(p => shellQuote(p)).join(' ')}`;
201
204
 
202
205
  return command;
203
206
  }
@@ -236,19 +239,19 @@ function buildMySQLRestoreCommand(backupFile, options) {
236
239
 
237
240
  // Decompress if needed
238
241
  if (backupFile.endsWith('.gz')) {
239
- command = `gunzip -c "${backupFile}" | `;
242
+ command = `gunzip -c ${shellQuote(backupFile)} | `;
240
243
  } else {
241
- command = `cat "${backupFile}" | `;
244
+ command = `cat ${shellQuote(backupFile)} | `;
242
245
  }
243
246
 
244
247
  command += 'mysql';
245
248
 
246
249
  // Connection parameters
247
- if (user) command += ` -u${user}`;
248
- if (password) command += ` -p'${password}'`;
249
- if (host) command += ` -h ${host}`;
250
- if (port) command += ` -P ${port}`;
251
- if (database) command += ` ${database}`;
250
+ if (user) command += ` -u${shellQuote(user)}`;
251
+ if (password) command += ` -p${shellQuote(password)}`;
252
+ if (host) command += ` -h ${shellQuote(host)}`;
253
+ if (port) command += ` -P ${safeInteger(port, 3306)}`;
254
+ if (database) command += ` ${shellQuote(database)}`;
252
255
 
253
256
  return command;
254
257
  }
@@ -267,25 +270,25 @@ function buildPostgreSQLRestoreCommand(backupFile, options) {
267
270
 
268
271
  let command = '';
269
272
  if (password) {
270
- command = `PGPASSWORD='${password}' `;
273
+ command = `PGPASSWORD=${shellQuote(password)} `;
271
274
  }
272
275
 
273
276
  command += 'pg_restore';
274
277
 
275
278
  // Connection parameters
276
- if (user) command += ` -U ${user}`;
277
- if (host) command += ` -h ${host}`;
278
- if (port) command += ` -p ${port}`;
279
- if (database) command += ` -d ${database}`;
279
+ if (user) command += ` -U ${shellQuote(user)}`;
280
+ if (host) command += ` -h ${shellQuote(host)}`;
281
+ if (port) command += ` -p ${safeInteger(port, 5432)}`;
282
+ if (database) command += ` -d ${shellQuote(database)}`;
280
283
 
281
284
  // Restore options
282
285
  command += ' --clean --if-exists';
283
286
 
284
287
  // Handle compressed files
285
288
  if (backupFile.endsWith('.gz')) {
286
- command = `gunzip -c "${backupFile}" | ${command}`;
289
+ command = `gunzip -c ${shellQuote(backupFile)} | ${command}`;
287
290
  } else {
288
- command += ` "${backupFile}"`;
291
+ command += ` ${shellQuote(backupFile)}`;
289
292
  }
290
293
 
291
294
  return command;
@@ -308,25 +311,25 @@ function buildMongoDBRestoreCommand(backupFile, options) {
308
311
  // Extract if compressed
309
312
  if (backupFile.endsWith('.tar.gz')) {
310
313
  const extractDir = backupFile.replace('.tar.gz', '');
311
- command = `tar -xzf "${backupFile}" -C "$(dirname ${backupFile})" && `;
314
+ command = `tar -xzf ${shellQuote(backupFile)} -C "$(dirname ${shellQuote(backupFile)})" && `;
312
315
  command += 'mongorestore';
313
316
 
314
317
  if (drop) command += ' --drop';
315
- if (host) command += ` --host ${host}`;
316
- if (port) command += ` --port ${port}`;
317
- if (user) command += ` --username ${user}`;
318
- if (password) command += ` --password '${password}'`;
318
+ if (host) command += ` --host ${shellQuote(host)}`;
319
+ if (port) command += ` --port ${safeInteger(port, 27017)}`;
320
+ if (user) command += ` --username ${shellQuote(user)}`;
321
+ if (password) command += ` --password ${shellQuote(password)}`;
319
322
 
320
- command += ` "${extractDir}"`;
321
- command += ` && rm -rf "${extractDir}"`;
323
+ command += ` ${shellQuote(extractDir)}`;
324
+ command += ` && rm -rf ${shellQuote(extractDir)}`;
322
325
  } else {
323
326
  command = 'mongorestore';
324
327
  if (drop) command += ' --drop';
325
- if (host) command += ` --host ${host}`;
326
- if (port) command += ` --port ${port}`;
327
- if (user) command += ` --username ${user}`;
328
- if (password) command += ` --password '${password}'`;
329
- command += ` "${backupFile}"`;
328
+ if (host) command += ` --host ${shellQuote(host)}`;
329
+ if (port) command += ` --port ${safeInteger(port, 27017)}`;
330
+ if (user) command += ` --username ${shellQuote(user)}`;
331
+ if (password) command += ` --password ${shellQuote(password)}`;
332
+ command += ` ${shellQuote(backupFile)}`;
330
333
  }
331
334
 
332
335
  return command;
@@ -347,8 +350,8 @@ function buildFilesRestoreCommand(backupFile, options) {
347
350
  command += ' -xf';
348
351
  }
349
352
 
350
- command += ` "${backupFile}"`;
351
- command += ` -C "${targetPath}"`;
353
+ command += ` ${shellQuote(backupFile)}`;
354
+ command += ` -C ${shellQuote(targetPath)}`;
352
355
 
353
356
  return command;
354
357
  }
@@ -377,19 +380,20 @@ export function createBackupMetadata(backupId, type, options = {}) {
377
380
  */
378
381
  export function buildSaveMetadataCommand(metadata, metadataPath) {
379
382
  const jsonData = JSON.stringify(metadata, null, 2);
380
- // Escape single quotes in JSON for shell
381
- const escapedJson = jsonData.replace(/'/g, '\'\\\'\'');
382
- return `echo '${escapedJson}' > "${metadataPath}"`;
383
+ // The metadata carries caller-supplied fields (database name, paths...), so
384
+ // both the payload and the destination go through shellQuote rather than
385
+ // hand-rolled escaping.
386
+ return `echo ${shellQuote(jsonData)} > ${shellQuote(metadataPath)}`;
383
387
  }
384
388
 
385
389
  /**
386
390
  * Build command to list backups from remote server
387
391
  */
388
392
  export function buildListBackupsCommand(backupDir = DEFAULT_BACKUP_DIR, type = null) {
389
- let command = `find "${backupDir}" -name "*.meta.json" -type f`;
393
+ let command = `find ${shellQuote(backupDir)} -name '*.meta.json' -type f`;
390
394
 
391
395
  if (type) {
392
- command += ` | grep "${type}_"`;
396
+ command += ` | grep ${shellQuote(`${type}_`)}`;
393
397
  }
394
398
 
395
399
  // Read and parse each metadata file
@@ -427,14 +431,17 @@ export function parseBackupsList(output) {
427
431
  */
428
432
  export function buildCleanupCommand(backupDir = DEFAULT_BACKUP_DIR, retentionDays = 7) {
429
433
  // Find backup files older than retention period and delete them
430
- return `find "${backupDir}" -name "*_*_*" -type f -mtime +${retentionDays} -delete`;
434
+ return `find ${shellQuote(backupDir)} -name '*_*_*' -type f -mtime +${safeInteger(retentionDays, 7)} -delete`;
431
435
  }
432
436
 
433
437
  /**
434
438
  * Build cron schedule command
435
439
  */
436
440
  export function buildCronScheduleCommand(schedule, backupCommand, cronComment) {
437
- // Add cron job with comment
441
+ // A crontab line is data here, not a command to evaluate: the whole line goes
442
+ // through shellQuote so a schedule or comment carrying quotes cannot break
443
+ // out of the echo and run something else. backupCommand is built by the
444
+ // builders above, which quote their own arguments.
438
445
  const cronLine = `${schedule} ${backupCommand} # ${cronComment}`;
439
- return `(crontab -l 2>/dev/null; echo '${cronLine}') | crontab -`;
446
+ return `(crontab -l 2>/dev/null; echo ${shellQuote(cronLine)}) | crontab -`;
440
447
  }
@@ -395,10 +395,13 @@ export class ConfigLoader {
395
395
  /** @type {Record<string, any>} */
396
396
  let config = {};
397
397
 
398
- // Load existing config if it exists
399
- if (fs.existsSync(codexConfigPath)) {
400
- const content = fs.readFileSync(codexConfigPath, 'utf8');
401
- config = TOML.parse(content);
398
+ // Load existing config if it exists. Read first and handle ENOENT, rather
399
+ // than checking then reading: between the two the file can be replaced or
400
+ // removed, and the check buys nothing the error handling does not.
401
+ try {
402
+ config = TOML.parse(fs.readFileSync(codexConfigPath, 'utf8'));
403
+ } catch (error) {
404
+ if (error.code !== 'ENOENT') throw error;
402
405
  }
403
406
 
404
407
  // Add MCP server configuration
@@ -12,25 +12,8 @@ export const DB_TYPES = {
12
12
 
13
13
  // A single quote character as a constant, so shellQuote()'s escaping stays
14
14
  // readable under the repo's single-quote lint style.
15
- const SQ = '\'';
16
-
17
- /**
18
- * Quote a value for safe inclusion as a single POSIX shell word.
19
- *
20
- * Wraps the value in single quotes and escapes any embedded single quote as
21
- * '\'' so the remote shell treats it literally — it never interprets $(...),
22
- * backticks, $VAR, ;, |, &, redirects, spaces, or newlines inside the value.
23
- * EVERY caller-controlled value interpolated into a database command string
24
- * MUST go through this: the database/table/collection names, file paths, and
25
- * connection fields all arrive from tool arguments (issue #48 — command
26
- * injection via ssh_db_list / ssh_db_dump / ssh_db_import builder arguments).
27
- * Numbers are coerced to string; null/undefined become an empty quoted word.
28
- */
29
- export function shellQuote(value) {
30
- if (value === null || value === undefined) return SQ + SQ;
31
- // Replace every ' with '\'' (close quote, escaped quote, reopen), then wrap.
32
- return SQ + String(value).replace(/'/g, SQ + '\\' + SQ + SQ) + SQ;
33
- }
15
+ import { shellQuote } from './shell-quote.js';
16
+ export { shellQuote };
34
17
 
35
18
  /**
36
19
  * Build MySQL dump command
@@ -4,6 +4,7 @@
4
4
  */
5
5
 
6
6
  import { logger } from './logger.js';
7
+ import { shellQuote, safeInteger } from './shell-quote.js';
7
8
 
8
9
  // Health status levels
9
10
  export const HEALTH_STATUS = {
@@ -169,17 +170,21 @@ function determineOverallHealth(cpu, memory, disks) {
169
170
  * Build command to check service status (systemd or sysv)
170
171
  */
171
172
  export function buildServiceStatusCommand(serviceName) {
173
+ // serviceName is a tool argument: resolveServiceName returns non-aliases
174
+ // unchanged, so it reaches the shell as-is. Quoting every occurrence is what
175
+ // stops `nginx; id > /tmp/pwned` from executing (GHSA-m793-whw6-f537).
176
+ const name = shellQuote(serviceName);
172
177
  // Try systemd first, fallback to sysv
173
178
  return `
174
179
  if command -v systemctl >/dev/null 2>&1; then
175
- systemctl is-active ${serviceName} 2>/dev/null >/dev/null && echo "ACTIVE" || echo "INACTIVE"
176
- systemctl is-enabled ${serviceName} 2>/dev/null >/dev/null && echo "ENABLED" || echo "DISABLED"
177
- systemctl status ${serviceName} 2>/dev/null | grep "Main PID" | awk '{print $3}' | cut -d'(' -f1
178
- systemctl status ${serviceName} 2>/dev/null | grep "Active:" | sed 's/.*Active: //' | awk '{print $1,$2,$3}'
180
+ systemctl is-active ${name} 2>/dev/null >/dev/null && echo "ACTIVE" || echo "INACTIVE"
181
+ systemctl is-enabled ${name} 2>/dev/null >/dev/null && echo "ENABLED" || echo "DISABLED"
182
+ systemctl status ${name} 2>/dev/null | grep "Main PID" | awk '{print $3}' | cut -d'(' -f1
183
+ systemctl status ${name} 2>/dev/null | grep "Active:" | sed 's/.*Active: //' | awk '{print $1,$2,$3}'
179
184
  elif command -v service >/dev/null 2>&1; then
180
- service ${serviceName} status >/dev/null 2>&1 && echo "ACTIVE" || echo "INACTIVE"
185
+ service ${name} status >/dev/null 2>&1 && echo "ACTIVE" || echo "INACTIVE"
181
186
  echo "UNKNOWN"
182
- pgrep -f ${serviceName} | head -1 || echo ""
187
+ pgrep -f ${name} | head -1 || echo ""
183
188
  echo "sysv"
184
189
  else
185
190
  echo "UNKNOWN"
@@ -218,10 +223,10 @@ export function buildProcessListCommand(options = {}) {
218
223
  } = options;
219
224
 
220
225
  let sortFlag = sortBy === 'memory' ? '-m' : '-c'; // -c for CPU, -m for memory
221
- let command = `ps aux --sort=${sortFlag === '-c' ? '-pcpu' : '-pmem'} | head -n ${limit + 1}`;
226
+ let command = `ps aux --sort=${sortFlag === '-c' ? '-pcpu' : '-pmem'} | head -n ${safeInteger(limit, 20) + 1}`;
222
227
 
223
228
  if (filter) {
224
- command += ` | grep -i "${filter}"`;
229
+ command += ` | grep -i ${shellQuote(filter)}`;
225
230
  }
226
231
 
227
232
  // Format output as JSON-like structure
@@ -270,6 +275,11 @@ export function buildKillProcessCommand(pid, signal = 'TERM') {
270
275
  * Build command to get process info
271
276
  */
272
277
  export function buildProcessInfoCommand(pid) {
278
+ // Same guard as buildKillProcessCommand: a PID is a number, and anything else
279
+ // has no business reaching the shell.
280
+ if (!Number.isInteger(pid) || pid <= 0) {
281
+ throw new Error(`Invalid PID: ${pid}`);
282
+ }
273
283
  return `ps -p ${pid} -o user,pid,pcpu,pmem,vsz,rss,stat,start,time,cmd --no-headers | awk '{printf "{\\"user\\":\\"%s\\",\\"pid\\":%s,\\"cpu\\":%.1f,\\"mem\\":%.1f,\\"vsz\\":%s,\\"rss\\":%s,\\"stat\\":\\"%s\\",\\"start\\":\\"%s\\",\\"time\\":\\"%s\\",\\"command\\":\\"%s\\"}", $1,$2,$3,$4,$5,$6,$7,$8,$9,substr($0,index($0,$10))}'`;
274
284
  }
275
285
 
@@ -296,15 +306,14 @@ export function createAlertConfig(thresholds) {
296
306
  */
297
307
  export function buildSaveAlertConfigCommand(config, configPath = '/etc/ssh-manager-alerts.json') {
298
308
  const jsonData = JSON.stringify(config, null, 2);
299
- const escapedJson = jsonData.replace(/'/g, '\'\\\'\'');
300
- return `echo '${escapedJson}' > "${configPath}"`;
309
+ return `echo ${shellQuote(jsonData)} > ${shellQuote(configPath)}`;
301
310
  }
302
311
 
303
312
  /**
304
313
  * Build command to load alert config
305
314
  */
306
315
  export function buildLoadAlertConfigCommand(configPath = '/etc/ssh-manager-alerts.json') {
307
- return `cat "${configPath}" 2>/dev/null || echo '{}'`;
316
+ return `cat ${shellQuote(configPath)} 2>/dev/null || echo '{}'`;
308
317
  }
309
318
 
310
319
  /**
package/src/index.js CHANGED
@@ -143,6 +143,7 @@ import {
143
143
  } from './database-manager.js';
144
144
  import { loadToolConfig, isToolEnabled } from './tool-config-manager.js';
145
145
  import { evaluatePolicy } from './policy.js';
146
+ import { shellQuote, safeInteger } from './shell-quote.js';
146
147
  import { auditLog } from './audit.js';
147
148
 
148
149
  const __filename = fileURLToPath(import.meta.url);
@@ -1257,19 +1258,28 @@ registerToolConditional(
1257
1258
  }
1258
1259
  },
1259
1260
  async ({ server: serverName, file, lines = 10, follow = true, grep }) => {
1261
+ // ssh_tail is read-only and therefore stays enabled in readonly/restricted
1262
+ // mode, which is exactly why it must consult the policy layer: without this
1263
+ // it was a way to run commands on a server the operator locked down
1264
+ // (GHSA-m793-whw6-f537).
1265
+ const denied = await applyServerPolicy(serverName, 'ssh_tail', { file, lines, follow, grep });
1266
+ if (denied) return denied;
1267
+
1260
1268
  try {
1261
1269
  const ssh = await getConnection(serverName);
1262
1270
 
1263
- // Build tail command
1264
- let command = `tail -n ${lines}`;
1271
+ // Build tail command. Every caller-controlled value is quoted: `file` and
1272
+ // `grep` sat inside double quotes, where $(...), backticks and a `"`
1273
+ // breakout all executed.
1274
+ let command = `tail -n ${safeInteger(lines, 10)}`;
1265
1275
  if (follow) {
1266
1276
  command += ' -f';
1267
1277
  }
1268
- command += ` "${file}"`;
1278
+ command += ` ${shellQuote(file)}`;
1269
1279
 
1270
1280
  // Add grep filter if specified
1271
1281
  if (grep) {
1272
- command += ` | grep "${grep}"`;
1282
+ command += ` | grep ${shellQuote(grep)}`;
1273
1283
  }
1274
1284
 
1275
1285
  logger.info(`Starting tail on ${serverName}`, {
@@ -3541,7 +3551,7 @@ registerToolConditional(
3541
3551
  }
3542
3552
 
3543
3553
  // Get backup file size
3544
- const sizeResult = await ssh.execCommand(`stat -f%z "${backupFile}" 2>/dev/null || stat -c%s "${backupFile}" 2>/dev/null`);
3554
+ const sizeResult = await ssh.execCommand(`stat -f%z ${shellQuote(backupFile)} 2>/dev/null || stat -c%s ${shellQuote(backupFile)} 2>/dev/null`);
3545
3555
  const size = parseInt(sizeResult.stdout.trim()) || 0;
3546
3556
 
3547
3557
  // Create and save metadata
@@ -4049,6 +4059,11 @@ registerToolConditional(
4049
4059
  }
4050
4060
  },
4051
4061
  async ({ server: serverName, services }) => {
4062
+ // Read-only tools stay enabled under readonly/restricted, so they are the
4063
+ // ones that most need the policy check (GHSA-m793-whw6-f537).
4064
+ const denied = await applyServerPolicy(serverName, 'ssh_service_status', { services });
4065
+ if (denied) return denied;
4066
+
4052
4067
  try {
4053
4068
  const ssh = await getConnection(serverName);
4054
4069
 
@@ -4527,7 +4542,7 @@ registerToolConditional(
4527
4542
  }
4528
4543
 
4529
4544
  // Get file size
4530
- const sizeCommand = `stat -f%z "${outputFile}" 2>/dev/null || stat -c%s "${outputFile}" 2>/dev/null`;
4545
+ const sizeCommand = `stat -f%z ${shellQuote(outputFile)} 2>/dev/null || stat -c%s ${shellQuote(outputFile)} 2>/dev/null`;
4531
4546
  const sizeResult = await ssh.execCommand(sizeCommand);
4532
4547
  const size = parseSize(sizeResult.stdout);
4533
4548
 
package/src/logger.js CHANGED
@@ -11,6 +11,12 @@ const __filename = fileURLToPath(import.meta.url);
11
11
  const __dirname = path.dirname(__filename);
12
12
 
13
13
  // Log levels
14
+ /**
15
+ * Log level constants. Exported as part of the package's public surface so a
16
+ * consumer can map SSH_LOG_LEVEL values; nothing inside the repository imports
17
+ * it, hence the @public tag telling knip this export is deliberate.
18
+ * @public
19
+ */
14
20
  export const LOG_LEVELS = {
15
21
  DEBUG: 0,
16
22
  INFO: 1,
@@ -35,6 +41,34 @@ const ICONS = {
35
41
  ERROR: '❌'
36
42
  };
37
43
 
44
+ // Field names whose values must never be written to a log, matched
45
+ // case-insensitively against the whole key (so `sudoPassword`, `SSH_PASSWORD`
46
+ // and `passphrase` are all caught).
47
+ const SECRET_KEY_PATTERN = /(pass(word|phrase)?|secret|token|credential|privatekey|private_key|apikey|api_key|auth)/i;
48
+ const REDACTED = '[redacted]';
49
+
50
+ /**
51
+ * Deep-copy a value with the value of any secret-looking key replaced.
52
+ * Cycles are broken so a self-referencing object cannot hang the logger.
53
+ * @param {any} value - Value to redact
54
+ * @param {WeakSet<object>} [seen] - Objects already visited on this path
55
+ * @returns {any} A redacted copy safe to serialise
56
+ */
57
+ function redactSecrets(value, seen = new WeakSet()) {
58
+ if (value === null || typeof value !== 'object') return value;
59
+ if (seen.has(value)) return '[circular]';
60
+ seen.add(value);
61
+
62
+ if (Array.isArray(value)) return value.map(item => redactSecrets(item, seen));
63
+
64
+ /** @type {Record<string, any>} */
65
+ const out = {};
66
+ for (const [key, item] of Object.entries(value)) {
67
+ out[key] = SECRET_KEY_PATTERN.test(key) ? REDACTED : redactSecrets(item, seen);
68
+ }
69
+ return out;
70
+ }
71
+
38
72
  class Logger {
39
73
  constructor() {
40
74
  // Set log level from environment variable
@@ -109,10 +143,15 @@ class Logger {
109
143
  // File format without colors
110
144
  const fileFormat = `[${timestamp}] [${levelName}] ${message}`;
111
145
 
112
- // Add data if present
146
+ // Add data if present, with secrets redacted first. This is deliberately
147
+ // done here rather than at each call site: a logger for an SSH manager will
148
+ // eventually be handed a whole server config, and one forgotten call would
149
+ // write a production password to ~/.ssh-manager.log and to stderr, where
150
+ // the MCP host captures it. Redacting structurally means no call site can
151
+ // leak one.
113
152
  let dataStr = '';
114
153
  if (Object.keys(data).length > 0) {
115
- dataStr = '\n ' + JSON.stringify(data, null, 2).replace(/\n/g, '\n ');
154
+ dataStr = '\n ' + JSON.stringify(redactSecrets(data), null, 2).replace(/\n/g, '\n ');
116
155
  }
117
156
 
118
157
  return {
@@ -0,0 +1,46 @@
1
+ // Single POSIX shell-word quoting, shared by every builder that hands a string
2
+ // to a remote shell.
3
+ //
4
+ // It lived in database-manager.js after the v3.6.7 fix (CVE-2026-77383), and
5
+ // that is exactly why the same class of bug survived elsewhere: backup-manager,
6
+ // health-monitor and several inline commands in index.js never imported it and
7
+ // kept interpolating caller-controlled values raw. Keeping it in one module
8
+ // makes "did this builder quote its inputs?" a question with one answer.
9
+
10
+ const SQ = '\'';
11
+
12
+ /**
13
+ * Quote a value for safe inclusion as a single POSIX shell word.
14
+ *
15
+ * Wraps the value in single quotes and escapes any embedded single quote as
16
+ * '\'' so the remote shell treats it literally — it never interprets $(...),
17
+ * backticks, $VAR, ;, |, &, redirects, spaces, or newlines inside the value.
18
+ * EVERY caller-controlled value interpolated into a command string MUST go
19
+ * through this. Numbers are coerced to string; null/undefined become an empty
20
+ * quoted word.
21
+ *
22
+ * @param {any} value - Value to quote
23
+ * @returns {string} The value as one safely quoted shell word
24
+ */
25
+ export function shellQuote(value) {
26
+ if (value === null || value === undefined) return SQ + SQ;
27
+ // Replace every ' with '\'' (close quote, escaped quote, reopen), then wrap.
28
+ return SQ + String(value).replace(/'/g, SQ + '\\' + SQ + SQ) + SQ;
29
+ }
30
+
31
+ /**
32
+ * Coerce a value to a safe non-negative integer for use in a command.
33
+ *
34
+ * Numeric tool arguments (line counts, ports, retention days) are declared as
35
+ * z.number() but still land inside command strings, where a non-finite or
36
+ * fractional value would serialise into something the shell reads oddly.
37
+ *
38
+ * @param {any} value - Value to coerce
39
+ * @param {number} fallback - Value used when the input is not a finite number
40
+ * @returns {number} A non-negative integer
41
+ */
42
+ export function safeInteger(value, fallback) {
43
+ const n = Number(value);
44
+ if (!Number.isFinite(n)) return fallback;
45
+ return Math.max(0, Math.trunc(n));
46
+ }