mcp-ssh-manager 3.0.0 → 3.1.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.
@@ -3,8 +3,6 @@
3
3
  * Provides database operations for MySQL, PostgreSQL, and MongoDB
4
4
  */
5
5
 
6
- import { logger } from './logger.js';
7
-
8
6
  // Supported database types
9
7
  export const DB_TYPES = {
10
8
  MYSQL: 'mysql',
@@ -254,7 +252,7 @@ export function buildMySQLListDatabasesCommand(options) {
254
252
  if (password) command += ` -p'${password}'`;
255
253
  if (host) command += ` -h ${host}`;
256
254
  if (port) command += ` -P ${port}`;
257
- command += ` -e "SHOW DATABASES;" | tail -n +2`;
255
+ command += ' -e "SHOW DATABASES;" | tail -n +2';
258
256
 
259
257
  return command;
260
258
  }
@@ -290,7 +288,7 @@ export function buildPostgreSQLListDatabasesCommand(options) {
290
288
  if (user) command += ` -U ${user}`;
291
289
  if (host) command += ` -h ${host}`;
292
290
  if (port) command += ` -p ${port}`;
293
- command += ` -t -c "SELECT datname FROM pg_database WHERE datistemplate = false;" | sed '/^$/d' | sed 's/^[ \\t]*//'`;
291
+ command += ' -t -c "SELECT datname FROM pg_database WHERE datistemplate = false;" | sed \'/^$/d\' | sed \'s/^[ \\t]*//\'';
294
292
 
295
293
  return command;
296
294
  }
@@ -311,7 +309,7 @@ export function buildPostgreSQLListTablesCommand(options) {
311
309
  if (host) command += ` -h ${host}`;
312
310
  if (port) command += ` -p ${port}`;
313
311
  command += ` -d ${database}`;
314
- command += ` -t -c "SELECT tablename FROM pg_tables WHERE schemaname = 'public';" | sed '/^$/d' | sed 's/^[ \\t]*//'`;
312
+ command += ' -t -c "SELECT tablename FROM pg_tables WHERE schemaname = \'public\';" | sed \'/^$/d\' | sed \'s/^[ \\t]*//\'';
315
313
 
316
314
  return command;
317
315
  }
@@ -327,7 +325,7 @@ export function buildMongoDBListDatabasesCommand(options) {
327
325
  if (port) command += ` --port ${port}`;
328
326
  if (user) command += ` --username ${user}`;
329
327
  if (password) command += ` --password '${password}'`;
330
- command += ` --quiet --eval "db.adminCommand('listDatabases').databases.forEach(function(d){print(d.name)})"`;
328
+ command += ' --quiet --eval "db.adminCommand(\'listDatabases\').databases.forEach(function(d){print(d.name)})"';
331
329
 
332
330
  return command;
333
331
  }
@@ -344,7 +342,7 @@ export function buildMongoDBListCollectionsCommand(options) {
344
342
  if (user) command += ` --username ${user}`;
345
343
  if (password) command += ` --password '${password}'`;
346
344
  command += ` ${database}`;
347
- command += ` --quiet --eval "db.getCollectionNames().forEach(function(c){print(c)})"`;
345
+ command += ' --quiet --eval "db.getCollectionNames().forEach(function(c){print(c)})"';
348
346
 
349
347
  return command;
350
348
  }
@@ -479,43 +477,43 @@ export function buildEstimateSizeCommand(type, database, options = {}) {
479
477
  const { user, password, host = 'localhost', port } = options;
480
478
 
481
479
  switch (type) {
482
- case DB_TYPES.MYSQL: {
483
- let command = 'mysql';
484
- if (user) command += ` -u${user}`;
485
- if (password) command += ` -p'${password}'`;
486
- if (host) command += ` -h ${host}`;
487
- if (port) command += ` -P ${port}`;
488
- command += ` -e "SELECT SUM(data_length + index_length) FROM information_schema.TABLES WHERE table_schema='${database}';" | tail -n 1`;
489
- return command;
490
- }
480
+ case DB_TYPES.MYSQL: {
481
+ let command = 'mysql';
482
+ if (user) command += ` -u${user}`;
483
+ if (password) command += ` -p'${password}'`;
484
+ if (host) command += ` -h ${host}`;
485
+ if (port) command += ` -P ${port}`;
486
+ command += ` -e "SELECT SUM(data_length + index_length) FROM information_schema.TABLES WHERE table_schema='${database}';" | tail -n 1`;
487
+ return command;
488
+ }
491
489
 
492
- case DB_TYPES.POSTGRESQL: {
493
- let command = '';
494
- if (password) {
495
- command = `PGPASSWORD='${password}' `;
496
- }
497
- command += 'psql';
498
- if (user) command += ` -U ${user}`;
499
- if (host) command += ` -h ${host}`;
500
- if (port) command += ` -p ${port}`;
501
- command += ` -d ${database}`;
502
- command += ` -t -c "SELECT pg_database_size('${database}');" | sed 's/^[ \\t]*//'`;
503
- return command;
490
+ case DB_TYPES.POSTGRESQL: {
491
+ let command = '';
492
+ if (password) {
493
+ command = `PGPASSWORD='${password}' `;
504
494
  }
495
+ command += 'psql';
496
+ if (user) command += ` -U ${user}`;
497
+ if (host) command += ` -h ${host}`;
498
+ if (port) command += ` -p ${port}`;
499
+ command += ` -d ${database}`;
500
+ command += ` -t -c "SELECT pg_database_size('${database}');" | sed 's/^[ \\t]*//'`;
501
+ return command;
502
+ }
505
503
 
506
- case DB_TYPES.MONGODB: {
507
- let command = 'mongo';
508
- if (host) command += ` --host ${host}`;
509
- if (port) command += ` --port ${port}`;
510
- if (user) command += ` --username ${user}`;
511
- if (password) command += ` --password '${password}'`;
512
- command += ` ${database}`;
513
- command += ` --quiet --eval "db.stats().dataSize"`;
514
- return command;
515
- }
504
+ case DB_TYPES.MONGODB: {
505
+ let command = 'mongo';
506
+ if (host) command += ` --host ${host}`;
507
+ if (port) command += ` --port ${port}`;
508
+ if (user) command += ` --username ${user}`;
509
+ if (password) command += ` --password '${password}'`;
510
+ command += ` ${database}`;
511
+ command += ' --quiet --eval "db.stats().dataSize"';
512
+ return command;
513
+ }
516
514
 
517
- default:
518
- throw new Error(`Unknown database type: ${type}`);
515
+ default:
516
+ throw new Error(`Unknown database type: ${type}`);
519
517
  }
520
518
  }
521
519
 
@@ -1,4 +1,3 @@
1
- import fs from 'fs';
2
1
  import path from 'path';
3
2
  import crypto from 'crypto';
4
3
 
@@ -43,8 +42,8 @@ export function buildDeploymentStrategy(remotePath, options = {}) {
43
42
  }
44
43
 
45
44
  // Step 2: Determine if we need sudo
46
- const needsSudo = remotePath.startsWith('/etc/') ||
47
- remotePath.startsWith('/var/') ||
45
+ const needsSudo = remotePath.startsWith('/etc/') ||
46
+ remotePath.startsWith('/var/') ||
48
47
  remotePath.startsWith('/usr/') ||
49
48
  owner || permissions;
50
49
 
@@ -53,11 +52,11 @@ export function buildDeploymentStrategy(remotePath, options = {}) {
53
52
  }
54
53
 
55
54
  // Step 3: Copy from temp to final location
56
- const copyCmd = needsSudo && sudoPassword ?
55
+ const copyCmd = needsSudo && sudoPassword ?
57
56
  `echo "${sudoPassword}" | sudo -S cp {{tempFile}} "${remotePath}"` :
58
57
  needsSudo ?
59
- `sudo cp {{tempFile}} "${remotePath}"` :
60
- `cp {{tempFile}} "${remotePath}"`;
58
+ `sudo cp {{tempFile}} "${remotePath}"` :
59
+ `cp {{tempFile}} "${remotePath}"`;
61
60
 
62
61
  strategy.steps.push({
63
62
  type: 'copy',
@@ -69,7 +68,7 @@ export function buildDeploymentStrategy(remotePath, options = {}) {
69
68
  const chownCmd = sudoPassword ?
70
69
  `echo "${sudoPassword}" | sudo -S chown ${owner} "${remotePath}"` :
71
70
  `sudo chown ${owner} "${remotePath}"`;
72
-
71
+
73
72
  strategy.steps.push({
74
73
  type: 'chown',
75
74
  command: chownCmd
@@ -81,7 +80,7 @@ export function buildDeploymentStrategy(remotePath, options = {}) {
81
80
  const chmodCmd = sudoPassword ?
82
81
  `echo "${sudoPassword}" | sudo -S chmod ${permissions} "${remotePath}"` :
83
82
  `sudo chmod ${permissions} "${remotePath}"`;
84
-
83
+
85
84
  strategy.steps.push({
86
85
  type: 'chmod',
87
86
  command: chmodCmd
@@ -151,11 +150,11 @@ export function detectDeploymentNeeds(remotePath) {
151
150
  */
152
151
  export function createBatchDeployScript(deployments) {
153
152
  const script = ['#!/bin/bash', 'set -e', ''];
154
-
153
+
155
154
  script.push('# Batch deployment script');
156
155
  script.push(`# Generated at ${new Date().toISOString()}`);
157
156
  script.push('');
158
-
157
+
159
158
  deployments.forEach((deploy, index) => {
160
159
  script.push(`# File ${index + 1}: ${deploy.localPath} -> ${deploy.remotePath}`);
161
160
  deploy.strategy.steps.forEach(step => {
@@ -165,12 +164,12 @@ export function createBatchDeployScript(deployments) {
165
164
  });
166
165
  script.push('');
167
166
  });
168
-
167
+
169
168
  // Cleanup all temp files at the end
170
169
  script.push('# Cleanup temporary files');
171
170
  deployments.forEach(deploy => {
172
171
  script.push(`rm -f ${deploy.tempFile}`);
173
172
  });
174
-
173
+
175
174
  return script.join('\n');
176
- }
175
+ }
@@ -30,7 +30,7 @@ export const COMMON_SERVICES = {
30
30
  */
31
31
  export function buildCPUCheckCommand() {
32
32
  // Get CPU usage using top, show idle percentage, calculate used
33
- return `top -bn1 | grep "Cpu(s)" | sed "s/.*, *\\([0-9.]*\\)%* id.*/\\1/" | awk '{print 100 - $1}'`;
33
+ return 'top -bn1 | grep "Cpu(s)" | sed "s/.*, *\\([0-9.]*\\)%* id.*/\\1/" | awk \'{print 100 - $1}\'';
34
34
  }
35
35
 
36
36
  /**
@@ -38,7 +38,7 @@ export function buildCPUCheckCommand() {
38
38
  */
39
39
  export function buildMemoryCheckCommand() {
40
40
  // Returns: total, used, free, available in MB and percentage
41
- return `free -m | awk 'NR==2{printf "{\\"total\\":%s,\\"used\\":%s,\\"free\\":%s,\\"percent\\":%.2f}", $2,$3,$4,$3*100/$2}'`;
41
+ return 'free -m | awk \'NR==2{printf "{\\"total\\":%s,\\"used\\":%s,\\"free\\":%s,\\"percent\\":%.2f}", $2,$3,$4,$3*100/$2}\'';
42
42
  }
43
43
 
44
44
  /**
@@ -47,7 +47,7 @@ export function buildMemoryCheckCommand() {
47
47
  export function buildDiskCheckCommand(mountPoint = '/') {
48
48
  // Returns JSON with disk usage for specific mount point or all
49
49
  if (mountPoint === 'all') {
50
- return `df -h | awk 'NR>1 {gsub(/%/,"",$5); printf "{\\"mount\\":\\"%s\\",\\"size\\":\\"%s\\",\\"used\\":\\"%s\\",\\"avail\\":\\"%s\\",\\"percent\\":%s}\\n", $6,$2,$3,$4,$5}'`;
50
+ return 'df -h | awk \'NR>1 {gsub(/%/,"",$5); printf "{\\"mount\\":\\"%s\\",\\"size\\":\\"%s\\",\\"used\\":\\"%s\\",\\"avail\\":\\"%s\\",\\"percent\\":%s}\\n", $6,$2,$3,$4,$5}\'';
51
51
  }
52
52
  return `df -h "${mountPoint}" | awk 'NR>1 {gsub(/%/,"",$5); printf "{\\"mount\\":\\"%s\\",\\"size\\":\\"%s\\",\\"used\\":\\"%s\\",\\"avail\\":\\"%s\\",\\"percent\\":%s}", $6,$2,$3,$4,$5}'`;
53
53
  }
@@ -57,21 +57,21 @@ export function buildDiskCheckCommand(mountPoint = '/') {
57
57
  */
58
58
  export function buildNetworkCheckCommand() {
59
59
  // Get basic network stats (RX/TX bytes)
60
- return `cat /proc/net/dev | awk 'NR>2 {printf "{\\"interface\\":\\"%s\\",\\"rx_bytes\\":%s,\\"tx_bytes\\":%s}\\n", $1,$2,$10}' | grep -v "lo:"`;
60
+ return 'cat /proc/net/dev | awk \'NR>2 {printf "{\\"interface\\":\\"%s\\",\\"rx_bytes\\":%s,\\"tx_bytes\\":%s}\\n", $1,$2,$10}\' | grep -v "lo:"';
61
61
  }
62
62
 
63
63
  /**
64
64
  * Build command to check load average
65
65
  */
66
66
  export function buildLoadAverageCommand() {
67
- return `uptime | awk -F'load average:' '{print $2}' | sed 's/^[ \\t]*//'`;
67
+ return 'uptime | awk -F\'load average:\' \'{print $2}\' | sed \'s/^[ \\t]*//\'';
68
68
  }
69
69
 
70
70
  /**
71
71
  * Build command to check system uptime
72
72
  */
73
73
  export function buildUptimeCommand() {
74
- return `uptime -p 2>/dev/null || uptime | awk '{print $3,$4}' | sed 's/,//'`;
74
+ return 'uptime -p 2>/dev/null || uptime | awk \'{print $3,$4}\' | sed \'s/,//\'';
75
75
  }
76
76
 
77
77
  /**
@@ -225,7 +225,7 @@ export function buildProcessListCommand(options = {}) {
225
225
  }
226
226
 
227
227
  // Format output as JSON-like structure
228
- command += ` | awk 'NR>1 {printf "{\\"user\\":\\"%s\\",\\"pid\\":%s,\\"cpu\\":%.1f,\\"mem\\":%.1f,\\"vsz\\":%s,\\"rss\\":%s,\\"stat\\":\\"%s\\",\\"start\\":\\"%s\\",\\"time\\":\\"%s\\",\\"command\\":\\"%s\\"}\\n", $1,$2,$3,$4,$5,$6,$8,$9,$10,substr($0,index($0,$11))}'`;
228
+ command += ' | awk \'NR>1 {printf "{\\"user\\":\\"%s\\",\\"pid\\":%s,\\"cpu\\":%.1f,\\"mem\\":%.1f,\\"vsz\\":%s,\\"rss\\":%s,\\"stat\\":\\"%s\\",\\"start\\":\\"%s\\",\\"time\\":\\"%s\\",\\"command\\":\\"%s\\"}\\n", $1,$2,$3,$4,$5,$6,$8,$9,$10,substr($0,index($0,$11))}\'';
229
229
 
230
230
  return command;
231
231
  }
@@ -296,7 +296,7 @@ export function createAlertConfig(thresholds) {
296
296
  */
297
297
  export function buildSaveAlertConfigCommand(config, configPath = '/etc/ssh-manager-alerts.json') {
298
298
  const jsonData = JSON.stringify(config, null, 2);
299
- const escapedJson = jsonData.replace(/'/g, "'\\''");
299
+ const escapedJson = jsonData.replace(/'/g, '\'\\\'\'');
300
300
  return `echo '${escapedJson}' > "${configPath}"`;
301
301
  }
302
302
 
@@ -383,24 +383,24 @@ export function parseComprehensiveHealthCheck(output) {
383
383
  const data = content.join('\n').trim();
384
384
 
385
385
  switch (name.toLowerCase().trim()) {
386
- case 'cpu ===':
387
- result.cpu = parseCPUUsage(data);
388
- break;
389
- case 'memory ===':
390
- result.memory = parseMemoryUsage(data);
391
- break;
392
- case 'disk ===':
393
- result.disks = parseDiskUsage(data);
394
- break;
395
- case 'load ===':
396
- result.load_average = data;
397
- break;
398
- case 'uptime ===':
399
- result.uptime = data;
400
- break;
401
- case 'network ===':
402
- result.network = parseNetworkStats(data);
403
- break;
386
+ case 'cpu ===':
387
+ result.cpu = parseCPUUsage(data);
388
+ break;
389
+ case 'memory ===':
390
+ result.memory = parseMemoryUsage(data);
391
+ break;
392
+ case 'disk ===':
393
+ result.disks = parseDiskUsage(data);
394
+ break;
395
+ case 'load ===':
396
+ result.load_average = data;
397
+ break;
398
+ case 'uptime ===':
399
+ result.uptime = data;
400
+ break;
401
+ case 'network ===':
402
+ result.network = parseNetworkStats(data);
403
+ break;
404
404
  }
405
405
  }
406
406
 
@@ -73,15 +73,15 @@ export async function initializeHooks() {
73
73
  if (!fs.existsSync(HOOKS_DIR)) {
74
74
  fs.mkdirSync(HOOKS_DIR, { recursive: true });
75
75
  }
76
-
76
+
77
77
  // Merge profile hooks with defaults
78
78
  const mergedHooks = { ...DEFAULT_HOOKS, ...profileHooks };
79
-
79
+
80
80
  // Create hooks configuration if it doesn't exist
81
81
  if (!fs.existsSync(HOOKS_CONFIG_FILE)) {
82
82
  saveHooksConfig(mergedHooks);
83
83
  }
84
-
84
+
85
85
  return true;
86
86
  }
87
87
 
@@ -92,12 +92,12 @@ export function loadHooksConfig() {
92
92
  try {
93
93
  // Start with profile hooks
94
94
  let hooks = { ...profileHooks };
95
-
95
+
96
96
  // Merge with custom hooks from file
97
97
  if (fs.existsSync(HOOKS_CONFIG_FILE)) {
98
98
  const data = fs.readFileSync(HOOKS_CONFIG_FILE, 'utf8');
99
99
  const customHooks = JSON.parse(data);
100
-
100
+
101
101
  // Deep merge hooks
102
102
  for (const [hookName, hookConfig] of Object.entries(customHooks)) {
103
103
  if (hooks[hookName]) {
@@ -112,7 +112,7 @@ export function loadHooksConfig() {
112
112
  }
113
113
  }
114
114
  }
115
-
115
+
116
116
  return hooks;
117
117
  } catch (error) {
118
118
  console.error(`Error loading hooks config: ${error.message}`);
@@ -139,14 +139,14 @@ export function saveHooksConfig(config) {
139
139
  export async function executeHook(hookName, context = {}) {
140
140
  const config = loadHooksConfig();
141
141
  const hook = config[hookName];
142
-
142
+
143
143
  if (!hook || !hook.enabled) {
144
144
  return { success: true, skipped: true };
145
145
  }
146
-
146
+
147
147
  console.error(`🎣 Executing hook: ${hookName}`);
148
148
  const results = [];
149
-
149
+
150
150
  for (const action of hook.actions) {
151
151
  try {
152
152
  // Check environment variables if required
@@ -160,25 +160,25 @@ export async function executeHook(hookName, context = {}) {
160
160
  continue;
161
161
  }
162
162
  }
163
-
163
+
164
164
  // Replace placeholders in command
165
165
  let command = action.command || action.remoteCommand || '';
166
166
  for (const [key, value] of Object.entries(context)) {
167
167
  command = command.replace(new RegExp(`{${key}}`, 'g'), value);
168
168
  }
169
-
169
+
170
170
  // Execute action based on type
171
171
  const result = await executeAction(action, command, context);
172
172
  results.push(result);
173
-
173
+
174
174
  // Check validation results
175
175
  if (action.type === 'validation' && !result.success && !action.optional) {
176
176
  const errorMsg = action.errorMessage || `Validation failed: ${action.name}`;
177
177
  throw new Error(errorMsg);
178
178
  }
179
-
179
+
180
180
  console.error(` ✅ ${action.name}: completed`);
181
-
181
+
182
182
  } catch (error) {
183
183
  if (!action.optional) {
184
184
  console.error(` ❌ ${action.name}: ${error.message}`);
@@ -193,7 +193,7 @@ export async function executeHook(hookName, context = {}) {
193
193
  console.error(` ⚠️ ${action.name}: ${error.message} (optional, continuing)`);
194
194
  }
195
195
  }
196
-
196
+
197
197
  return {
198
198
  success: true,
199
199
  hook: hookName,
@@ -210,61 +210,61 @@ async function executeAction(action, command, context) {
210
210
  type: action.type,
211
211
  timestamp: new Date().toISOString()
212
212
  };
213
-
213
+
214
214
  try {
215
215
  if (action.remoteCommand && context.sshConnection) {
216
216
  // Execute on remote server
217
217
  const output = await context.sshConnection.execCommand(command, {
218
218
  cwd: context.cwd || context.defaultDir
219
219
  });
220
-
220
+
221
221
  result.output = output.stdout;
222
222
  result.error = output.stderr;
223
223
  result.success = output.code === 0;
224
-
224
+
225
225
  if (action.expectEmpty && output.stdout.trim()) {
226
226
  result.success = false;
227
227
  }
228
228
  } else if (action.command) {
229
229
  // Execute locally
230
230
  const { stdout, stderr } = await execAsync(command);
231
-
231
+
232
232
  result.output = stdout;
233
233
  result.error = stderr;
234
234
  result.success = true;
235
-
235
+
236
236
  if (action.expectEmpty && stdout.trim()) {
237
237
  result.success = false;
238
238
  }
239
239
  }
240
-
240
+
241
241
  // Handle specific action types
242
242
  switch (action.type) {
243
- case 'backup':
244
- result.backupInfo = {
245
- timestamp: new Date().toISOString(),
246
- command: command
247
- };
248
- break;
249
-
250
- case 'notification':
251
- result.notified = true;
252
- break;
253
-
254
- case 'validation':
255
- result.validated = result.success;
256
- break;
257
-
258
- case 'verification':
259
- result.verified = result.success;
260
- break;
243
+ case 'backup':
244
+ result.backupInfo = {
245
+ timestamp: new Date().toISOString(),
246
+ command: command
247
+ };
248
+ break;
249
+
250
+ case 'notification':
251
+ result.notified = true;
252
+ break;
253
+
254
+ case 'validation':
255
+ result.validated = result.success;
256
+ break;
257
+
258
+ case 'verification':
259
+ result.verified = result.success;
260
+ break;
261
261
  }
262
-
262
+
263
263
  } catch (error) {
264
264
  result.success = false;
265
265
  result.error = error.message;
266
266
  }
267
-
267
+
268
268
  return result;
269
269
  }
270
270
 
@@ -316,7 +316,7 @@ export function listHooks() {
316
316
  */
317
317
  export async function createHookScript(scriptName, scriptContent) {
318
318
  const scriptPath = path.join(HOOKS_DIR, scriptName);
319
-
319
+
320
320
  try {
321
321
  fs.writeFileSync(scriptPath, scriptContent);
322
322
  fs.chmodSync(scriptPath, '755');
@@ -324,4 +324,4 @@ export async function createHookScript(scriptName, scriptContent) {
324
324
  } catch (error) {
325
325
  throw new Error(`Failed to create hook script: ${error.message}`);
326
326
  }
327
- }
327
+ }