mcp-ssh-manager 3.6.3 → 3.6.5

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/CHANGELOG.md CHANGED
@@ -5,6 +5,36 @@ All notable changes to MCP SSH Manager will be documented in this file.
5
5
  The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
6
6
  and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
7
 
8
+ ## [3.6.5] - 2026-06-30
9
+
10
+ ### Security
11
+
12
+ - **`ssh_db_query` could execute arbitrary shell commands on the remote host** ([#44](https://github.com/bvisible/mcp-ssh-manager/pull/44) — thanks [@technophile77](https://github.com/technophile77))
13
+ - The query builders interpolated the raw query into a **double-quoted** shell string (`mysql -e "${query}"`, `psql -c "${query}"`, `mongo --eval "${query}"`), so the remote shell evaluated backticks `` `…` `` and `$(…)`/`$VAR` **before** the database engine ever saw the query. The "SELECT-only" tool could therefore run shell commands on the target server (e.g. `` SELECT `id` `` / `SELECT '$(id)'`).
14
+ - The query is now delivered to `mysql`/`psql`/`mongo` on **stdin via a single-quoted heredoc** (`<<'__MCP_SQL_EOF__'`), so the remote shell never parses it — only the database engine interprets the SQL/JS. A shared `buildHeredoc()` helper keeps the existing `awk` JSON-wrapper pipe on the heredoc opening line (MySQL JSON output is byte-for-byte unchanged) and defensively rejects a delimiter collision. `isSafeQuery()` is intentionally left as-is, since the heredoc — not keyword filtering — closes the injection path.
15
+
16
+ ### Fixed
17
+
18
+ - **`ssh_db_query` (MySQL) silently corrupted backtick-quoted identifiers** ([#44](https://github.com/bvisible/mcp-ssh-manager/pull/44) — thanks [@technophile77](https://github.com/technophile77))
19
+ - The same shell-evaluation bug meant any query using backtick identifiers — hyphenated database names, cross-database joins, reserved-word columns — was rewritten by the shell and returned empty/incorrect results **with no error**. The stdin heredoc fix above restores these queries verbatim.
20
+ - **`ssh_db_query` reported `row_count` off by one** ([#45](https://github.com/bvisible/mcp-ssh-manager/pull/45) — thanks [@technophile77](https://github.com/technophile77))
21
+ - The handler reported `output.split('\n').length`, which counted cosmetic lines (the leading `[` of the MySQL JSON wrapper, psql header/separator lines) rather than result rows: 1 row → `2`, 13 rows → `14`, 0 rows → `2`. A new `countQueryRows()` derives the count from each engine's actual output structure — MySQL JSON `{"row":N,…}` entries, MySQL `--batch` lines, psql's authoritative `(N rows)` footer (with a header/separator fallback), and MongoDB `printjson` documents — so empty output is `0` and the count tracks real rows.
22
+
23
+ ### Tests
24
+
25
+ - **New `tests/test-database-query-quoting.js`** (`test:dbquoting`) — verifies the SQL/JS query text is carried verbatim on stdin for all three builders (never via `-e "`/`-c "`/`--eval "`), that the `awk` pipe stays on the heredoc opening line with the terminator alone, that `buildHeredoc` rejects a delimiter collision, and a stochastic round-trip of 500 random shell-metacharacter queries.
26
+ - **New `tests/test-database-row-count.js`** (`test:dbrowcount`) — covers the exact issue cases (MySQL 0/1/13 rows), a look-alike `{"row":` value inside a cell, MySQL text format, psql `(N rows)`/`(1 row)`/`(0 rows)` footers and the no-footer fallback, MongoDB single/multi-document counting, and empty/whitespace → `0`.
27
+
28
+ ## [3.6.4] - 2026-06-18
29
+
30
+ ### Changed
31
+
32
+ - **Internal dead-code cleanup — no behavioral change.** Removed 27 unused exports and 2 duplicate exports across the codebase (−343 lines): fully-unused helper functions deleted, internally-used symbols un-exported, and redundant `export default`s removed. The public surface (the MCP server + CLI) is unchanged — command builders and parsers are byte-identical before/after (verified by a differential test of `main` vs the change), and all 37 tools were exercised end-to-end against a live SSH server (Ubuntu + MariaDB) with no regression.
33
+
34
+ ### Tooling
35
+
36
+ - **Dead-code quality gate.** Added a calibrated `knip.json` and a **blocking** `knip` step to the `quality` CI workflow, so unused exports/files/dependencies now fail the build and can't creep back in. `eslint src/` is clean (0 errors, 0 warnings).
37
+
8
38
  ## [3.6.3] - 2026-06-18
9
39
 
10
40
  ### Fixed
package/README.md CHANGED
@@ -6,7 +6,7 @@ A Model Context Protocol (MCP) server that enables **Claude Code** and **OpenAI
6
6
 
7
7
  [![npm version](https://img.shields.io/npm/v/mcp-ssh-manager.svg?style=for-the-badge&logo=npm)](https://www.npmjs.com/package/mcp-ssh-manager)
8
8
  [![npm downloads](https://img.shields.io/npm/dt/mcp-ssh-manager.svg?style=for-the-badge&logo=npm)](https://www.npmjs.com/package/mcp-ssh-manager)
9
- [![Version](https://img.shields.io/badge/Version-3.6.3-brightgreen?style=for-the-badge)](https://github.com/bvisible/mcp-ssh-manager/releases/tag/v3.6.3)
9
+ [![Version](https://img.shields.io/badge/Version-3.6.5-brightgreen?style=for-the-badge)](https://github.com/bvisible/mcp-ssh-manager/releases/tag/v3.6.5)
10
10
  [![Claude Code](https://img.shields.io/badge/Claude_Code-Compatible-5A67D8?style=for-the-badge&logo=anthropic)](https://claude.ai/code)
11
11
  [![OpenAI Codex](https://img.shields.io/badge/OpenAI_Codex-Compatible-00A67E?style=for-the-badge&logo=openai)](https://openai.com/codex)
12
12
  [![MCP](https://img.shields.io/badge/MCP-Server-orange?style=for-the-badge)](https://modelcontextprotocol.io)
@@ -20,19 +20,27 @@ A Model Context Protocol (MCP) server that enables **Claude Code** and **OpenAI
20
20
 
21
21
  ---
22
22
 
23
- ## 🎉 What's New in v3.6.3
23
+ ## 🎉 What's New in v3.6.5
24
24
 
25
- **`ssh_sync` now reports the real transfer count** (Released: June 18, 2026)
25
+ **Security fix: `ssh_db_query` shell injection + a row-count fix** (Released: June 30, 2026)
26
26
 
27
- - **📊 No more false "No files needed to be transferred"** ([#42](https://github.com/bvisible/mcp-ssh-manager/pull/42) — thanks [@MakksSh](https://github.com/MakksSh)) — `ssh_sync` scraped rsync's `--stats` block incorrectly: stats were only requested in `verbose` mode and the regex only matched rsync 2.x wording, so `filesTransferred` stayed `0` and agents kept re-verifying or retrying a sync that had actually succeeded. Now `--stats` is always passed and both rsync 2.x and 3.x output is parsed.
28
- - **🍏 Correct on macOS and in any locale** — openrsync (the default `/usr/bin/rsync` on recent macOS) writes byte counts as `B`, not `bytes`, and locale-formatted numbers use `,`/`.` as thousands separators; both are handled now. Parsing was extracted to `src/rsync-stats.js` and covered by 46 new assertions in `tests/test-sync-stats.js`.
27
+ - **🔒 `ssh_db_query` no longer lets the remote shell parse your query** ([#44](https://github.com/bvisible/mcp-ssh-manager/pull/44) — thanks [@technophile77](https://github.com/technophile77)) — the builders interpolated the query into a double-quoted shell string (`mysql -e "${query}"`, `psql -c "${query}"`, `mongo --eval "${query}"`), so the remote shell evaluated backticks and `$(…)` **before** the database saw it. That both **corrupted** backtick identifiers (hyphenated DB names, cross-DB joins → empty results, no error) **and** let the "SELECT-only" tool **run arbitrary shell commands** on the host. The query is now delivered on **stdin via a single-quoted heredoc**, so only the database engine ever interprets it.
28
+ - **🔢 `ssh_db_query` reports the real `row_count`** ([#45](https://github.com/bvisible/mcp-ssh-manager/pull/45) — thanks [@technophile77](https://github.com/technophile77)) — it used to count the cosmetic JSON-wrapper line (1 row → `2`, 0 rows → `2`); it now derives the count from each engine's actual output (MySQL JSON entries, psql's `(N rows)` footer, MongoDB documents).
29
29
 
30
- [Read full changelog →](CHANGELOG.md#363---2026-06-18)
30
+ [Read full changelog →](CHANGELOG.md#365---2026-06-30)
31
31
 
32
32
  ---
33
33
 
34
34
  ## Previous Releases
35
35
 
36
+ ### v3.6.4 - Internal cleanup + a dead-code quality gate (June 18, 2026)
37
+
38
+ - **🧹 Dead-code removal (−343 lines), zero behavioral change** — removed 27 unused exports and 2 duplicate exports; the MCP server and CLI behave identically (command builders/parsers byte-identical, all 37 tools verified end-to-end). A calibrated `knip.json` plus a **blocking** `knip` CI step keep unused code from creeping back. [Full changelog →](CHANGELOG.md#364---2026-06-18)
39
+
40
+ ### v3.6.3 - `ssh_sync` reports the real transfer count (June 18, 2026)
41
+
42
+ - **📊 No more false "No files needed to be transferred"** ([#42](https://github.com/bvisible/mcp-ssh-manager/pull/42) — thanks [@MakksSh](https://github.com/MakksSh)) — fixed rsync `--stats` parsing: `--stats` is always passed now, and rsync 2.x/3.x wording, openrsync's `B` suffix, and locale separators are all handled. [Full changelog →](CHANGELOG.md#363---2026-06-18)
43
+
36
44
  ### v3.6.2 - Richer tool descriptions (June 9, 2026)
37
45
 
38
46
  - **📝 All 37 tool descriptions rewritten** — every MCP tool now documents its real behavior (side effects, destructive vs read-only nature, idempotency, sudo/auth requirements, security-mode gating, parameter semantics) instead of a 4-to-10-word summary. Agents now know the consequences before invoking a tool; no behavioral change — only `description` strings changed. [Full changelog →](CHANGELOG.md#362---2026-06-09)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "mcp-ssh-manager",
3
- "version": "3.6.3",
3
+ "version": "3.6.5",
4
4
  "description": "MCP SSH Manager: Model Context Protocol server for SSH remote server management. Control SSH connections from Claude Code and OpenAI Codex - execute commands, transfer files, database operations, backups, health monitoring, and DevOps automation. NEW: Tool activation system reduces context usage by 92%",
5
5
  "main": "src/index.js",
6
6
  "bin": {
@@ -13,7 +13,7 @@
13
13
  "setup": "npm install && pip install -r tools/requirements.txt",
14
14
  "configure": "python tools/server-manager.py",
15
15
  "test-connection": "python tools/test-connection.py",
16
- "test": "npm run test:profiles && npm run test:aliases && npm run test:hooks && npm run test:tools && npm run test:policy && npm run test:ping && npm run test:config && npm run test:lifecycle && npm run test:sync",
16
+ "test": "npm run test:profiles && npm run test:aliases && npm run test:hooks && npm run test:tools && npm run test:policy && npm run test:ping && npm run test:config && npm run test:lifecycle && npm run test:sync && npm run test:dbquoting && npm run test:dbrowcount",
17
17
  "test:profiles": "node tests/test-profiles.js",
18
18
  "test:aliases": "node tests/test-command-aliases.js",
19
19
  "test:hooks": "node tests/test-hooks.js",
@@ -23,6 +23,8 @@
23
23
  "test:config": "node tests/test-server-config-manager.js",
24
24
  "test:lifecycle": "node tests/test-lifecycle.js",
25
25
  "test:sync": "node tests/test-sync-stats.js",
26
+ "test:dbquoting": "node tests/test-database-query-quoting.js",
27
+ "test:dbrowcount": "node tests/test-database-row-count.js",
26
28
  "test:all": "npm test && ./scripts/validate.sh",
27
29
  "validate": "./scripts/validate.sh",
28
30
  "lint": "eslint src/*.js",
@@ -87,6 +89,7 @@
87
89
  },
88
90
  "devDependencies": {
89
91
  "eslint": "^8.56.0",
92
+ "knip": "^5.0.0",
90
93
  "prettier": "^3.2.4"
91
94
  },
92
95
  "engines": {
@@ -296,7 +296,6 @@ function buildPostgreSQLRestoreCommand(backupFile, options) {
296
296
  */
297
297
  function buildMongoDBRestoreCommand(backupFile, options) {
298
298
  const {
299
- database,
300
299
  user,
301
300
  password,
302
301
  host = 'localhost',
@@ -439,31 +438,3 @@ export function buildCronScheduleCommand(schedule, backupCommand, cronComment) {
439
438
  const cronLine = `${schedule} ${backupCommand} # ${cronComment}`;
440
439
  return `(crontab -l 2>/dev/null; echo '${cronLine}') | crontab -`;
441
440
  }
442
-
443
- /**
444
- * Parse cron list output
445
- */
446
- export function parseCronJobs(output) {
447
- if (!output || !output.trim()) {
448
- return [];
449
- }
450
-
451
- const jobs = [];
452
- const lines = output.split('\n');
453
-
454
- for (const line of lines) {
455
- if (line.trim() && !line.startsWith('#') && line.includes('ssh-manager-backup')) {
456
- const parts = line.split('#');
457
- const schedule = parts[0].trim();
458
- const comment = parts[1] ? parts[1].trim() : '';
459
-
460
- jobs.push({
461
- schedule,
462
- comment,
463
- command: schedule.split(/\s+/).slice(5).join(' ')
464
- });
465
- }
466
- }
467
-
468
- return jobs;
469
- }
@@ -46,7 +46,7 @@ export function loadCommandAliases() {
46
46
  /**
47
47
  * Save command aliases to file
48
48
  */
49
- export function saveCommandAliases(aliases) {
49
+ function saveCommandAliases(aliases) {
50
50
  try {
51
51
  // Only save custom aliases (not from profile)
52
52
  const customAliases = {};
@@ -381,6 +381,3 @@ export class ConfigLoader {
381
381
  return this.servers.size;
382
382
  }
383
383
  }
384
-
385
- // Export singleton instance
386
- export const configLoader = new ConfigLoader();
package/src/config.js CHANGED
@@ -1,7 +1,7 @@
1
1
  // Configuration constants for MCP SSH Manager
2
2
 
3
3
  // Output limits to prevent Claude Code crashes
4
- export const OUTPUT_LIMITS = {
4
+ const OUTPUT_LIMITS = {
5
5
  // Maximum length of stdout/stderr in responses (characters)
6
6
  MAX_OUTPUT_LENGTH: process.env.MCP_SSH_MAX_OUTPUT_LENGTH
7
7
  ? parseInt(process.env.MCP_SSH_MAX_OUTPUT_LENGTH)
@@ -42,7 +42,7 @@ export const TIMEOUTS = {
42
42
  };
43
43
 
44
44
  // Response formatting
45
- export const RESPONSE_FORMAT = {
45
+ const RESPONSE_FORMAT = {
46
46
  // Whether to use compact JSON (no formatting)
47
47
  COMPACT_JSON: process.env.MCP_SSH_COMPACT_JSON === 'true',
48
48
 
@@ -10,13 +10,6 @@ export const DB_TYPES = {
10
10
  MONGODB: 'mongodb'
11
11
  };
12
12
 
13
- // Default ports
14
- export const DB_PORTS = {
15
- mysql: 3306,
16
- postgresql: 5432,
17
- mongodb: 27017
18
- };
19
-
20
13
  /**
21
14
  * Build MySQL dump command
22
15
  */
@@ -206,7 +199,6 @@ export function buildPostgreSQLImportCommand(options) {
206
199
  */
207
200
  export function buildMongoDBRestoreCommand(options) {
208
201
  const {
209
- database,
210
202
  user,
211
203
  password,
212
204
  host = 'localhost',
@@ -347,6 +339,41 @@ export function buildMongoDBListCollectionsCommand(options) {
347
339
  return command;
348
340
  }
349
341
 
342
+ /**
343
+ * Build a single-quoted shell heredoc that carries `body` to a command's stdin.
344
+ *
345
+ * The delimiter is single-quoted (`<<'DELIM'`) so the remote shell takes the body
346
+ * literally — backticks, `$VAR`, and `$(...)` inside `body` are never expanded by the
347
+ * shell. This is how SQL/JS query text is delivered to mysql/psql/mongo without the
348
+ * shell parsing it first (the cause of issue #44: corruption of backtick-quoted
349
+ * identifiers and remote command injection).
350
+ *
351
+ * When the command pipes its stdout onward (e.g. `mysql ... | awk ...`), the pipe must
352
+ * stay on the heredoc's opening line — the terminator has to be alone on its own line —
353
+ * so the pipeline is passed via `options.pipeline` and emitted as `<<'DELIM' | awk ...`.
354
+ *
355
+ * @param body Text fed to the command's stdin (e.g. a SQL statement). Passed verbatim.
356
+ * @param options.delimiter Heredoc terminator. Must not appear as a standalone line in
357
+ * `body`, otherwise the heredoc would end early; this is rejected defensively.
358
+ * @param options.pipeline Shell pipeline appended after the heredoc marker on the
359
+ * opening line (e.g. `"| awk '...'"`). Omit for a plain stdin redirect.
360
+ * @returns The redirection fragment to append after a command, ending with the
361
+ * terminator on its own line.
362
+ * @throws {Error} If a line of `body` equals `delimiter`.
363
+ * @example
364
+ * `mysql app${buildHeredoc('SELECT 1')}`
365
+ * // mysql app <<'__MCP_SQL_EOF__'\nSELECT 1\n__MCP_SQL_EOF__
366
+ * @see buildMySQLQueryCommand
367
+ */
368
+ export function buildHeredoc(body, { delimiter = '__MCP_SQL_EOF__', pipeline = '' } = {}) {
369
+ const text = body == null ? '' : String(body);
370
+ if (text.split('\n').some(line => line === delimiter)) {
371
+ throw new Error(`Query contains the heredoc delimiter "${delimiter}" on its own line`);
372
+ }
373
+ const suffix = pipeline ? ` ${pipeline}` : '';
374
+ return ` <<'${delimiter}'${suffix}\n${text}\n${delimiter}`;
375
+ }
376
+
350
377
  /**
351
378
  * Build MySQL query command (SELECT only)
352
379
  */
@@ -365,11 +392,16 @@ export function buildMySQLQueryCommand(options) {
365
392
  if (port) command += ` -P ${port}`;
366
393
  command += ` ${database}`;
367
394
 
395
+ // Feed the SQL via stdin (quoted heredoc) so the remote shell never parses it —
396
+ // backtick-quoted identifiers and `$` survive intact, and query text cannot inject
397
+ // shell commands. See buildHeredoc and issue #44.
368
398
  if (format === 'json') {
369
- // Use JSON output if MySQL 5.7.8+
370
- command += ` -e "${query}" --batch --skip-column-names | awk 'BEGIN{print "["} {if(NR>1)print ","; printf "{\\"row\\":%d,\\"data\\":\\"%s\\"}", NR, $0} END{print "]"}'`;
399
+ // Use JSON output if MySQL 5.7.8+. The awk pipe stays on the heredoc opening line so
400
+ // the terminator remains alone on its own line.
401
+ const awk = 'awk \'BEGIN{print "["} {if(NR>1)print ","; printf "{\\"row\\":%d,\\"data\\":\\"%s\\"}", NR, $0} END{print "]"}\'';
402
+ command += ` --batch --skip-column-names${buildHeredoc(query, { pipeline: `| ${awk}` })}`;
371
403
  } else {
372
- command += ` -e "${query}"`;
404
+ command += buildHeredoc(query);
373
405
  }
374
406
 
375
407
  return command;
@@ -395,7 +427,9 @@ export function buildPostgreSQLQueryCommand(options) {
395
427
  if (host) command += ` -h ${host}`;
396
428
  if (port) command += ` -p ${port}`;
397
429
  command += ` -d ${database}`;
398
- command += ` -c "${query}"`;
430
+ // Feed SQL via stdin (quoted heredoc) instead of `-c "${query}"` so the remote shell
431
+ // never parses it. See buildHeredoc and issue #44.
432
+ command += buildHeredoc(query);
399
433
 
400
434
  return command;
401
435
  }
@@ -412,7 +446,11 @@ export function buildMongoDBQueryCommand(options) {
412
446
  if (user) command += ` --username ${user}`;
413
447
  if (password) command += ` --password '${password}'`;
414
448
  command += ` ${database}`;
415
- command += ` --quiet --eval "db.${collection}.find(${query || '{}'}).forEach(printjson)"`;
449
+ // Feed the JS script via stdin (quoted heredoc) instead of `--eval "..."` so the
450
+ // remote shell never expands backticks/`$` in the query. mongo still evaluates the
451
+ // script as JavaScript (expected). See buildHeredoc and issue #44.
452
+ const script = `db.${collection}.find(${query || '{}'}).forEach(printjson)`;
453
+ command += ` --quiet${buildHeredoc(script)}`;
416
454
 
417
455
  return command;
418
456
  }
@@ -443,6 +481,64 @@ export function isSafeQuery(query) {
443
481
  return true;
444
482
  }
445
483
 
484
+ /**
485
+ * Count the actual result rows in the raw output of an `ssh_db_query` command.
486
+ *
487
+ * The handler previously reported `output.split('\n').length`, which counts cosmetic
488
+ * lines (the leading `[` of the MySQL JSON wrapper, psql headers/separators) rather than
489
+ * data rows — so it was off by one for MySQL and over-counted for psql (issue #45). This
490
+ * derives the count from the structure each engine actually produces.
491
+ *
492
+ * @param output Raw, already-trimmed stdout of the query command.
493
+ * @param type One of {@link DB_TYPES} (`'mysql' | 'postgresql' | 'mongodb'`).
494
+ * @param format Output format used to build the command; only `'json'` MySQL is wrapped
495
+ * by the `awk` JSON formatter, which is what this counts. Defaults to `'json'`.
496
+ * @returns The number of result rows (documents for MongoDB). `0` for empty output.
497
+ * @example
498
+ * countQueryRows('[\n{"row":1,"data":"a"},\n{"row":2,"data":"b"}]', 'mysql') // => 2
499
+ * countQueryRows(' id \n----\n 1\n(1 row)', 'postgresql') // => 1
500
+ * @see buildMySQLQueryCommand
501
+ */
502
+ export function countQueryRows(output, type, format = 'json') {
503
+ if (!output || !output.trim()) {
504
+ return 0;
505
+ }
506
+ const lines = output.split('\n');
507
+
508
+ if (type === DB_TYPES.MYSQL) {
509
+ if (format === 'json') {
510
+ // The awk wrapper emits exactly one `{"row":N,...}` entry per result row, anchored
511
+ // at the start of its own line, bracketed by cosmetic `[` / `]` lines.
512
+ return lines.filter(line => /^\{"row":\d+,/.test(line)).length;
513
+ }
514
+ // Tabular `--batch` output: one row per non-empty line (column names are suppressed).
515
+ return lines.filter(line => line.trim() !== '').length;
516
+ }
517
+
518
+ if (type === DB_TYPES.POSTGRESQL) {
519
+ // psql prints an authoritative footer like `(13 rows)` — trust it when present.
520
+ const footer = output.match(/\((\d+)\s+rows?\)/);
521
+ if (footer) {
522
+ return Number(footer[1]);
523
+ }
524
+ // Otherwise fall back to the data lines, dropping the column-header line, the
525
+ // `---+---` separator, and any `(N rows)` footer line.
526
+ const dataLines = lines.filter(line => {
527
+ const trimmed = line.trim();
528
+ return trimmed !== '' && !/^[-+\s]+$/.test(trimmed) && !/^\(\d+\s+rows?\)$/.test(trimmed);
529
+ });
530
+ return Math.max(0, dataLines.length - 1); // first remaining line is the header
531
+ }
532
+
533
+ if (type === DB_TYPES.MONGODB) {
534
+ // `printjson` closes each document with a `}` at column 0 — one per document.
535
+ return lines.filter(line => line === '}').length;
536
+ }
537
+
538
+ // Unknown type: best-effort non-empty line count.
539
+ return lines.filter(line => line.trim() !== '').length;
540
+ }
541
+
446
542
  /**
447
543
  * Parse database list output
448
544
  */
@@ -470,53 +566,6 @@ export function parseTableList(output) {
470
566
  return output.trim().split('\n').filter(l => l.trim());
471
567
  }
472
568
 
473
- /**
474
- * Estimate dump size command
475
- */
476
- export function buildEstimateSizeCommand(type, database, options = {}) {
477
- const { user, password, host = 'localhost', port } = options;
478
-
479
- switch (type) {
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
- }
489
-
490
- case DB_TYPES.POSTGRESQL: {
491
- let command = '';
492
- if (password) {
493
- command = `PGPASSWORD='${password}' `;
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
- }
503
-
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
- }
514
-
515
- default:
516
- throw new Error(`Unknown database type: ${type}`);
517
- }
518
- }
519
-
520
569
  /**
521
570
  * Parse size output to bytes
522
571
  */
@@ -535,19 +584,3 @@ export function formatBytes(bytes) {
535
584
  const i = Math.floor(Math.log(bytes) / Math.log(k));
536
585
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
537
586
  }
538
-
539
- /**
540
- * Get database connection info
541
- */
542
- export function getConnectionInfo(type, options) {
543
- const { host = 'localhost', port, user, database } = options;
544
- const defaultPort = DB_PORTS[type];
545
-
546
- return {
547
- type,
548
- host,
549
- port: port || defaultPort,
550
- user: user || 'default',
551
- database: database || 'all'
552
- };
553
- }
@@ -144,32 +144,3 @@ export function detectDeploymentNeeds(remotePath) {
144
144
 
145
145
  return needs;
146
146
  }
147
-
148
- /**
149
- * Create batch deployment script for multiple files
150
- */
151
- export function createBatchDeployScript(deployments) {
152
- const script = ['#!/bin/bash', 'set -e', ''];
153
-
154
- script.push('# Batch deployment script');
155
- script.push(`# Generated at ${new Date().toISOString()}`);
156
- script.push('');
157
-
158
- deployments.forEach((deploy, index) => {
159
- script.push(`# File ${index + 1}: ${deploy.localPath} -> ${deploy.remotePath}`);
160
- deploy.strategy.steps.forEach(step => {
161
- if (step.type !== 'cleanup') {
162
- script.push(step.command.replace('{{tempFile}}', deploy.tempFile));
163
- }
164
- });
165
- script.push('');
166
- });
167
-
168
- // Cleanup all temp files at the end
169
- script.push('# Cleanup temporary files');
170
- deployments.forEach(deploy => {
171
- script.push(`rm -f ${deploy.tempFile}`);
172
- });
173
-
174
- return script.join('\n');
175
- }
@@ -14,7 +14,7 @@ export const HEALTH_STATUS = {
14
14
  };
15
15
 
16
16
  // Common services to monitor
17
- export const COMMON_SERVICES = {
17
+ const COMMON_SERVICES = {
18
18
  nginx: { systemd: 'nginx', sysv: 'nginx' },
19
19
  apache: { systemd: 'apache2', sysv: 'apache2' },
20
20
  mysql: { systemd: 'mysql', sysv: 'mysql' },
@@ -28,7 +28,7 @@ export const COMMON_SERVICES = {
28
28
  /**
29
29
  * Build command to check CPU usage
30
30
  */
31
- export function buildCPUCheckCommand() {
31
+ function buildCPUCheckCommand() {
32
32
  // Get CPU usage using top, show idle percentage, calculate used
33
33
  return 'top -bn1 | grep "Cpu(s)" | sed "s/.*, *\\([0-9.]*\\)%* id.*/\\1/" | awk \'{print 100 - $1}\'';
34
34
  }
@@ -36,7 +36,7 @@ export function buildCPUCheckCommand() {
36
36
  /**
37
37
  * Build command to check memory usage
38
38
  */
39
- export function buildMemoryCheckCommand() {
39
+ function buildMemoryCheckCommand() {
40
40
  // Returns: total, used, free, available in MB and percentage
41
41
  return 'free -m | awk \'NR==2{printf "{\\"total\\":%s,\\"used\\":%s,\\"free\\":%s,\\"percent\\":%.2f}", $2,$3,$4,$3*100/$2}\'';
42
42
  }
@@ -44,7 +44,7 @@ export function buildMemoryCheckCommand() {
44
44
  /**
45
45
  * Build command to check disk usage
46
46
  */
47
- export function buildDiskCheckCommand(mountPoint = '/') {
47
+ function buildDiskCheckCommand(mountPoint = '/') {
48
48
  // Returns JSON with disk usage for specific mount point or all
49
49
  if (mountPoint === 'all') {
50
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}\'';
@@ -55,7 +55,7 @@ export function buildDiskCheckCommand(mountPoint = '/') {
55
55
  /**
56
56
  * Build command to check network statistics
57
57
  */
58
- export function buildNetworkCheckCommand() {
58
+ function buildNetworkCheckCommand() {
59
59
  // Get basic network stats (RX/TX bytes)
60
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
  }
@@ -63,21 +63,21 @@ export function buildNetworkCheckCommand() {
63
63
  /**
64
64
  * Build command to check load average
65
65
  */
66
- export function buildLoadAverageCommand() {
66
+ function buildLoadAverageCommand() {
67
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
- export function buildUptimeCommand() {
73
+ function buildUptimeCommand() {
74
74
  return 'uptime -p 2>/dev/null || uptime | awk \'{print $3,$4}\' | sed \'s/,//\'';
75
75
  }
76
76
 
77
77
  /**
78
78
  * Parse CPU usage output
79
79
  */
80
- export function parseCPUUsage(output) {
80
+ function parseCPUUsage(output) {
81
81
  const usage = parseFloat(output.trim());
82
82
  return {
83
83
  usage: usage.toFixed(2),
@@ -89,7 +89,7 @@ export function parseCPUUsage(output) {
89
89
  /**
90
90
  * Parse memory usage output
91
91
  */
92
- export function parseMemoryUsage(output) {
92
+ function parseMemoryUsage(output) {
93
93
  try {
94
94
  const mem = JSON.parse(output.trim());
95
95
  return {
@@ -108,7 +108,7 @@ export function parseMemoryUsage(output) {
108
108
  /**
109
109
  * Parse disk usage output
110
110
  */
111
- export function parseDiskUsage(output) {
111
+ function parseDiskUsage(output) {
112
112
  const lines = output.trim().split('\n').filter(l => l);
113
113
  const disks = [];
114
114
 
@@ -128,7 +128,7 @@ export function parseDiskUsage(output) {
128
128
  /**
129
129
  * Parse network statistics
130
130
  */
131
- export function parseNetworkStats(output) {
131
+ function parseNetworkStats(output) {
132
132
  const lines = output.trim().split('\n').filter(l => l);
133
133
  const interfaces = [];
134
134
 
@@ -150,7 +150,7 @@ export function parseNetworkStats(output) {
150
150
  /**
151
151
  * Determine overall health status
152
152
  */
153
- export function determineOverallHealth(cpu, memory, disks) {
153
+ function determineOverallHealth(cpu, memory, disks) {
154
154
  const statuses = [cpu.status, memory.status, ...disks.map(d => d.status)];
155
155
 
156
156
  if (statuses.includes(HEALTH_STATUS.CRITICAL)) {
@@ -412,13 +412,6 @@ export function parseComprehensiveHealthCheck(output) {
412
412
  return result;
413
413
  }
414
414
 
415
- /**
416
- * Get common service names for detection
417
- */
418
- export function getCommonServices() {
419
- return Object.keys(COMMON_SERVICES);
420
- }
421
-
422
415
  /**
423
416
  * Resolve service name (handle both systemd and sysv names)
424
417
  */
@@ -123,7 +123,7 @@ export function loadHooksConfig() {
123
123
  /**
124
124
  * Save hooks configuration
125
125
  */
126
- export function saveHooksConfig(config) {
126
+ function saveHooksConfig(config) {
127
127
  try {
128
128
  fs.writeFileSync(HOOKS_CONFIG_FILE, JSON.stringify(config, null, 2));
129
129
  return true;
@@ -310,18 +310,3 @@ export function listHooks() {
310
310
  actionCount: hook.actions ? hook.actions.length : 0
311
311
  }));
312
312
  }
313
-
314
- /**
315
- * Create a custom hook script
316
- */
317
- export async function createHookScript(scriptName, scriptContent) {
318
- const scriptPath = path.join(HOOKS_DIR, scriptName);
319
-
320
- try {
321
- fs.writeFileSync(scriptPath, scriptContent);
322
- fs.chmodSync(scriptPath, '755');
323
- return scriptPath;
324
- } catch (error) {
325
- throw new Error(`Failed to create hook script: ${error.message}`);
326
- }
327
- }
package/src/index.js CHANGED
@@ -29,7 +29,6 @@ import {
29
29
  suggestAliases
30
30
  } from './command-aliases.js';
31
31
  import {
32
- OUTPUT_LIMITS,
33
32
  TIMEOUTS,
34
33
  truncateOutput,
35
34
  formatJSONResponse
@@ -52,27 +51,22 @@ import {
52
51
  createSession,
53
52
  getSession,
54
53
  listSessions,
55
- closeSession,
56
- SESSION_STATES
54
+ closeSession
57
55
  } from './session-manager.js';
58
56
  import {
59
- getGroup,
60
57
  createGroup,
61
58
  updateGroup,
62
59
  deleteGroup,
63
60
  addServersToGroup,
64
61
  removeServersFromGroup,
65
62
  listGroups,
66
- executeOnGroup,
67
- EXECUTION_STRATEGIES
63
+ executeOnGroup
68
64
  } from './server-groups.js';
69
65
  import {
70
66
  createTunnel,
71
- getTunnel,
72
67
  listTunnels,
73
68
  closeTunnel,
74
- closeServerTunnels,
75
- TUNNEL_TYPES
69
+ closeServerTunnels
76
70
  } from './tunnel-manager.js';
77
71
  import {
78
72
  getHostKeyFingerprint,
@@ -102,23 +96,10 @@ import {
102
96
  buildListBackupsCommand,
103
97
  parseBackupsList,
104
98
  buildCleanupCommand,
105
- buildCronScheduleCommand,
106
- parseCronJobs
99
+ buildCronScheduleCommand
107
100
  } from './backup-manager.js';
108
101
  import {
109
102
  HEALTH_STATUS,
110
- COMMON_SERVICES,
111
- buildCPUCheckCommand,
112
- buildMemoryCheckCommand,
113
- buildDiskCheckCommand,
114
- buildNetworkCheckCommand,
115
- buildLoadAverageCommand,
116
- buildUptimeCommand,
117
- parseCPUUsage,
118
- parseMemoryUsage,
119
- parseDiskUsage,
120
- parseNetworkStats,
121
- determineOverallHealth,
122
103
  buildServiceStatusCommand,
123
104
  parseServiceStatus,
124
105
  buildProcessListCommand,
@@ -131,12 +112,10 @@ import {
131
112
  checkAlertThresholds,
132
113
  buildComprehensiveHealthCheckCommand,
133
114
  parseComprehensiveHealthCheck,
134
- getCommonServices,
135
115
  resolveServiceName
136
116
  } from './health-monitor.js';
137
117
  import {
138
118
  DB_TYPES,
139
- DB_PORTS,
140
119
  buildMySQLDumpCommand as buildDBMySQLDumpCommand,
141
120
  buildPostgreSQLDumpCommand as buildDBPostgreSQLDumpCommand,
142
121
  buildMongoDBDumpCommand as buildDBMongoDBDumpCommand,
@@ -153,12 +132,11 @@ import {
153
132
  buildPostgreSQLQueryCommand,
154
133
  buildMongoDBQueryCommand,
155
134
  isSafeQuery,
135
+ countQueryRows,
156
136
  parseDatabaseList,
157
137
  parseTableList,
158
- buildEstimateSizeCommand,
159
138
  parseSize,
160
- formatBytes,
161
- getConnectionInfo
139
+ formatBytes
162
140
  } from './database-manager.js';
163
141
  import { loadToolConfig, isToolEnabled } from './tool-config-manager.js';
164
142
  import { evaluatePolicy } from './policy.js';
@@ -329,7 +307,7 @@ async function execCommandWithTimeout(ssh, command, options = {}, timeoutMs = 30
329
307
  // pipes, etc. Base64 sidesteps all escape issues entirely.
330
308
  if (platform === 'windows' && !rawCommand) {
331
309
  // Suppress progress (avoids CLIXML sentinels in stderr) + force UTF-8 stdout
332
- const prelude = `$ProgressPreference='SilentlyContinue'; [Console]::OutputEncoding=[System.Text.Encoding]::UTF8;`;
310
+ const prelude = '$ProgressPreference=\'SilentlyContinue\'; [Console]::OutputEncoding=[System.Text.Encoding]::UTF8;';
333
311
  const fullPSCommand = `${prelude} ${command}`;
334
312
  const utf16le = Buffer.from(fullPSCommand, 'utf16le');
335
313
  const b64 = utf16le.toString('base64');
@@ -704,7 +682,7 @@ registerToolConditional(
704
682
  let fullCommand;
705
683
  if (workingDir) {
706
684
  if (platform === 'windows') {
707
- const escapedDir = workingDir.replace(/'/g, "''");
685
+ const escapedDir = workingDir.replace(/'/g, '\'\'');
708
686
  fullCommand = `Set-Location '${escapedDir}'; ${expandedCommand}`;
709
687
  } else {
710
688
  fullCommand = `cd ${workingDir} && ${expandedCommand}`;
@@ -915,7 +893,7 @@ registerToolConditional(
915
893
  if (denied) return denied;
916
894
 
917
895
  try {
918
- const ssh = await getConnection(serverName);
896
+ await getConnection(serverName);
919
897
  const servers = await loadServerConfig();
920
898
  const serverConfig = servers[serverName.toLowerCase()];
921
899
 
@@ -1266,7 +1244,7 @@ registerToolConditional(
1266
1244
  const sessionId = `tail_${Date.now()}`;
1267
1245
 
1268
1246
  // Store the SSH stream for later cleanup
1269
- const stream = await ssh.execCommandStream(command, {
1247
+ await ssh.execCommandStream(command, {
1270
1248
  onStdout: (chunk) => {
1271
1249
  // In a real implementation, this would stream to the client
1272
1250
  console.error(`[${serverName}:${file}] ${chunk}`);
@@ -1921,7 +1899,7 @@ registerToolConditional(
1921
1899
  if (workingDir) {
1922
1900
  if (platform === 'windows') {
1923
1901
  // Single-quote escaping: replace ' with '' (PowerShell convention)
1924
- const escapedDir = workingDir.replace(/'/g, "''");
1902
+ const escapedDir = workingDir.replace(/'/g, '\'\'');
1925
1903
  fullCommand = `Set-Location '${escapedDir}'; ${command}`;
1926
1904
  } else {
1927
1905
  fullCommand = `cd ${workingDir} && ${command}`;
@@ -2325,14 +2303,14 @@ registerToolConditional(
2325
2303
  const platform = serverConfig?.platform || 'linux';
2326
2304
  if (cwd) {
2327
2305
  if (platform === 'windows') {
2328
- const escapedDir = cwd.replace(/'/g, "''");
2306
+ const escapedDir = cwd.replace(/'/g, '\'\'');
2329
2307
  fullCommand = `Set-Location '${escapedDir}'; ${fullCommand}`;
2330
2308
  } else {
2331
2309
  fullCommand = `cd ${cwd} && ${fullCommand}`;
2332
2310
  }
2333
2311
  } else if (serverConfig?.default_dir) {
2334
2312
  if (platform === 'windows') {
2335
- const escapedDir = serverConfig.default_dir.replace(/'/g, "''");
2313
+ const escapedDir = serverConfig.default_dir.replace(/'/g, '\'\'');
2336
2314
  fullCommand = `Set-Location '${escapedDir}'; ${fullCommand}`;
2337
2315
  } else {
2338
2316
  fullCommand = `cd ${serverConfig.default_dir} && ${fullCommand}`;
@@ -4806,12 +4784,14 @@ registerToolConditional(
4806
4784
 
4807
4785
  // Parse output (basic parsing, output depends on database type)
4808
4786
  const output = result.stdout.trim();
4809
- const lines = output.split('\n');
4787
+ // Derive the real row count from each engine's output structure rather than the
4788
+ // raw line count, which counts cosmetic wrapper/header lines (issue #45).
4789
+ const rowCount = countQueryRows(output, type);
4810
4790
 
4811
4791
  logger.info('Query executed successfully', {
4812
4792
  server: serverName,
4813
4793
  database,
4814
- rows: lines.length
4794
+ rows: rowCount
4815
4795
  });
4816
4796
 
4817
4797
  return {
@@ -4825,7 +4805,7 @@ registerToolConditional(
4825
4805
  database,
4826
4806
  collection: collection || null,
4827
4807
  query,
4828
- row_count: lines.length,
4808
+ row_count: rowCount,
4829
4809
  output: output,
4830
4810
  timestamp: new Date().toISOString()
4831
4811
  }, null, 2)
package/src/logger.js CHANGED
@@ -270,7 +270,3 @@ class Logger {
270
270
 
271
271
  // Export singleton instance
272
272
  export const logger = new Logger();
273
-
274
- // Export for convenience
275
- export const { debug, info, warn, error } = logger;
276
- export default logger;
package/src/policy.js CHANGED
@@ -56,7 +56,7 @@ export const COMMAND_BEARING_TOOLS = new Set([
56
56
  //
57
57
  // The user can layer their own DENY_PATTERNS on top via restricted mode for
58
58
  // finer control.
59
- export const READONLY_DENY_REGEX = [
59
+ const READONLY_DENY_REGEX = [
60
60
  /(^|[\s;&|])rm(\s|$)/,
61
61
  /(^|[\s;&|])rmdir(\s|$)/,
62
62
  /(^|[\s;&|])mv(\s|$)/,
@@ -139,49 +139,3 @@ export function setActiveProfile(profileName) {
139
139
  return false;
140
140
  }
141
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
- }
@@ -15,7 +15,7 @@ const ALIASES_FILE = path.join(__dirname, '..', '.server-aliases.json');
15
15
  /**
16
16
  * Load server aliases from configuration file
17
17
  */
18
- export function loadAliases() {
18
+ function loadAliases() {
19
19
  try {
20
20
  if (fs.existsSync(ALIASES_FILE)) {
21
21
  const content = fs.readFileSync(ALIASES_FILE, 'utf8');
@@ -30,7 +30,7 @@ export function loadAliases() {
30
30
  /**
31
31
  * Save server aliases to configuration file
32
32
  */
33
- export function saveAliases(aliases) {
33
+ function saveAliases(aliases) {
34
34
  try {
35
35
  fs.writeFileSync(ALIASES_FILE, JSON.stringify(aliases, null, 2));
36
36
  return true;
@@ -88,38 +88,6 @@ export function resolveServerName(nameOrAlias, servers) {
88
88
  return null;
89
89
  }
90
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
91
  /**
124
92
  * Add or update an alias
125
93
  */
@@ -15,7 +15,7 @@ const __dirname = path.dirname(__filename);
15
15
  const GROUPS_FILE = path.join(__dirname, '..', '.server-groups.json');
16
16
 
17
17
  // Group execution strategies
18
- export const EXECUTION_STRATEGIES = {
18
+ const EXECUTION_STRATEGIES = {
19
19
  PARALLEL: 'parallel', // Execute on all servers at once
20
20
  SEQUENTIAL: 'sequential', // Execute one by one
21
21
  ROLLING: 'rolling' // Execute with delay between servers
@@ -115,7 +115,7 @@ class ServerGroups {
115
115
  // This will be populated from the main server config
116
116
  const servers = [];
117
117
 
118
- for (const [key, value] of Object.entries(process.env)) {
118
+ for (const key of Object.keys(process.env)) {
119
119
  if (key.startsWith('SSH_SERVER_') && key.endsWith('_HOST')) {
120
120
  const serverName = key.replace('SSH_SERVER_', '').replace('_HOST', '').toLowerCase();
121
121
  servers.push(serverName);
@@ -395,10 +395,9 @@ class ServerGroups {
395
395
  }
396
396
 
397
397
  // Export singleton instance
398
- export const serverGroups = new ServerGroups();
398
+ const serverGroups = new ServerGroups();
399
399
 
400
400
  // Export convenience functions
401
- export const getGroup = (name) => serverGroups.getGroup(name);
402
401
  export const createGroup = (name, servers, options) => serverGroups.createGroup(name, servers, options);
403
402
  export const updateGroup = (name, updates) => serverGroups.updateGroup(name, updates);
404
403
  export const deleteGroup = (name) => serverGroups.deleteGroup(name);
@@ -406,5 +405,3 @@ export const addServersToGroup = (name, servers) => serverGroups.addServers(name
406
405
  export const removeServersFromGroup = (name, servers) => serverGroups.removeServers(name, servers);
407
406
  export const listGroups = () => serverGroups.listGroups();
408
407
  export const executeOnGroup = (name, executor, options) => serverGroups.executeOnGroup(name, executor, options);
409
-
410
- export default serverGroups;
@@ -14,7 +14,7 @@ function generateMarker(prefix) {
14
14
  }
15
15
 
16
16
  // Session states
17
- export const SESSION_STATES = {
17
+ const SESSION_STATES = {
18
18
  INITIALIZING: 'initializing',
19
19
  READY: 'ready',
20
20
  BUSY: 'busy',
@@ -332,7 +332,7 @@ export function getSession(sessionId) {
332
332
  export function listSessions() {
333
333
  const activeSessions = [];
334
334
 
335
- for (const [id, session] of sessions.entries()) {
335
+ for (const [, session] of sessions.entries()) {
336
336
  if (session.state !== SESSION_STATES.CLOSED) {
337
337
  activeSessions.push(session.getInfo());
338
338
  }
@@ -355,26 +355,10 @@ export function closeSession(sessionId) {
355
355
  return true;
356
356
  }
357
357
 
358
- /**
359
- * Close all sessions for a server
360
- */
361
- export function closeServerSessions(serverName) {
362
- let closedCount = 0;
363
-
364
- for (const [id, session] of sessions.entries()) {
365
- if (session.serverName === serverName) {
366
- session.close();
367
- closedCount++;
368
- }
369
- }
370
-
371
- return closedCount;
372
- }
373
-
374
358
  /**
375
359
  * Cleanup old sessions
376
360
  */
377
- export function cleanupSessions(maxAge = 30 * 60 * 1000) { // 30 minutes default
361
+ function cleanupSessions(maxAge = 30 * 60 * 1000) { // 30 minutes default
378
362
  const now = Date.now();
379
363
  let cleanedCount = 0;
380
364
 
@@ -403,13 +387,3 @@ const sessionCleanup = setInterval(() => {
403
387
  }
404
388
  }, 5 * 60 * 1000); // Every 5 minutes
405
389
  if (typeof sessionCleanup.unref === 'function') sessionCleanup.unref();
406
-
407
- export default {
408
- createSession,
409
- getSession,
410
- listSessions,
411
- closeSession,
412
- closeServerSessions,
413
- cleanupSessions,
414
- SESSION_STATES
415
- };
@@ -345,35 +345,3 @@ export function extractHostFromSSHError(stderr) {
345
345
 
346
346
  return null;
347
347
  }
348
-
349
- /**
350
- * Handle SSH key error automatically
351
- */
352
- export async function handleSSHKeyError(stderr, options = {}) {
353
- const { autoAccept = false, interactive = true } = options;
354
-
355
- const hostInfo = extractHostFromSSHError(stderr);
356
- if (!hostInfo) {
357
- throw new Error('Could not extract host information from SSH error');
358
- }
359
-
360
- logger.warn('SSH host key verification failed', hostInfo);
361
-
362
- if (autoAccept) {
363
- // Automatically update the key
364
- await updateHostKey(hostInfo.host, hostInfo.port);
365
- return { action: 'updated', ...hostInfo };
366
- }
367
-
368
- if (!interactive) {
369
- throw new Error(`Host key verification failed for ${hostInfo.host}:${hostInfo.port}. Use ssh_key_manage tool to update the key.`);
370
- }
371
-
372
- // In interactive mode, we would prompt the user
373
- // For now, just return the error info
374
- return {
375
- action: 'prompt_required',
376
- ...hostInfo,
377
- message: `Host key has changed for ${hostInfo.host}:${hostInfo.port}. Use ssh_key_manage tool to verify and update the key.`
378
- };
379
- }
@@ -1,10 +1,7 @@
1
1
  import { Client } from 'ssh2';
2
2
  import fs from 'fs';
3
3
  import os from 'os';
4
- import { promisify } from 'util';
5
- import crypto from 'crypto';
6
- import { isHostKnown, getCurrentHostKey, addHostKey, updateHostKey } from './ssh-key-manager.js';
7
- import { configLoader } from './config-loader.js';
4
+ import { isHostKnown, addHostKey } from './ssh-key-manager.js';
8
5
  import { logger } from './logger.js';
9
6
 
10
7
  // Validate liveness-probe output across shells (bash, cmd.exe, PowerShell).
@@ -111,7 +108,7 @@ class SSHManager {
111
108
 
112
109
  // Add host key verification callback if enabled
113
110
  if (this.hostKeyVerification) {
114
- connConfig.hostVerifier = (hashedKey) => {
111
+ connConfig.hostVerifier = () => {
115
112
  const port = this.config.port || 22;
116
113
  const host = this.config.host;
117
114
 
@@ -480,7 +477,7 @@ class SSHManager {
480
477
  }
481
478
 
482
479
  async putFiles(files, options = {}) {
483
- const sftp = await this.getSFTP();
480
+ await this.getSFTP();
484
481
  const results = [];
485
482
 
486
483
  for (const file of files) {
@@ -21,7 +21,7 @@ const CONFIG_FILE = path.join(CONFIG_DIR, 'tools-config.json');
21
21
  /**
22
22
  * Tool Configuration Manager Class
23
23
  */
24
- export class ToolConfigManager {
24
+ class ToolConfigManager {
25
25
  constructor() {
26
26
  this.config = null;
27
27
  this.configPath = CONFIG_FILE;
@@ -424,11 +424,3 @@ export function isToolEnabled(toolName) {
424
424
  }
425
425
  return toolConfigInstance.isToolEnabled(toolName);
426
426
  }
427
-
428
- /**
429
- * Get the tool configuration manager instance
430
- * @returns {ToolConfigManager|null} Configuration manager or null if not loaded
431
- */
432
- export function getToolConfigManager() {
433
- return toolConfigInstance;
434
- }
@@ -11,14 +11,14 @@ import { logger } from './logger.js';
11
11
  const tunnels = new Map();
12
12
 
13
13
  // Tunnel types
14
- export const TUNNEL_TYPES = {
14
+ const TUNNEL_TYPES = {
15
15
  LOCAL: 'local', // Local port forwarding (access remote service locally)
16
16
  REMOTE: 'remote', // Remote port forwarding (expose local service remotely)
17
17
  DYNAMIC: 'dynamic' // SOCKS proxy
18
18
  };
19
19
 
20
20
  // Tunnel states
21
- export const TUNNEL_STATES = {
21
+ const TUNNEL_STATES = {
22
22
  CONNECTING: 'connecting',
23
23
  ACTIVE: 'active',
24
24
  RECONNECTING: 'reconnecting',
@@ -182,7 +182,7 @@ class SSHTunnel {
182
182
  });
183
183
 
184
184
  // Handle incoming connections from remote
185
- this.ssh.on('tcp connection', (info, accept, reject) => {
185
+ this.ssh.on('tcp connection', (info, accept) => {
186
186
  if (info.destPort !== remotePort) return;
187
187
 
188
188
  this.stats.connectionsTotal++;
@@ -478,26 +478,13 @@ export async function createTunnel(serverName, ssh, config) {
478
478
  }
479
479
  }
480
480
 
481
- /**
482
- * Get an existing tunnel
483
- */
484
- export function getTunnel(tunnelId) {
485
- const tunnel = tunnels.get(tunnelId);
486
-
487
- if (!tunnel) {
488
- throw new Error(`Tunnel ${tunnelId} not found`);
489
- }
490
-
491
- return tunnel;
492
- }
493
-
494
481
  /**
495
482
  * List all active tunnels
496
483
  */
497
484
  export function listTunnels(serverName = null) {
498
485
  const activeTunnels = [];
499
486
 
500
- for (const [id, tunnel] of tunnels.entries()) {
487
+ for (const [, tunnel] of tunnels.entries()) {
501
488
  if (tunnel.state !== TUNNEL_STATES.CLOSED) {
502
489
  if (!serverName || tunnel.serverName === serverName) {
503
490
  activeTunnels.push(tunnel.getInfo());
@@ -528,7 +515,7 @@ export function closeTunnel(tunnelId) {
528
515
  export function closeServerTunnels(serverName) {
529
516
  let closedCount = 0;
530
517
 
531
- for (const [id, tunnel] of tunnels.entries()) {
518
+ for (const [, tunnel] of tunnels.entries()) {
532
519
  if (tunnel.serverName === serverName) {
533
520
  tunnel.close();
534
521
  closedCount++;
@@ -541,7 +528,7 @@ export function closeServerTunnels(serverName) {
541
528
  /**
542
529
  * Monitor tunnel health
543
530
  */
544
- export function monitorTunnels() {
531
+ function monitorTunnels() {
545
532
  const now = Date.now();
546
533
  const healthTimeout = 60 * 1000; // 1 minute
547
534
 
@@ -568,13 +555,3 @@ export function monitorTunnels() {
568
555
  // a background timer.
569
556
  const tunnelMonitor = setInterval(monitorTunnels, 30 * 1000); // Every 30 seconds
570
557
  if (typeof tunnelMonitor.unref === 'function') tunnelMonitor.unref();
571
-
572
- export default {
573
- createTunnel,
574
- getTunnel,
575
- listTunnels,
576
- closeTunnel,
577
- closeServerTunnels,
578
- TUNNEL_TYPES,
579
- TUNNEL_STATES
580
- };