mcp-ssh-manager 3.8.5 → 3.8.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/logger.js CHANGED
@@ -5,10 +5,7 @@
5
5
 
6
6
  import fs from 'fs';
7
7
  import path from 'path';
8
- import { fileURLToPath } from 'url';
9
-
10
- const __filename = fileURLToPath(import.meta.url);
11
- const __dirname = path.dirname(__filename);
8
+ import { managerHome } from './config-paths.js';
12
9
 
13
10
  // Log levels
14
11
  /**
@@ -78,23 +75,49 @@ class Logger {
78
75
  // Enable verbose mode from environment
79
76
  this.verbose = process.env.SSH_VERBOSE === 'true';
80
77
 
81
- // Log file path
82
- this.logFile = process.env.SSH_LOG_FILE || path.join(__dirname, '..', '.ssh-manager.log');
83
-
84
- // Command history file
85
- this.historyFile = path.join(__dirname, '..', '.ssh-command-history.json');
86
-
87
78
  // Initialize command history
88
79
  this.commandHistory = this.loadCommandHistory();
89
80
  }
90
81
 
82
+ /**
83
+ * Where the log goes. SSH_LOG_FILE wins; otherwise ssh-manager.log in the
84
+ * manager home, beside the .env. Up to 3.8.5 the default was inside the
85
+ * installed package: lost on upgrade, readable by every local user, and a
86
+ * write into the install directory (issue #87). The home is never created
87
+ * just for a log, so a user who keeps no settings there gets stderr only,
88
+ * and starting the server leaves a pristine home pristine.
89
+ * @returns {string|null}
90
+ */
91
+ get logFile() {
92
+ return process.env.SSH_LOG_FILE || this.homeFile('ssh-manager.log');
93
+ }
94
+
95
+ /**
96
+ * The command history behind ssh_history, under the same rule. Overridable
97
+ * for the same reason the log is: a host that runs the engine from somewhere
98
+ * it must not write — inside a signed application bundle, where one added
99
+ * file breaks the seal and macOS then refuses to launch it — has to be able
100
+ * to say where these go.
101
+ * @returns {string|null}
102
+ */
103
+ get historyFile() {
104
+ return process.env.SSH_HISTORY_FILE || this.homeFile('command-history.json');
105
+ }
106
+
107
+ /** @param {string} name */
108
+ homeFile(name) {
109
+ const home = managerHome();
110
+ return fs.existsSync(home) ? path.join(home, name) : null;
111
+ }
112
+
91
113
  /**
92
114
  * Load command history from file
93
115
  */
94
116
  loadCommandHistory() {
95
117
  try {
96
- if (fs.existsSync(this.historyFile)) {
97
- const data = fs.readFileSync(this.historyFile, 'utf8');
118
+ const file = this.historyFile;
119
+ if (file && fs.existsSync(file)) {
120
+ const data = fs.readFileSync(file, 'utf8');
98
121
  return JSON.parse(data);
99
122
  }
100
123
  } catch (error) {
@@ -124,7 +147,8 @@ class Logger {
124
147
  }
125
148
 
126
149
  try {
127
- fs.writeFileSync(this.historyFile, JSON.stringify(this.commandHistory, null, 2));
150
+ const file = this.historyFile;
151
+ if (file) fs.writeFileSync(file, JSON.stringify(this.commandHistory, null, 2), { mode: 0o600 });
128
152
  } catch (error) {
129
153
  // Ignore write errors
130
154
  }
@@ -174,9 +198,11 @@ class Logger {
174
198
  // Output to stderr for proper MCP logging
175
199
  console.error(formatted.console);
176
200
 
177
- // Also write to file
201
+ // Also write to file, readable by its owner only: it records the commands
202
+ // run on remote servers.
178
203
  try {
179
- fs.appendFileSync(this.logFile, formatted.file + '\n');
204
+ const file = this.logFile;
205
+ if (file) fs.appendFileSync(file, formatted.file + '\n', { mode: 0o600 });
180
206
  } catch (error) {
181
207
  // Ignore file write errors
182
208
  }
@@ -298,8 +324,8 @@ class Logger {
298
324
  clear() {
299
325
  this.commandHistory = [];
300
326
  try {
301
- fs.writeFileSync(this.historyFile, '[]');
302
- fs.writeFileSync(this.logFile, '');
327
+ if (this.historyFile) fs.writeFileSync(this.historyFile, '[]', { mode: 0o600 });
328
+ if (this.logFile) fs.writeFileSync(this.logFile, '', { mode: 0o600 });
303
329
  this.info('Logs and history cleared');
304
330
  } catch (error) {
305
331
  this.error('Failed to clear logs', { error: error.message });
package/src/policy.js CHANGED
@@ -6,14 +6,19 @@
6
6
  * - "readonly": blocks mutating tools entirely; for ssh_execute / ssh_execute_sudo /
7
7
  * ssh_execute_group / ssh_session_send, blocks commands matching the
8
8
  * built-in destructive denylist below.
9
- * - "restricted": command must match at least one ALLOW_PATTERNS regex AND no
10
- * DENY_PATTERNS regex. DENY wins over ALLOW.
9
+ * - "restricted": every command on the line (each part of a list or pipeline)
10
+ * must match at least one ALLOW_PATTERNS regex, and neither the
11
+ * line nor any of its commands may match a DENY_PATTERNS regex.
12
+ * DENY wins over ALLOW. Command substitution and redirections
13
+ * that write a file are refused: they run or change things the
14
+ * patterns never see.
11
15
  *
12
16
  * Returns { allowed: boolean, reason?: string } — never throws. Callers translate
13
17
  * a refusal into an MCP-level error response.
14
18
  */
15
19
 
16
20
  import { logger } from './logger.js';
21
+ import { splitShellCommand } from './shell-segments.js';
17
22
 
18
23
  const MODE_UNRESTRICTED = 'unrestricted';
19
24
  const MODE_READONLY = 'readonly';
@@ -170,12 +175,17 @@ export function evaluatePolicy(serverConfig, toolName, command) {
170
175
  };
171
176
  }
172
177
  if (COMMAND_BEARING_TOOLS.has(toolName) && typeof command === 'string') {
173
- for (const re of READONLY_DENY_REGEX) {
174
- if (re.test(command)) {
175
- return {
176
- allowed: false,
177
- reason: `Command refused on server "${serverConfig.name}" (mode: readonly): matches built-in destructive pattern ${re}.`,
178
- };
178
+ // The whole line, then each command in it, including those inside $(…)
179
+ // and backticks: `echo $(rm -rf x)` has no space before its `rm`.
180
+ const { segments, substitutions } = splitShellCommand(command);
181
+ for (const text of [command, ...segments, ...substitutions]) {
182
+ for (const re of READONLY_DENY_REGEX) {
183
+ if (re.test(text)) {
184
+ return {
185
+ allowed: false,
186
+ reason: `Command refused on server "${serverConfig.name}" (mode: readonly): matches built-in destructive pattern ${re}.`,
187
+ };
188
+ }
179
189
  }
180
190
  }
181
191
  }
@@ -206,32 +216,43 @@ export function evaluatePolicy(serverConfig, toolName, command) {
206
216
  };
207
217
  }
208
218
 
219
+ const refuse = why => ({
220
+ allowed: false,
221
+ reason: `Command refused on server "${serverConfig.name}" (mode: restricted): ${why}.`,
222
+ });
223
+
224
+ // Each pattern is tested against every command on the line, not the line
225
+ // as a whole: tested against the line, `^docker ps` only checked how it
226
+ // started, and `docker ps; id` passed (GHSA-rfxw-26h6-7w42).
227
+ const { segments, substitutions, writes, problem } = splitShellCommand(command);
228
+
209
229
  for (const re of deny) {
210
- if (re.test(command)) {
211
- return {
212
- allowed: false,
213
- reason: `Command refused on server "${serverConfig.name}" (mode: restricted): matches DENY pattern ${re}.`,
214
- };
230
+ for (const text of [command, ...segments]) {
231
+ if (re.test(text)) return refuse(`matches DENY pattern ${re}`);
215
232
  }
216
233
  }
217
234
 
218
235
  if (allow.length === 0) {
219
- return {
220
- allowed: false,
221
- reason: `Command refused on server "${serverConfig.name}" (mode: restricted): no ALLOW_PATTERNS configured — restricted mode requires an explicit allowlist.`,
222
- };
236
+ return refuse('no ALLOW_PATTERNS configured — restricted mode requires an explicit allowlist');
223
237
  }
224
238
 
225
- for (const re of allow) {
226
- if (re.test(command)) {
227
- return { allowed: true };
228
- }
239
+ if (problem) return refuse(`the command could not be checked (${problem})`);
240
+ if (substitutions.length) {
241
+ return refuse('command substitution ($(…), backticks, <(…)) runs commands the allowlist cannot check');
229
242
  }
243
+ if (writes.length) {
244
+ return refuse(`redirecting output to "${writes[0]}" writes a file, which restricted mode does not allow`);
245
+ }
246
+ if (!segments.length) return refuse('empty command');
230
247
 
231
- return {
232
- allowed: false,
233
- reason: `Command refused on server "${serverConfig.name}" (mode: restricted): does not match any ALLOW_PATTERNS.`,
234
- };
248
+ for (const segment of segments) {
249
+ if (!allow.some(re => re.test(segment))) {
250
+ return refuse(segments.length > 1
251
+ ? `"${segment}" does not match any ALLOW_PATTERNS (every command in a list or pipeline must)`
252
+ : 'does not match any ALLOW_PATTERNS');
253
+ }
254
+ }
255
+ return { allowed: true };
235
256
  }
236
257
 
237
258
  // Unknown mode — fail-closed with a clear message rather than silently allowing.
@@ -6,12 +6,20 @@
6
6
  import fs from 'fs';
7
7
  import path from 'path';
8
8
  import { fileURLToPath } from 'url';
9
+ import { readUserState, writeUserState } from './user-state.js';
9
10
 
10
11
  const __filename = fileURLToPath(import.meta.url);
11
12
  const __dirname = path.dirname(__filename);
12
13
 
13
14
  const PROFILES_DIR = path.join(__dirname, '..', 'profiles');
14
- const PROFILE_CONFIG_FILE = path.join(__dirname, '..', '.ssh-manager-profile');
15
+ // The active profile is remembered in the manager home; the package copy is
16
+ // read only as a fallback for a source checkout (see user-state.js, issue #87).
17
+ const PROFILE_STATE_NAME = 'profile';
18
+ const LEGACY_PROFILE_CONFIG_FILE = path.join(__dirname, '..', '.ssh-manager-profile');
19
+
20
+ // A profile name becomes a file name under profiles/: nothing that could
21
+ // climb out of that directory and load some other JSON file as hooks.
22
+ const PROFILE_NAME = /^[A-Za-z0-9_-]+$/;
15
23
 
16
24
  /**
17
25
  * Get the active profile name
@@ -23,15 +31,13 @@ export function getActiveProfileName() {
23
31
  }
24
32
 
25
33
  // 2. Check configuration file
26
- if (fs.existsSync(PROFILE_CONFIG_FILE)) {
27
- try {
28
- const profileName = fs.readFileSync(PROFILE_CONFIG_FILE, 'utf8').trim();
29
- if (profileName) {
30
- return profileName;
31
- }
32
- } catch (error) {
33
- console.error(`Error reading profile config: ${error.message}`);
34
+ try {
35
+ const profileName = readUserState(PROFILE_STATE_NAME, LEGACY_PROFILE_CONFIG_FILE)?.text.trim();
36
+ if (profileName) {
37
+ return profileName;
34
38
  }
39
+ } catch (error) {
40
+ console.error(`Error reading profile config: ${error.message}`);
35
41
  }
36
42
 
37
43
  // 3. Default to 'default' profile
@@ -46,7 +52,7 @@ export function loadProfile(profileName = null) {
46
52
  const profilePath = path.join(PROFILES_DIR, `${name}.json`);
47
53
 
48
54
  try {
49
- if (fs.existsSync(profilePath)) {
55
+ if (PROFILE_NAME.test(name) && fs.existsSync(profilePath)) {
50
56
  const profileData = fs.readFileSync(profilePath, 'utf8');
51
57
  const profile = JSON.parse(profileData);
52
58
 
@@ -127,12 +133,12 @@ export function setActiveProfile(profileName) {
127
133
  try {
128
134
  // Verify profile exists
129
135
  const profilePath = path.join(PROFILES_DIR, `${profileName}.json`);
130
- if (!fs.existsSync(profilePath)) {
136
+ if (!PROFILE_NAME.test(String(profileName)) || !fs.existsSync(profilePath)) {
131
137
  throw new Error(`Profile '${profileName}' does not exist`);
132
138
  }
133
139
 
134
140
  // Write to config file
135
- fs.writeFileSync(PROFILE_CONFIG_FILE, profileName);
141
+ writeUserState(PROFILE_STATE_NAME, `${profileName}\n`);
136
142
  return true;
137
143
  } catch (error) {
138
144
  console.error(`Error setting active profile: ${error.message}`);
@@ -1,6 +1,6 @@
1
- import fs from 'fs';
2
1
  import path from 'path';
3
2
  import { fileURLToPath } from 'url';
3
+ import { readUserState, writeUserState } from './user-state.js';
4
4
 
5
5
  const __filename = fileURLToPath(import.meta.url);
6
6
  const __dirname = path.dirname(__filename);
@@ -10,16 +10,19 @@ const __dirname = path.dirname(__filename);
10
10
  * Allows using aliases like "prod" instead of full server names
11
11
  */
12
12
 
13
- const ALIASES_FILE = path.join(__dirname, '..', '.server-aliases.json');
13
+ // Kept in the manager home; the package copy is read only as a fallback for a
14
+ // source checkout (see user-state.js, issue #87).
15
+ const ALIASES_NAME = 'server-aliases.json';
16
+ const LEGACY_ALIASES_FILE = path.join(__dirname, '..', '.server-aliases.json');
14
17
 
15
18
  /**
16
19
  * Load server aliases from configuration file
17
20
  */
18
21
  function loadAliases() {
19
22
  try {
20
- if (fs.existsSync(ALIASES_FILE)) {
21
- const content = fs.readFileSync(ALIASES_FILE, 'utf8');
22
- return JSON.parse(content);
23
+ const state = readUserState(ALIASES_NAME, LEGACY_ALIASES_FILE);
24
+ if (state) {
25
+ return JSON.parse(state.text);
23
26
  }
24
27
  } catch (error) {
25
28
  console.error(`Warning: Could not load aliases: ${error.message}`);
@@ -32,7 +35,7 @@ function loadAliases() {
32
35
  */
33
36
  function saveAliases(aliases) {
34
37
  try {
35
- fs.writeFileSync(ALIASES_FILE, JSON.stringify(aliases, null, 2));
38
+ writeUserState(ALIASES_NAME, JSON.stringify(aliases, null, 2));
36
39
  return true;
37
40
  } catch (error) {
38
41
  console.error(`Error saving aliases: ${error.message}`);
@@ -28,6 +28,14 @@ export function shellQuote(value) {
28
28
  return SQ + String(value).replace(/'/g, SQ + '\\' + SQ + SQ) + SQ;
29
29
  }
30
30
 
31
+ /** Quote a POSIX path while preserving the documented ~/ home shorthand. */
32
+ export function shellPath(value) {
33
+ const text = String(value);
34
+ if (text === '~') return '"$HOME"';
35
+ if (text.startsWith('~/')) return `"$HOME"/${shellQuote(text.slice(2))}`;
36
+ return shellQuote(text);
37
+ }
38
+
31
39
  /**
32
40
  * Coerce a value to a safe non-negative integer for use in a command.
33
41
  *
@@ -0,0 +1,189 @@
1
+ /**
2
+ * Split a shell command line into the simple commands it would run, for the
3
+ * per-server security policy.
4
+ *
5
+ * The policy used to test its regexes against the whole command line. An
6
+ * allow pattern such as `^docker ps` therefore only checked how a line
7
+ * started, and `docker ps; id` passed (GHSA-rfxw-26h6-7w42); a deny pattern
8
+ * such as `^rm ` missed `echo x; rm -rf /data` for the same reason. Splitting
9
+ * the line lets every command in a list or pipeline be checked on its own.
10
+ *
11
+ * This is a conservative reader, not a shell. Whatever it cannot place with
12
+ * confidence is reported so the caller can refuse it: command substitution
13
+ * (`$(…)`, backticks), process substitution, and redirections that write to a
14
+ * file. It does not recognise comments, so `ls # a; b` yields a second segment
15
+ * ` b` that a caller will refuse: a false refusal, never a missed command.
16
+ */
17
+
18
+ const CONTROL_OPERATORS = /^(;;|;&|&&|\|\||\|&)/;
19
+ const HARMLESS_WRITE_TARGETS = new Set(['/dev/null', '/dev/stdout', '/dev/stderr']);
20
+
21
+ /**
22
+ * Index of the `)` closing the `(` at `open`, skipping quoted text and nested
23
+ * parentheses, or -1 when there is none.
24
+ * @param {string} text
25
+ * @param {number} open
26
+ */
27
+ function closingParen(text, open) {
28
+ let depth = 0;
29
+ for (let i = open; i < text.length; i++) {
30
+ const ch = text[i];
31
+ if (ch === '\\') { i++; continue; }
32
+ if (ch === '\'') {
33
+ const end = text.indexOf('\'', i + 1);
34
+ if (end < 0) return -1;
35
+ i = end;
36
+ } else if (ch === '"') {
37
+ i++;
38
+ while (i < text.length && text[i] !== '"') i += text[i] === '\\' ? 2 : 1;
39
+ if (i >= text.length) return -1;
40
+ } else if (ch === '(') {
41
+ depth++;
42
+ } else if (ch === ')') {
43
+ depth--;
44
+ if (depth === 0) return i;
45
+ }
46
+ }
47
+ return -1;
48
+ }
49
+
50
+ /**
51
+ * Index of the backtick closing the one before `start`, or -1.
52
+ * @param {string} text
53
+ * @param {number} start
54
+ */
55
+ function closingBacktick(text, start) {
56
+ for (let i = start; i < text.length; i++) {
57
+ if (text[i] === '\\') { i++; continue; }
58
+ if (text[i] === '`') return i;
59
+ }
60
+ return -1;
61
+ }
62
+
63
+ /**
64
+ * @typedef {object} ShellSegments
65
+ * @property {string[]} segments - Each simple command, trimmed, in order
66
+ * @property {string[]} substitutions - The command text inside every `$(…)`,
67
+ * backtick pair or process substitution, split the same way, nested ones included
68
+ * @property {string[]} writes - Targets of redirections that open a file for
69
+ * writing; /dev/null, /dev/stdout, /dev/stderr and descriptor copies (`2>&1`)
70
+ * are not listed
71
+ * @property {string|null} problem - Why the line could not be read, if it could not
72
+ */
73
+
74
+ /**
75
+ * @param {string} command
76
+ * @returns {ShellSegments}
77
+ */
78
+ export function splitShellCommand(command) {
79
+ /** @type {ShellSegments} */
80
+ const result = { segments: [], substitutions: [], writes: [], problem: null };
81
+ const text = String(command);
82
+ let current = '';
83
+
84
+ const endSegment = () => {
85
+ if (current.trim()) result.segments.push(current.trim());
86
+ current = '';
87
+ };
88
+ /** @param {string} body */
89
+ const addSubstitution = body => {
90
+ const inner = splitShellCommand(body);
91
+ result.substitutions.push(...inner.segments, ...inner.substitutions);
92
+ result.writes.push(...inner.writes);
93
+ result.problem ||= inner.problem;
94
+ if (!inner.segments.length && !inner.substitutions.length) result.substitutions.push(body);
95
+ };
96
+ /** @param {string} reason */
97
+ const fail = reason => {
98
+ result.problem = reason;
99
+ return result;
100
+ };
101
+
102
+ for (let i = 0; i < text.length;) {
103
+ const ch = text[i];
104
+
105
+ if (ch === '\\') {
106
+ current += text.slice(i, i + 2);
107
+ i += 2;
108
+ continue;
109
+ }
110
+ if (ch === '\'') {
111
+ const end = text.indexOf('\'', i + 1);
112
+ if (end < 0) return fail('an unterminated single quote');
113
+ current += text.slice(i, end + 1);
114
+ i = end + 1;
115
+ continue;
116
+ }
117
+ if (ch === '"') {
118
+ // Double quotes do not stop $(…) or backticks from running.
119
+ let j = i + 1;
120
+ while (j < text.length && text[j] !== '"') {
121
+ if (text[j] === '\\') { j += 2; continue; }
122
+ if (text[j] === '$' && text[j + 1] === '(') {
123
+ const end = closingParen(text, j + 1);
124
+ if (end < 0) return fail('an unterminated $(');
125
+ addSubstitution(text.slice(j + 2, end));
126
+ j = end + 1;
127
+ continue;
128
+ }
129
+ if (text[j] === '`') {
130
+ const end = closingBacktick(text, j + 1);
131
+ if (end < 0) return fail('an unterminated backtick');
132
+ addSubstitution(text.slice(j + 1, end));
133
+ j = end + 1;
134
+ continue;
135
+ }
136
+ j++;
137
+ }
138
+ if (j >= text.length) return fail('an unterminated double quote');
139
+ current += text.slice(i, j + 1);
140
+ i = j + 1;
141
+ continue;
142
+ }
143
+ if ((ch === '$' || ch === '<' || ch === '>') && text[i + 1] === '(') {
144
+ // $(…) command substitution, <(…) and >(…) process substitution.
145
+ const end = closingParen(text, i + 1);
146
+ if (end < 0) return fail(`an unterminated ${ch}(`);
147
+ addSubstitution(text.slice(i + 2, end));
148
+ current += text.slice(i, end + 1);
149
+ i = end + 1;
150
+ continue;
151
+ }
152
+ if (ch === '`') {
153
+ const end = closingBacktick(text, i + 1);
154
+ if (end < 0) return fail('an unterminated backtick');
155
+ addSubstitution(text.slice(i + 1, end));
156
+ current += text.slice(i, end + 1);
157
+ i = end + 1;
158
+ continue;
159
+ }
160
+ if (ch === '>' || (ch === '&' && text[i + 1] === '>') || (ch === '<' && text[i + 1] === '>')) {
161
+ // >, >>, >|, &>, &>>, >&N and <> all open something for writing.
162
+ let j = i + (ch === '>' ? 1 : 2);
163
+ if (ch !== '<' && (text[j] === '>' || text[j] === '|')) j++;
164
+ let copiesDescriptor = false;
165
+ if (text[j] === '&') { copiesDescriptor = true; j++; }
166
+ while (text[j] === ' ' || text[j] === '\t') j++;
167
+ let k = j;
168
+ while (k < text.length && !/[\s;&|<>()]/.test(text[k])) k++;
169
+ const target = text.slice(j, k);
170
+ const harmless = (copiesDescriptor && /^(\d+|-)$/.test(target))
171
+ || (ch !== '<' && HARMLESS_WRITE_TARGETS.has(target));
172
+ if (!harmless) result.writes.push(target || '(no target)');
173
+ current += text.slice(i, k);
174
+ i = k;
175
+ continue;
176
+ }
177
+ if (ch === ';' || ch === '\n' || ch === '|' || ch === '&') {
178
+ endSegment();
179
+ const operator = CONTROL_OPERATORS.exec(text.slice(i));
180
+ i += operator ? operator[0].length : 1;
181
+ continue;
182
+ }
183
+ current += ch;
184
+ i++;
185
+ }
186
+
187
+ endSegment();
188
+ return result;
189
+ }