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.
@@ -0,0 +1,344 @@
1
+ // A Claude Code hook that stops an agent from opening an SSH connection from its
2
+ // own shell, and the code that installs it. Opt-in: nothing in this package
3
+ // calls it unless the user runs `ssh-manager guard install`.
4
+ //
5
+ // Why: the approval, the policy and the audit log of ssh-manager only see what
6
+ // goes through its MCP tools. An agent that also has a terminal can run `ssh
7
+ // host command` there and none of it applies. Idea from fyq163's fork, whose
8
+ // hook reminded the agent; this one can refuse, or ask the user each time.
9
+ //
10
+ // What it is not: a security boundary. It reads the command text, so a determined
11
+ // agent can get around it (an interpreter that opens the socket itself, a script
12
+ // it wrote earlier). It prevents the accident, and says why to the agent. The
13
+ // boundary is not giving that account SSH keys or an agent socket.
14
+ //
15
+ // This file is self-contained on purpose (node: modules only): `guard install`
16
+ // copies it to ~/.ssh-manager/hooks/ssh-guard.mjs, which Claude Code runs as the
17
+ // hook, so it must keep working without the package around it.
18
+ import fs from 'node:fs';
19
+ import os from 'node:os';
20
+ import path from 'node:path';
21
+ import { fileURLToPath } from 'node:url';
22
+
23
+ export const HOOK_FILE_NAME = 'ssh-guard.mjs';
24
+ export const MODES = ['deny', 'ask'];
25
+
26
+ // ── finding an SSH connection in a shell command ────────────────────────────
27
+
28
+ const SHELLS = new Set(['sh', 'bash', 'zsh', 'dash', 'ksh', 'ash']);
29
+ const RESERVED = new Set(['if', 'then', 'else', 'elif', 'fi', 'do', 'done', 'while', 'until', 'for', 'in', 'case', 'esac', '!', '{', '}', 'function']);
30
+ // Words that run the next command: skip them, and the options they take.
31
+ const WRAPPERS = {
32
+ sudo: new Set(['-u', '-g', '-h', '-p', '-C', '-D', '-R', '-T', '-U']),
33
+ doas: new Set(['-u', '-C']),
34
+ env: new Set(['-u', '-C', '-S']),
35
+ command: new Set(), exec: new Set(['-a']), builtin: new Set(), nohup: new Set(), time: new Set(['-f', '-o']),
36
+ nice: new Set(['-n']), ionice: new Set(['-c', '-n', '-p']), setsid: new Set(), timeout: new Set(['-s', '-k']),
37
+ xargs: new Set(['-I', '-n', '-P', '-d', '-a', '-L', '-s', '-E']), stdbuf: new Set(['-i', '-o', '-e']),
38
+ caffeinate: new Set(['-t', '-w']), unbuffer: new Set(), watch: new Set(['-n', '-d']),
39
+ };
40
+ const REMOTE_COMMANDS = new Set(['ssh', 'scp', 'sftp', 'ssh-copy-id', 'autossh', 'mosh']);
41
+ const MAX_DEPTH = 4;
42
+
43
+ /**
44
+ * Split a shell command into simple commands (lists of words, quotes removed),
45
+ * following command substitutions and `sh -c` strings into theirs.
46
+ * @param {string} input
47
+ * @param {number} [depth]
48
+ * @returns {string[][]}
49
+ */
50
+ function simpleCommands(input, depth = 0) {
51
+ /** @type {string[][]} */
52
+ const commands = [];
53
+ if (depth > MAX_DEPTH) return commands;
54
+ /** @type {string[]} */
55
+ let words = [];
56
+ let word = '';
57
+ let inWord = false;
58
+ const endWord = () => { if (inWord) { words.push(word); word = ''; inWord = false; } };
59
+ const endCommand = () => { endWord(); if (words.length) commands.push(words); words = []; };
60
+ const nested = text => { for (const inner of simpleCommands(text, depth + 1)) commands.push(inner); };
61
+ const text = String(input ?? '');
62
+
63
+ /** Index just past the `)` that closes a `$(` opened before `from`. */
64
+ const closeParen = from => {
65
+ let level = 1;
66
+ for (let k = from; k < text.length; k++) {
67
+ if (text[k] === '\\') { k++; continue; }
68
+ if (text[k] === '(') level++;
69
+ else if (text[k] === ')' && --level === 0) return k;
70
+ }
71
+ return text.length;
72
+ };
73
+
74
+ for (let i = 0; i < text.length; i++) {
75
+ const c = text[i];
76
+ if (c === '\\') {
77
+ if (text[i + 1] === '\n') { i++; continue; }
78
+ word += text[i + 1] ?? ''; inWord = true; i++; continue;
79
+ }
80
+ if (c === '\'') {
81
+ const end = text.indexOf('\'', i + 1);
82
+ word += text.slice(i + 1, end === -1 ? text.length : end); inWord = true;
83
+ i = end === -1 ? text.length : end; continue;
84
+ }
85
+ if (c === '"') {
86
+ inWord = true;
87
+ for (i++; i < text.length && text[i] !== '"'; i++) {
88
+ if (text[i] === '\\') { word += text[i + 1] ?? ''; i++; continue; }
89
+ if (text[i] === '$' && text[i + 1] === '(') { const end = closeParen(i + 2); nested(text.slice(i + 2, end)); word += '$(…)'; i = end; continue; }
90
+ if (text[i] === '`') { const end = text.indexOf('`', i + 1); nested(text.slice(i + 1, end === -1 ? text.length : end)); word += '`…`'; i = end === -1 ? text.length : end; continue; }
91
+ word += text[i];
92
+ }
93
+ continue;
94
+ }
95
+ if (c === '$' && text[i + 1] === '(') {
96
+ const end = closeParen(i + 2); nested(text.slice(i + 2, end)); word += '$(…)'; inWord = true; i = end; continue;
97
+ }
98
+ if (c === '`') {
99
+ const end = text.indexOf('`', i + 1); nested(text.slice(i + 1, end === -1 ? text.length : end)); word += '`…`'; inWord = true; i = end === -1 ? text.length : end; continue;
100
+ }
101
+ if (c === '#' && !inWord) { while (i < text.length && text[i] !== '\n') i++; i--; continue; }
102
+ if (c === '\n' || c === ';' || c === '&' || c === '|' || c === '(' || c === ')') { endCommand(); continue; }
103
+ if (c === ' ' || c === '\t' || c === '\r') { endWord(); continue; }
104
+ word += c; inWord = true;
105
+ }
106
+ endCommand();
107
+
108
+ // Strings that are commands themselves: sh -c '…', eval …
109
+ for (const command of [...commands]) {
110
+ const run = unwrap(command);
111
+ if (!run.length) continue;
112
+ const exe = path.basename(run[0]);
113
+ if (SHELLS.has(exe)) {
114
+ const flag = run.findIndex((w, index) => index > 0 && /^-[A-Za-z]*c[A-Za-z]*$/.test(w));
115
+ if (flag !== -1 && run[flag + 1] !== undefined) nested(run[flag + 1]);
116
+ } else if (exe === 'eval') {
117
+ nested(run.slice(1).join(' '));
118
+ }
119
+ }
120
+ return commands;
121
+ }
122
+
123
+ /**
124
+ * The command a simple command really runs: assignments, reserved words,
125
+ * redirections and wrappers such as sudo, env, time or xargs skipped.
126
+ * @param {string[]} words
127
+ * @returns {string[]}
128
+ */
129
+ function unwrap(words) {
130
+ let i = 0;
131
+ while (i < words.length) {
132
+ const word = words[i];
133
+ if (RESERVED.has(word) || /^[A-Za-z_][A-Za-z0-9_]*=/.test(word)) { i++; continue; }
134
+ if (/^\d*[<>]/.test(word)) { i += /^\d*(>>?|<|>&|<&)$/.test(word) ? 2 : 1; continue; }
135
+ const wrapper = Object.hasOwn(WRAPPERS, path.basename(word)) ? WRAPPERS[path.basename(word)] : null;
136
+ if (!wrapper) break;
137
+ i++;
138
+ const lookup = path.basename(word) === 'command';
139
+ while (i < words.length) {
140
+ const next = words[i];
141
+ // `command -v ssh` looks the command up, it does not run it.
142
+ if (lookup && (next === '-v' || next === '-V')) return [];
143
+ if (wrapper.has(next)) { i += 2; continue; }
144
+ if (next.startsWith('-') || /^[A-Za-z_][A-Za-z0-9_]*=/.test(next) || /^\d+(\.\d+)?[smhd]?$/.test(next)) { i++; continue; }
145
+ break;
146
+ }
147
+ }
148
+ return words.slice(i);
149
+ }
150
+
151
+ /**
152
+ * Whether a shell command opens an SSH connection from the shell.
153
+ * @param {string} command
154
+ * @returns {{ command: string, reason: string } | null}
155
+ */
156
+ export function findRawSsh(command) {
157
+ for (const simple of simpleCommands(command)) {
158
+ const run = unwrap(simple);
159
+ if (!run.length) continue;
160
+ const exe = path.basename(run[0]);
161
+ const args = run.slice(1);
162
+ if (REMOTE_COMMANDS.has(exe)) {
163
+ if (args.length && args.every(arg => ['-V', '-h', '-?', '--help', '--version'].includes(arg))) continue;
164
+ return { command: exe, reason: `${exe} connects to a host from the shell` };
165
+ }
166
+ if (exe === 'rsync') {
167
+ const remote = args.find(arg => /^(?:[^@\s/:]+@)?[A-Za-z0-9][A-Za-z0-9._-]+:(?!\/\/|:)/.test(arg));
168
+ const shell = args.find(arg => arg === '-e' || arg === '--rsh' || arg.startsWith('--rsh=') || /^-[A-Za-z]*e[A-Za-z]*$/.test(arg));
169
+ if (remote || shell) return { command: 'rsync', reason: 'rsync reaches a host over SSH from the shell' };
170
+ }
171
+ }
172
+ return null;
173
+ }
174
+
175
+ // ── the hook ────────────────────────────────────────────────────────────────
176
+
177
+ /**
178
+ * What the hook answers for the payload Claude Code sends before a tool runs:
179
+ * null to let it through, else the PreToolUse answer.
180
+ * @param {any} payload
181
+ * @param {'deny'|'ask'} [mode]
182
+ */
183
+ export function decide(payload, mode = 'deny') {
184
+ if (payload?.tool_name !== 'Bash') return null;
185
+ const command = payload?.tool_input?.command;
186
+ if (typeof command !== 'string') return null;
187
+ const found = findRawSsh(command);
188
+ if (!found) return null;
189
+ const message = `${found.reason}, which skips the approval, the policy and the audit log of ssh-manager. `
190
+ + 'Use its MCP tools instead: ssh_execute for commands, ssh_upload and ssh_download for files, ssh_sync for rsync, '
191
+ + 'ssh_tunnel_create for tunnels. If this really has to run in the shell, ask the user to run it.';
192
+ return {
193
+ hookSpecificOutput: {
194
+ hookEventName: 'PreToolUse',
195
+ permissionDecision: mode === 'ask' ? 'ask' : 'deny',
196
+ permissionDecisionReason: message,
197
+ },
198
+ };
199
+ }
200
+
201
+ /** Run as the hook: payload on stdin, answer on stdout, never a failure. */
202
+ async function runHook(argv) {
203
+ const modeIndex = argv.indexOf('--mode');
204
+ const mode = argv[modeIndex + 1] === 'ask' ? 'ask' : 'deny';
205
+ let text = '';
206
+ for await (const chunk of process.stdin) text += chunk;
207
+ let answer = null;
208
+ try { answer = decide(JSON.parse(text), mode); } catch { /* not ours to judge: let it through */ }
209
+ if (answer) process.stdout.write(`${JSON.stringify(answer)}\n`);
210
+ }
211
+
212
+ // ── installing it ───────────────────────────────────────────────────────────
213
+
214
+ /** Claude Code's user settings file. */
215
+ export function claudeSettingsPath(env = process.env, home = os.homedir()) {
216
+ return path.join(env.CLAUDE_CONFIG_DIR || path.join(home, '.claude'), 'settings.json');
217
+ }
218
+
219
+ export function hookScriptPath(home = os.homedir(), env = process.env) {
220
+ return path.join(env.SSH_MANAGER_HOME || path.join(home, '.ssh-manager'), 'hooks', HOOK_FILE_NAME);
221
+ }
222
+
223
+ function readSettings(file) {
224
+ if (!fs.existsSync(file)) return {};
225
+ const text = fs.readFileSync(file, 'utf8');
226
+ if (!text.trim()) return {};
227
+ let parsed;
228
+ try { parsed = JSON.parse(text); } catch { parsed = null; }
229
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
230
+ throw new Error(`${file} could not be read as JSON: change it by hand`);
231
+ }
232
+ return parsed;
233
+ }
234
+
235
+ function writeAtomically(file, text) {
236
+ fs.mkdirSync(path.dirname(file), { recursive: true });
237
+ const temporary = `${file}.ssh-manager-${process.pid}.tmp`;
238
+ let mode = 0o600;
239
+ try { mode = fs.statSync(file).mode & 0o777; } catch { /* a new file: private */ }
240
+ fs.writeFileSync(temporary, text, { mode });
241
+ fs.renameSync(temporary, file);
242
+ }
243
+
244
+ const isOurs = hook => typeof hook?.command === 'string' && hook.command.includes(HOOK_FILE_NAME);
245
+
246
+ /** Where our hook is in a settings object, whatever else is around it. */
247
+ function ourHooks(settings) {
248
+ const groups = Array.isArray(settings.hooks?.PreToolUse) ? settings.hooks.PreToolUse : [];
249
+ return groups.flatMap(group => (Array.isArray(group?.hooks) ? group.hooks.filter(isOurs) : []));
250
+ }
251
+
252
+ /**
253
+ * The command Claude Code runs; the quotes keep a path with spaces in one piece.
254
+ * `node` is found on the PATH like any other command: a versioned install path
255
+ * (Homebrew's Cellar, nvm) would break at the next Node upgrade, and a hook that
256
+ * cannot start only fails open.
257
+ */
258
+ export function hookCommand(script, mode, node = 'node') {
259
+ return `${node} "${script}" --mode ${mode}`;
260
+ }
261
+
262
+ /**
263
+ * Add the hook to Claude Code's settings and copy the script it runs. Replaces
264
+ * a previous install, keeps every other setting and hook, and keeps a copy of
265
+ * the file as it was the first time.
266
+ * @param {{ mode?: 'deny'|'ask', settingsFile?: string, script?: string, node?: string }} [options]
267
+ */
268
+ export function installGuard({ mode = 'deny', settingsFile = claudeSettingsPath(), script = hookScriptPath(), node = 'node' } = {}) {
269
+ if (!MODES.includes(mode)) throw new Error(`mode must be one of ${MODES.join(', ')}`);
270
+ const settings = readSettings(settingsFile);
271
+ if (settings.hooks !== undefined && (typeof settings.hooks !== 'object' || settings.hooks === null || Array.isArray(settings.hooks))) {
272
+ throw new Error(`${settingsFile}: "hooks" is not an object: change it by hand`);
273
+ }
274
+ if (settings.hooks?.PreToolUse !== undefined && !Array.isArray(settings.hooks.PreToolUse)) {
275
+ throw new Error(`${settingsFile}: "hooks.PreToolUse" is not a list: change it by hand`);
276
+ }
277
+
278
+ fs.mkdirSync(path.dirname(script), { recursive: true });
279
+ fs.copyFileSync(fileURLToPath(import.meta.url), script);
280
+ fs.chmodSync(script, 0o700);
281
+
282
+ const backup = `${settingsFile}.ssh-manager.bak`;
283
+ if (fs.existsSync(settingsFile) && !fs.existsSync(backup)) fs.copyFileSync(settingsFile, backup);
284
+
285
+ stripOurs(settings);
286
+ settings.hooks = settings.hooks || {};
287
+ settings.hooks.PreToolUse = settings.hooks.PreToolUse || [];
288
+ settings.hooks.PreToolUse.push({ matcher: 'Bash', hooks: [{ type: 'command', command: hookCommand(script, mode, node) }] });
289
+ writeAtomically(settingsFile, `${JSON.stringify(settings, null, 2)}\n`);
290
+ return { settingsFile, script, mode };
291
+ }
292
+
293
+ /** Take our hook out of a settings object, and the containers it leaves empty. */
294
+ function stripOurs(settings) {
295
+ const groups = settings.hooks?.PreToolUse;
296
+ if (!Array.isArray(groups)) return 0;
297
+ let removed = 0;
298
+ const kept = [];
299
+ for (const group of groups) {
300
+ if (!Array.isArray(group?.hooks)) { kept.push(group); continue; }
301
+ const rest = group.hooks.filter(hook => !isOurs(hook));
302
+ removed += group.hooks.length - rest.length;
303
+ if (rest.length) kept.push({ ...group, hooks: rest });
304
+ else if (rest.length !== group.hooks.length) continue;
305
+ else kept.push(group);
306
+ }
307
+ if (kept.length) settings.hooks.PreToolUse = kept;
308
+ else delete settings.hooks.PreToolUse;
309
+ if (!Object.keys(settings.hooks).length) delete settings.hooks;
310
+ return removed;
311
+ }
312
+
313
+ /**
314
+ * Remove the hook. The copied script stays unless asked, so a second install
315
+ * does not have to fetch it again.
316
+ * @param {{ settingsFile?: string, script?: string, deleteScript?: boolean }} [options]
317
+ */
318
+ export function removeGuard({ settingsFile = claudeSettingsPath(), script = hookScriptPath(), deleteScript = false } = {}) {
319
+ const settings = readSettings(settingsFile);
320
+ const removed = stripOurs(settings);
321
+ if (removed) writeAtomically(settingsFile, `${JSON.stringify(settings, null, 2)}\n`);
322
+ if (deleteScript) fs.rmSync(script, { force: true });
323
+ return { settingsFile, removed };
324
+ }
325
+
326
+ /** Whether the hook is installed, and in which mode. */
327
+ export function guardStatus({ settingsFile = claudeSettingsPath(), script = hookScriptPath() } = {}) {
328
+ const hooks = ourHooks(readSettings(settingsFile));
329
+ const command = hooks[0]?.command ?? '';
330
+ return {
331
+ settingsFile,
332
+ installed: hooks.length > 0,
333
+ mode: /--mode ask\b/.test(command) ? 'ask' : hooks.length ? 'deny' : null,
334
+ scriptPresent: fs.existsSync(script),
335
+ command: hooks.length ? command : null,
336
+ };
337
+ }
338
+
339
+ // Run as the entry point under its installed name only: imported, or run as
340
+ // src/ssh-guard.js, it is a library. (Compared by name: a symlinked folder such
341
+ // as macOS's /var makes the same file show two different paths.)
342
+ if (process.argv[1] && path.basename(process.argv[1]) === HOOK_FILE_NAME) {
343
+ runHook(process.argv.slice(2)).catch(() => {});
344
+ }
@@ -724,6 +724,57 @@ class SSHManager {
724
724
  });
725
725
  }
726
726
 
727
+ /**
728
+ * Ask the server to listen on remoteHost:remotePort and send each connection
729
+ * back over this one (ssh -R). Remote tunnels call it on this wrapper, which
730
+ * until now only had forwardOut: every remote tunnel failed with
731
+ * "forwardIn is not a function".
732
+ * @param {string} remoteHost
733
+ * @param {number} remotePort
734
+ * @param {(error?: Error, boundPort?: number) => void} callback
735
+ */
736
+ forwardIn(remoteHost, remotePort, callback) {
737
+ if (!this.connected) {
738
+ callback(new Error('Not connected to SSH server'));
739
+ return;
740
+ }
741
+ this.client.forwardIn(remoteHost, remotePort, callback);
742
+ }
743
+
744
+ /**
745
+ * Stop a remote forward asked for with forwardIn.
746
+ * @param {string} remoteHost
747
+ * @param {number} remotePort
748
+ * @param {(error?: Error) => void} [callback]
749
+ */
750
+ unforwardIn(remoteHost, remotePort, callback) {
751
+ if (!this.connected) {
752
+ callback?.(new Error('Not connected to SSH server'));
753
+ return;
754
+ }
755
+ this.client.unforwardIn(remoteHost, remotePort, callback);
756
+ }
757
+
758
+ /**
759
+ * Listen to an event of the underlying ssh2 connection ('tcp connection'
760
+ * for remote forwards).
761
+ * @param {string} event
762
+ * @param {(...args: any[]) => void} listener
763
+ */
764
+ on(event, listener) {
765
+ this.client.on(event, listener);
766
+ return this;
767
+ }
768
+
769
+ /**
770
+ * @param {string} event
771
+ * @param {(...args: any[]) => void} listener
772
+ */
773
+ off(event, listener) {
774
+ this.client.off(event, listener);
775
+ return this;
776
+ }
777
+
727
778
  async ping() {
728
779
  try {
729
780
  // Use `echo ping` WITHOUT quotes: cmd.exe echoes surrounding quotes
@@ -72,6 +72,8 @@ class SSHTunnel {
72
72
  this.createdAt = new Date();
73
73
  this.lastActivity = new Date();
74
74
  this.connections = new Set();
75
+ /** @type {((info: any, accept: () => any) => void) | null} */
76
+ this.onRemoteConnection = null;
75
77
  this.server = null;
76
78
  this.reconnectAttempts = 0;
77
79
  this.maxReconnectAttempts = 5;
@@ -213,8 +215,9 @@ class SSHTunnel {
213
215
  });
214
216
  await forwarded;
215
217
 
216
- // Handle incoming connections from remote
217
- this.ssh.on('tcp connection', (info, accept) => {
218
+ // Handle incoming connections from remote. The listener is kept so close()
219
+ // can take it off the shared connection: other tunnels use it too.
220
+ this.onRemoteConnection = (info, accept) => {
218
221
  if (info.destPort !== remotePort) return;
219
222
 
220
223
  this.stats.connectionsTotal++;
@@ -258,7 +261,8 @@ class SSHTunnel {
258
261
 
259
262
  remoteSocket.on('close', cleanup);
260
263
  localSocket.on('close', cleanup);
261
- });
264
+ };
265
+ this.ssh.on('tcp connection', this.onRemoteConnection);
262
266
 
263
267
  logger.info('Remote forwarding established', {
264
268
  local: `${localHost}:${localPort}`,
@@ -421,7 +425,13 @@ class SSHTunnel {
421
425
 
422
426
  // Cancel remote forwarding if needed
423
427
  if (this.type === TUNNEL_TYPES.REMOTE) {
424
- this.ssh.unforwardIn(this.config.remoteHost, this.config.remotePort);
428
+ if (this.onRemoteConnection) this.ssh.off('tcp connection', this.onRemoteConnection);
429
+ try {
430
+ this.ssh.unforwardIn(this.config.remoteHost, this.config.remotePort);
431
+ } catch (error) {
432
+ // The connection may already be gone; the server drops the forward with it.
433
+ logger.warn(`Could not cancel remote forwarding for tunnel ${this.id}`, { error: error.message });
434
+ }
425
435
  }
426
436
 
427
437
  tunnels.delete(this.id);