|
| 1 | +#!/usr/bin/env node |
| 2 | +/** |
| 3 | + * PreToolUse hook for the Bash tool. Detects a simple ssh/scp/rsync invocation |
| 4 | + * against a configured server and prints a soft, non-blocking nudge toward the |
| 5 | + * matching ssh_* MCP tool. Best-effort: simple shapes nudged, complex command |
| 6 | + * lines passed through. Fail-open -- any error exits 0 with no nudge. |
| 7 | + * |
| 8 | + * Wired in .claude/settings.json under hooks.PreToolUse, matcher "Bash". |
| 9 | + */ |
| 10 | +import { readFileSync } from 'fs'; |
| 11 | +import { fileURLToPath } from 'url'; |
| 12 | + |
| 13 | +// Shell metacharacters => the command line is not a simple invocation. Bail. |
| 14 | +const COMPLEX = /[|&;<>`]|\$\(/; |
| 15 | + |
| 16 | +/** Configured server names from the project .env (best-effort, never throws). */ |
| 17 | +export function configuredServers(envPath) { |
| 18 | + try { |
| 19 | + const text = readFileSync(envPath, 'utf8'); |
| 20 | + const names = new Set(); |
| 21 | + for (const line of text.split('\n')) { |
| 22 | + // SSH_SERVER_<NAME>_HOST=... -- <NAME> is the server identifier. |
| 23 | + const m = /^\s*SSH_SERVER_([A-Za-z0-9]+)_HOST\s*=/.exec(line); |
| 24 | + if (m) names.add(m[1].toLowerCase()); |
| 25 | + } |
| 26 | + return [...names]; |
| 27 | + } catch { |
| 28 | + return []; |
| 29 | + } |
| 30 | +} |
| 31 | + |
| 32 | +/** Strip a leading user@ and return the bare host token, lowercased. */ |
| 33 | +function bareHost(token) { |
| 34 | + const at = token.lastIndexOf('@'); |
| 35 | + return (at === -1 ? token : token.slice(at + 1)).toLowerCase(); |
| 36 | +} |
| 37 | + |
| 38 | +/** |
| 39 | + * Inspect a Bash command string. Returns { tool, message } when it is a simple |
| 40 | + * ssh/scp/rsync call against a configured server, else null. Never throws. |
| 41 | + */ |
| 42 | +export function detectSshNudge(command, servers) { |
| 43 | + try { |
| 44 | + if (!command || typeof command !== 'string') return null; |
| 45 | + if (!Array.isArray(servers) || servers.length === 0) return null; |
| 46 | + if (COMPLEX.test(command)) return null; |
| 47 | + |
| 48 | + const set = new Set(servers.map((s) => String(s).toLowerCase())); |
| 49 | + const tokens = command.trim().split(/\s+/); |
| 50 | + const head = tokens[0]; |
| 51 | + |
| 52 | + if (head === 'ssh') { |
| 53 | + // First token after the flags that is not a flag or a flag-value is the host. |
| 54 | + for (let i = 1; i < tokens.length; i++) { |
| 55 | + const t = tokens[i]; |
| 56 | + if (t === '-p' || t === '-i' || t === '-l' || t === '-o' || t === '-F') { |
| 57 | + i++; // skip this flag's value |
| 58 | + continue; |
| 59 | + } |
| 60 | + if (t.startsWith('-')) continue; |
| 61 | + return set.has(bareHost(t)) |
| 62 | + ? { tool: 'ssh_run', message: nudgeText(bareHost(t), 'ssh_run', 'ssh') } |
| 63 | + : null; |
| 64 | + } |
| 65 | + return null; |
| 66 | + } |
| 67 | + |
| 68 | + if (head === 'scp' || head === 'rsync') { |
| 69 | + // Any non-flag token of the form host:path against a configured server. |
| 70 | + for (let i = 1; i < tokens.length; i++) { |
| 71 | + const t = tokens[i]; |
| 72 | + if (t.startsWith('-')) continue; |
| 73 | + const colon = t.indexOf(':'); |
| 74 | + if (colon > 0 && set.has(bareHost(t.slice(0, colon)))) { |
| 75 | + const host = bareHost(t.slice(0, colon)); |
| 76 | + return { tool: 'ssh_file', message: nudgeText(host, 'ssh_file', head) }; |
| 77 | + } |
| 78 | + } |
| 79 | + return null; |
| 80 | + } |
| 81 | + |
| 82 | + return null; |
| 83 | + } catch { |
| 84 | + return null; |
| 85 | + } |
| 86 | +} |
| 87 | + |
| 88 | +/** The soft nudge text shown in the PreToolUse hook output. */ |
| 89 | +function nudgeText(host, tool, rawCmd) { |
| 90 | + return `[ssh-manager] '${host}' is a configured server. Consider the ` |
| 91 | + + `${tool} MCP tool instead of raw \`${rawCmd}\` -- pooled connection, ` |
| 92 | + + `bounded output, structured result. (This is a hint, not a block.)`; |
| 93 | +} |
| 94 | + |
| 95 | +// --- CLI shell: invoked by Claude Code as a PreToolUse hook -------------- |
| 96 | +// Reads the hook JSON payload on stdin; prints a nudge on stdout if one |
| 97 | +// applies; always exits 0 so the Bash call is never blocked. |
| 98 | +function main() { |
| 99 | + let raw = ''; |
| 100 | + try { |
| 101 | + raw = readFileSync(0, 'utf8'); |
| 102 | + } catch { |
| 103 | + process.exit(0); // no stdin -> nothing to inspect |
| 104 | + } |
| 105 | + |
| 106 | + let payload; |
| 107 | + try { |
| 108 | + payload = JSON.parse(raw); |
| 109 | + } catch { |
| 110 | + process.exit(0); // unparseable payload -> fail open |
| 111 | + } |
| 112 | + |
| 113 | + const command = payload && payload.tool_input && payload.tool_input.command; |
| 114 | + const envPath = fileURLToPath(new URL('../../.env', import.meta.url)); |
| 115 | + const nudge = detectSshNudge(command, configuredServers(envPath)); |
| 116 | + if (nudge) console.log(nudge.message); |
| 117 | + process.exit(0); |
| 118 | +} |
| 119 | + |
| 120 | +// Run main() only when executed directly, never when imported by a test. |
| 121 | +if (import.meta.url === `file://${process.argv[1]}`) { |
| 122 | + main(); |
| 123 | +} |
0 commit comments