mcp-ssh-manager 4.0.3 → 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.
Files changed (43) hide show
  1. package/CHANGELOG.md +199 -0
  2. package/CLAUDE.md +17 -5
  3. package/Formula/ssh-manager.rb +2 -2
  4. package/INSTALLATION.md +4 -0
  5. package/README.md +41 -5
  6. package/brand/README.md +1 -0
  7. package/cli/codex.js +67 -0
  8. package/cli/guard.js +69 -0
  9. package/cli/lib/config.sh +102 -37
  10. package/cli/ssh-manager +13 -0
  11. package/cli/ssh-manager.js +1 -1
  12. package/desktop/electron/electron-builder.yml +3 -0
  13. package/desktop/electron/locale.mjs +34 -0
  14. package/desktop/electron/main.js +52 -65
  15. package/desktop/electron/native-menu.mjs +44 -0
  16. package/desktop/electron/native.zh-CN.json +58 -0
  17. package/desktop/electron/package-lock.json +15 -40
  18. package/desktop/electron/package.json +4 -1
  19. package/desktop/electron/smoke-test.mjs +11 -1
  20. package/dist/ui/app.css +1 -1
  21. package/dist/ui/app.js +123 -115
  22. package/docs/MIGRATION.md +1 -1
  23. package/docs/SECURITY_MODES.md +15 -8
  24. package/docs/SEO.md +1 -1
  25. package/llms-install.md +97 -0
  26. package/package.json +17 -3
  27. package/scripts/check-action-pins.mjs +57 -0
  28. package/scripts/test-upgrade-from-published.mjs +24 -2
  29. package/server.json +2 -2
  30. package/src/audit.js +6 -15
  31. package/src/background-job.js +44 -0
  32. package/src/backup-manager.js +24 -29
  33. package/src/config-loader.js +10 -1
  34. package/src/database-manager.js +13 -31
  35. package/src/dump-guard.js +79 -0
  36. package/src/filtered-agent.js +53 -0
  37. package/src/health-monitor.js +8 -4
  38. package/src/index.js +216 -21
  39. package/src/logger.js +3 -1
  40. package/src/quiet-stderr.js +15 -0
  41. package/src/ssh-guard.js +344 -0
  42. package/src/ssh-manager.js +71 -2
  43. package/src/tunnel-manager.js +14 -4
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.0.3 ([release](https://github.com/bvisible/mcp-ssh-manager/releases/tag/v4.0.3)).
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`:
@@ -0,0 +1,97 @@
1
+ # Installing MCP SSH Manager — instructions for AI agents
2
+
3
+ These steps let an AI agent (Cline or any MCP client) set up this server for its
4
+ user. Follow them in order. Ask the user for anything you do not know; never
5
+ guess a host, a user name or a key.
6
+
7
+ ## 1. Check Node.js
8
+
9
+ ```bash
10
+ node --version
11
+ ```
12
+
13
+ Version 18 or later is required. If Node is missing or older, ask the user to
14
+ install a current LTS from https://nodejs.org before going on.
15
+
16
+ ## 2. Register the server with the MCP client
17
+
18
+ The server speaks MCP over stdio. Add this entry to the client's MCP settings
19
+ (for Cline: `cline_mcp_settings.json`, opened from *MCP Servers → Configure*):
20
+
21
+ ```json
22
+ {
23
+ "mcpServers": {
24
+ "ssh-manager": {
25
+ "command": "npx",
26
+ "args": ["-y", "mcp-ssh-manager"]
27
+ }
28
+ }
29
+ }
30
+ ```
31
+
32
+ `npx` downloads the published package on first use; nothing else needs to be
33
+ installed. A user who prefers a global install can run
34
+ `npm install -g mcp-ssh-manager` and use `"command": "mcp-ssh-manager"` with no
35
+ `args` instead.
36
+
37
+ ## 3. Describe the user's servers
38
+
39
+ Servers are read from `~/.ssh-manager/.env` (on Windows,
40
+ `%USERPROFILE%\.ssh-manager\.env`). Ask the user, for each server: a short name,
41
+ the host, the SSH user, the port if it is not 22, and the path of the private key
42
+ they use for it. Then create the directory and the file:
43
+
44
+ ```bash
45
+ mkdir -p ~/.ssh-manager
46
+ touch ~/.ssh-manager/.env
47
+ chmod 600 ~/.ssh-manager/.env
48
+ ```
49
+
50
+ Append one block per server. The name is the part between `SSH_SERVER_` and the
51
+ field, in capitals, with letters, digits and underscores only; the tools refer to
52
+ it in lower case (`PRODUCTION` below is `production`).
53
+
54
+ ```env
55
+ SSH_SERVER_PRODUCTION_HOST=203.0.113.10
56
+ SSH_SERVER_PRODUCTION_USER=deploy
57
+ SSH_SERVER_PRODUCTION_KEYPATH=~/.ssh/id_ed25519
58
+ SSH_SERVER_PRODUCTION_PORT=22
59
+ ```
60
+
61
+ Rules that matter:
62
+
63
+ - **Prefer a key.** Do not ask the user to type a password or a key passphrase
64
+ into the conversation. If a server only accepts a password, tell the user to
65
+ add `SSH_SERVER_<NAME>_PASSWORD=...` to the file themselves, or to run
66
+ `npx -y -p mcp-ssh-manager ssh-manager server add`, which asks for it in their
67
+ own terminal.
68
+ - **Offer a safety mode** for servers that matter. `SSH_SERVER_<NAME>_MODE=readonly`
69
+ refuses every tool that changes the server; `restricted` allows only commands
70
+ matching `SSH_SERVER_<NAME>_ALLOW_PATTERNS`. The default, `unrestricted`, allows
71
+ everything. See `docs/SECURITY_MODES.md`.
72
+ - **Do not overwrite** an existing `~/.ssh-manager/.env`: it may already hold the
73
+ user's servers. Append to it, and leave existing blocks as they are.
74
+
75
+ The first connection to a host records its key in `~/.ssh/known_hosts` (trust on
76
+ first use); later connections are refused if the key changes.
77
+
78
+ ## 4. Restart and check
79
+
80
+ Restart the MCP server in the client (for Cline: the restart button next to
81
+ `ssh-manager` in *MCP Servers*) so it reads the file, then:
82
+
83
+ 1. Call `ssh_list_servers`. Each server written above must be listed.
84
+ 2. Call `ssh_execute` with `{"server": "production", "command": "uptime"}` (use
85
+ the user's server name). A result with an exit code of 0 means the setup works.
86
+
87
+ If the server is missing from the list, check the variable names in the file. If
88
+ the connection is refused, check the key path, the user name and the port with the
89
+ user; `Permission denied` usually means the key is not authorised on the server.
90
+
91
+ ## Optional
92
+
93
+ - **Desktop application**: the same engine with an interface (approvals, live
94
+ output, a terminal, a file browser), no Node.js needed. Downloads:
95
+ https://github.com/bvisible/mcp-ssh-manager/releases/latest
96
+ - **Credentials in an encrypted vault** instead of the `.env`, and the full list of
97
+ options (jump hosts, groups, sudo, TOML configuration): see the `README.md`.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "mcp-ssh-manager",
3
- "version": "4.0.3",
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:ping && npm run test:config && npm run test:fieldnames && npm run test:groups && npm run test:agentforward && 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",
@@ -28,10 +28,12 @@
28
28
  "test:hooks": "node tests/test-hooks.js",
29
29
  "test:tools": "node tests/test-tool-registry.js",
30
30
  "test:policy": "node tests/test-policy.js",
31
+ "test:auditsuccess": "node tests/test-audit-success.js",
31
32
  "test:ping": "node tests/test-ssh-ping.js",
32
33
  "test:config": "node tests/test-server-config-manager.js",
33
34
  "test:fieldnames": "node tests/test-config-field-names.js",
34
35
  "test:groups": "node tests/test-server-groups.js",
36
+ "test:agentkey": "node --test tests/test-agent-key-selection.js tests/test-agent-key-selection-integration.js tests/test-agent-key-config.js tests/test-agent-openssh.js",
35
37
  "test:agentforward": "node tests/test-agent-forward.js",
36
38
  "test:certpath": "node tests/test-cert-path.js",
37
39
  "test:agentannounce": "node tests/test-agent-announce.js",
@@ -48,6 +50,13 @@
48
50
  "test:dbrowcount": "node tests/test-database-row-count.js",
49
51
  "test:dbclientcmds": "node tests/test-db-client-commands.js",
50
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",
51
60
  "test:cli-edit": "node tests/test-cli-edit-server.js",
52
61
  "test:all": "npm test && npm run typecheck && ./scripts/validate.sh",
53
62
  "validate": "./scripts/validate.sh",
@@ -81,7 +90,12 @@
81
90
  "test:preview": "node tests/test-preview-candidate.js",
82
91
  "test:desktop-smoke": "node tests/test-desktop-smoke.js",
83
92
  "test:local-shell": "node tests/test-local-shell.js",
84
- "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"
85
99
  },
86
100
  "keywords": [
87
101
  "mcp",
@@ -0,0 +1,57 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Check that every action a workflow pins by SHA is pinned to a commit of that
4
+ * action's own repository.
5
+ *
6
+ * Two ways a pin can look right and be wrong:
7
+ *
8
+ * - the SHA of an annotated tag object instead of the commit it points to.
9
+ * GitHub Actions runs it, but OpenSSF Scorecard refuses to publish results
10
+ * from such a workflow ("imposter commit"), and from 2026-08-28 to 2026-11-09
11
+ * the Scorecard results of this repository were never published because of
12
+ * one, with every run green.
13
+ * - a commit from a fork. GitHub resolves those through the parent repository,
14
+ * which is how an "imposter commit" smuggles code in under a trusted name.
15
+ *
16
+ * Asks the GitHub API (GITHUB_TOKEN or GH_TOKEN when set) whether
17
+ * repos/<owner>/<repo>/commits/<sha> exists. Exits 1 on any pin that is not one.
18
+ *
19
+ * node scripts/check-action-pins.mjs [workflow files…] (default: .github/workflows/*.yml)
20
+ */
21
+ import fs from 'node:fs';
22
+ import path from 'node:path';
23
+
24
+ const root = path.resolve(path.dirname(new URL(import.meta.url).pathname), '..');
25
+ const files = process.argv.slice(2).length
26
+ ? process.argv.slice(2)
27
+ : fs.readdirSync(path.join(root, '.github', 'workflows')).filter(name => /\.ya?ml$/.test(name))
28
+ .map(name => path.join(root, '.github', 'workflows', name));
29
+
30
+ const pins = new Map();
31
+ for (const file of files) {
32
+ for (const match of fs.readFileSync(file, 'utf8').matchAll(/uses:\s*([\w.-]+\/[\w.-]+)(?:\/[\w./-]+)?@([0-9a-f]{40})/g)) {
33
+ const key = `${match[1]}@${match[2]}`;
34
+ if (!pins.has(key)) pins.set(key, []);
35
+ pins.get(key).push(path.relative(root, file));
36
+ }
37
+ }
38
+
39
+ const token = process.env.GITHUB_TOKEN || process.env.GH_TOKEN;
40
+ const headers = { accept: 'application/vnd.github+json', 'user-agent': 'mcp-ssh-manager-pin-check', ...(token ? { authorization: `Bearer ${token}` } : {}) };
41
+ let bad = 0;
42
+ for (const [key, where] of pins) {
43
+ const [repo, sha] = key.split('@');
44
+ const response = await fetch(`https://api.github.com/repos/${repo}/commits/${sha}`, { headers });
45
+ if (response.ok) {
46
+ console.log(`ok ${repo}@${sha.slice(0, 12)}`);
47
+ continue;
48
+ }
49
+ bad++;
50
+ const tag = await fetch(`https://api.github.com/repos/${repo}/git/tags/${sha}`, { headers });
51
+ const reason = tag.ok
52
+ ? `the SHA of a tag object; pin the commit it points to, ${(await tag.json()).object.sha}`
53
+ : `not a commit of ${repo} (HTTP ${response.status})`;
54
+ console.log(`FAIL ${repo}@${sha.slice(0, 12)} in ${where.join(', ')}: ${reason}`);
55
+ }
56
+ console.log(bad ? `\n${bad} pinned action(s) do not point to a commit of their repository` : `\nall ${pins.size} pinned actions point to commits of their repositories`);
57
+ process.exit(bad ? 1 : 0);
@@ -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.0.3",
9
+ "version": "4.2.0",
10
10
  "packages": [
11
11
  {
12
12
  "registryType": "npm",
13
13
  "identifier": "mcp-ssh-manager",
14
- "version": "4.0.3",
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';
@@ -25,6 +26,7 @@ import { resolveConfigOptions } from './config-paths.js';
25
26
  * @property {string} [user] SSH user.
26
27
  * @property {string} [password] Password for password authentication.
27
28
  * @property {string} [keyPath] Path to the private key (`KEYPATH` / `key_path`).
29
+ * @property {string} [agentPublicKeyPath] Public key selecting one SSH Agent identity (`AGENT_PUBLIC_KEY_PATH` / `agent_public_key_path`).
28
30
  * @property {string} [certPath] OpenSSH user certificate for keyPath (`CERTPATH` / `cert_path`).
29
31
  * @property {string} [passphrase] Passphrase for a protected private key.
30
32
  * @property {number} [port] TCP port; defaults to 22.
@@ -266,6 +268,7 @@ export class ConfigLoader {
266
268
  password: serverConfig.password,
267
269
  keyPath: serverConfig.key_path || serverConfig.keypath || serverConfig.ssh_key,
268
270
  certPath: serverConfig.cert_path,
271
+ agentPublicKeyPath: serverConfig.agent_public_key_path,
269
272
  passphrase: serverConfig.passphrase,
270
273
  port: serverConfig.port || 22,
271
274
  defaultDir: serverConfig.default_dir || serverConfig.default_directory || serverConfig.cwd,
@@ -344,6 +347,7 @@ export class ConfigLoader {
344
347
  password: env[`SSH_SERVER_${match[1]}_PASSWORD`],
345
348
  keyPath: env[`SSH_SERVER_${match[1]}_KEYPATH`],
346
349
  certPath: env[`SSH_SERVER_${match[1]}_CERTPATH`],
350
+ agentPublicKeyPath: env[`SSH_SERVER_${match[1]}_AGENT_PUBLIC_KEY_PATH`],
347
351
  passphrase: env[`SSH_SERVER_${match[1]}_PASSPHRASE`],
348
352
  port: parseInt(env[`SSH_SERVER_${match[1]}_PORT`] || '22'),
349
353
  defaultDir: env[`SSH_SERVER_${match[1]}_DEFAULT_DIR`],
@@ -429,6 +433,7 @@ export class ConfigLoader {
429
433
  if (server.password) serverConfig.password = server.password;
430
434
  if (server.keyPath) serverConfig.key_path = server.keyPath;
431
435
  if (server.certPath) serverConfig.cert_path = server.certPath;
436
+ if (server.agentPublicKeyPath) serverConfig.agent_public_key_path = server.agentPublicKeyPath;
432
437
  if (server.passphrase) serverConfig.passphrase = server.passphrase;
433
438
  if (server.defaultDir) serverConfig.default_dir = server.defaultDir;
434
439
  if (server.sudoPassword) serverConfig.sudo_password = server.sudoPassword;
@@ -475,6 +480,7 @@ export class ConfigLoader {
475
480
  if (server.password) lines.push(`SSH_SERVER_${upperName}_PASSWORD="${server.password}"`);
476
481
  if (server.keyPath) lines.push(`SSH_SERVER_${upperName}_KEYPATH=${server.keyPath}`);
477
482
  if (server.certPath) lines.push(`SSH_SERVER_${upperName}_CERTPATH=${server.certPath}`);
483
+ if (server.agentPublicKeyPath) lines.push(`SSH_SERVER_${upperName}_AGENT_PUBLIC_KEY_PATH=${server.agentPublicKeyPath}`);
478
484
  if (server.passphrase) lines.push(`SSH_SERVER_${upperName}_PASSPHRASE="${server.passphrase}"`);
479
485
  lines.push(`SSH_SERVER_${upperName}_PORT=${server.port || 22}`);
480
486
  if (server.defaultDir) lines.push(`SSH_SERVER_${upperName}_DEFAULT_DIR=${server.defaultDir}`);
@@ -532,7 +538,10 @@ export class ConfigLoader {
532
538
 
533
539
  config.mcp_servers['ssh-manager'] = {
534
540
  command: 'node',
535
- 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')],
536
545
  env: {
537
546
  SSH_CONFIG_PATH: path.join(os.homedir(), '.codex', 'ssh-config.toml')
538
547
  },