mcp-ssh-manager 4.1.0 → 4.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/docs/MIGRATION.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # Upgrading from 3.8 to 4.0
2
2
 
3
- **4.0 is released, on npm and as a desktop application**; the latest is 4.1.0 ([release](https://github.com/bvisible/mcp-ssh-manager/releases/tag/v4.1.0)).
3
+ **4.0 is released, on npm and as a desktop application**; the latest is 4.2.0 ([release](https://github.com/bvisible/mcp-ssh-manager/releases/tag/v4.2.0)).
4
4
  The last 3.8 release is 3.8.7, for anyone who pins the 3.8 line.
5
5
 
6
6
  The upgrade path preserves headless npm/CLI use. The application, vault import
@@ -87,22 +87,29 @@ parity with the `.env` form.
87
87
  ## Audit log
88
88
 
89
89
  When `AUDIT_LOG` (`.env`) or `audit_log` (TOML) is set to a file path, every
90
- **gated** tool invocation appends a JSONL record:
90
+ tool that targets the server appends a JSONL record of what happened: the
91
+ outcome of each one that ran, and the reason for each one that was refused.
91
92
 
92
93
  ```json
93
94
  {"ts":"2026-05-18T15:30:00.123Z","server":"prod","tool":"ssh_execute","args":{"command":"ls /tmp"},"allowed":true,"exitCode":0,"success":true}
94
95
  {"ts":"2026-05-18T15:30:14.789Z","server":"prod","tool":"ssh_execute","args":{"command":"rm /tmp/x"},"allowed":false,"reason":"Command refused on server \"prod\" (mode: readonly): matches built-in destructive pattern /(^|[\\s;&|])rm(\\s|$)/."}
96
+ {"ts":"2026-05-18T15:31:02.004Z","server":"prod","tool":"ssh_tail","args":{"file":"/var/log/app.log","lines":5,"follow":false},"allowed":true,"success":true}
95
97
  ```
96
98
 
97
- Secrets (`password`, `passphrase`, `sudoPassword`, `token`, `secret`, `apikey`)
98
- are redacted to `***` before being written, even if a tool somehow passed them
99
- through args.
99
+ - A tool that knows its exit code (`ssh_execute`, `ssh_execute_sudo`, `ssh_upload`,
100
+ `ssh_download`, group and session commands) records `exitCode` and `success`;
101
+ every other tool records `success`, with `error` when it failed.
102
+ - Tools that only read or edit local state (`ssh_list_servers`, aliases, tunnel
103
+ lists, `ssh_history`…) leave no line: nothing reached a server.
104
+ - A value whose key looks like a secret (`password`, `dbPassword`, `passphrase`,
105
+ `sudoPassword`, `token`, `secret`, `apiKey`, `credential`, `privateKey`…) is
106
+ replaced by `***` before it is written, and in the approval request too.
107
+ - Before 4.2.0 only `ssh_execute` and `ssh_upload` (and, from 4.1.0, sudo,
108
+ downloads, group and session commands) recorded their outcome; a refusal was
109
+ recorded for every tool.
100
110
 
101
111
  Log rotation is not handled by `mcp-ssh-manager` — use `logrotate`, `vector`,
102
- or your log shipper of choice. v3.5.0 audits cover the gated tool set:
103
- `ssh_execute`, `ssh_upload`, `ssh_execute_sudo`, plus denials on every other
104
- mutating tool. Pure read tools (`ssh_health_check`, `ssh_db_query`, `ssh_tail`…)
105
- are not audited in v3.5.0 — open an issue if you need full coverage.
112
+ or your log shipper of choice.
106
113
 
107
114
  ## Recipes
108
115
 
package/docs/SEO.md CHANGED
@@ -57,7 +57,7 @@ Once installed, simply ask Claude Code:
57
57
 
58
58
  ```bash
59
59
  ssh-manager codex setup
60
- ssh-manager codex migrate
60
+ ssh-manager export servers.toml
61
61
  ```
62
62
 
63
63
  Configure in `~/.codex/config.toml`:
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "mcp-ssh-manager",
3
- "version": "4.1.0",
3
+ "version": "4.2.0",
4
4
  "mcpName": "io.github.bvisible/mcp-ssh-manager",
5
5
  "description": "MCP server for SSH: let AI agents (Claude Code, Codex, any MCP client) run commands, transfer files and manage servers over SSH, with human approval, an encrypted vault and a live audit trail.",
6
6
  "main": "src/index.js",
@@ -14,7 +14,7 @@
14
14
  "setup": "npm install && pip install -r tools/requirements.txt",
15
15
  "configure": "python tools/server-manager.py",
16
16
  "test-connection": "python tools/test-connection.py",
17
- "test": "npm run test:lockfile && npm run test:sudostdin && npm run test:vault && npm run test:recovery && npm run test:upgrade && npm run test:notify && npm run test:commands && npm run test:commandlog && npm run test:portability && npm run test:approval && npm run test:controlplane && npm run test:terminal && npm run test:files && npm run test:livestream && npm run test:skills && npm run test:redaction && npm run test:profiles && npm run test:aliases && npm run test:hooks && npm run test:tools && npm run test:policy && npm run test:policynames && npm run test:auditsuccess && npm run test:ping && npm run test:config && npm run test:fieldnames && npm run test:groups && npm run test:agentforward && npm run test:agentkey && npm run test:certpath && npm run test:agentannounce && npm run test:autherrors && npm run test:envchoice && npm run test:lifecycle && npm run test:tunnel && npm run test:sync && npm run test:sync-path && npm run test:dbquoting && npm run test:dbinjection && npm run test:quoteprops && npm run test:backupinjection && npm run test:dbrowcount && npm run test:dbclientcmds && npm run test:migration && npm run test:security && npm run test:hostkeys && npm run test:proxy && npm run test:working-directory && npm run test:groups-persistence && npm run test:release && npm run test:cli-experience && npm run test:desktop-install && npm run test:agent-clients && npm run test:appupdate && npm run test:preview && npm run test:desktop-smoke && npm run test:local-shell && npm run test:cli-edit && npm run test:timeoutwrap",
17
+ "test": "npm run test:lockfile && npm run test:sudostdin && npm run test:vault && npm run test:recovery && npm run test:upgrade && npm run test:notify && npm run test:commands && npm run test:commandlog && npm run test:portability && npm run test:approval && npm run test:controlplane && npm run test:terminal && npm run test:files && npm run test:livestream && npm run test:skills && npm run test:redaction && npm run test:profiles && npm run test:aliases && npm run test:hooks && npm run test:tools && npm run test:policy && npm run test:policynames && npm run test:auditsuccess && npm run test:ping && npm run test:config && npm run test:fieldnames && npm run test:groups && npm run test:agentforward && npm run test:agentkey && npm run test:certpath && npm run test:agentannounce && npm run test:autherrors && npm run test:envchoice && npm run test:lifecycle && npm run test:tunnel && npm run test:sync && npm run test:sync-path && npm run test:dbquoting && npm run test:dbinjection && npm run test:quoteprops && npm run test:backupinjection && npm run test:dbrowcount && npm run test:dbclientcmds && npm run test:migration && npm run test:security && npm run test:hostkeys && npm run test:proxy && npm run test:working-directory && npm run test:groups-persistence && npm run test:release && npm run test:cli-experience && npm run test:desktop-install && npm run test:agent-clients && npm run test:appupdate && npm run test:preview && npm run test:desktop-smoke && npm run test:local-shell && npm run test:cli-edit && npm run test:timeoutwrap && npm run test:downloadstats && npm run test:remotetunnel && npm run test:connsharing && npm run test:auditcoverage && npm run test:background && npm run test:quietstderr && npm run test:sshguard && npm run test:locale && npm run test:healthdisks && npm run test:backupintegrity && npm run test:clienvlines && npm run test:clicodex",
18
18
  "test:lockfile": "node tests/test-lockfile.js",
19
19
  "test:sudostdin": "node tests/test-sudo-stdin.js",
20
20
  "test:vault": "node tests/test-secret-store.js",
@@ -50,6 +50,13 @@
50
50
  "test:dbrowcount": "node tests/test-database-row-count.js",
51
51
  "test:dbclientcmds": "node tests/test-db-client-commands.js",
52
52
  "test:timeoutwrap": "node tests/test-timeout-wrapper.js",
53
+ "test:remotetunnel": "node tests/test-remote-tunnel.js",
54
+ "test:connsharing": "node tests/test-connection-sharing.js",
55
+ "test:auditcoverage": "node tests/test-audit-coverage.js",
56
+ "test:background": "node tests/test-background-job.js",
57
+ "test:quietstderr": "node tests/test-quiet-stderr.js",
58
+ "test:sshguard": "node tests/test-ssh-guard.js",
59
+ "test:downloadstats": "node tests/test-download-stats.js",
53
60
  "test:cli-edit": "node tests/test-cli-edit-server.js",
54
61
  "test:all": "npm test && npm run typecheck && ./scripts/validate.sh",
55
62
  "validate": "./scripts/validate.sh",
@@ -83,7 +90,12 @@
83
90
  "test:preview": "node tests/test-preview-candidate.js",
84
91
  "test:desktop-smoke": "node tests/test-desktop-smoke.js",
85
92
  "test:local-shell": "node tests/test-local-shell.js",
86
- "test:policynames": "node tests/test-policy-name-resolution.js"
93
+ "test:policynames": "node tests/test-policy-name-resolution.js",
94
+ "test:locale": "node tests/test-locale.js",
95
+ "test:healthdisks": "node tests/test-health-disks.js",
96
+ "test:backupintegrity": "node tests/test-backup-integrity.js",
97
+ "test:clienvlines": "node tests/test-cli-env-lines.js",
98
+ "test:clicodex": "node tests/test-cli-codex.js"
87
99
  },
88
100
  "keywords": [
89
101
  "mcp",
@@ -21,6 +21,27 @@ const FIELDS = ['name', 'host', 'user', 'password', 'keyPath', 'passphrase', 'po
21
21
  'proxyCommand', 'forwardAgent', 'mode', 'allowPatterns', 'denyPatterns', 'auditLog', 'source'];
22
22
  let passed = 0;
23
23
  const ok = label => console.log(`✓ ${++passed}. ${label}`);
24
+ // Optional input properties a release may ADD to an existing tool. The check
25
+ // below still fails on anything else that differs from the previous release: a
26
+ // removed or renamed property, a changed type or description, a required
27
+ // property that was not there. An old client can trip on those; it cannot on a
28
+ // property it never sends. List an addition here on purpose, with its release.
29
+ const ADDED_OPTIONAL_INPUTS = {
30
+ ssh_execute: ['background'], // 4.2.0
31
+ };
32
+ /** The schemas with the declared additions taken out, each checked to be optional. */
33
+ function withoutDeclaredAdditions(schemas) {
34
+ const copy = structuredClone(schemas);
35
+ for (const [tool, names] of Object.entries(ADDED_OPTIONAL_INPUTS)) {
36
+ for (const name of names) {
37
+ const schema = copy[tool];
38
+ if (!schema?.properties || !(name in schema.properties)) continue;
39
+ assert.ok(!(schema.required || []).includes(name), `${tool}.${name} was added as required: an old client would fail`);
40
+ delete schema.properties[name];
41
+ }
42
+ }
43
+ return copy;
44
+ }
24
45
  const canonical = value => Array.isArray(value) ? value.map(canonical)
25
46
  : value && typeof value === 'object' ? Object.fromEntries(Object.keys(value).sort().map(key => [key, canonical(value[key])])) : value;
26
47
 
@@ -210,8 +231,9 @@ async function main() {
210
231
  const after = { protocol: await interrogate(item, path.join(installed, 'src/index.js')), loader: loaderSnapshot(installed, item) };
211
232
  assert.deepEqual(after.loader, before[item.name].loader, `${item.name}: effective ConfigLoader field fingerprints differ`);
212
233
  assert.deepEqual(after.protocol.listing, before[item.name].protocol.listing, `${item.name}: MCP listing changed`);
213
- assert.deepEqual(after.protocol.schemas, before[item.name].protocol.schemas, `${item.name}: MCP tool names or input schemas changed`);
214
- ok(`${item.name}: effective fields, MCP listing and all 37 tool input schemas unchanged`);
234
+ assert.deepEqual(withoutDeclaredAdditions(after.protocol.schemas), withoutDeclaredAdditions(before[item.name].protocol.schemas), `${item.name}: MCP tool names or input schemas changed`);
235
+ const added = Object.entries(ADDED_OPTIONAL_INPUTS).flatMap(([tool, names]) => names.filter(name => after.protocol.schemas[tool]?.properties?.[name] && !before[item.name].protocol.schemas[tool]?.properties?.[name]).map(name => `${tool}.${name}`));
236
+ ok(`${item.name}: effective fields, MCP listing and all 37 tool input schemas unchanged${added.length ? ` (declared optional additions: ${added.join(', ')})` : ''}`);
215
237
  }
216
238
  untouched(scenarios); ok('upgrade leaves original config bytes intact and starts no UI, listener, prompt or vault');
217
239
  installPrevious(); assert.equal(packageVersion(), PREVIOUS);
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": "4.1.0",
9
+ "version": "4.2.0",
10
10
  "packages": [
11
11
  {
12
12
  "registryType": "npm",
13
13
  "identifier": "mcp-ssh-manager",
14
- "version": "4.1.0",
14
+ "version": "4.2.0",
15
15
  "transport": {
16
16
  "type": "stdio"
17
17
  },
package/src/audit.js CHANGED
@@ -12,21 +12,12 @@
12
12
 
13
13
  import fs from 'fs';
14
14
  import path from 'path';
15
- import { logger } from './logger.js';
16
-
17
- // Field names whose values should never appear in the audit log even if a tool
18
- // somehow passed them through args. Case-insensitive.
19
- const REDACT_FIELDS = new Set([
20
- 'password',
21
- 'passphrase',
22
- 'sudopassword',
23
- 'sudo_password',
24
- 'token',
25
- 'secret',
26
- 'apikey',
27
- 'api_key',
28
- ]);
15
+ import { logger, SECRET_KEY_PATTERN } from './logger.js';
29
16
 
17
+ // A value whose key looks like a secret never appears in the audit log, even if
18
+ // a tool passed it through args. The rule is the logger's (SECRET_KEY_PATTERN),
19
+ // not a list of exact names: a list missed dbPassword and db_password, so a
20
+ // database password reached the log, and the approval request, in clear text.
30
21
  const REDACTED = '***';
31
22
 
32
23
  /**
@@ -44,7 +35,7 @@ export function sanitize(value) {
44
35
  if (Array.isArray(value)) return value.map(sanitize);
45
36
  const out = {};
46
37
  for (const [k, v] of Object.entries(value)) {
47
- if (REDACT_FIELDS.has(k.toLowerCase())) {
38
+ if (SECRET_KEY_PATTERN.test(k)) {
48
39
  out[k] = REDACTED;
49
40
  } else {
50
41
  out[k] = sanitize(v);
@@ -0,0 +1,44 @@
1
+ // Run a command on the target fully detached from the SSH session, for the jobs
2
+ // that outlive an ssh_execute call (a training run, a long build): the call
3
+ // returns at once with the job's pid and the file its output goes to.
4
+ //
5
+ // Idea from SEU-zhc's fork, built differently on one point: the log file is
6
+ // never chosen by the caller. A free path would let a command that passes the
7
+ // readonly policy (`echo "<key>"`) overwrite any file the SSH user can write,
8
+ // ~/.ssh/authorized_keys included, so the engine creates its own private file
9
+ // with mktemp instead.
10
+ import { shellQuote } from './shell-quote.js';
11
+
12
+ // Run by `sh` with the command as $1, so the command is never spliced into this
13
+ // text. nohup keeps the job past the end of the session; stdout and stderr go to
14
+ // a fresh private file and stdin to /dev/null, so no descriptor of the SSH
15
+ // channel stays open and the call can finish while the job runs on.
16
+ const BACKGROUND_SCRIPT = 'log=$(mktemp "${TMPDIR:-/tmp}/ssh-manager-bg-XXXXXX") || exit 1;'
17
+ + ' nohup sh -c "$1" > "$log" 2>&1 < /dev/null & echo "$! $log"';
18
+
19
+ /**
20
+ * Wrap a command so it starts detached and prints "<pid> <log file>".
21
+ *
22
+ * Like withRemoteTimeout, the result is one simple command made only of
23
+ * single-quoted words: the SSH server hands it to the account's login shell,
24
+ * which may be csh or tcsh and would reject `$(...)` or `if ... fi` at the top
25
+ * level.
26
+ * @param {string} command
27
+ * @returns {string}
28
+ */
29
+ export function buildBackgroundCommand(command) {
30
+ return `sh -c ${shellQuote(BACKGROUND_SCRIPT)} sh ${shellQuote(command)}`;
31
+ }
32
+
33
+ /**
34
+ * Read what buildBackgroundCommand printed.
35
+ * @param {string} stdout
36
+ * @returns {{pid: number, logFile: string} | null} null if the job did not start
37
+ */
38
+ export function parseBackgroundStart(stdout) {
39
+ for (const line of String(stdout ?? '').split('\n').reverse()) {
40
+ const match = /^(\d+) (\/.+)$/.exec(line.trim());
41
+ if (match) return { pid: Number(match[1]), logFile: match[2] };
42
+ }
43
+ return null;
44
+ }
@@ -8,6 +8,7 @@ import path from 'path';
8
8
  import crypto from 'crypto';
9
9
  import { logger } from './logger.js';
10
10
  import { shellQuote, safeInteger } from './shell-quote.js';
11
+ import { guardedDump, guardedFeed, mongoArchivePath } from './dump-guard.js';
11
12
 
12
13
  // Backup types
13
14
  export const BACKUP_TYPES = {
@@ -90,6 +91,18 @@ export function getBackupFilePath(backupId, backupDir = DEFAULT_BACKUP_DIR, exte
90
91
  return path.join(backupDir, `${backupId}${extension}`);
91
92
  }
92
93
 
94
+ /**
95
+ * The extension of the file (or directory) a backup of this kind is stored as.
96
+ * MongoDB is the one that differs: a compressed dump is the archive mongoArchivePath()
97
+ * names, <id>.tar.gz, and an uncompressed one is the dump directory itself.
98
+ * @param {string} type
99
+ * @param {boolean} [compressed]
100
+ */
101
+ export function backupExtension(type, compressed = true) {
102
+ if (type !== BACKUP_TYPES.MONGODB) return '.gz';
103
+ return compressed ? '.tar.gz' : '';
104
+ }
105
+
93
106
  /**
94
107
  * Build MySQL dump command
95
108
  */
@@ -121,13 +134,8 @@ export function buildMySQLDumpCommand(options) {
121
134
  command += ` ${shellQuote(database)}`;
122
135
 
123
136
  // Output handling
124
- if (compress) {
125
- command += ` | gzip > ${shellQuote(outputFile)}`;
126
- } else {
127
- command += ` > ${shellQuote(outputFile)}`;
128
- }
129
-
130
- return command;
137
+ // A producer that fails must fail the whole command and leave no file: see dump-guard.js.
138
+ return guardedDump(command, outputFile, compress);
131
139
  }
132
140
 
133
141
  /**
@@ -164,13 +172,8 @@ export function buildPostgreSQLDumpCommand(options) {
164
172
  command += ` ${shellQuote(database)}`;
165
173
 
166
174
  // Output handling
167
- if (compress) {
168
- command += ` | gzip > ${shellQuote(outputFile)}`;
169
- } else {
170
- command += ` > ${shellQuote(outputFile)}`;
171
- }
172
-
173
- return command;
175
+ // A producer that fails must fail the whole command and leave no file: see dump-guard.js.
176
+ return guardedDump(command, outputFile, compress);
174
177
  }
175
178
 
176
179
  /**
@@ -203,7 +206,7 @@ export function buildMongoDBDumpCommand(options) {
203
206
 
204
207
  // Compress the output directory
205
208
  if (compress) {
206
- const archiveName = `${outputDir}.tar.gz`;
209
+ const archiveName = mongoArchivePath(outputDir);
207
210
  // dirname/basename receive the quoted value, so the substitution itself
208
211
  // cannot be steered by the caller.
209
212
  command += ` && tar -czf ${shellQuote(archiveName)} -C "$(dirname ${shellQuote(outputDir)})" "$(basename ${shellQuote(outputDir)})"`;
@@ -283,14 +286,7 @@ function buildMySQLRestoreCommand(backupFile, options) {
283
286
 
284
287
  let command = '';
285
288
 
286
- // Decompress if needed
287
- if (backupFile.endsWith('.gz')) {
288
- command = `gunzip -c ${shellQuote(backupFile)} | `;
289
- } else {
290
- command = `cat ${shellQuote(backupFile)} | `;
291
- }
292
-
293
- command += 'mysql';
289
+ command = 'mysql';
294
290
 
295
291
  // Connection parameters
296
292
  if (user) command += ` -u${shellQuote(user)}`;
@@ -299,7 +295,9 @@ function buildMySQLRestoreCommand(backupFile, options) {
299
295
  if (port) command += ` -P ${safeInteger(port, 3306)}`;
300
296
  if (database) command += ` ${shellQuote(database)}`;
301
297
 
302
- return command;
298
+ // A gzip file is verified whole before mysql reads a byte of it (dump-guard.js).
299
+ if (backupFile.endsWith('.gz')) return guardedFeed(backupFile, command);
300
+ return `cat ${shellQuote(backupFile)} | ${command}`;
303
301
  }
304
302
 
305
303
  /**
@@ -331,11 +329,8 @@ function buildPostgreSQLRestoreCommand(backupFile, options) {
331
329
  command += ' --clean --if-exists';
332
330
 
333
331
  // Handle compressed files
334
- if (backupFile.endsWith('.gz')) {
335
- command = `gunzip -c ${shellQuote(backupFile)} | ${command}`;
336
- } else {
337
- command += ` ${shellQuote(backupFile)}`;
338
- }
332
+ if (backupFile.endsWith('.gz')) return guardedFeed(backupFile, command);
333
+ command += ` ${shellQuote(backupFile)}`;
339
334
 
340
335
  return command;
341
336
  }
@@ -3,6 +3,7 @@ import TOML from '@iarna/toml';
3
3
  import fs from 'fs';
4
4
  import path from 'path';
5
5
  import os from 'os';
6
+ import { fileURLToPath } from 'url';
6
7
  import { logger } from './logger.js';
7
8
  import { VALID_MODES } from './policy.js';
8
9
  import { SecretStore, defaultVaultPath } from './secret-store.js';
@@ -537,7 +538,10 @@ export class ConfigLoader {
537
538
 
538
539
  config.mcp_servers['ssh-manager'] = {
539
540
  command: 'node',
540
- args: [path.join(process.cwd(), 'src', 'index.js')],
541
+ // This module's own folder, not the working directory: the entry has to name an
542
+ // engine that exists wherever the command is run from (an npm install has no
543
+ // src/ under the current directory).
544
+ args: [path.join(path.dirname(fileURLToPath(import.meta.url)), 'index.js')],
541
545
  env: {
542
546
  SSH_CONFIG_PATH: path.join(os.homedir(), '.codex', 'ssh-config.toml')
543
547
  },
@@ -13,7 +13,8 @@ export const DB_TYPES = {
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
15
  import { shellQuote } from './shell-quote.js';
16
- export { shellQuote };
16
+ import { guardedDump, guardedFeed, mongoArchivePath } from './dump-guard.js';
17
+ export { shellQuote, mongoArchivePath };
17
18
 
18
19
  /**
19
20
  * Build MySQL dump command
@@ -44,13 +45,8 @@ export function buildMySQLDumpCommand(options) {
44
45
  command += ` ${tables.map(shellQuote).join(' ')}`;
45
46
  }
46
47
 
47
- if (compress) {
48
- command += ` | gzip > ${shellQuote(outputFile)}`;
49
- } else {
50
- command += ` > ${shellQuote(outputFile)}`;
51
- }
52
-
53
- return command;
48
+ // A producer that fails must fail the whole command and leave no file: see dump-guard.js.
49
+ return guardedDump(command, outputFile, compress);
54
50
  }
55
51
 
56
52
  /**
@@ -87,13 +83,8 @@ export function buildPostgreSQLDumpCommand(options) {
87
83
 
88
84
  command += ` ${shellQuote(database)}`;
89
85
 
90
- if (compress) {
91
- command += ` | gzip > ${shellQuote(outputFile)}`;
92
- } else {
93
- command += ` > ${shellQuote(outputFile)}`;
94
- }
95
-
96
- return command;
86
+ // A producer that fails must fail the whole command and leave no file: see dump-guard.js.
87
+ return guardedDump(command, outputFile, compress);
97
88
  }
98
89
 
99
90
  /**
@@ -127,7 +118,7 @@ export function buildMongoDBDumpCommand(options) {
127
118
  command += ` --out ${shellQuote(outputDir)}`;
128
119
 
129
120
  if (compress) {
130
- command += ` && tar -czf ${shellQuote(outputDir + '.tar.gz')} -C "$(dirname ${shellQuote(outputDir)})" "$(basename ${shellQuote(outputDir)})"`;
121
+ command += ` && tar -czf ${shellQuote(mongoArchivePath(outputDir))} -C "$(dirname ${shellQuote(outputDir)})" "$(basename ${shellQuote(outputDir)})"`;
131
122
  command += ` && rm -rf ${shellQuote(outputDir)}`;
132
123
  }
133
124
 
@@ -147,22 +138,16 @@ export function buildMySQLImportCommand(options) {
147
138
  inputFile
148
139
  } = options;
149
140
 
150
- let command = '';
151
-
152
- if (inputFile.endsWith('.gz')) {
153
- command = `gunzip -c ${shellQuote(inputFile)} | `;
154
- } else {
155
- command = `cat ${shellQuote(inputFile)} | `;
156
- }
157
-
158
- command += 'mysql';
141
+ let command = 'mysql';
159
142
  if (user) command += ` -u${shellQuote(user)}`;
160
143
  if (password) command += ` -p${shellQuote(password)}`;
161
144
  if (host) command += ` -h ${shellQuote(host)}`;
162
145
  if (port) command += ` -P ${shellQuote(port)}`;
163
146
  command += ` ${shellQuote(database)}`;
164
147
 
165
- return command;
148
+ // A gzip file is verified whole before mysql reads a byte of it (dump-guard.js).
149
+ if (inputFile.endsWith('.gz')) return guardedFeed(inputFile, command);
150
+ return `cat ${shellQuote(inputFile)} | ${command}`;
166
151
  }
167
152
 
168
153
  /**
@@ -190,11 +175,8 @@ export function buildPostgreSQLImportCommand(options) {
190
175
  command += ' --clean --if-exists';
191
176
  command += ` -d ${shellQuote(database)}`;
192
177
 
193
- if (inputFile.endsWith('.gz')) {
194
- command = `gunzip -c ${shellQuote(inputFile)} | ${command}`;
195
- } else {
196
- command += ` ${shellQuote(inputFile)}`;
197
- }
178
+ if (inputFile.endsWith('.gz')) return guardedFeed(inputFile, command);
179
+ command += ` ${shellQuote(inputFile)}`;
198
180
 
199
181
  return command;
200
182
  }
@@ -0,0 +1,79 @@
1
+ // Backups and restores whose exit code means what it says.
2
+ //
3
+ // `mysqldump ... | gzip > out` reports the exit code of the LAST command of the
4
+ // pipeline: when the dump failed (wrong password, missing database, full disk),
5
+ // gzip still succeeded, the file was an empty archive of 20 bytes, and ssh_db_dump
6
+ // and ssh_backup_create answered success with it. The mirror image on the way in:
7
+ // `gunzip -c dump.gz | mysql` runs mysql on whatever gunzip managed to read, so a
8
+ // truncated archive was restored in part, without an error.
9
+ //
10
+ // Found by reading jaredshuai's fork, which hit the same two defects and fixed them
11
+ // with a temporary file; this keeps the dump streaming (a database can be bigger than
12
+ // the free space on its own disk) by recording the producer's exit status on the side.
13
+ //
14
+ // Both commands are one simple command of single-quoted words (sh -c '<script>' sh
15
+ // <args>), like withRemoteTimeout: the SSH server hands them to the account's login
16
+ // shell, which may be csh or tcsh and would reject `{ }` and `$?` at the top level.
17
+ // The producer and the file names are positional parameters, never spliced into the
18
+ // script, and the producer is the same quoted text that used to run as it was.
19
+ import { shellQuote } from './shell-quote.js';
20
+
21
+ // $1 = file to write, $2 = the producing command, $3 = 1 to compress.
22
+ // The producer's status goes to a file next to the output (no mktemp: it is not on
23
+ // every system, and the folder is known to be writable since the output goes there).
24
+ // A failed run leaves no output file at all, so nothing can be mistaken for a backup.
25
+ const GUARDED_DUMP_SCRIPT = [
26
+ 'out=$1; st="$1.status.$$"; trap \'rm -f "$st"\' EXIT;',
27
+ 'if [ "$3" = 1 ]; then',
28
+ '{ eval "$2"; echo $? > "$st"; } | gzip -c > "$out"; gz=$?;',
29
+ 'read status < "$st" || status=1;',
30
+ 'if [ "$status" != 0 ] || [ "$gz" != 0 ]; then rm -f "$out"; exit 1; fi;',
31
+ 'else eval "$2" > "$out" || { rm -f "$out"; exit 1; }; fi',
32
+ ].join(' ');
33
+
34
+ // $1 = the gzip file, $2 = the command that reads the decompressed stream.
35
+ // A real gzip file is tested whole before a byte reaches the consumer. A file that
36
+ // is not gzip at all (a plain dump a backup left under a .gz name when it was made
37
+ // without compression) is fed as it is, so it is not refused for its name.
38
+ const GUARDED_FEED_SCRIPT = [
39
+ 'f=$1;',
40
+ 'if [ "$(head -c 2 "$f" | od -An -tx1 | tr -d " \\n")" = 1f8b ];',
41
+ 'then gzip -t "$f" || exit 1; gunzip -c "$f" | eval "$2";',
42
+ 'else eval "$2" < "$f"; fi',
43
+ ].join(' ');
44
+
45
+ /**
46
+ * The command that runs `producer` and writes its output to `outputFile`
47
+ * (gzipped when `compress`), and fails, leaving no file, if the producer does.
48
+ * @param {string} producer - A command line already built from quoted words
49
+ * @param {string} outputFile
50
+ * @param {boolean} [compress]
51
+ * @returns {string}
52
+ */
53
+ export function guardedDump(producer, outputFile, compress = true) {
54
+ return `sh -c ${shellQuote(GUARDED_DUMP_SCRIPT)} sh ${shellQuote(outputFile)} ${shellQuote(producer)} ${compress ? '1' : '0'}`;
55
+ }
56
+
57
+ /**
58
+ * The command that feeds a gzip file to `consumer` once the whole file has been
59
+ * verified, and fails without running the consumer if it is corrupt.
60
+ * @param {string} gzipFile
61
+ * @param {string} consumer - A command line already built from quoted words
62
+ * @returns {string}
63
+ */
64
+ export function guardedFeed(gzipFile, consumer) {
65
+ return `sh -c ${shellQuote(GUARDED_FEED_SCRIPT)} sh ${shellQuote(gzipFile)} ${shellQuote(consumer)}`;
66
+ }
67
+
68
+ /**
69
+ * Where mongodump's output ends up when it is compressed: one archive beside the
70
+ * dump directory. The one place that knows it: the dump builders write it, and
71
+ * ssh_backup_create, ssh_backup_restore and ssh_db_dump measure, record and read the
72
+ * same path. They used to disagree (written as <id>.tar.gz, measured and restored as
73
+ * <id>.gz), so a MongoDB backup reported a size of 0 and could not be restored.
74
+ * @param {string} outputDir
75
+ * @returns {string}
76
+ */
77
+ export function mongoArchivePath(outputDir) {
78
+ return `${outputDir}.tar.gz`;
79
+ }
@@ -48,7 +48,7 @@ function buildMemoryCheckCommand() {
48
48
  function buildDiskCheckCommand(mountPoint = '/') {
49
49
  // Returns JSON with disk usage for specific mount point or all
50
50
  if (mountPoint === 'all') {
51
- return 'df -h | awk \'NR>1 {gsub(/%/,"",$5); printf "{\\"mount\\":\\"%s\\",\\"size\\":\\"%s\\",\\"used\\":\\"%s\\",\\"avail\\":\\"%s\\",\\"percent\\":%s}\\n", $6,$2,$3,$4,$5}\'';
51
+ return 'LC_ALL=C df -PTh | awk \'NR>1 {gsub(/%/,"",$6); printf "{\\"filesystem\\":\\"%s\\",\\"mount\\":\\"%s\\",\\"size\\":\\"%s\\",\\"used\\":\\"%s\\",\\"avail\\":\\"%s\\",\\"percent\\":%s}\\n", $2,$7,$3,$4,$5,$6}\'';
52
52
  }
53
53
  return `df -h "${mountPoint}" | awk 'NR>1 {gsub(/%/,"",$5); printf "{\\"mount\\":\\"%s\\",\\"size\\":\\"%s\\",\\"used\\":\\"%s\\",\\"avail\\":\\"%s\\",\\"percent\\":%s}", $6,$2,$3,$4,$5}'`;
54
54
  }
@@ -116,6 +116,10 @@ function parseDiskUsage(output) {
116
116
  for (const line of lines) {
117
117
  try {
118
118
  const disk = JSON.parse(line);
119
+ // Container layers share the backing disk's free space. RAM-backed and
120
+ // read-only image mounts are not independent persistent disks either.
121
+ // Keep / even when the monitored host itself runs inside a container.
122
+ if (disk.mount !== '/' && ['overlay', 'aufs', 'tmpfs', 'devtmpfs', 'squashfs'].includes(disk.filesystem)) continue;
119
123
  disk.status = disk.percent > 90 ? HEALTH_STATUS.CRITICAL : disk.percent > 80 ? HEALTH_STATUS.WARNING : HEALTH_STATUS.HEALTHY;
120
124
  disks.push(disk);
121
125
  } catch (error) {
@@ -322,7 +326,7 @@ export function buildLoadAlertConfigCommand(configPath = '/etc/ssh-manager-alert
322
326
  export function checkAlertThresholds(metrics, thresholds) {
323
327
  const alerts = [];
324
328
 
325
- if (thresholds.cpu && metrics.cpu && metrics.cpu.percent > thresholds.cpu) {
329
+ if (thresholds.cpu && metrics.cpu && metrics.cpu.percent >= thresholds.cpu) {
326
330
  alerts.push({
327
331
  type: 'cpu',
328
332
  severity: 'warning',
@@ -332,7 +336,7 @@ export function checkAlertThresholds(metrics, thresholds) {
332
336
  });
333
337
  }
334
338
 
335
- if (thresholds.memory && metrics.memory && metrics.memory.percent > thresholds.memory) {
339
+ if (thresholds.memory && metrics.memory && metrics.memory.percent >= thresholds.memory) {
336
340
  alerts.push({
337
341
  type: 'memory',
338
342
  severity: 'warning',
@@ -344,7 +348,7 @@ export function checkAlertThresholds(metrics, thresholds) {
344
348
 
345
349
  if (thresholds.disk && metrics.disks) {
346
350
  for (const disk of metrics.disks) {
347
- if (disk.percent > thresholds.disk) {
351
+ if (disk.percent >= thresholds.disk) {
348
352
  alerts.push({
349
353
  type: 'disk',
350
354
  severity: 'warning',