mcp-ssh-manager 3.0.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 (56) hide show
  1. package/.claude/settings.local.json +87 -0
  2. package/.flake8 +15 -0
  3. package/.hooks-config.json +131 -0
  4. package/.pre-commit-config.yaml +105 -0
  5. package/CHANGELOG.md +137 -0
  6. package/CLAUDE.md +190 -0
  7. package/CONTRIBUTING.md +114 -0
  8. package/DESCRIPTION +1 -0
  9. package/INSTALLATION.md +180 -0
  10. package/LICENSE +21 -0
  11. package/QUICKSTART.md +77 -0
  12. package/README.md +718 -0
  13. package/cli/README.md +286 -0
  14. package/cli/build.sh +199 -0
  15. package/cli/commands/server.sh +284 -0
  16. package/cli/demo.sh +107 -0
  17. package/cli/install.sh +164 -0
  18. package/cli/lib/colors.sh +174 -0
  19. package/cli/lib/config.sh +284 -0
  20. package/cli/lib/menu.sh +430 -0
  21. package/cli/migrate.sh +168 -0
  22. package/cli/ssh-manager +525 -0
  23. package/docs/ALIASES_AND_HOOKS.md +285 -0
  24. package/docs/BACKUP_GUIDE.md +500 -0
  25. package/docs/DEPLOYMENT_GUIDE.md +241 -0
  26. package/docs/SEO.md +257 -0
  27. package/examples/backup-workflow.js +481 -0
  28. package/examples/claude-code-config.example.json +40 -0
  29. package/examples/codex-ssh-config.example.toml +71 -0
  30. package/examples/deploy-workflow.py +183 -0
  31. package/glama.json +6 -0
  32. package/package.json +85 -0
  33. package/profiles/README.md +40 -0
  34. package/profiles/default.json +52 -0
  35. package/profiles/docker.json +62 -0
  36. package/profiles/frappe.json +107 -0
  37. package/profiles/nodejs.json +63 -0
  38. package/pyproject.toml +17 -0
  39. package/scripts/setup-hooks.sh +60 -0
  40. package/scripts/validate.sh +76 -0
  41. package/src/backup-manager.js +469 -0
  42. package/src/command-aliases.js +151 -0
  43. package/src/config-loader.js +281 -0
  44. package/src/database-manager.js +555 -0
  45. package/src/deploy-helper.js +176 -0
  46. package/src/health-monitor.js +428 -0
  47. package/src/hooks-system.js +327 -0
  48. package/src/index.js +4499 -0
  49. package/src/logger.js +276 -0
  50. package/src/profile-loader.js +187 -0
  51. package/src/server-aliases.js +150 -0
  52. package/src/server-groups.js +409 -0
  53. package/src/session-manager.js +410 -0
  54. package/src/ssh-key-manager.js +378 -0
  55. package/src/ssh-manager.js +435 -0
  56. package/src/tunnel-manager.js +576 -0
package/src/logger.js ADDED
@@ -0,0 +1,276 @@
1
+ /**
2
+ * Logger module for MCP SSH Manager
3
+ * Provides structured logging with levels and optional verbose mode
4
+ */
5
+
6
+ import fs from 'fs';
7
+ import path from 'path';
8
+ import { fileURLToPath } from 'url';
9
+
10
+ const __filename = fileURLToPath(import.meta.url);
11
+ const __dirname = path.dirname(__filename);
12
+
13
+ // Log levels
14
+ export const LOG_LEVELS = {
15
+ DEBUG: 0,
16
+ INFO: 1,
17
+ WARN: 2,
18
+ ERROR: 3
19
+ };
20
+
21
+ // Colors for terminal output
22
+ const COLORS = {
23
+ DEBUG: '\x1b[36m', // Cyan
24
+ INFO: '\x1b[32m', // Green
25
+ WARN: '\x1b[33m', // Yellow
26
+ ERROR: '\x1b[31m', // Red
27
+ RESET: '\x1b[0m'
28
+ };
29
+
30
+ // Icons for each level
31
+ const ICONS = {
32
+ DEBUG: '🔍',
33
+ INFO: '✅',
34
+ WARN: '⚠️',
35
+ ERROR: '❌'
36
+ };
37
+
38
+ class Logger {
39
+ constructor() {
40
+ // Set log level from environment variable
41
+ const envLevel = process.env.SSH_LOG_LEVEL?.toUpperCase() || 'INFO';
42
+ this.currentLevel = LOG_LEVELS[envLevel] ?? LOG_LEVELS.INFO;
43
+
44
+ // Enable verbose mode from environment
45
+ this.verbose = process.env.SSH_VERBOSE === 'true';
46
+
47
+ // Log file path
48
+ this.logFile = process.env.SSH_LOG_FILE || path.join(__dirname, '..', '.ssh-manager.log');
49
+
50
+ // Command history file
51
+ this.historyFile = path.join(__dirname, '..', '.ssh-command-history.json');
52
+
53
+ // Initialize command history
54
+ this.commandHistory = this.loadCommandHistory();
55
+ }
56
+
57
+ /**
58
+ * Load command history from file
59
+ */
60
+ loadCommandHistory() {
61
+ try {
62
+ if (fs.existsSync(this.historyFile)) {
63
+ const data = fs.readFileSync(this.historyFile, 'utf8');
64
+ return JSON.parse(data);
65
+ }
66
+ } catch (error) {
67
+ // Ignore errors, start with empty history
68
+ }
69
+ return [];
70
+ }
71
+
72
+ /**
73
+ * Save command to history
74
+ */
75
+ saveCommandToHistory(command, server, result) {
76
+ const entry = {
77
+ timestamp: new Date().toISOString(),
78
+ server,
79
+ command,
80
+ success: result.success,
81
+ duration: result.duration,
82
+ error: result.error
83
+ };
84
+
85
+ this.commandHistory.push(entry);
86
+
87
+ // Keep only last 1000 commands
88
+ if (this.commandHistory.length > 1000) {
89
+ this.commandHistory = this.commandHistory.slice(-1000);
90
+ }
91
+
92
+ try {
93
+ fs.writeFileSync(this.historyFile, JSON.stringify(this.commandHistory, null, 2));
94
+ } catch (error) {
95
+ // Ignore write errors
96
+ }
97
+ }
98
+
99
+ /**
100
+ * Format log message with timestamp and level
101
+ */
102
+ formatMessage(level, message, data = {}) {
103
+ const timestamp = new Date().toISOString();
104
+ const levelName = Object.keys(LOG_LEVELS).find(key => LOG_LEVELS[key] === level) || 'INFO';
105
+
106
+ // Console format with colors
107
+ const consoleFormat = `${COLORS[levelName]}${ICONS[levelName]} [${timestamp}] [${levelName}]${COLORS.RESET} ${message}`;
108
+
109
+ // File format without colors
110
+ const fileFormat = `[${timestamp}] [${levelName}] ${message}`;
111
+
112
+ // Add data if present
113
+ let dataStr = '';
114
+ if (Object.keys(data).length > 0) {
115
+ dataStr = '\n ' + JSON.stringify(data, null, 2).replace(/\n/g, '\n ');
116
+ }
117
+
118
+ return {
119
+ console: consoleFormat + (this.verbose && dataStr ? dataStr : ''),
120
+ file: fileFormat + dataStr
121
+ };
122
+ }
123
+
124
+ /**
125
+ * Main log function
126
+ */
127
+ log(level, message, data = {}) {
128
+ // Check if we should log this level
129
+ if (level < this.currentLevel) {
130
+ return;
131
+ }
132
+
133
+ const formatted = this.formatMessage(level, message, data);
134
+
135
+ // Output to stderr for proper MCP logging
136
+ console.error(formatted.console);
137
+
138
+ // Also write to file
139
+ try {
140
+ fs.appendFileSync(this.logFile, formatted.file + '\n');
141
+ } catch (error) {
142
+ // Ignore file write errors
143
+ }
144
+ }
145
+
146
+ // Convenience methods
147
+ debug(message, data) {
148
+ this.log(LOG_LEVELS.DEBUG, message, data);
149
+ }
150
+
151
+ info(message, data) {
152
+ this.log(LOG_LEVELS.INFO, message, data);
153
+ }
154
+
155
+ warn(message, data) {
156
+ this.log(LOG_LEVELS.WARN, message, data);
157
+ }
158
+
159
+ error(message, data) {
160
+ this.log(LOG_LEVELS.ERROR, message, data);
161
+ }
162
+
163
+ /**
164
+ * Log SSH command execution
165
+ */
166
+ logCommand(server, command, cwd = null) {
167
+ const logData = {
168
+ server,
169
+ command: this.verbose ? command : command.substring(0, 100) + (command.length > 100 ? '...' : ''),
170
+ cwd
171
+ };
172
+
173
+ if (this.verbose) {
174
+ this.debug(`Executing SSH command`, logData);
175
+ } else {
176
+ this.info(`SSH execute on ${server}`, { command: logData.command });
177
+ }
178
+
179
+ return Date.now(); // Return start time for duration calculation
180
+ }
181
+
182
+ /**
183
+ * Log SSH command result
184
+ */
185
+ logCommandResult(server, command, startTime, result) {
186
+ const duration = Date.now() - startTime;
187
+
188
+ const resultData = {
189
+ success: !result.code,
190
+ duration: `${duration}ms`,
191
+ error: result.code ? result.stderr : undefined
192
+ };
193
+
194
+ // Save to history
195
+ this.saveCommandToHistory(command, server, resultData);
196
+
197
+ if (result.code) {
198
+ this.error(`Command failed on ${server}`, resultData);
199
+ } else if (this.verbose) {
200
+ this.debug(`Command completed on ${server}`, resultData);
201
+ }
202
+ }
203
+
204
+ /**
205
+ * Log SSH connection events
206
+ */
207
+ logConnection(server, event, data = {}) {
208
+ const message = `SSH connection ${event}: ${server}`;
209
+
210
+ switch (event) {
211
+ case 'established':
212
+ this.info(message, data);
213
+ break;
214
+ case 'reused':
215
+ this.debug(message, data);
216
+ break;
217
+ case 'closed':
218
+ this.info(message, data);
219
+ break;
220
+ case 'failed':
221
+ this.error(message, data);
222
+ break;
223
+ default:
224
+ this.debug(message, data);
225
+ }
226
+ }
227
+
228
+ /**
229
+ * Log file transfer operations
230
+ */
231
+ logTransfer(operation, server, source, destination, result = null) {
232
+ const data = { server, source, destination };
233
+
234
+ if (result) {
235
+ data.success = result.success;
236
+ data.size = result.size;
237
+ data.duration = result.duration;
238
+ }
239
+
240
+ const message = `File ${operation} ${result ? (result.success ? 'completed' : 'failed') : 'started'}`;
241
+
242
+ if (result && !result.success) {
243
+ this.error(message, data);
244
+ } else {
245
+ this.info(message, data);
246
+ }
247
+ }
248
+
249
+ /**
250
+ * Get command history
251
+ */
252
+ getHistory(limit = 100) {
253
+ return this.commandHistory.slice(-limit);
254
+ }
255
+
256
+ /**
257
+ * Clear logs and history
258
+ */
259
+ clear() {
260
+ this.commandHistory = [];
261
+ try {
262
+ fs.writeFileSync(this.historyFile, '[]');
263
+ fs.writeFileSync(this.logFile, '');
264
+ this.info('Logs and history cleared');
265
+ } catch (error) {
266
+ this.error('Failed to clear logs', { error: error.message });
267
+ }
268
+ }
269
+ }
270
+
271
+ // Export singleton instance
272
+ export const logger = new Logger();
273
+
274
+ // Export for convenience
275
+ export const { debug, info, warn, error } = logger;
276
+ export default logger;
@@ -0,0 +1,187 @@
1
+ /**
2
+ * Profile Loader for SSH Manager
3
+ * Loads configuration profiles for different project types
4
+ */
5
+
6
+ import fs from 'fs';
7
+ import path from 'path';
8
+ import { fileURLToPath } from 'url';
9
+
10
+ const __filename = fileURLToPath(import.meta.url);
11
+ const __dirname = path.dirname(__filename);
12
+
13
+ const PROFILES_DIR = path.join(__dirname, '..', 'profiles');
14
+ const PROFILE_CONFIG_FILE = path.join(__dirname, '..', '.ssh-manager-profile');
15
+
16
+ /**
17
+ * Get the active profile name
18
+ */
19
+ export function getActiveProfileName() {
20
+ // 1. Check environment variable
21
+ if (process.env.SSH_MANAGER_PROFILE) {
22
+ return process.env.SSH_MANAGER_PROFILE;
23
+ }
24
+
25
+ // 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
+ }
35
+ }
36
+
37
+ // 3. Default to 'default' profile
38
+ return 'default';
39
+ }
40
+
41
+ /**
42
+ * Load a profile by name
43
+ */
44
+ export function loadProfile(profileName = null) {
45
+ const name = profileName || getActiveProfileName();
46
+ const profilePath = path.join(PROFILES_DIR, `${name}.json`);
47
+
48
+ try {
49
+ if (fs.existsSync(profilePath)) {
50
+ const profileData = fs.readFileSync(profilePath, 'utf8');
51
+ const profile = JSON.parse(profileData);
52
+
53
+ console.error(`📦 Loaded profile: ${profile.name} - ${profile.description}`);
54
+ return profile;
55
+ } else {
56
+ console.error(`⚠️ Profile '${name}' not found, using default profile`);
57
+ return loadDefaultProfile();
58
+ }
59
+ } catch (error) {
60
+ console.error(`❌ Error loading profile '${name}': ${error.message}`);
61
+ return loadDefaultProfile();
62
+ }
63
+ }
64
+
65
+ /**
66
+ * Load the default profile
67
+ */
68
+ function loadDefaultProfile() {
69
+ const defaultPath = path.join(PROFILES_DIR, 'default.json');
70
+
71
+ try {
72
+ if (fs.existsSync(defaultPath)) {
73
+ const profileData = fs.readFileSync(defaultPath, 'utf8');
74
+ return JSON.parse(profileData);
75
+ }
76
+ } catch (error) {
77
+ console.error(`Error loading default profile: ${error.message}`);
78
+ }
79
+
80
+ // Return minimal profile if default doesn't exist
81
+ return {
82
+ name: 'minimal',
83
+ description: 'Minimal profile',
84
+ commandAliases: {},
85
+ hooks: {}
86
+ };
87
+ }
88
+
89
+ /**
90
+ * List all available profiles
91
+ */
92
+ export function listProfiles() {
93
+ try {
94
+ const files = fs.readdirSync(PROFILES_DIR);
95
+ const profiles = [];
96
+
97
+ for (const file of files) {
98
+ if (file.endsWith('.json')) {
99
+ const profilePath = path.join(PROFILES_DIR, file);
100
+ try {
101
+ const data = fs.readFileSync(profilePath, 'utf8');
102
+ const profile = JSON.parse(data);
103
+ profiles.push({
104
+ name: profile.name || file.replace('.json', ''),
105
+ description: profile.description || 'No description',
106
+ file: file,
107
+ aliasCount: Object.keys(profile.commandAliases || {}).length,
108
+ hookCount: Object.keys(profile.hooks || {}).length
109
+ });
110
+ } catch (error) {
111
+ console.error(`Error reading profile ${file}: ${error.message}`);
112
+ }
113
+ }
114
+ }
115
+
116
+ return profiles;
117
+ } catch (error) {
118
+ console.error(`Error listing profiles: ${error.message}`);
119
+ return [];
120
+ }
121
+ }
122
+
123
+ /**
124
+ * Set the active profile
125
+ */
126
+ export function setActiveProfile(profileName) {
127
+ try {
128
+ // Verify profile exists
129
+ const profilePath = path.join(PROFILES_DIR, `${profileName}.json`);
130
+ if (!fs.existsSync(profilePath)) {
131
+ throw new Error(`Profile '${profileName}' does not exist`);
132
+ }
133
+
134
+ // Write to config file
135
+ fs.writeFileSync(PROFILE_CONFIG_FILE, profileName);
136
+ return true;
137
+ } catch (error) {
138
+ console.error(`Error setting active profile: ${error.message}`);
139
+ return false;
140
+ }
141
+ }
142
+
143
+ /**
144
+ * Create a custom profile
145
+ */
146
+ export function createProfile(name, config) {
147
+ try {
148
+ const profilePath = path.join(PROFILES_DIR, `${name}.json`);
149
+
150
+ // Check if profile already exists
151
+ if (fs.existsSync(profilePath)) {
152
+ throw new Error(`Profile '${name}' already exists`);
153
+ }
154
+
155
+ const profile = {
156
+ name: name,
157
+ description: config.description || `Custom profile: ${name}`,
158
+ commandAliases: config.commandAliases || {},
159
+ hooks: config.hooks || {}
160
+ };
161
+
162
+ fs.writeFileSync(profilePath, JSON.stringify(profile, null, 2));
163
+ return true;
164
+ } catch (error) {
165
+ console.error(`Error creating profile: ${error.message}`);
166
+ return false;
167
+ }
168
+ }
169
+
170
+ /**
171
+ * Merge profiles (useful for extending base profiles)
172
+ */
173
+ export function mergeProfiles(baseProfileName, extensions) {
174
+ const baseProfile = loadProfile(baseProfileName);
175
+
176
+ return {
177
+ ...baseProfile,
178
+ commandAliases: {
179
+ ...baseProfile.commandAliases,
180
+ ...extensions.commandAliases
181
+ },
182
+ hooks: {
183
+ ...baseProfile.hooks,
184
+ ...extensions.hooks
185
+ }
186
+ };
187
+ }
@@ -0,0 +1,150 @@
1
+ import fs from 'fs';
2
+ import path from 'path';
3
+ import { fileURLToPath } from 'url';
4
+
5
+ const __filename = fileURLToPath(import.meta.url);
6
+ const __dirname = path.dirname(__filename);
7
+
8
+ /**
9
+ * Server alias management
10
+ * Allows using aliases like "prod" instead of full server names
11
+ */
12
+
13
+ const ALIASES_FILE = path.join(__dirname, '..', '.server-aliases.json');
14
+
15
+ /**
16
+ * Load server aliases from configuration file
17
+ */
18
+ export function loadAliases() {
19
+ try {
20
+ if (fs.existsSync(ALIASES_FILE)) {
21
+ const content = fs.readFileSync(ALIASES_FILE, 'utf8');
22
+ return JSON.parse(content);
23
+ }
24
+ } catch (error) {
25
+ console.error(`Warning: Could not load aliases: ${error.message}`);
26
+ }
27
+ return {};
28
+ }
29
+
30
+ /**
31
+ * Save server aliases to configuration file
32
+ */
33
+ export function saveAliases(aliases) {
34
+ try {
35
+ fs.writeFileSync(ALIASES_FILE, JSON.stringify(aliases, null, 2));
36
+ return true;
37
+ } catch (error) {
38
+ console.error(`Error saving aliases: ${error.message}`);
39
+ return false;
40
+ }
41
+ }
42
+
43
+ /**
44
+ * Resolve server name from alias
45
+ */
46
+ export function resolveServerName(nameOrAlias, servers) {
47
+ const aliases = loadAliases();
48
+
49
+ // Check if it's an alias
50
+ if (aliases[nameOrAlias]) {
51
+ return aliases[nameOrAlias];
52
+ }
53
+
54
+ // Check if it's a direct server name
55
+ const normalizedName = nameOrAlias.toLowerCase();
56
+ if (servers[normalizedName]) {
57
+ return normalizedName;
58
+ }
59
+
60
+ // Try to find partial match
61
+ const serverNames = Object.keys(servers);
62
+ const matches = serverNames.filter(name => name.includes(normalizedName));
63
+
64
+ if (matches.length === 1) {
65
+ return matches[0];
66
+ } else if (matches.length > 1) {
67
+ throw new Error(
68
+ `Ambiguous server name "${nameOrAlias}". Matches: ${matches.join(', ')}`
69
+ );
70
+ }
71
+
72
+ // Check if nameOrAlias contains a domain that matches a server
73
+ if (nameOrAlias.includes('.')) {
74
+ const matchingServer = serverNames.find(name => {
75
+ const serverHost = servers[name].host;
76
+ return serverHost && (
77
+ serverHost === nameOrAlias ||
78
+ serverHost.includes(nameOrAlias) ||
79
+ nameOrAlias.includes(serverHost)
80
+ );
81
+ });
82
+
83
+ if (matchingServer) {
84
+ return matchingServer;
85
+ }
86
+ }
87
+
88
+ return null;
89
+ }
90
+
91
+ /**
92
+ * Create default aliases based on common patterns
93
+ */
94
+ export function createDefaultAliases(servers) {
95
+ const aliases = {};
96
+
97
+ Object.entries(servers).forEach(([name, config]) => {
98
+ // Create short aliases for common patterns
99
+ if (name.includes('production')) {
100
+ aliases['prod'] = name;
101
+ } else if (name.includes('staging')) {
102
+ aliases['stage'] = name;
103
+ } else if (name.includes('development')) {
104
+ aliases['dev'] = name;
105
+ } else if (name.includes('testing')) {
106
+ aliases['test'] = name;
107
+ }
108
+
109
+ // Create aliases from hostname patterns
110
+ const host = config.host;
111
+ if (host) {
112
+ // Extract subdomain as potential alias
113
+ const subdomain = host.split('.')[0];
114
+ if (subdomain && subdomain !== 'www' && !aliases[subdomain]) {
115
+ aliases[subdomain] = name;
116
+ }
117
+ }
118
+ });
119
+
120
+ return aliases;
121
+ }
122
+
123
+ /**
124
+ * Add or update an alias
125
+ */
126
+ export function addAlias(alias, serverName) {
127
+ const aliases = loadAliases();
128
+ aliases[alias] = serverName;
129
+ return saveAliases(aliases);
130
+ }
131
+
132
+ /**
133
+ * Remove an alias
134
+ */
135
+ export function removeAlias(alias) {
136
+ const aliases = loadAliases();
137
+ delete aliases[alias];
138
+ return saveAliases(aliases);
139
+ }
140
+
141
+ /**
142
+ * List all aliases with their targets
143
+ */
144
+ export function listAliases() {
145
+ const aliases = loadAliases();
146
+ return Object.entries(aliases).map(([alias, target]) => ({
147
+ alias,
148
+ target
149
+ }));
150
+ }