@akms/mcp-ssh 0.0.3 → 0.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.
package/lib/cli.cjs CHANGED
@@ -2,10 +2,12 @@
2
2
  'use strict';
3
3
 
4
4
  var stdio_js = require('@modelcontextprotocol/sdk/server/stdio.js');
5
- var os = require('os');
6
- var path2 = require('path');
5
+ var fs7 = require('fs');
6
+ var os4 = require('os');
7
+ var path = require('path');
8
+ var child_process = require('child_process');
7
9
  var crypto = require('crypto');
8
- var fs = require('fs');
10
+ var stream = require('stream');
9
11
  var string_decoder = require('string_decoder');
10
12
  var ssh2 = require('ssh2');
11
13
  var timers = require('timers');
@@ -14,9 +16,9 @@ var zod = require('zod');
14
16
 
15
17
  function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
16
18
 
17
- var os__default = /*#__PURE__*/_interopDefault(os);
18
- var path2__default = /*#__PURE__*/_interopDefault(path2);
19
- var fs__default = /*#__PURE__*/_interopDefault(fs);
19
+ var fs7__default = /*#__PURE__*/_interopDefault(fs7);
20
+ var os4__default = /*#__PURE__*/_interopDefault(os4);
21
+ var path__default = /*#__PURE__*/_interopDefault(path);
20
22
  var ssh2__default = /*#__PURE__*/_interopDefault(ssh2);
21
23
 
22
24
  // src/_defs/defaults.ts
@@ -32,7 +34,8 @@ var SESSION_SWEEP_INTERVAL_MS = 6e4;
32
34
  var CWD_MARKER = "__AKMS_SSH_CWD__";
33
35
  var MAX_DIRECTORY_ENTRIES = 1e3;
34
36
  var SERVER_NAME = "akms-mcp-ssh";
35
- var SERVER_VERSION = "0.0.3";
37
+ var PACKAGE_NAME = "@akms/mcp-ssh";
38
+ var SERVER_VERSION = "0.1.0";
36
39
 
37
40
  // src/_defs/command-rules.ts
38
41
  var CRITICAL_PATH_PATTERN = new RegExp(
@@ -454,6 +457,22 @@ var SINGLE_HOST_ENV = {
454
457
  DESCRIPTION: "SSH_DESCRIPTION",
455
458
  /** Directory new sessions start in. */
456
459
  CWD: "SSH_CWD",
460
+ /**
461
+ * Command whose stdin/stdout carry the SSH stream, like OpenSSH's `ProxyCommand`.
462
+ * `%h` / `%p` / `%r` expand to the first hop's host, port and user.
463
+ */
464
+ PROXY_COMMAND: "SSH_PROXY_COMMAND",
465
+ /** Presence of this variable routes the connection through a jump host. */
466
+ JUMP_HOST: "SSH_JUMP_HOST",
467
+ JUMP_PORT: "SSH_JUMP_PORT",
468
+ /** Defaults to `SSH_USER`. */
469
+ JUMP_USER: "SSH_JUMP_USER",
470
+ /** Path to the jump host's private key file; defaults to `SSH_KEY`. */
471
+ JUMP_KEY: "SSH_JUMP_KEY",
472
+ JUMP_PASSPHRASE: "SSH_JUMP_PASSPHRASE",
473
+ JUMP_PASSWORD: "SSH_JUMP_PASSWORD",
474
+ /** Pinned jump host key, `SHA256:…`. */
475
+ JUMP_HOST_KEY: "SSH_JUMP_HOST_KEY",
457
476
  READONLY: "SSH_READONLY",
458
477
  ALLOW_SUDO: "SSH_ALLOW_SUDO",
459
478
  /** Comma-separated binary names. */
@@ -580,20 +599,38 @@ function formatBytes(bytes) {
580
599
  const megabytes = bytes / (1024 * 1024);
581
600
  return `${megabytes.toFixed(1)} MB`;
582
601
  }
602
+ function findExecutable(name) {
603
+ const searchPath = process.env.PATH ?? "";
604
+ const directories = searchPath.split(path__default.default.delimiter).filter((directory) => directory !== "");
605
+ let suffixes = [""];
606
+ if (process.platform === "win32") {
607
+ const pathExt = process.env.PATHEXT ?? ".COM;.EXE;.BAT;.CMD";
608
+ suffixes = pathExt.split(";").filter((suffix) => suffix !== "");
609
+ }
610
+ for (const directory of directories) {
611
+ for (const suffix of suffixes) {
612
+ const candidate = path__default.default.join(directory, `${name}${suffix}`);
613
+ if (fs7__default.default.existsSync(candidate) == true && fs7__default.default.statSync(candidate).isFile() == true) {
614
+ return candidate;
615
+ }
616
+ }
617
+ }
618
+ return null;
619
+ }
583
620
  function expandHomePath(inputPath) {
584
621
  let expanded = inputPath;
585
622
  if (inputPath === "~") {
586
- expanded = os__default.default.homedir();
623
+ expanded = os4__default.default.homedir();
587
624
  } else if (inputPath.startsWith("~/") == true || inputPath.startsWith("~\\") == true) {
588
- expanded = path2__default.default.join(os__default.default.homedir(), inputPath.slice(2));
625
+ expanded = path__default.default.join(os4__default.default.homedir(), inputPath.slice(2));
589
626
  }
590
- return path2__default.default.resolve(expanded);
627
+ return path__default.default.resolve(expanded);
591
628
  }
592
629
  function isAbsoluteRemotePath(remotePath) {
593
630
  return remotePath.startsWith("/");
594
631
  }
595
632
  function normalizeRemotePath(remotePath) {
596
- return path2__default.default.posix.normalize(remotePath);
633
+ return path__default.default.posix.normalize(remotePath);
597
634
  }
598
635
  function isRemotePathWithin(candidate, allowedPrefix) {
599
636
  const normalizedCandidate = normalizeRemotePath(candidate);
@@ -606,6 +643,195 @@ function isRemotePathWithin(candidate, allowedPrefix) {
606
643
  }
607
644
  return normalizedCandidate.startsWith(`${normalizedPrefix}/`);
608
645
  }
646
+ function readEnv(env, name) {
647
+ const value = env[name];
648
+ if (value == null) {
649
+ return void 0;
650
+ }
651
+ const trimmed = value.trim();
652
+ if (trimmed === "") {
653
+ return void 0;
654
+ }
655
+ return trimmed;
656
+ }
657
+ function readBooleanEnv(env, name) {
658
+ const value = readEnv(env, name);
659
+ if (value == null) {
660
+ return void 0;
661
+ }
662
+ const normalized = value.toLowerCase();
663
+ if (TRUTHY_ENV_VALUES.includes(normalized) == true) {
664
+ return true;
665
+ }
666
+ if (FALSY_ENV_VALUES.includes(normalized) == false) {
667
+ throw new Error(`${name} must be one of ${[...TRUTHY_ENV_VALUES, ...FALSY_ENV_VALUES].join(", ")} (got "${value}")`);
668
+ }
669
+ return false;
670
+ }
671
+ function readIntegerEnv(env, name) {
672
+ const value = readEnv(env, name);
673
+ if (value == null) {
674
+ return void 0;
675
+ }
676
+ const parsed = Number(value);
677
+ if (Number.isInteger(parsed) == false || parsed <= 0) {
678
+ throw new Error(`${name} must be a positive integer (got "${value}")`);
679
+ }
680
+ return parsed;
681
+ }
682
+ function readListEnv(env, name) {
683
+ const value = readEnv(env, name);
684
+ if (value == null) {
685
+ return void 0;
686
+ }
687
+ const items = value.split(",").map((item) => item.trim()).filter((item) => item !== "");
688
+ if (items.length === 0) {
689
+ return void 0;
690
+ }
691
+ return items;
692
+ }
693
+ function compileDenyPatterns(sources) {
694
+ return sources.map((source) => {
695
+ try {
696
+ return new RegExp(source, "i");
697
+ } catch (ex) {
698
+ const _logger = $logger.child({ context: "compileDenyPatterns" });
699
+ _logger.error(ex, "denyPatterns entry is not a valid regular expression");
700
+ let detail = String(ex);
701
+ if (ex instanceof Error) {
702
+ detail = ex.message;
703
+ }
704
+ throw new Error(`${SINGLE_HOST_ENV.DENY_PATTERNS} has an invalid entry /${source}/: ${detail}`);
705
+ }
706
+ });
707
+ }
708
+ function loadHostProfile(env = process.env) {
709
+ const host = readEnv(env, SINGLE_HOST_ENV.HOST);
710
+ if (host == null) {
711
+ const _startupLogger = $logger.child({ context: "loadHostProfile" });
712
+ _startupLogger.warn("no host is registered; set the connection variables and restart", {
713
+ env_vars: [SINGLE_HOST_ENV.HOST, SINGLE_HOST_ENV.USER]
714
+ });
715
+ return null;
716
+ }
717
+ const username = readEnv(env, SINGLE_HOST_ENV.USER);
718
+ if (username == null) {
719
+ throw new Error(`${SINGLE_HOST_ENV.HOST} is set, so ${SINGLE_HOST_ENV.USER} is required`);
720
+ }
721
+ const name = readEnv(env, SINGLE_HOST_ENV.NAME) ?? host;
722
+ const _logger = $logger.child({ context: "loadHostProfile", profile: name });
723
+ const allowCommands = readListEnv(env, SINGLE_HOST_ENV.ALLOW_COMMANDS) ?? [];
724
+ if (allowCommands.length > 0 && allowCommands.includes("pwd") == false) {
725
+ allowCommands.push("pwd");
726
+ }
727
+ const policy = {
728
+ readonly: readBooleanEnv(env, SINGLE_HOST_ENV.READONLY) ?? false,
729
+ allowSudo: readBooleanEnv(env, SINGLE_HOST_ENV.ALLOW_SUDO) ?? true,
730
+ execTimeoutMs: readIntegerEnv(env, SINGLE_HOST_ENV.EXEC_TIMEOUT_MS) ?? DEFAULT_EXEC_TIMEOUT_MS,
731
+ connectTimeoutMs: readIntegerEnv(env, SINGLE_HOST_ENV.CONNECT_TIMEOUT_MS) ?? DEFAULT_CONNECT_TIMEOUT_MS,
732
+ maxOutputCharacters: readIntegerEnv(env, SINGLE_HOST_ENV.MAX_OUTPUT_CHARACTERS) ?? DEFAULT_MAX_OUTPUT_CHARACTERS,
733
+ maxReadFileBytes: readIntegerEnv(env, SINGLE_HOST_ENV.MAX_READ_FILE_BYTES) ?? DEFAULT_MAX_READ_FILE_BYTES,
734
+ allowCommands,
735
+ denyPatterns: compileDenyPatterns(readListEnv(env, SINGLE_HOST_ENV.DENY_PATTERNS) ?? []),
736
+ allowedPaths: readListEnv(env, SINGLE_HOST_ENV.ALLOWED_PATHS) ?? []
737
+ };
738
+ const profile = {
739
+ name,
740
+ host,
741
+ port: readIntegerEnv(env, SINGLE_HOST_ENV.PORT) ?? DEFAULT_SSH_PORT,
742
+ username,
743
+ description: readEnv(env, SINGLE_HOST_ENV.DESCRIPTION),
744
+ passphrase: readEnv(env, SINGLE_HOST_ENV.PASSPHRASE),
745
+ password: readEnv(env, SINGLE_HOST_ENV.PASSWORD),
746
+ hostKeyFingerprint: readEnv(env, SINGLE_HOST_ENV.HOST_KEY),
747
+ defaultCwd: readEnv(env, SINGLE_HOST_ENV.CWD),
748
+ policy
749
+ };
750
+ const keyPath = readEnv(env, SINGLE_HOST_ENV.KEY);
751
+ if (keyPath != null) {
752
+ const expandedKeyPath = expandHomePath(keyPath);
753
+ profile.privateKeyPath = expandedKeyPath;
754
+ if (fs7__default.default.existsSync(expandedKeyPath) == false) {
755
+ _logger.warn(`${SINGLE_HOST_ENV.KEY} does not exist; connections will fail`, {
756
+ private_key_path: expandedKeyPath
757
+ });
758
+ }
759
+ }
760
+ profile.proxyCommand = readEnv(env, SINGLE_HOST_ENV.PROXY_COMMAND);
761
+ const jumpHost = readEnv(env, SINGLE_HOST_ENV.JUMP_HOST);
762
+ if (jumpHost == null) {
763
+ const strayJumpVariables = [
764
+ SINGLE_HOST_ENV.JUMP_PORT,
765
+ SINGLE_HOST_ENV.JUMP_USER,
766
+ SINGLE_HOST_ENV.JUMP_KEY,
767
+ SINGLE_HOST_ENV.JUMP_PASSPHRASE,
768
+ SINGLE_HOST_ENV.JUMP_PASSWORD,
769
+ SINGLE_HOST_ENV.JUMP_HOST_KEY
770
+ ].filter((variable) => readEnv(env, variable) != null);
771
+ if (strayJumpVariables.length > 0) {
772
+ throw new Error(`${strayJumpVariables.join(", ")} is set, so ${SINGLE_HOST_ENV.JUMP_HOST} is required`);
773
+ }
774
+ } else {
775
+ profile.jump = {
776
+ host: jumpHost,
777
+ port: readIntegerEnv(env, SINGLE_HOST_ENV.JUMP_PORT) ?? DEFAULT_SSH_PORT,
778
+ username: readEnv(env, SINGLE_HOST_ENV.JUMP_USER) ?? username,
779
+ password: readEnv(env, SINGLE_HOST_ENV.JUMP_PASSWORD),
780
+ hostKeyFingerprint: readEnv(env, SINGLE_HOST_ENV.JUMP_HOST_KEY)
781
+ };
782
+ const jumpKeyPath = readEnv(env, SINGLE_HOST_ENV.JUMP_KEY);
783
+ if (jumpKeyPath != null) {
784
+ profile.jump.privateKeyPath = expandHomePath(jumpKeyPath);
785
+ profile.jump.passphrase = readEnv(env, SINGLE_HOST_ENV.JUMP_PASSPHRASE);
786
+ if (fs7__default.default.existsSync(profile.jump.privateKeyPath) == false) {
787
+ _logger.warn(`${SINGLE_HOST_ENV.JUMP_KEY} does not exist; connections will fail`, {
788
+ private_key_path: profile.jump.privateKeyPath
789
+ });
790
+ }
791
+ } else {
792
+ profile.jump.privateKeyPath = profile.privateKeyPath;
793
+ profile.jump.passphrase = readEnv(env, SINGLE_HOST_ENV.JUMP_PASSPHRASE) ?? profile.passphrase;
794
+ }
795
+ }
796
+ _logger.info("host profile loaded", {
797
+ host,
798
+ port: profile.port,
799
+ username,
800
+ readonly: policy.readonly,
801
+ jump_host: profile.jump?.host,
802
+ via_proxy_command: profile.proxyCommand != null
803
+ });
804
+ return profile;
805
+ }
806
+ function toHostSummary(profile) {
807
+ let authMethod = "agent";
808
+ if (profile.privateKeyPath != null) {
809
+ authMethod = "privateKey";
810
+ } else if (profile.password != null) {
811
+ authMethod = "password";
812
+ }
813
+ const summary = {
814
+ name: profile.name,
815
+ host: profile.host,
816
+ port: profile.port,
817
+ username: profile.username,
818
+ description: profile.description,
819
+ authMethod,
820
+ viaProxyCommand: profile.proxyCommand != null,
821
+ readonly: profile.policy.readonly,
822
+ allowSudo: profile.policy.allowSudo,
823
+ allowedPaths: profile.policy.allowedPaths,
824
+ allowCommands: profile.policy.allowCommands
825
+ };
826
+ if (profile.jump != null) {
827
+ summary.jump = {
828
+ host: profile.jump.host,
829
+ port: profile.jump.port,
830
+ username: profile.jump.username
831
+ };
832
+ }
833
+ return summary;
834
+ }
609
835
 
610
836
  // src/modules/guard/command-guard.ts
611
837
  var WRAPPER_BINARY_SET = new Set(COMMAND_WRAPPER_BINARIES);
@@ -1043,20 +1269,20 @@ function inspectRemotePath(remotePath, policy, access) {
1043
1269
  function toRealPath(inputPath) {
1044
1270
  const _logger = $logger.child({ context: "toRealPath" });
1045
1271
  try {
1046
- return fs__default.default.realpathSync.native(inputPath);
1272
+ return fs7__default.default.realpathSync.native(inputPath);
1047
1273
  } catch (ex) {
1048
1274
  _logger.debug("path does not resolve, falling back to its parent directory", {
1049
1275
  reason: ex instanceof Error ? ex.name : "unknown"
1050
1276
  });
1051
1277
  }
1052
1278
  try {
1053
- const parentRealPath = fs__default.default.realpathSync.native(path2__default.default.dirname(inputPath));
1054
- return path2__default.default.join(parentRealPath, path2__default.default.basename(inputPath));
1279
+ const parentRealPath = fs7__default.default.realpathSync.native(path__default.default.dirname(inputPath));
1280
+ return path__default.default.join(parentRealPath, path__default.default.basename(inputPath));
1055
1281
  } catch (ex) {
1056
1282
  _logger.debug("parent directory does not resolve either, comparing lexically", {
1057
1283
  reason: ex instanceof Error ? ex.name : "unknown"
1058
1284
  });
1059
- return path2__default.default.resolve(inputPath);
1285
+ return path__default.default.resolve(inputPath);
1060
1286
  }
1061
1287
  }
1062
1288
  function toComparablePath(inputPath) {
@@ -1136,42 +1362,56 @@ function resolveAgentPath() {
1136
1362
  }
1137
1363
  return void 0;
1138
1364
  }
1139
- function readPrivateKey(profile, keyPath) {
1365
+ function readPrivateKey(label, keyPath) {
1140
1366
  const cached = PRIVATE_KEY_CACHE.get(keyPath);
1141
1367
  if (cached != null) {
1142
1368
  return cached;
1143
1369
  }
1144
1370
  try {
1145
- const contents = fs__default.default.readFileSync(keyPath);
1371
+ const contents = fs7__default.default.readFileSync(keyPath);
1146
1372
  PRIVATE_KEY_CACHE.set(keyPath, contents);
1147
1373
  return contents;
1148
1374
  } catch (ex) {
1149
- const _logger = $logger.child({ context: "readPrivateKey", profile: profile.name });
1150
- _logger.error(ex, "cannot read the profile's private key file");
1151
- throw new Error(`cannot read the private key configured for profile '${profile.name}' (see the server log for the path)`);
1375
+ const _logger = $logger.child({ context: "readPrivateKey", profile: label });
1376
+ _logger.error(ex, "cannot read the private key file");
1377
+ throw new Error(`cannot read the private key configured for '${label}' (see the server log for the path)`);
1378
+ }
1379
+ }
1380
+ function applyAuth(connectConfig, credentials, label) {
1381
+ if (credentials.privateKeyPath != null) {
1382
+ connectConfig.privateKey = readPrivateKey(label, credentials.privateKeyPath);
1383
+ }
1384
+ if (credentials.passphrase != null) {
1385
+ connectConfig.passphrase = credentials.passphrase;
1386
+ }
1387
+ if (credentials.password != null) {
1388
+ connectConfig.password = credentials.password;
1389
+ }
1390
+ if (connectConfig.privateKey == null && connectConfig.password == null) {
1391
+ connectConfig.agent = resolveAgentPath();
1152
1392
  }
1153
1393
  }
1154
1394
  function toHostKeyFingerprint(hostKey) {
1155
1395
  const digest = crypto.createHash("sha256").update(hostKey).digest("base64").replace(/=+$/, "");
1156
1396
  return `SHA256:${digest}`;
1157
1397
  }
1158
- function buildHostVerifier(profile, onHostKeySeen) {
1398
+ function buildHostVerifier(hop, onHostKeySeen) {
1159
1399
  return (hostKey) => {
1160
1400
  const fingerprint = toHostKeyFingerprint(hostKey);
1161
1401
  onHostKeySeen(fingerprint);
1162
- const _logger = $logger.child({ context: "hostVerifier", profile: profile.name, host: profile.host });
1163
- if (profile.hostKeyFingerprint == null) {
1164
- _logger.info("host key accepted unpinned; add hostKeyFingerprint to the profile to pin it", {
1402
+ const _logger = $logger.child({ context: "hostVerifier", profile: hop.label, host: hop.host });
1403
+ if (hop.pinnedFingerprint == null) {
1404
+ _logger.info("host key accepted unpinned; pin the fingerprint in the profile to detect a changed key", {
1165
1405
  host_key_fingerprint: fingerprint
1166
1406
  });
1167
1407
  return true;
1168
1408
  }
1169
- if (profile.hostKeyFingerprint === fingerprint) {
1409
+ if (hop.pinnedFingerprint === fingerprint) {
1170
1410
  _logger.debug("host key matches the pinned fingerprint");
1171
1411
  return true;
1172
1412
  }
1173
1413
  _logger.error(null, "host key does not match the pinned fingerprint", {
1174
- expected: profile.hostKeyFingerprint,
1414
+ expected: hop.pinnedFingerprint,
1175
1415
  actual: fingerprint
1176
1416
  });
1177
1417
  return false;
@@ -1184,21 +1424,152 @@ function buildConnectConfig(profile, onHostKeySeen) {
1184
1424
  username: profile.username,
1185
1425
  readyTimeout: profile.policy.connectTimeoutMs,
1186
1426
  keepaliveInterval: KEEPALIVE_INTERVAL_MS,
1187
- hostVerifier: buildHostVerifier(profile, onHostKeySeen)
1427
+ hostVerifier: buildHostVerifier(
1428
+ { label: profile.name, host: profile.host, pinnedFingerprint: profile.hostKeyFingerprint },
1429
+ onHostKeySeen
1430
+ )
1188
1431
  };
1189
- if (profile.privateKeyPath != null) {
1190
- connectConfig.privateKey = readPrivateKey(profile, profile.privateKeyPath);
1191
- }
1192
- if (profile.passphrase != null) {
1193
- connectConfig.passphrase = profile.passphrase;
1432
+ applyAuth(connectConfig, profile, profile.name);
1433
+ return connectConfig;
1434
+ }
1435
+ function expandProxyCommand(template, hop) {
1436
+ return template.replace(/%[hpr%]/g, (token) => {
1437
+ if (token === "%h") {
1438
+ return hop.host;
1439
+ }
1440
+ if (token === "%p") {
1441
+ return String(hop.port);
1442
+ }
1443
+ if (token === "%r") {
1444
+ return hop.username;
1445
+ }
1446
+ return "%";
1447
+ });
1448
+ }
1449
+ function openProxyCommand(profile, hop) {
1450
+ const command = expandProxyCommand(profile.proxyCommand ?? "", hop);
1451
+ const _logger = $logger.child({ context: "openProxyCommand", profile: profile.name });
1452
+ _logger.debug("starting the proxy command", { command });
1453
+ const child = child_process.spawn(command, { shell: true, stdio: ["pipe", "pipe", "pipe"], windowsHide: true });
1454
+ const stderrDecoder = new string_decoder.StringDecoder("utf8");
1455
+ child.stderr.on("data", (chunk) => {
1456
+ const text = stderrDecoder.write(chunk).trim();
1457
+ if (text !== "") {
1458
+ _logger.warn("proxy command stderr", { text });
1459
+ }
1460
+ });
1461
+ child.on("exit", (code, signal) => {
1462
+ _logger.debug("proxy command exited", { exit_code: code, signal });
1463
+ });
1464
+ const sock = stream.Duplex.from({ readable: child.stdout, writable: child.stdin });
1465
+ sock.on("error", (error) => {
1466
+ _logger.debug("proxy command stream error", { error_message: error.message });
1467
+ });
1468
+ child.on("error", (error) => {
1469
+ sock.destroy(error);
1470
+ });
1471
+ let closed = false;
1472
+ return {
1473
+ sock,
1474
+ close: () => {
1475
+ if (closed == true) {
1476
+ return;
1477
+ }
1478
+ closed = true;
1479
+ if (child.exitCode != null || child.signalCode != null) {
1480
+ return;
1481
+ }
1482
+ if (process.platform === "win32" && child.pid != null) {
1483
+ const killer = child_process.spawn("taskkill", ["/pid", String(child.pid), "/T", "/F"], { stdio: "ignore", windowsHide: true });
1484
+ killer.on("error", (error) => {
1485
+ _logger.error(error, "failed to kill the proxy command's process tree");
1486
+ });
1487
+ return;
1488
+ }
1489
+ child.kill();
1490
+ }
1491
+ };
1492
+ }
1493
+ function openJumpTransport(profile, jump, proxy, onHostKeySeen) {
1494
+ const label = `${profile.name} jump host`;
1495
+ const endpoint = `${jump.username}@${jump.host}:${jump.port}`;
1496
+ const _logger = $logger.child({ context: "openJumpTransport", profile: profile.name, jump_host: jump.host });
1497
+ const jumpConfig = {
1498
+ host: jump.host,
1499
+ port: jump.port,
1500
+ username: jump.username,
1501
+ readyTimeout: profile.policy.connectTimeoutMs,
1502
+ keepaliveInterval: KEEPALIVE_INTERVAL_MS,
1503
+ hostVerifier: buildHostVerifier(
1504
+ { label, host: jump.host, pinnedFingerprint: jump.hostKeyFingerprint },
1505
+ onHostKeySeen
1506
+ )
1507
+ };
1508
+ applyAuth(jumpConfig, jump, label);
1509
+ if (proxy != null) {
1510
+ jumpConfig.sock = proxy.sock;
1511
+ }
1512
+ return new Promise((resolve, reject) => {
1513
+ const jumpClient = new Client();
1514
+ let settled = false;
1515
+ jumpClient.on("error", (error) => {
1516
+ if (settled == false) {
1517
+ settled = true;
1518
+ jumpClient.destroy();
1519
+ reject(new Error(`jump host ${endpoint}: ${error.message}`));
1520
+ return;
1521
+ }
1522
+ _logger.error(error, "jump host connection error after ready");
1523
+ });
1524
+ jumpClient.on("close", () => {
1525
+ _logger.debug("jump host connection closed");
1526
+ proxy?.close();
1527
+ if (settled == false) {
1528
+ settled = true;
1529
+ reject(new Error(`jump host ${endpoint}: connection closed before the handshake completed`));
1530
+ }
1531
+ });
1532
+ jumpClient.once("ready", () => {
1533
+ if (settled == true) {
1534
+ return;
1535
+ }
1536
+ jumpClient.forwardOut("127.0.0.1", 0, profile.host, profile.port, (error, stream) => {
1537
+ if (settled == true) {
1538
+ return;
1539
+ }
1540
+ settled = true;
1541
+ if (error != null) {
1542
+ jumpClient.end();
1543
+ reject(new Error(`jump host ${endpoint} refused the forward to ${profile.host}:${profile.port}: ${error.message}`));
1544
+ return;
1545
+ }
1546
+ _logger.info("jump host connected, target channel forwarded");
1547
+ resolve({
1548
+ sock: stream,
1549
+ close: () => {
1550
+ jumpClient.end();
1551
+ }
1552
+ });
1553
+ });
1554
+ });
1555
+ jumpClient.connect(jumpConfig);
1556
+ });
1557
+ }
1558
+ async function openTransport(profile, onJumpHostKeySeen) {
1559
+ let proxy = null;
1560
+ if (profile.proxyCommand != null) {
1561
+ proxy = openProxyCommand(profile, profile.jump ?? profile);
1194
1562
  }
1195
- if (profile.password != null) {
1196
- connectConfig.password = profile.password;
1563
+ if (profile.jump == null) {
1564
+ return proxy;
1197
1565
  }
1198
- if (connectConfig.privateKey == null && connectConfig.password == null) {
1199
- connectConfig.agent = resolveAgentPath();
1566
+ try {
1567
+ const jumpTransport = await openJumpTransport(profile, profile.jump, proxy, onJumpHostKeySeen);
1568
+ return jumpTransport;
1569
+ } catch (ex) {
1570
+ proxy?.close();
1571
+ throw ex;
1200
1572
  }
1201
- return connectConfig;
1202
1573
  }
1203
1574
  function buildRemoteCommand(command, cwd, trackCwd) {
1204
1575
  const lines = [];
@@ -1240,6 +1611,7 @@ var SshConnection = class {
1240
1611
  /** Set when the peer closed a previously established connection. */
1241
1612
  this.droppedAfterReady = false;
1242
1613
  this.observedFingerprint = null;
1614
+ this.observedJumpFingerprint = null;
1243
1615
  }
1244
1616
  get isConnected() {
1245
1617
  return this.client != null;
@@ -1248,6 +1620,10 @@ var SshConnection = class {
1248
1620
  get hostKeyFingerprint() {
1249
1621
  return this.observedFingerprint;
1250
1622
  }
1623
+ /** Host key the jump host presented; null without a jump host or before its handshake. */
1624
+ get jumpHostKeyFingerprint() {
1625
+ return this.observedJumpFingerprint;
1626
+ }
1251
1627
  /** True when a connection was established and then lost, so shell state is gone. */
1252
1628
  get wasDropped() {
1253
1629
  return this.droppedAfterReady;
@@ -1255,8 +1631,11 @@ var SshConnection = class {
1255
1631
  /**
1256
1632
  * Opens the connection, or joins the in-flight attempt when one is already running.
1257
1633
  *
1634
+ * With a proxy command or a jump host the carrier is opened first and handed to ssh2
1635
+ * as the socket; it is torn down with the target connection, whichever side closes.
1636
+ *
1258
1637
  * @throws {Error} If the connection was closed, authentication fails, the host is
1259
- * unreachable, or the handshake times out.
1638
+ * unreachable, the handshake times out, or the carrier cannot be opened.
1260
1639
  */
1261
1640
  async connect() {
1262
1641
  if (this.disposed == true) {
@@ -1279,43 +1658,66 @@ var SshConnection = class {
1279
1658
  const connectConfig = buildConnectConfig(this.profile, (fingerprint) => {
1280
1659
  this.observedFingerprint = fingerprint;
1281
1660
  });
1282
- this.connecting = new Promise((resolve, reject) => {
1283
- const client = new Client();
1284
- this.pendingClient = client;
1285
- let settled = false;
1286
- client.on("error", (error) => {
1287
- if (settled == false) {
1661
+ this.connecting = (async () => {
1662
+ const transport = await openTransport(this.profile, (fingerprint) => {
1663
+ this.observedJumpFingerprint = fingerprint;
1664
+ });
1665
+ if (this.disposed == true) {
1666
+ transport?.close();
1667
+ throw new Error(`ssh connection for '${this.profile.name}' was closed during the handshake`);
1668
+ }
1669
+ if (transport != null) {
1670
+ connectConfig.sock = transport.sock;
1671
+ }
1672
+ await new Promise((resolve, reject) => {
1673
+ const client = new Client();
1674
+ this.pendingClient = client;
1675
+ let settled = false;
1676
+ client.on("error", (error) => {
1677
+ if (settled == false) {
1678
+ settled = true;
1679
+ this.pendingClient = null;
1680
+ client.destroy();
1681
+ reject(error);
1682
+ return;
1683
+ }
1684
+ if (this.client !== client) {
1685
+ _logger.debug("ssh connection error during teardown", { error_message: error.message });
1686
+ return;
1687
+ }
1688
+ _logger.error(error, "ssh connection error after ready");
1689
+ });
1690
+ client.on("close", () => {
1691
+ transport?.close();
1692
+ if (this.client === client) {
1693
+ _logger.debug("ssh connection closed by the peer");
1694
+ this.client = null;
1695
+ this.droppedAfterReady = true;
1696
+ return;
1697
+ }
1698
+ if (settled == false) {
1699
+ settled = true;
1700
+ this.pendingClient = null;
1701
+ reject(new Error("connection closed before the handshake completed"));
1702
+ }
1703
+ });
1704
+ client.once("ready", () => {
1705
+ if (settled == true) {
1706
+ return;
1707
+ }
1288
1708
  settled = true;
1289
1709
  this.pendingClient = null;
1290
- client.destroy();
1291
- reject(error);
1292
- return;
1293
- }
1294
- _logger.error(error, "ssh connection error after ready");
1295
- });
1296
- client.on("close", () => {
1297
- if (this.client === client) {
1298
- _logger.debug("ssh connection closed by the peer");
1299
- this.client = null;
1300
- this.droppedAfterReady = true;
1301
- }
1302
- });
1303
- client.once("ready", () => {
1304
- if (settled == true) {
1305
- return;
1306
- }
1307
- settled = true;
1308
- this.pendingClient = null;
1309
- if (this.disposed == true) {
1310
- client.destroy();
1311
- reject(new Error(`ssh connection for '${this.profile.name}' was closed during the handshake`));
1312
- return;
1313
- }
1314
- this.client = client;
1315
- resolve();
1710
+ if (this.disposed == true) {
1711
+ client.destroy();
1712
+ reject(new Error(`ssh connection for '${this.profile.name}' was closed during the handshake`));
1713
+ return;
1714
+ }
1715
+ this.client = client;
1716
+ resolve();
1717
+ });
1718
+ client.connect(connectConfig);
1316
1719
  });
1317
- client.connect(connectConfig);
1318
- });
1720
+ })();
1319
1721
  try {
1320
1722
  await this.connecting;
1321
1723
  _logger.info("ssh connection established");
@@ -1917,7 +2319,7 @@ async function writeRemoteFile(connection, args) {
1917
2319
  }
1918
2320
  async function uploadFile(connection, localPath, remotePath) {
1919
2321
  requirePermittedPath(connection, remotePath, "write");
1920
- const localStats = fs__default.default.statSync(localPath);
2322
+ const localStats = fs7__default.default.statSync(localPath);
1921
2323
  if (localStats.isFile() == false) {
1922
2324
  throw new Error(`local path is not a file: ${localPath}`);
1923
2325
  }
@@ -1954,7 +2356,7 @@ async function downloadFile(connection, remotePath, localPath) {
1954
2356
  });
1955
2357
  });
1956
2358
  });
1957
- const localStats = fs__default.default.statSync(localPath);
2359
+ const localStats = fs7__default.default.statSync(localPath);
1958
2360
  const _logger = $logger.child({
1959
2361
  context: "downloadFile",
1960
2362
  profile: connection.profile.name,
@@ -1964,147 +2366,1667 @@ async function downloadFile(connection, remotePath, localPath) {
1964
2366
  _logger.info("file downloaded", { bytes: localStats.size });
1965
2367
  return localStats.size;
1966
2368
  }
1967
- function readEnv(name) {
1968
- const value = process.env[name];
1969
- if (value == null) {
1970
- return void 0;
2369
+
2370
+ // src/modules/manage/connection-check.ts
2371
+ function describeAuth(profile) {
2372
+ if (profile.privateKeyPath != null) {
2373
+ return `key ${profile.privateKeyPath}`;
1971
2374
  }
1972
- const trimmed = value.trim();
1973
- if (trimmed === "") {
1974
- return void 0;
2375
+ if (profile.password != null) {
2376
+ return "password";
1975
2377
  }
1976
- return trimmed;
2378
+ return "ssh agent";
1977
2379
  }
1978
- function readBooleanEnv(name) {
1979
- const value = readEnv(name);
1980
- if (value == null) {
1981
- return void 0;
1982
- }
1983
- const normalized = value.toLowerCase();
1984
- if (TRUTHY_ENV_VALUES.includes(normalized) == true) {
1985
- return true;
2380
+ async function runConnectionCheck(profile, output) {
2381
+ const endpoint = `${profile.username}@${profile.host}:${profile.port}`;
2382
+ const auth = describeAuth(profile);
2383
+ output.write(`Checking ${profile.name} \u2192 ${endpoint}
2384
+ `);
2385
+ if (profile.proxyCommand != null) {
2386
+ output.write(` via proxy command: ${profile.proxyCommand}
2387
+ `);
1986
2388
  }
1987
- if (FALSY_ENV_VALUES.includes(normalized) == false) {
1988
- throw new Error(`${name} must be one of ${[...TRUTHY_ENV_VALUES, ...FALSY_ENV_VALUES].join(", ")} (got "${value}")`);
2389
+ if (profile.jump != null) {
2390
+ output.write(` via jump host: ${profile.jump.username}@${profile.jump.host}:${profile.jump.port}
2391
+ `);
1989
2392
  }
1990
- return false;
2393
+ output.write("\n");
2394
+ const connection = new SshConnection(profile);
2395
+ const startedAt = Date.now();
2396
+ let connected = false;
2397
+ let detail = "";
2398
+ try {
2399
+ await connection.connect();
2400
+ connected = true;
2401
+ } catch (ex) {
2402
+ detail = String(ex);
2403
+ if (ex instanceof Error) {
2404
+ detail = ex.message;
2405
+ }
2406
+ } finally {
2407
+ connection.disconnect();
2408
+ }
2409
+ const durationMs = Date.now() - startedAt;
2410
+ if (connected == true) {
2411
+ output.write(` OK ${endpoint} (${auth}, ${durationMs}ms)
2412
+ `);
2413
+ } else {
2414
+ output.write(` FAILED ${endpoint} (${auth})
2415
+ `);
2416
+ output.write(` ${detail}
2417
+ `);
2418
+ }
2419
+ if (connection.hostKeyFingerprint != null) {
2420
+ let pinNote = `not pinned \u2014 set ${SINGLE_HOST_ENV.HOST_KEY} to it to detect a changed key`;
2421
+ if (profile.hostKeyFingerprint != null) {
2422
+ pinNote = "pinned";
2423
+ }
2424
+ output.write(` host key ${connection.hostKeyFingerprint} (${pinNote})
2425
+ `);
2426
+ }
2427
+ if (connection.jumpHostKeyFingerprint != null) {
2428
+ let pinNote = `not pinned \u2014 set ${SINGLE_HOST_ENV.JUMP_HOST_KEY} to it to detect a changed key`;
2429
+ if (profile.jump?.hostKeyFingerprint != null) {
2430
+ pinNote = "pinned";
2431
+ }
2432
+ output.write(` jump host key ${connection.jumpHostKeyFingerprint} (${pinNote})
2433
+ `);
2434
+ }
2435
+ return {
2436
+ connected,
2437
+ hostKeyFingerprint: connection.hostKeyFingerprint,
2438
+ jumpHostKeyFingerprint: connection.jumpHostKeyFingerprint
2439
+ };
2440
+ }
2441
+
2442
+ // src/modules/manage/entry.ts
2443
+ var MANAGED_ENV_NAMES = [
2444
+ SINGLE_HOST_ENV.HOST,
2445
+ SINGLE_HOST_ENV.PORT,
2446
+ SINGLE_HOST_ENV.USER,
2447
+ SINGLE_HOST_ENV.KEY,
2448
+ SINGLE_HOST_ENV.PASSPHRASE,
2449
+ SINGLE_HOST_ENV.PASSWORD,
2450
+ SINGLE_HOST_ENV.DESCRIPTION,
2451
+ SINGLE_HOST_ENV.JUMP_HOST,
2452
+ SINGLE_HOST_ENV.JUMP_PORT,
2453
+ SINGLE_HOST_ENV.JUMP_USER,
2454
+ SINGLE_HOST_ENV.PROXY_COMMAND,
2455
+ SINGLE_HOST_ENV.READONLY,
2456
+ SINGLE_HOST_ENV.ALLOWED_PATHS,
2457
+ SINGLE_HOST_ENV.HOST_KEY,
2458
+ SINGLE_HOST_ENV.JUMP_HOST_KEY
2459
+ ];
2460
+ var JUMP_ENV_PREFIX = "SSH_JUMP_";
2461
+ var SERVER_NAME_PATTERN = /^[A-Za-z0-9_-]{1,48}$/;
2462
+ function isOurEntry(entry) {
2463
+ if (entry.args.includes(PACKAGE_NAME) == true) {
2464
+ return true;
2465
+ }
2466
+ const commandBase = entry.command.replace(/\\/g, "/").split("/").pop() ?? "";
2467
+ return commandBase === SERVER_NAME || commandBase.startsWith(`${SERVER_NAME}.`) == true;
2468
+ }
2469
+ function launchCommand() {
2470
+ if (process.platform === "win32") {
2471
+ return { command: "cmd", args: ["/c", "npx", "-y", PACKAGE_NAME] };
2472
+ }
2473
+ return { command: "npx", args: ["-y", PACKAGE_NAME] };
2474
+ }
2475
+ function answersToEntry(answers) {
2476
+ const env = {};
2477
+ env[SINGLE_HOST_ENV.HOST] = answers.host;
2478
+ if (answers.port !== DEFAULT_SSH_PORT) {
2479
+ env[SINGLE_HOST_ENV.PORT] = String(answers.port);
2480
+ }
2481
+ env[SINGLE_HOST_ENV.USER] = answers.username;
2482
+ if (answers.auth === "key" && answers.keyPath != null) {
2483
+ env[SINGLE_HOST_ENV.KEY] = answers.keyPath;
2484
+ if (answers.passphrase != null && answers.passphrase !== "") {
2485
+ env[SINGLE_HOST_ENV.PASSPHRASE] = answers.passphrase;
2486
+ }
2487
+ }
2488
+ if (answers.auth === "password" && answers.password != null) {
2489
+ env[SINGLE_HOST_ENV.PASSWORD] = answers.password;
2490
+ }
2491
+ if (answers.hostKeyFingerprint != null) {
2492
+ env[SINGLE_HOST_ENV.HOST_KEY] = answers.hostKeyFingerprint;
2493
+ }
2494
+ if (answers.description != null && answers.description !== "") {
2495
+ env[SINGLE_HOST_ENV.DESCRIPTION] = answers.description;
2496
+ }
2497
+ if (answers.jumpHost != null) {
2498
+ env[SINGLE_HOST_ENV.JUMP_HOST] = answers.jumpHost;
2499
+ if (answers.jumpPort != null && answers.jumpPort !== DEFAULT_SSH_PORT) {
2500
+ env[SINGLE_HOST_ENV.JUMP_PORT] = String(answers.jumpPort);
2501
+ }
2502
+ if (answers.jumpUser != null && answers.jumpUser !== answers.username) {
2503
+ env[SINGLE_HOST_ENV.JUMP_USER] = answers.jumpUser;
2504
+ }
2505
+ if (answers.jumpHostKeyFingerprint != null) {
2506
+ env[SINGLE_HOST_ENV.JUMP_HOST_KEY] = answers.jumpHostKeyFingerprint;
2507
+ }
2508
+ }
2509
+ if (answers.proxyCommand != null && answers.proxyCommand !== "") {
2510
+ env[SINGLE_HOST_ENV.PROXY_COMMAND] = answers.proxyCommand;
2511
+ }
2512
+ if (answers.readonly == true) {
2513
+ env[SINGLE_HOST_ENV.READONLY] = "true";
2514
+ }
2515
+ if (answers.allowedPaths.length > 0) {
2516
+ env[SINGLE_HOST_ENV.ALLOWED_PATHS] = answers.allowedPaths.join(",");
2517
+ }
2518
+ for (const [name, value] of Object.entries(answers.extraEnv)) {
2519
+ if (MANAGED_ENV_NAMES.includes(name) == true) {
2520
+ continue;
2521
+ }
2522
+ if (answers.jumpHost == null && name.startsWith(JUMP_ENV_PREFIX) == true) {
2523
+ continue;
2524
+ }
2525
+ env[name] = value;
2526
+ }
2527
+ const launch = launchCommand();
2528
+ return {
2529
+ command: launch.command,
2530
+ args: launch.args,
2531
+ env
2532
+ };
2533
+ }
2534
+ function readPort(value) {
2535
+ if (value == null) {
2536
+ return DEFAULT_SSH_PORT;
2537
+ }
2538
+ const parsed = Number(value);
2539
+ if (Number.isInteger(parsed) == false || parsed <= 0) {
2540
+ return DEFAULT_SSH_PORT;
2541
+ }
2542
+ return parsed;
2543
+ }
2544
+ function isTruthy(value) {
2545
+ if (value == null) {
2546
+ return false;
2547
+ }
2548
+ return TRUTHY_ENV_VALUES.includes(value.trim().toLowerCase());
2549
+ }
2550
+ function entryToAnswers(name, entry) {
2551
+ const env = entry.env;
2552
+ const host = env[SINGLE_HOST_ENV.HOST] ?? "";
2553
+ const username = env[SINGLE_HOST_ENV.USER] ?? "";
2554
+ let auth = "agent";
2555
+ if (env[SINGLE_HOST_ENV.KEY] != null) {
2556
+ auth = "key";
2557
+ } else if (env[SINGLE_HOST_ENV.PASSWORD] != null) {
2558
+ auth = "password";
2559
+ }
2560
+ let allowedPaths = [];
2561
+ const allowedPathsValue = env[SINGLE_HOST_ENV.ALLOWED_PATHS];
2562
+ if (allowedPathsValue != null) {
2563
+ allowedPaths = allowedPathsValue.split(",").map((item) => item.trim()).filter((item) => item !== "");
2564
+ }
2565
+ const extraEnv = {};
2566
+ for (const [variable, value] of Object.entries(env)) {
2567
+ if (MANAGED_ENV_NAMES.includes(variable) == false) {
2568
+ extraEnv[variable] = value;
2569
+ }
2570
+ }
2571
+ const answers = {
2572
+ name,
2573
+ host,
2574
+ port: readPort(env[SINGLE_HOST_ENV.PORT]),
2575
+ username,
2576
+ auth,
2577
+ keyPath: env[SINGLE_HOST_ENV.KEY],
2578
+ passphrase: env[SINGLE_HOST_ENV.PASSPHRASE],
2579
+ password: env[SINGLE_HOST_ENV.PASSWORD],
2580
+ description: env[SINGLE_HOST_ENV.DESCRIPTION],
2581
+ proxyCommand: env[SINGLE_HOST_ENV.PROXY_COMMAND],
2582
+ readonly: isTruthy(env[SINGLE_HOST_ENV.READONLY]),
2583
+ allowedPaths,
2584
+ hostKeyFingerprint: env[SINGLE_HOST_ENV.HOST_KEY],
2585
+ extraEnv
2586
+ };
2587
+ const jumpHost = env[SINGLE_HOST_ENV.JUMP_HOST];
2588
+ if (jumpHost != null) {
2589
+ answers.jumpHost = jumpHost;
2590
+ answers.jumpPort = readPort(env[SINGLE_HOST_ENV.JUMP_PORT]);
2591
+ answers.jumpUser = env[SINGLE_HOST_ENV.JUMP_USER] ?? username;
2592
+ answers.jumpHostKeyFingerprint = env[SINGLE_HOST_ENV.JUMP_HOST_KEY];
2593
+ }
2594
+ return answers;
2595
+ }
2596
+ function summarizeEntry(entry) {
2597
+ const env = entry.env;
2598
+ const host = env[SINGLE_HOST_ENV.HOST] ?? "?";
2599
+ const port = env[SINGLE_HOST_ENV.PORT] ?? String(DEFAULT_SSH_PORT);
2600
+ const username = env[SINGLE_HOST_ENV.USER] ?? "?";
2601
+ let auth = "agent";
2602
+ if (env[SINGLE_HOST_ENV.KEY] != null) {
2603
+ auth = "key";
2604
+ } else if (env[SINGLE_HOST_ENV.PASSWORD] != null) {
2605
+ auth = "password";
2606
+ }
2607
+ const notes = [];
2608
+ if (env[SINGLE_HOST_ENV.JUMP_HOST] != null) {
2609
+ notes.push(`jump ${env[SINGLE_HOST_ENV.JUMP_HOST]}`);
2610
+ }
2611
+ if (env[SINGLE_HOST_ENV.PROXY_COMMAND] != null) {
2612
+ notes.push("proxy");
2613
+ }
2614
+ if (isTruthy(env[SINGLE_HOST_ENV.READONLY]) == true) {
2615
+ notes.push("readonly");
2616
+ }
2617
+ if (env[SINGLE_HOST_ENV.ALLOWED_PATHS] != null) {
2618
+ notes.push(`paths ${env[SINGLE_HOST_ENV.ALLOWED_PATHS]}`);
2619
+ }
2620
+ if (env[SINGLE_HOST_ENV.HOST_KEY] != null) {
2621
+ notes.push("pinned");
2622
+ }
2623
+ return {
2624
+ endpoint: `${username}@${host}:${port}`,
2625
+ auth,
2626
+ notes: notes.join(", ")
2627
+ };
2628
+ }
2629
+
2630
+ // src/modules/manage/prompter.ts
2631
+ var PromptClosedError = class extends Error {
2632
+ constructor() {
2633
+ super("input closed before the prompt was answered");
2634
+ this.name = "PromptClosedError";
2635
+ }
2636
+ };
2637
+ var Prompter = class {
2638
+ constructor(input, output) {
2639
+ this.input = input;
2640
+ this.output = output;
2641
+ this.lineBuffer = "";
2642
+ this.pendingLines = [];
2643
+ this.waiter = null;
2644
+ this.inputEnded = false;
2645
+ this.secretMode = false;
2646
+ this.secretBuffer = "";
2647
+ input.setEncoding("utf8");
2648
+ input.on("data", (chunk) => {
2649
+ this.onData(chunk);
2650
+ });
2651
+ input.on("end", () => {
2652
+ this.inputEnded = true;
2653
+ if (this.waiter != null) {
2654
+ const waiter = this.waiter;
2655
+ this.waiter = null;
2656
+ waiter(null);
2657
+ }
2658
+ });
2659
+ }
2660
+ /** Stops reading so the process can exit once the command is done. */
2661
+ close() {
2662
+ this.input.pause();
2663
+ }
2664
+ write(text) {
2665
+ this.output.write(text);
2666
+ }
2667
+ /**
2668
+ * Free-text prompt. Enter accepts `defaultValue` when one is shown.
2669
+ *
2670
+ * @throws {PromptClosedError} If the input closes before a line arrives.
2671
+ */
2672
+ async ask(question, defaultValue) {
2673
+ let suffix = "";
2674
+ if (defaultValue != null && defaultValue !== "") {
2675
+ suffix = ` [${defaultValue}]`;
2676
+ }
2677
+ this.output.write(`${question}${suffix}: `);
2678
+ const line = await this.readLine();
2679
+ if (line == null) {
2680
+ throw new PromptClosedError();
2681
+ }
2682
+ const trimmed = line.trim();
2683
+ if (trimmed === "" && defaultValue != null) {
2684
+ return defaultValue;
2685
+ }
2686
+ return trimmed;
2687
+ }
2688
+ /** Like `ask`, re-asking until something non-empty is entered. */
2689
+ async askRequired(question, defaultValue) {
2690
+ for (; ; ) {
2691
+ const answer = await this.ask(question, defaultValue);
2692
+ if (answer !== "") {
2693
+ return answer;
2694
+ }
2695
+ this.output.write(" A value is required.\n");
2696
+ }
2697
+ }
2698
+ async askYesNo(question, defaultValue) {
2699
+ let hint = "[y/N]";
2700
+ if (defaultValue == true) {
2701
+ hint = "[Y/n]";
2702
+ }
2703
+ for (; ; ) {
2704
+ this.output.write(`${question} ${hint}: `);
2705
+ const line = await this.readLine();
2706
+ if (line == null) {
2707
+ throw new PromptClosedError();
2708
+ }
2709
+ const normalized = line.trim().toLowerCase();
2710
+ if (normalized === "") {
2711
+ return defaultValue;
2712
+ }
2713
+ if (normalized === "y" || normalized === "yes") {
2714
+ return true;
2715
+ }
2716
+ if (normalized === "n" || normalized === "no") {
2717
+ return false;
2718
+ }
2719
+ this.output.write(" Answer y or n.\n");
2720
+ }
2721
+ }
2722
+ /** Lists the choices one per line and accepts a key, case-insensitively. */
2723
+ async askChoice(question, choices, defaultKey) {
2724
+ this.output.write(`${question}
2725
+ `);
2726
+ for (const choice of choices) {
2727
+ this.output.write(` ${choice.key}) ${choice.label}
2728
+ `);
2729
+ }
2730
+ for (; ; ) {
2731
+ const answer = await this.ask("Choice", defaultKey);
2732
+ const matched = choices.find((choice) => choice.key.toLowerCase() === answer.toLowerCase());
2733
+ if (matched != null) {
2734
+ return matched.key;
2735
+ }
2736
+ this.output.write(` Pick one of ${choices.map((choice) => choice.key).join(", ")}.
2737
+ `);
2738
+ }
2739
+ }
2740
+ /**
2741
+ * Reads a value without echoing it on a TTY. Empty means "none", or "keep" when the
2742
+ * caller says a value already exists.
2743
+ */
2744
+ async askSecret(question) {
2745
+ const rawModeStream = this.input;
2746
+ if (rawModeStream.isTTY != true || rawModeStream.setRawMode == null) {
2747
+ const answer = await this.ask(question);
2748
+ return answer;
2749
+ }
2750
+ this.output.write(`${question}: `);
2751
+ this.secretBuffer = "";
2752
+ this.secretMode = true;
2753
+ rawModeStream.setRawMode(true);
2754
+ try {
2755
+ const line = await this.readLine();
2756
+ if (line == null) {
2757
+ throw new PromptClosedError();
2758
+ }
2759
+ return line;
2760
+ } finally {
2761
+ rawModeStream.setRawMode(false);
2762
+ this.secretMode = false;
2763
+ this.output.write("\n");
2764
+ }
2765
+ }
2766
+ readLine() {
2767
+ const queued = this.pendingLines.shift();
2768
+ if (queued != null) {
2769
+ return Promise.resolve(queued);
2770
+ }
2771
+ if (this.inputEnded == true) {
2772
+ return Promise.resolve(null);
2773
+ }
2774
+ return new Promise((resolve) => {
2775
+ this.waiter = resolve;
2776
+ });
2777
+ }
2778
+ deliver(line) {
2779
+ if (this.waiter != null) {
2780
+ const waiter = this.waiter;
2781
+ this.waiter = null;
2782
+ waiter(line);
2783
+ return;
2784
+ }
2785
+ this.pendingLines.push(line);
2786
+ }
2787
+ onData(chunk) {
2788
+ if (this.secretMode == true) {
2789
+ for (const character of chunk) {
2790
+ if (character === "\r" || character === "\n") {
2791
+ const secret = this.secretBuffer;
2792
+ this.secretBuffer = "";
2793
+ this.deliver(secret);
2794
+ continue;
2795
+ }
2796
+ if (character === "") {
2797
+ this.output.write("\n");
2798
+ process.exit(130);
2799
+ }
2800
+ if (character === "\x7F" || character === "\b") {
2801
+ this.secretBuffer = this.secretBuffer.slice(0, -1);
2802
+ continue;
2803
+ }
2804
+ this.secretBuffer += character;
2805
+ }
2806
+ return;
2807
+ }
2808
+ this.lineBuffer += chunk;
2809
+ let newlineIndex = this.lineBuffer.indexOf("\n");
2810
+ while (newlineIndex >= 0) {
2811
+ const line = this.lineBuffer.slice(0, newlineIndex).replace(/\r$/, "");
2812
+ this.lineBuffer = this.lineBuffer.slice(newlineIndex + 1);
2813
+ this.deliver(line);
2814
+ newlineIndex = this.lineBuffer.indexOf("\n");
2815
+ }
2816
+ }
2817
+ };
2818
+ var DEFAULT_KEY_CANDIDATES = ["~/.ssh/id_ed25519", "~/.ssh/id_ecdsa", "~/.ssh/id_rsa"];
2819
+ var CLEAR_ANSWER = "-";
2820
+ async function askPort(prompter, question, current) {
2821
+ for (; ; ) {
2822
+ const answer = await prompter.ask(question, String(current));
2823
+ const parsed = Number(answer);
2824
+ if (Number.isInteger(parsed) == true && parsed > 0 && parsed <= 65535) {
2825
+ return parsed;
2826
+ }
2827
+ prompter.write(" Enter a port number between 1 and 65535.\n");
2828
+ }
2829
+ }
2830
+ async function askOptional(prompter, question, current) {
2831
+ const answer = await prompter.ask(question, current);
2832
+ if (answer === "" || answer === CLEAR_ANSWER) {
2833
+ return void 0;
2834
+ }
2835
+ return answer;
2836
+ }
2837
+ async function askOptionalSecret(prompter, question, current) {
2838
+ let suffix = " (empty for none)";
2839
+ if (current != null) {
2840
+ suffix = ` [keep current, ${CLEAR_ANSWER} to clear]`;
2841
+ }
2842
+ const answer = await prompter.askSecret(`${question}${suffix}`);
2843
+ if (answer === CLEAR_ANSWER) {
2844
+ return void 0;
2845
+ }
2846
+ if (answer === "") {
2847
+ return current;
2848
+ }
2849
+ return answer;
2850
+ }
2851
+ async function askHostQuestions(prompter, existing) {
2852
+ if (existing != null) {
2853
+ prompter.write(` Enter keeps the value in brackets; ${CLEAR_ANSWER} clears an optional one.
2854
+
2855
+ `);
2856
+ }
2857
+ const host = await prompter.askRequired("Host (hostname or IP)", existing?.host);
2858
+ const port = await askPort(prompter, "Port", existing?.port ?? DEFAULT_SSH_PORT);
2859
+ const username = await prompter.askRequired("Login user", existing?.username);
2860
+ let name = "";
2861
+ const defaultName = existing?.name ?? `ssh-${host}`.replace(/[^A-Za-z0-9_-]+/g, "-").slice(0, 48);
2862
+ for (; ; ) {
2863
+ name = await prompter.askRequired("Server name the agent sees", defaultName);
2864
+ if (SERVER_NAME_PATTERN.test(name) == true) {
2865
+ break;
2866
+ }
2867
+ prompter.write(" Use letters, digits, '-' and '_' only (max 48) \u2014 the name becomes part of every tool name.\n");
2868
+ }
2869
+ const auth = await prompter.askChoice(
2870
+ "Authentication",
2871
+ [
2872
+ { key: "key", label: "private key file (recommended \u2014 only the path is stored)" },
2873
+ { key: "password", label: "password (stored in the config file in plain text)" },
2874
+ { key: "agent", label: "ssh agent (SSH_AUTH_SOCK / OpenSSH agent pipe)" }
2875
+ ],
2876
+ existing?.auth ?? "key"
2877
+ );
2878
+ let keyPath;
2879
+ let passphrase;
2880
+ let password;
2881
+ if (auth === "key") {
2882
+ let defaultKeyPath = existing?.keyPath;
2883
+ if (defaultKeyPath == null) {
2884
+ defaultKeyPath = DEFAULT_KEY_CANDIDATES.find((candidate) => fs7__default.default.existsSync(expandHomePath(candidate)) == true);
2885
+ }
2886
+ for (; ; ) {
2887
+ keyPath = await prompter.askRequired("Private key path", defaultKeyPath);
2888
+ if (fs7__default.default.existsSync(expandHomePath(keyPath)) == true) {
2889
+ break;
2890
+ }
2891
+ prompter.write(` ${expandHomePath(keyPath)} does not exist.
2892
+ `);
2893
+ const useAnyway = await prompter.askYesNo("Use this path anyway?", false);
2894
+ if (useAnyway == true) {
2895
+ break;
2896
+ }
2897
+ }
2898
+ passphrase = await askOptionalSecret(prompter, "Key passphrase", existing?.passphrase);
2899
+ }
2900
+ if (auth === "password") {
2901
+ prompter.write(" The password is written into the config file as plain text. A key file is safer.\n");
2902
+ password = await askOptionalSecret(prompter, "Password", existing?.password);
2903
+ if (password == null) {
2904
+ prompter.write(" No password given \u2014 falling back to the ssh agent.\n");
2905
+ }
2906
+ }
2907
+ let jumpHost;
2908
+ let jumpPort;
2909
+ let jumpUser;
2910
+ const viaJump = await prompter.askYesNo("Reach it through a jump host (ssh -J)?", existing?.jumpHost != null);
2911
+ if (viaJump == true) {
2912
+ jumpHost = await prompter.askRequired("Jump host", existing?.jumpHost);
2913
+ jumpPort = await askPort(prompter, "Jump host port", existing?.jumpPort ?? DEFAULT_SSH_PORT);
2914
+ jumpUser = await prompter.askRequired("Jump host user", existing?.jumpUser ?? username);
2915
+ }
2916
+ let proxyCommand;
2917
+ const viaProxy = await prompter.askYesNo("Start a proxy command for the first hop (e.g. cloudflared)?", existing?.proxyCommand != null);
2918
+ if (viaProxy == true) {
2919
+ prompter.write(" %h / %p / %r expand to the first hop's host, port and user.\n");
2920
+ proxyCommand = await prompter.askRequired("Proxy command", existing?.proxyCommand ?? "cloudflared access ssh --hostname %h");
2921
+ }
2922
+ const description = await askOptional(prompter, "Description shown to the agent (what the host is for)", existing?.description);
2923
+ const readonly = await prompter.askYesNo("Read-only? (rejects writes, redirections, uploads)", existing?.readonly ?? false);
2924
+ let currentAllowedPaths;
2925
+ if (existing != null && existing.allowedPaths.length > 0) {
2926
+ currentAllowedPaths = existing.allowedPaths.join(",");
2927
+ }
2928
+ let allowedPaths = [];
2929
+ const allowedPathsAnswer = await askOptional(
2930
+ prompter,
2931
+ "Restrict file tools to these path prefixes (comma-separated, empty = unrestricted)",
2932
+ currentAllowedPaths
2933
+ );
2934
+ if (allowedPathsAnswer != null) {
2935
+ allowedPaths = allowedPathsAnswer.split(",").map((item) => item.trim()).filter((item) => item !== "");
2936
+ }
2937
+ let resolvedAuth = auth;
2938
+ if (auth === "password" && password == null) {
2939
+ resolvedAuth = "agent";
2940
+ }
2941
+ const answers = {
2942
+ name,
2943
+ host,
2944
+ port,
2945
+ username,
2946
+ auth: resolvedAuth,
2947
+ keyPath,
2948
+ passphrase,
2949
+ password,
2950
+ description,
2951
+ jumpHost,
2952
+ jumpPort,
2953
+ jumpUser,
2954
+ proxyCommand,
2955
+ readonly,
2956
+ allowedPaths,
2957
+ extraEnv: existing?.extraEnv ?? {}
2958
+ };
2959
+ if (existing != null && existing.host === host && existing.port === port) {
2960
+ answers.hostKeyFingerprint = existing.hostKeyFingerprint;
2961
+ }
2962
+ if (existing != null && existing.jumpHost === jumpHost && existing.jumpPort === jumpPort) {
2963
+ answers.jumpHostKeyFingerprint = existing.jumpHostKeyFingerprint;
2964
+ }
2965
+ return answers;
2966
+ }
2967
+ function toMcpServerEntry(value) {
2968
+ if (typeof value !== "object" || value == null) {
2969
+ return null;
2970
+ }
2971
+ const record = value;
2972
+ if (typeof record.command !== "string") {
2973
+ return null;
2974
+ }
2975
+ let args = [];
2976
+ if (Array.isArray(record.args) == true) {
2977
+ args = record.args.filter((item) => typeof item === "string");
2978
+ }
2979
+ const env = {};
2980
+ if (typeof record.env === "object" && record.env != null) {
2981
+ for (const [key, item] of Object.entries(record.env)) {
2982
+ if (typeof item === "string") {
2983
+ env[key] = item;
2984
+ }
2985
+ }
2986
+ }
2987
+ return { command: record.command, args, env };
2988
+ }
2989
+ function readMcpServersJson(document) {
2990
+ if (typeof document !== "object" || document == null || Array.isArray(document) == true) {
2991
+ throw new Error("the config file is not a JSON object");
2992
+ }
2993
+ const entries = {};
2994
+ const servers = document.mcpServers;
2995
+ if (typeof servers !== "object" || servers == null) {
2996
+ return entries;
2997
+ }
2998
+ for (const [name, value] of Object.entries(servers)) {
2999
+ const entry = toMcpServerEntry(value);
3000
+ if (entry != null) {
3001
+ entries[name] = entry;
3002
+ }
3003
+ }
3004
+ return entries;
3005
+ }
3006
+ function readDocument(filePath) {
3007
+ if (fs7__default.default.existsSync(filePath) == false) {
3008
+ return {};
3009
+ }
3010
+ const text = fs7__default.default.readFileSync(filePath, "utf8");
3011
+ if (text.trim() === "") {
3012
+ return {};
3013
+ }
3014
+ let document;
3015
+ try {
3016
+ document = JSON.parse(text);
3017
+ } catch (ex) {
3018
+ let detail = String(ex);
3019
+ if (ex instanceof Error) {
3020
+ detail = ex.message;
3021
+ }
3022
+ throw new Error(`${filePath} is not valid JSON: ${detail}`);
3023
+ }
3024
+ if (typeof document !== "object" || document == null || Array.isArray(document) == true) {
3025
+ throw new Error(`${filePath} is not a JSON object`);
3026
+ }
3027
+ return document;
3028
+ }
3029
+ function createJsonFileTarget(options) {
3030
+ const { id, label, filePath } = options;
3031
+ function writeDocument(document) {
3032
+ fs7__default.default.mkdirSync(path__default.default.dirname(filePath), { recursive: true });
3033
+ fs7__default.default.writeFileSync(filePath, `${JSON.stringify(document, null, 4)}
3034
+ `, "utf8");
3035
+ }
3036
+ return {
3037
+ id,
3038
+ label,
3039
+ location: filePath,
3040
+ detected: fs7__default.default.existsSync(filePath),
3041
+ readEntries() {
3042
+ const document = readDocument(filePath);
3043
+ return readMcpServersJson(document);
3044
+ },
3045
+ writeEntry(name, entry) {
3046
+ const document = readDocument(filePath);
3047
+ let servers = document.mcpServers;
3048
+ if (typeof servers !== "object" || servers == null || Array.isArray(servers) == true) {
3049
+ servers = {};
3050
+ }
3051
+ servers[name] = entry;
3052
+ document.mcpServers = servers;
3053
+ writeDocument(document);
3054
+ return { status: "written", detail: filePath };
3055
+ },
3056
+ removeEntry(name) {
3057
+ const document = readDocument(filePath);
3058
+ const servers = document.mcpServers;
3059
+ if (typeof servers !== "object" || servers == null || Array.isArray(servers) == true) {
3060
+ return { status: "written", detail: filePath };
3061
+ }
3062
+ delete servers[name];
3063
+ writeDocument(document);
3064
+ return { status: "written", detail: filePath };
3065
+ }
3066
+ };
3067
+ }
3068
+
3069
+ // src/modules/manage/targets/claude-code.ts
3070
+ var CLAUDE_CODE_CONFIG_PATH = path__default.default.join(os4__default.default.homedir(), ".claude.json");
3071
+ var CMD_META_CHARACTER_PATTERN = /([()\][%!^"`<>&|;, *?])/g;
3072
+ function toClaudeAddJsonPayload(entry) {
3073
+ return JSON.stringify({ type: "stdio", command: entry.command, args: entry.args, env: entry.env });
3074
+ }
3075
+ function formatClaudeAddCommand(name, entry) {
3076
+ const payload = toClaudeAddJsonPayload(entry);
3077
+ return `claude mcp add-json ${name} '${payload}' -s user`;
3078
+ }
3079
+ function escapeCmdArgument(argument) {
3080
+ let escaped = argument.replace(/(\\*)"/g, '$1$1\\"');
3081
+ escaped = escaped.replace(/(\\*)$/, "$1$1");
3082
+ escaped = `"${escaped}"`;
3083
+ escaped = escaped.replace(CMD_META_CHARACTER_PATTERN, "^$1");
3084
+ escaped = escaped.replace(CMD_META_CHARACTER_PATTERN, "^$1");
3085
+ return escaped;
3086
+ }
3087
+ function runCliCommand(executable, args) {
3088
+ const isBatchShim = /\.(cmd|bat)$/i.test(executable) == true;
3089
+ if (process.platform !== "win32" || isBatchShim == false) {
3090
+ const result2 = child_process.spawnSync(executable, args, { encoding: "utf8", windowsHide: true });
3091
+ return result2;
3092
+ }
3093
+ const commandLine = [executable.replace(CMD_META_CHARACTER_PATTERN, "^$1"), ...args.map(escapeCmdArgument)].join(" ");
3094
+ const result = child_process.spawnSync(process.env.ComSpec ?? "cmd.exe", ["/d", "/s", "/c", `"${commandLine}"`], {
3095
+ encoding: "utf8",
3096
+ windowsHide: true,
3097
+ windowsVerbatimArguments: true
3098
+ });
3099
+ return result;
3100
+ }
3101
+ function runClaude(executable, args) {
3102
+ const result = runCliCommand(executable, args);
3103
+ if (result.error != null) {
3104
+ return { status: "unavailable", detail: `could not run claude: ${result.error.message}` };
3105
+ }
3106
+ if (result.status !== 0) {
3107
+ let output = (result.stderr ?? "").trim();
3108
+ if (output === "") {
3109
+ output = (result.stdout ?? "").trim();
3110
+ }
3111
+ return { status: "unavailable", detail: `claude exited with ${result.status}: ${output}` };
3112
+ }
3113
+ return { status: "written", detail: CLAUDE_CODE_CONFIG_PATH };
3114
+ }
3115
+ function readClaudeEntries() {
3116
+ if (fs7__default.default.existsSync(CLAUDE_CODE_CONFIG_PATH) == false) {
3117
+ return {};
3118
+ }
3119
+ const text = fs7__default.default.readFileSync(CLAUDE_CODE_CONFIG_PATH, "utf8");
3120
+ let document;
3121
+ try {
3122
+ document = JSON.parse(text);
3123
+ } catch (ex) {
3124
+ let detail = String(ex);
3125
+ if (ex instanceof Error) {
3126
+ detail = ex.message;
3127
+ }
3128
+ throw new Error(`${CLAUDE_CODE_CONFIG_PATH} is not valid JSON: ${detail}`);
3129
+ }
3130
+ return readMcpServersJson(document);
3131
+ }
3132
+ function createClaudeCodeTarget() {
3133
+ const executable = findExecutable("claude");
3134
+ return {
3135
+ id: "claude-code",
3136
+ label: "Claude Code (user scope)",
3137
+ location: CLAUDE_CODE_CONFIG_PATH,
3138
+ detected: executable != null || fs7__default.default.existsSync(CLAUDE_CODE_CONFIG_PATH) == true,
3139
+ readEntries: readClaudeEntries,
3140
+ writeEntry(name, entry) {
3141
+ if (executable == null) {
3142
+ return {
3143
+ status: "unavailable",
3144
+ detail: `the claude CLI is not on PATH \u2014 run this yourself:
3145
+ ${formatClaudeAddCommand(name, entry)}`
3146
+ };
3147
+ }
3148
+ const previous = readClaudeEntries()[name];
3149
+ if (previous != null) {
3150
+ const removed = runClaude(executable, ["mcp", "remove", name, "-s", "user"]);
3151
+ if (removed.status === "unavailable") {
3152
+ return removed;
3153
+ }
3154
+ }
3155
+ const added = runClaude(executable, ["mcp", "add-json", name, toClaudeAddJsonPayload(entry), "-s", "user"]);
3156
+ if (added.status === "unavailable" && previous != null) {
3157
+ runClaude(executable, ["mcp", "add-json", name, toClaudeAddJsonPayload(previous), "-s", "user"]);
3158
+ return { status: "unavailable", detail: `${added.detail}
3159
+ the previous entry was restored` };
3160
+ }
3161
+ return added;
3162
+ },
3163
+ removeEntry(name) {
3164
+ if (executable == null) {
3165
+ return {
3166
+ status: "unavailable",
3167
+ detail: `the claude CLI is not on PATH \u2014 run this yourself:
3168
+ claude mcp remove ${name} -s user`
3169
+ };
3170
+ }
3171
+ return runClaude(executable, ["mcp", "remove", name, "-s", "user"]);
3172
+ }
3173
+ };
3174
+ }
3175
+
3176
+ // src/modules/manage/targets/toml-subset.ts
3177
+ var BARE_KEY_PATTERN = /^[A-Za-z0-9_-]+$/;
3178
+ var ANY_HEADER_PATTERN = /^\s*\[/;
3179
+ var SERVER_HEADER_PATTERN = /^\s*\[\s*mcp_servers\s*\.\s*([A-Za-z0-9_-]+|"(?:[^"\\]|\\.)*")\s*((?:\.[^\]]*)?)\]\s*(?:#.*)?$/;
3180
+ var KEY_VALUE_PATTERN = /^\s*([A-Za-z0-9_-]+|"(?:[^"\\]|\\.)*")\s*=\s*(.*)$/;
3181
+ var OWNED_TABLE_KEYS = ["command", "args", "env"];
3182
+ var TomlValueParser = class {
3183
+ constructor(text) {
3184
+ this.text = text;
3185
+ this.position = 0;
3186
+ }
3187
+ parse() {
3188
+ const value = this.parseValue();
3189
+ return value;
3190
+ }
3191
+ skipWhitespace() {
3192
+ while (this.position < this.text.length && /\s/.test(this.text[this.position]) == true) {
3193
+ this.position += 1;
3194
+ }
3195
+ }
3196
+ parseValue() {
3197
+ this.skipWhitespace();
3198
+ const current = this.text[this.position];
3199
+ if (current === '"') {
3200
+ return this.parseBasicString();
3201
+ }
3202
+ if (current === "'") {
3203
+ return this.parseLiteralString();
3204
+ }
3205
+ if (current === "[") {
3206
+ return this.parseArray();
3207
+ }
3208
+ if (current === "{") {
3209
+ return this.parseInlineTable();
3210
+ }
3211
+ throw new Error(`unsupported toml value at offset ${this.position}`);
3212
+ }
3213
+ parseBasicString() {
3214
+ this.position += 1;
3215
+ let result = "";
3216
+ while (this.position < this.text.length) {
3217
+ const current = this.text[this.position];
3218
+ if (current === '"') {
3219
+ this.position += 1;
3220
+ return result;
3221
+ }
3222
+ if (current !== "\\") {
3223
+ result += current;
3224
+ this.position += 1;
3225
+ continue;
3226
+ }
3227
+ const escaped = this.text[this.position + 1];
3228
+ this.position += 2;
3229
+ if (escaped === "n") {
3230
+ result += "\n";
3231
+ } else if (escaped === "t") {
3232
+ result += " ";
3233
+ } else if (escaped === "r") {
3234
+ result += "\r";
3235
+ } else if (escaped === "u" || escaped === "U") {
3236
+ let length = 4;
3237
+ if (escaped === "U") {
3238
+ length = 8;
3239
+ }
3240
+ const hex = this.text.slice(this.position, this.position + length);
3241
+ result += String.fromCodePoint(Number.parseInt(hex, 16));
3242
+ this.position += length;
3243
+ } else {
3244
+ result += escaped;
3245
+ }
3246
+ }
3247
+ throw new Error("unterminated toml string");
3248
+ }
3249
+ parseLiteralString() {
3250
+ const end = this.text.indexOf("'", this.position + 1);
3251
+ if (end < 0) {
3252
+ throw new Error("unterminated toml literal string");
3253
+ }
3254
+ const result = this.text.slice(this.position + 1, end);
3255
+ this.position = end + 1;
3256
+ return result;
3257
+ }
3258
+ parseArray() {
3259
+ this.position += 1;
3260
+ const items = [];
3261
+ for (; ; ) {
3262
+ this.skipWhitespace();
3263
+ if (this.position >= this.text.length) {
3264
+ throw new Error("unterminated toml array");
3265
+ }
3266
+ if (this.text[this.position] === "]") {
3267
+ this.position += 1;
3268
+ return items;
3269
+ }
3270
+ items.push(this.parseValue());
3271
+ this.skipWhitespace();
3272
+ if (this.text[this.position] === ",") {
3273
+ this.position += 1;
3274
+ }
3275
+ }
3276
+ }
3277
+ parseInlineTable() {
3278
+ this.position += 1;
3279
+ const table = {};
3280
+ for (; ; ) {
3281
+ this.skipWhitespace();
3282
+ if (this.position >= this.text.length) {
3283
+ throw new Error("unterminated toml inline table");
3284
+ }
3285
+ if (this.text[this.position] === "}") {
3286
+ this.position += 1;
3287
+ return table;
3288
+ }
3289
+ let key;
3290
+ if (this.text[this.position] === '"') {
3291
+ key = this.parseBasicString();
3292
+ } else {
3293
+ const match = /^[A-Za-z0-9_-]+/.exec(this.text.slice(this.position));
3294
+ if (match == null) {
3295
+ throw new Error(`invalid inline table key at offset ${this.position}`);
3296
+ }
3297
+ key = match[0];
3298
+ this.position += key.length;
3299
+ }
3300
+ this.skipWhitespace();
3301
+ if (this.text[this.position] !== "=") {
3302
+ throw new Error(`expected '=' at offset ${this.position}`);
3303
+ }
3304
+ this.position += 1;
3305
+ table[key] = this.parseValue();
3306
+ this.skipWhitespace();
3307
+ if (this.text[this.position] === ",") {
3308
+ this.position += 1;
3309
+ }
3310
+ }
3311
+ }
3312
+ };
3313
+ function unquoteKey(rawKey) {
3314
+ if (rawKey.startsWith('"') == false) {
3315
+ return rawKey;
3316
+ }
3317
+ const parsed = new TomlValueParser(rawKey).parse();
3318
+ return parsed;
3319
+ }
3320
+ function bracketBalance(text) {
3321
+ let balance = 0;
3322
+ let quote = null;
3323
+ for (let index = 0; index < text.length; index += 1) {
3324
+ const current = text[index];
3325
+ if (quote != null) {
3326
+ if (current === "\\" && quote === '"') {
3327
+ index += 1;
3328
+ } else if (current === quote) {
3329
+ quote = null;
3330
+ }
3331
+ continue;
3332
+ }
3333
+ if (current === '"' || current === "'") {
3334
+ quote = current;
3335
+ } else if (current === "#") {
3336
+ break;
3337
+ } else if (current === "[" || current === "{") {
3338
+ balance += 1;
3339
+ } else if (current === "]" || current === "}") {
3340
+ balance -= 1;
3341
+ }
3342
+ }
3343
+ return balance;
3344
+ }
3345
+ function stripComment(text) {
3346
+ let quote = null;
3347
+ for (let index = 0; index < text.length; index += 1) {
3348
+ const current = text[index];
3349
+ if (quote != null) {
3350
+ if (current === "\\" && quote === '"') {
3351
+ index += 1;
3352
+ } else if (current === quote) {
3353
+ quote = null;
3354
+ }
3355
+ continue;
3356
+ }
3357
+ if (current === '"' || current === "'") {
3358
+ quote = current;
3359
+ } else if (current === "#") {
3360
+ return text.slice(0, index);
3361
+ }
3362
+ }
3363
+ return text;
3364
+ }
3365
+ function readStatements(body) {
3366
+ const statements = [];
3367
+ let index = 0;
3368
+ while (index < body.length) {
3369
+ const match = KEY_VALUE_PATTERN.exec(body[index]);
3370
+ if (match == null) {
3371
+ index += 1;
3372
+ continue;
3373
+ }
3374
+ const start = index;
3375
+ let rawValue = stripComment(match[2]);
3376
+ let balance = bracketBalance(rawValue);
3377
+ index += 1;
3378
+ while (balance > 0 && index < body.length) {
3379
+ const continuation = stripComment(body[index]);
3380
+ rawValue += `
3381
+ ${continuation}`;
3382
+ balance += bracketBalance(continuation);
3383
+ index += 1;
3384
+ }
3385
+ statements.push({ key: unquoteKey(match[1]), rawValue, start, end: index });
3386
+ }
3387
+ return statements;
3388
+ }
3389
+ function splitSections(lines) {
3390
+ const sections = [{ header: null, serverName: null, subPath: "", body: [] }];
3391
+ let balance = 0;
3392
+ for (const line of lines) {
3393
+ const current = sections[sections.length - 1];
3394
+ if (balance > 0) {
3395
+ current.body.push(line);
3396
+ balance += bracketBalance(stripComment(line));
3397
+ continue;
3398
+ }
3399
+ if (ANY_HEADER_PATTERN.test(line) == true) {
3400
+ const serverMatch = SERVER_HEADER_PATTERN.exec(line);
3401
+ let serverName = null;
3402
+ let subPath = "";
3403
+ if (serverMatch != null) {
3404
+ serverName = unquoteKey(serverMatch[1]);
3405
+ subPath = serverMatch[2].replace(/^\./, "").replace(/\s+/g, "");
3406
+ }
3407
+ sections.push({ header: line, serverName, subPath, body: [] });
3408
+ continue;
3409
+ }
3410
+ current.body.push(line);
3411
+ const keyValueMatch = KEY_VALUE_PATTERN.exec(line);
3412
+ if (keyValueMatch != null) {
3413
+ balance = bracketBalance(stripComment(keyValueMatch[2]));
3414
+ }
3415
+ }
3416
+ return sections;
3417
+ }
3418
+ function parseStatementValue(statement) {
3419
+ try {
3420
+ const value = new TomlValueParser(statement.rawValue).parse();
3421
+ return value;
3422
+ } catch {
3423
+ return null;
3424
+ }
3425
+ }
3426
+ function parseMcpServersToml(text) {
3427
+ const sections = splitSections(text.split(/\r?\n/));
3428
+ const entries = {};
3429
+ const envTables = {};
3430
+ for (const section of sections) {
3431
+ if (section.serverName == null) {
3432
+ continue;
3433
+ }
3434
+ if (section.subPath === "env") {
3435
+ const envTable = {};
3436
+ for (const statement of readStatements(section.body)) {
3437
+ const value = parseStatementValue(statement);
3438
+ if (typeof value === "string") {
3439
+ envTable[statement.key] = value;
3440
+ }
3441
+ }
3442
+ envTables[section.serverName] = envTable;
3443
+ continue;
3444
+ }
3445
+ if (section.subPath !== "") {
3446
+ continue;
3447
+ }
3448
+ let command = null;
3449
+ let args = [];
3450
+ const env = {};
3451
+ for (const statement of readStatements(section.body)) {
3452
+ const value = parseStatementValue(statement);
3453
+ if (statement.key === "command" && typeof value === "string") {
3454
+ command = value;
3455
+ } else if (statement.key === "args" && Array.isArray(value) == true) {
3456
+ args = value.filter((item) => typeof item === "string");
3457
+ } else if (statement.key === "env" && value != null && typeof value === "object" && Array.isArray(value) == false) {
3458
+ for (const [key, item] of Object.entries(value)) {
3459
+ if (typeof item === "string") {
3460
+ env[key] = item;
3461
+ }
3462
+ }
3463
+ }
3464
+ }
3465
+ if (command != null) {
3466
+ entries[section.serverName] = { command, args, env };
3467
+ }
3468
+ }
3469
+ for (const [name, envTable] of Object.entries(envTables)) {
3470
+ if (entries[name] != null) {
3471
+ Object.assign(entries[name].env, envTable);
3472
+ }
3473
+ }
3474
+ return entries;
3475
+ }
3476
+ function quoteTomlString(value) {
3477
+ const escaped = value.replace(/\\/g, "\\\\").replace(/"/g, '\\"').replace(/\n/g, "\\n").replace(/\r/g, "\\r").replace(/\t/g, "\\t");
3478
+ return `"${escaped}"`;
3479
+ }
3480
+ function formatTomlKey(key) {
3481
+ if (BARE_KEY_PATTERN.test(key) == true) {
3482
+ return key;
3483
+ }
3484
+ return quoteTomlString(key);
3485
+ }
3486
+ function renderOwnedLines(entry) {
3487
+ return [
3488
+ `command = ${quoteTomlString(entry.command)}`,
3489
+ `args = [${entry.args.map((argument) => quoteTomlString(argument)).join(", ")}]`
3490
+ ];
3491
+ }
3492
+ function renderEnvLines(entry) {
3493
+ return Object.entries(entry.env).map(([key, value]) => `${formatTomlKey(key)} = ${quoteTomlString(value)}`);
3494
+ }
3495
+ function renderMcpServerTable(name, entry) {
3496
+ const tableKey = formatTomlKey(name);
3497
+ const lines = [`[mcp_servers.${tableKey}]`, ...renderOwnedLines(entry)];
3498
+ const envLines = renderEnvLines(entry);
3499
+ if (envLines.length > 0) {
3500
+ lines.push("");
3501
+ lines.push(`[mcp_servers.${tableKey}.env]`);
3502
+ lines.push(...envLines);
3503
+ }
3504
+ return `${lines.join("\n")}
3505
+ `;
3506
+ }
3507
+ function isBlank(line) {
3508
+ return line.trim() === "";
3509
+ }
3510
+ function joinSections(sections, eol) {
3511
+ const lines = [];
3512
+ for (const section of sections) {
3513
+ if (section.header != null) {
3514
+ lines.push(section.header);
3515
+ }
3516
+ lines.push(...section.body);
3517
+ }
3518
+ return lines.join(eol);
3519
+ }
3520
+ function writeMcpServerToml(text, name, entry) {
3521
+ let eol = "\n";
3522
+ if (text.includes("\r\n") == true) {
3523
+ eol = "\r\n";
3524
+ }
3525
+ const sections = splitSections(text.split(/\r?\n/));
3526
+ const isOwn = (section) => section.serverName === name;
3527
+ if (entry == null) {
3528
+ const kept = sections.filter((section) => isOwn(section) == false);
3529
+ const removedText = joinSections(kept, eol);
3530
+ return removedText;
3531
+ }
3532
+ const tableKey = formatTomlKey(name);
3533
+ const envLines = renderEnvLines(entry);
3534
+ const tableIndex = sections.findIndex((section) => isOwn(section) == true && section.subPath === "");
3535
+ if (tableIndex < 0) {
3536
+ const withoutStrayEnv = sections.filter((section) => (isOwn(section) == true && section.subPath === "env") == false);
3537
+ let prefix = joinSections(withoutStrayEnv, eol);
3538
+ if (prefix.trim() === "") {
3539
+ prefix = "";
3540
+ } else {
3541
+ prefix = prefix.replace(/(\r?\n)*$/, "");
3542
+ prefix = `${prefix}${eol}${eol}`;
3543
+ }
3544
+ const block = renderMcpServerTable(name, entry).replace(/\n/g, eol);
3545
+ return `${prefix}${block}`;
3546
+ }
3547
+ const table = sections[tableIndex];
3548
+ const ownedLineIndexes = /* @__PURE__ */ new Set();
3549
+ for (const statement of readStatements(table.body)) {
3550
+ if (OWNED_TABLE_KEYS.includes(statement.key) == true) {
3551
+ for (let index = statement.start; index < statement.end; index += 1) {
3552
+ ownedLineIndexes.add(index);
3553
+ }
3554
+ }
3555
+ }
3556
+ const userLines = table.body.filter((_line, index) => ownedLineIndexes.has(index) == false);
3557
+ let trailingBlankCount = 0;
3558
+ while (trailingBlankCount < userLines.length && isBlank(userLines[userLines.length - 1 - trailingBlankCount]) == true) {
3559
+ trailingBlankCount += 1;
3560
+ }
3561
+ const trailingBlanks = userLines.slice(userLines.length - trailingBlankCount);
3562
+ const userContent = userLines.slice(0, userLines.length - trailingBlankCount);
3563
+ const rebuilt = [];
3564
+ for (let index = 0; index < sections.length; index += 1) {
3565
+ const section = sections[index];
3566
+ if (isOwn(section) == true && section.subPath === "env") {
3567
+ continue;
3568
+ }
3569
+ if (index !== tableIndex) {
3570
+ rebuilt.push(section);
3571
+ continue;
3572
+ }
3573
+ if (envLines.length === 0) {
3574
+ rebuilt.push({ ...section, body: [...renderOwnedLines(entry), ...userContent, ...trailingBlanks] });
3575
+ continue;
3576
+ }
3577
+ rebuilt.push({ ...section, body: [...renderOwnedLines(entry), ...userContent, ""] });
3578
+ rebuilt.push({
3579
+ header: `[mcp_servers.${tableKey}.env]`,
3580
+ serverName: name,
3581
+ subPath: "env",
3582
+ body: [...envLines, ...trailingBlanks]
3583
+ });
3584
+ }
3585
+ const rebuiltText = joinSections(rebuilt, eol);
3586
+ return rebuiltText;
3587
+ }
3588
+
3589
+ // src/modules/manage/targets/codex.ts
3590
+ var CODEX_CONFIG_PATH = path__default.default.join(os4__default.default.homedir(), ".codex", "config.toml");
3591
+ function createCodexTarget() {
3592
+ function readText() {
3593
+ if (fs7__default.default.existsSync(CODEX_CONFIG_PATH) == false) {
3594
+ return "";
3595
+ }
3596
+ return fs7__default.default.readFileSync(CODEX_CONFIG_PATH, "utf8");
3597
+ }
3598
+ function writeText(text) {
3599
+ fs7__default.default.mkdirSync(path__default.default.dirname(CODEX_CONFIG_PATH), { recursive: true });
3600
+ fs7__default.default.writeFileSync(CODEX_CONFIG_PATH, text, "utf8");
3601
+ return { status: "written", detail: CODEX_CONFIG_PATH };
3602
+ }
3603
+ return {
3604
+ id: "codex",
3605
+ label: "Codex CLI",
3606
+ location: CODEX_CONFIG_PATH,
3607
+ detected: findExecutable("codex") != null || fs7__default.default.existsSync(CODEX_CONFIG_PATH) == true,
3608
+ readEntries() {
3609
+ const text = readText();
3610
+ return parseMcpServersToml(text);
3611
+ },
3612
+ writeEntry(name, entry) {
3613
+ const text = readText();
3614
+ const updated = writeMcpServerToml(text, name, entry);
3615
+ return writeText(updated);
3616
+ },
3617
+ removeEntry(name) {
3618
+ const text = readText();
3619
+ const updated = writeMcpServerToml(text, name, null);
3620
+ return writeText(updated);
3621
+ }
3622
+ };
1991
3623
  }
1992
- function readIntegerEnv(name) {
1993
- const value = readEnv(name);
1994
- if (value == null) {
1995
- return void 0;
3624
+
3625
+ // src/modules/manage/targets/index.ts
3626
+ function claudeDesktopConfigPath() {
3627
+ if (process.platform === "win32") {
3628
+ const appData = process.env.APPDATA ?? path__default.default.join(os4__default.default.homedir(), "AppData", "Roaming");
3629
+ return path__default.default.join(appData, "Claude", "claude_desktop_config.json");
1996
3630
  }
1997
- const parsed = Number(value);
1998
- if (Number.isInteger(parsed) == false || parsed <= 0) {
1999
- throw new Error(`${name} must be a positive integer (got "${value}")`);
3631
+ if (process.platform === "darwin") {
3632
+ return path__default.default.join(os4__default.default.homedir(), "Library", "Application Support", "Claude", "claude_desktop_config.json");
2000
3633
  }
2001
- return parsed;
3634
+ return path__default.default.join(os4__default.default.homedir(), ".config", "Claude", "claude_desktop_config.json");
2002
3635
  }
2003
- function readListEnv(name) {
2004
- const value = readEnv(name);
2005
- if (value == null) {
2006
- return void 0;
3636
+ function listConfigTargets() {
3637
+ const targets = [
3638
+ createClaudeCodeTarget(),
3639
+ createCodexTarget(),
3640
+ createJsonFileTarget({ id: "claude-desktop", label: "Claude Desktop", filePath: claudeDesktopConfigPath() }),
3641
+ createJsonFileTarget({ id: "cursor", label: "Cursor", filePath: path__default.default.join(os4__default.default.homedir(), ".cursor", "mcp.json") })
3642
+ ];
3643
+ const detected = targets.filter((target) => target.detected == true);
3644
+ const others = targets.filter((target) => target.detected == false);
3645
+ return [...detected, ...others];
3646
+ }
3647
+
3648
+ // src/modules/manage/index.ts
3649
+ var SECRET_ENV_NAMES = [
3650
+ SINGLE_HOST_ENV.PASSWORD,
3651
+ SINGLE_HOST_ENV.PASSPHRASE,
3652
+ SINGLE_HOST_ENV.JUMP_PASSWORD,
3653
+ SINGLE_HOST_ENV.JUMP_PASSPHRASE
3654
+ ];
3655
+ function errorMessage(error) {
3656
+ if (error instanceof Error) {
3657
+ return error.message;
2007
3658
  }
2008
- const items = value.split(",").map((item) => item.trim()).filter((item) => item !== "");
2009
- if (items.length === 0) {
2010
- return void 0;
3659
+ return String(error);
3660
+ }
3661
+ function maskSecrets(entry) {
3662
+ const env = {};
3663
+ for (const [name, value] of Object.entries(entry.env)) {
3664
+ if (SECRET_ENV_NAMES.includes(name) == true) {
3665
+ env[name] = "********";
3666
+ continue;
3667
+ }
3668
+ env[name] = value;
2011
3669
  }
2012
- return items;
3670
+ return { ...entry, env };
2013
3671
  }
2014
- function compileDenyPatterns(sources) {
2015
- return sources.map((source) => {
2016
- try {
2017
- return new RegExp(source, "i");
2018
- } catch (ex) {
2019
- const _logger = $logger.child({ context: "compileDenyPatterns" });
2020
- _logger.error(ex, "denyPatterns entry is not a valid regular expression");
2021
- let detail = String(ex);
2022
- if (ex instanceof Error) {
2023
- detail = ex.message;
3672
+ function formatForTarget(target, name, entry) {
3673
+ if (target.id === "codex") {
3674
+ return renderMcpServerTable(name, entry);
3675
+ }
3676
+ return `"${name}": ${JSON.stringify(entry, null, 4)}
3677
+ `;
3678
+ }
3679
+ function indent(text) {
3680
+ return text.replace(/\n$/, "").split("\n").map((line) => ` ${line}`).join("\n");
3681
+ }
3682
+ function reportWrite(output, result, action) {
3683
+ if (result.status === "written") {
3684
+ output.write(` ${action} \u2014 ${result.detail}
3685
+ `);
3686
+ output.write(" Restart the client (or reconnect it from its MCP menu) to pick up the change.\n\n");
3687
+ return;
3688
+ }
3689
+ output.write(` Not ${action.toLowerCase()}: ${result.detail}
3690
+
3691
+ `);
3692
+ }
3693
+ function profileFromEntry(output, entry) {
3694
+ try {
3695
+ const profile = loadHostProfile(entry.env);
3696
+ if (profile == null) {
3697
+ output.write(" The entry has no host.\n");
3698
+ }
3699
+ return profile;
3700
+ } catch (ex) {
3701
+ output.write(` The server would refuse to start with this entry: ${errorMessage(ex)}
3702
+ `);
3703
+ return null;
3704
+ }
3705
+ }
3706
+ async function verifyAnswers(prompter, output, initial) {
3707
+ let answers = initial;
3708
+ for (; ; ) {
3709
+ const testNow = await prompter.askYesNo("Test the connection now?", true);
3710
+ if (testNow == false) {
3711
+ return answers;
3712
+ }
3713
+ output.write("\n");
3714
+ const profile = profileFromEntry(output, answersToEntry(answers));
3715
+ if (profile != null) {
3716
+ const result = await runConnectionCheck(profile, output);
3717
+ output.write("\n");
3718
+ if (result.connected == true) {
3719
+ if (result.hostKeyFingerprint != null && answers.hostKeyFingerprint == null) {
3720
+ const pin = await prompter.askYesNo(`Pin the host key ${result.hostKeyFingerprint}? (a changed key then aborts the connection)`, true);
3721
+ if (pin == true) {
3722
+ answers = { ...answers, hostKeyFingerprint: result.hostKeyFingerprint };
3723
+ }
3724
+ }
3725
+ if (result.jumpHostKeyFingerprint != null && answers.jumpHost != null && answers.jumpHostKeyFingerprint == null) {
3726
+ const pin = await prompter.askYesNo(`Pin the jump host key ${result.jumpHostKeyFingerprint}?`, true);
3727
+ if (pin == true) {
3728
+ answers = { ...answers, jumpHostKeyFingerprint: result.jumpHostKeyFingerprint };
3729
+ }
3730
+ }
3731
+ return answers;
3732
+ }
3733
+ const hostKeyChanged = result.hostKeyFingerprint != null && answers.hostKeyFingerprint != null && result.hostKeyFingerprint !== answers.hostKeyFingerprint;
3734
+ if (hostKeyChanged == true) {
3735
+ output.write(" The host presented a different key than the pinned one. Re-pin only if you know it was rebuilt.\n");
3736
+ const repin = await prompter.askYesNo(`Pin ${result.hostKeyFingerprint} instead?`, false);
3737
+ if (repin == true) {
3738
+ answers = { ...answers, hostKeyFingerprint: result.hostKeyFingerprint ?? void 0 };
3739
+ continue;
3740
+ }
3741
+ }
3742
+ const jumpKeyChanged = result.jumpHostKeyFingerprint != null && answers.jumpHostKeyFingerprint != null && result.jumpHostKeyFingerprint !== answers.jumpHostKeyFingerprint;
3743
+ if (jumpKeyChanged == true) {
3744
+ output.write(" The jump host presented a different key than the pinned one. Re-pin only if you know it was rebuilt.\n");
3745
+ const repin = await prompter.askYesNo(`Pin ${result.jumpHostKeyFingerprint} instead?`, false);
3746
+ if (repin == true) {
3747
+ answers = { ...answers, jumpHostKeyFingerprint: result.jumpHostKeyFingerprint ?? void 0 };
3748
+ continue;
3749
+ }
2024
3750
  }
2025
- throw new Error(`${SINGLE_HOST_ENV.DENY_PATTERNS} has an invalid entry /${source}/: ${detail}`);
2026
3751
  }
2027
- });
3752
+ const next = await prompter.askChoice(
3753
+ "What now?",
3754
+ [
3755
+ { key: "r", label: "retry the check" },
3756
+ { key: "e", label: "edit the answers" },
3757
+ { key: "w", label: "write it anyway" },
3758
+ { key: "c", label: "cancel" }
3759
+ ],
3760
+ "e"
3761
+ );
3762
+ if (next === "c") {
3763
+ return null;
3764
+ }
3765
+ if (next === "w") {
3766
+ return answers;
3767
+ }
3768
+ if (next === "e") {
3769
+ output.write("\n");
3770
+ answers = await askHostQuestions(prompter, answers);
3771
+ }
3772
+ }
2028
3773
  }
2029
- function loadHostProfile() {
2030
- const host = readEnv(SINGLE_HOST_ENV.HOST);
2031
- if (host == null) {
2032
- const _startupLogger = $logger.child({ context: "loadHostProfile" });
2033
- _startupLogger.warn("no host is registered; set the connection variables and restart", {
2034
- env_vars: [SINGLE_HOST_ENV.HOST, SINGLE_HOST_ENV.USER]
2035
- });
3774
+ async function addOrEditHost(prompter, output, target, entries, existingName) {
3775
+ let existing;
3776
+ if (existingName != null) {
3777
+ existing = entryToAnswers(existingName, entries[existingName]);
3778
+ output.write(`
3779
+ Editing ${existingName}
3780
+ `);
3781
+ } else {
3782
+ output.write("\nAdding a host\n");
3783
+ }
3784
+ const asked = await askHostQuestions(prompter, existing);
3785
+ output.write("\n");
3786
+ const answers = await verifyAnswers(prompter, output, asked);
3787
+ if (answers == null) {
3788
+ output.write(" Cancelled \u2014 nothing was written.\n\n");
3789
+ return;
3790
+ }
3791
+ if (answers.name !== existingName && entries[answers.name] != null) {
3792
+ const replace = await prompter.askYesNo(`"${answers.name}" already exists in this file. Replace it?`, false);
3793
+ if (replace == false) {
3794
+ output.write(" Cancelled \u2014 nothing was written.\n\n");
3795
+ return;
3796
+ }
3797
+ }
3798
+ const entry = answersToEntry(answers);
3799
+ output.write(`
3800
+ This goes into ${target.location}:
3801
+
3802
+ `);
3803
+ output.write(`${indent(formatForTarget(target, answers.name, maskSecrets(entry)))}
3804
+
3805
+ `);
3806
+ const confirmed = await prompter.askYesNo("Write it?", true);
3807
+ if (confirmed == false) {
3808
+ output.write(" Not written. The print view (p) gives the same entry ready to paste.\n\n");
3809
+ return;
3810
+ }
3811
+ const written = target.writeEntry(answers.name, entry);
3812
+ reportWrite(output, written, "Written");
3813
+ if (written.status === "written" && existingName != null && existingName !== answers.name) {
3814
+ const removed = target.removeEntry(existingName);
3815
+ if (removed.status === "unavailable") {
3816
+ output.write(` The old name ${existingName} is still there: ${removed.detail}
3817
+
3818
+ `);
3819
+ }
3820
+ }
3821
+ }
3822
+ async function checkHost(prompter, output, target, name, entry) {
3823
+ output.write("\n");
3824
+ const profile = profileFromEntry(output, entry);
3825
+ if (profile == null) {
3826
+ output.write("\n");
3827
+ return;
3828
+ }
3829
+ const result = await runConnectionCheck(profile, output);
3830
+ output.write("\n");
3831
+ if (result.connected == false) {
3832
+ return;
3833
+ }
3834
+ const env = { ...entry.env };
3835
+ let changed = false;
3836
+ if (result.hostKeyFingerprint != null && env[SINGLE_HOST_ENV.HOST_KEY] == null) {
3837
+ const pin = await prompter.askYesNo(`Pin the host key ${result.hostKeyFingerprint}?`, true);
3838
+ if (pin == true) {
3839
+ env[SINGLE_HOST_ENV.HOST_KEY] = result.hostKeyFingerprint;
3840
+ changed = true;
3841
+ }
3842
+ }
3843
+ if (result.jumpHostKeyFingerprint != null && env[SINGLE_HOST_ENV.JUMP_HOST_KEY] == null) {
3844
+ const pin = await prompter.askYesNo(`Pin the jump host key ${result.jumpHostKeyFingerprint}?`, true);
3845
+ if (pin == true) {
3846
+ env[SINGLE_HOST_ENV.JUMP_HOST_KEY] = result.jumpHostKeyFingerprint;
3847
+ changed = true;
3848
+ }
3849
+ }
3850
+ if (changed == true) {
3851
+ const written = target.writeEntry(name, { ...entry, env });
3852
+ reportWrite(output, written, "Pinned");
3853
+ }
3854
+ }
3855
+ function printHost(output, name, entry) {
3856
+ output.write('\n JSON \u2014 Claude Desktop, Cursor, .mcp.json (inside "mcpServers"):\n\n');
3857
+ output.write(`${indent(`"${name}": ${JSON.stringify(entry, null, 4)}`)}
3858
+
3859
+ `);
3860
+ output.write(" TOML \u2014 Codex (~/.codex/config.toml):\n\n");
3861
+ output.write(`${indent(renderMcpServerTable(name, entry))}
3862
+
3863
+ `);
3864
+ output.write(" Claude Code CLI (bash / zsh / Git Bash):\n\n");
3865
+ output.write(`${indent(formatClaudeAddCommand(name, entry))}
3866
+
3867
+ `);
3868
+ }
3869
+ async function pickHost(prompter, output, names) {
3870
+ if (names.length === 0) {
3871
+ output.write(" No hosts yet \u2014 add one with a.\n\n");
2036
3872
  return null;
2037
3873
  }
2038
- const username = readEnv(SINGLE_HOST_ENV.USER);
2039
- if (username == null) {
2040
- throw new Error(`${SINGLE_HOST_ENV.HOST} is set, so ${SINGLE_HOST_ENV.USER} is required`);
3874
+ if (names.length === 1) {
3875
+ return names[0];
2041
3876
  }
2042
- const name = readEnv(SINGLE_HOST_ENV.NAME) ?? host;
2043
- const _logger = $logger.child({ context: "loadHostProfile", profile: name });
2044
- const allowCommands = readListEnv(SINGLE_HOST_ENV.ALLOW_COMMANDS) ?? [];
2045
- if (allowCommands.length > 0 && allowCommands.includes("pwd") == false) {
2046
- allowCommands.push("pwd");
3877
+ for (; ; ) {
3878
+ const answer = await prompter.ask("Which host (number or name, empty to go back)");
3879
+ if (answer === "") {
3880
+ return null;
3881
+ }
3882
+ const index = Number(answer);
3883
+ if (Number.isInteger(index) == true && index >= 1 && index <= names.length) {
3884
+ return names[index - 1];
3885
+ }
3886
+ if (names.includes(answer) == true) {
3887
+ return answer;
3888
+ }
3889
+ output.write(` No host "${answer}".
3890
+ `);
2047
3891
  }
2048
- const policy = {
2049
- readonly: readBooleanEnv(SINGLE_HOST_ENV.READONLY) ?? false,
2050
- allowSudo: readBooleanEnv(SINGLE_HOST_ENV.ALLOW_SUDO) ?? true,
2051
- execTimeoutMs: readIntegerEnv(SINGLE_HOST_ENV.EXEC_TIMEOUT_MS) ?? DEFAULT_EXEC_TIMEOUT_MS,
2052
- connectTimeoutMs: readIntegerEnv(SINGLE_HOST_ENV.CONNECT_TIMEOUT_MS) ?? DEFAULT_CONNECT_TIMEOUT_MS,
2053
- maxOutputCharacters: readIntegerEnv(SINGLE_HOST_ENV.MAX_OUTPUT_CHARACTERS) ?? DEFAULT_MAX_OUTPUT_CHARACTERS,
2054
- maxReadFileBytes: readIntegerEnv(SINGLE_HOST_ENV.MAX_READ_FILE_BYTES) ?? DEFAULT_MAX_READ_FILE_BYTES,
2055
- allowCommands,
2056
- denyPatterns: compileDenyPatterns(readListEnv(SINGLE_HOST_ENV.DENY_PATTERNS) ?? []),
2057
- allowedPaths: readListEnv(SINGLE_HOST_ENV.ALLOWED_PATHS) ?? []
2058
- };
2059
- const profile = {
2060
- name,
2061
- host,
2062
- port: readIntegerEnv(SINGLE_HOST_ENV.PORT) ?? DEFAULT_SSH_PORT,
2063
- username,
2064
- description: readEnv(SINGLE_HOST_ENV.DESCRIPTION),
2065
- passphrase: readEnv(SINGLE_HOST_ENV.PASSPHRASE),
2066
- password: readEnv(SINGLE_HOST_ENV.PASSWORD),
2067
- hostKeyFingerprint: readEnv(SINGLE_HOST_ENV.HOST_KEY),
2068
- defaultCwd: readEnv(SINGLE_HOST_ENV.CWD),
2069
- policy
2070
- };
2071
- const keyPath = readEnv(SINGLE_HOST_ENV.KEY);
2072
- if (keyPath != null) {
2073
- const expandedKeyPath = expandHomePath(keyPath);
2074
- profile.privateKeyPath = expandedKeyPath;
2075
- if (fs__default.default.existsSync(expandedKeyPath) == false) {
2076
- _logger.warn(`${SINGLE_HOST_ENV.KEY} does not exist; connections will fail`, {
2077
- private_key_path: expandedKeyPath
2078
- });
3892
+ }
3893
+ function renderHostList(output, target, entries) {
3894
+ const names = Object.keys(entries).filter((name) => isOurEntry(entries[name]) == true);
3895
+ const otherCount = Object.keys(entries).length - names.length;
3896
+ output.write(`
3897
+ ${target.label} \u2014 ${target.location}
3898
+
3899
+ `);
3900
+ if (names.length === 0) {
3901
+ output.write(" No SSH hosts registered here yet.\n");
3902
+ } else {
3903
+ const rows = names.map((name, index) => {
3904
+ const summary = summarizeEntry(entries[name]);
3905
+ return [String(index + 1), name, summary.endpoint, summary.auth, summary.notes];
3906
+ });
3907
+ const header = ["#", "Server", "Endpoint", "Auth", "Notes"];
3908
+ const widths = header.map((title, column) => Math.max(title.length, ...rows.map((row) => row[column].length)));
3909
+ for (const row of [header, ...rows]) {
3910
+ const line = row.map((cell, column) => cell.padEnd(widths[column])).join(" ").trimEnd();
3911
+ output.write(` ${line}
3912
+ `);
2079
3913
  }
2080
3914
  }
2081
- _logger.info("host profile loaded", {
2082
- host,
2083
- port: profile.port,
2084
- username,
2085
- readonly: policy.readonly
2086
- });
2087
- return profile;
3915
+ if (otherCount > 0) {
3916
+ output.write(`
3917
+ ${otherCount} other MCP server(s) in this file are not managed here.
3918
+ `);
3919
+ }
3920
+ output.write("\n");
3921
+ return names;
2088
3922
  }
2089
- function toHostSummary(profile) {
2090
- let authMethod = "agent";
2091
- if (profile.privateKeyPath != null) {
2092
- authMethod = "privateKey";
2093
- } else if (profile.password != null) {
2094
- authMethod = "password";
3923
+ async function runConfigCommand(options) {
3924
+ const { input, output } = options;
3925
+ const targets = options.targets ?? listConfigTargets();
3926
+ let target = targets[0];
3927
+ if (options.targetId != null) {
3928
+ const requested = targets.find((candidate) => candidate.id === options.targetId);
3929
+ if (requested == null) {
3930
+ output.write(`Unknown client "${options.targetId}". One of: ${targets.map((candidate) => candidate.id).join(", ")}
3931
+ `);
3932
+ return 1;
3933
+ }
3934
+ target = requested;
3935
+ }
3936
+ const prompter = new Prompter(input, output);
3937
+ try {
3938
+ for (; ; ) {
3939
+ let entries = {};
3940
+ let names = [];
3941
+ let readable = true;
3942
+ try {
3943
+ entries = target.readEntries();
3944
+ names = renderHostList(output, target, entries);
3945
+ } catch (ex) {
3946
+ readable = false;
3947
+ output.write(`
3948
+ ${target.label} \u2014 ${target.location}
3949
+
3950
+ Cannot read it: ${errorMessage(ex)}
3951
+ Fix the file by hand, or switch to another client.
3952
+
3953
+ `);
3954
+ }
3955
+ let menu = " t) switch client q) quit";
3956
+ if (readable == true && names.length > 0) {
3957
+ menu = " a) add e) edit r) remove c) check p) print t) switch client q) quit";
3958
+ } else if (readable == true) {
3959
+ menu = " a) add t) switch client q) quit";
3960
+ }
3961
+ output.write(`${menu}
3962
+ `);
3963
+ const action = (await prompter.ask("Choice")).toLowerCase();
3964
+ if (action === "q" || action === "quit") {
3965
+ return 0;
3966
+ }
3967
+ if (action === "t") {
3968
+ const picked = await prompter.askChoice(
3969
+ "Which client?",
3970
+ targets.map((candidate) => {
3971
+ let mark = "";
3972
+ if (candidate.detected == true) {
3973
+ mark = " (detected)";
3974
+ }
3975
+ return { key: candidate.id, label: `${candidate.label} \u2014 ${candidate.location}${mark}` };
3976
+ }),
3977
+ target.id
3978
+ );
3979
+ target = targets.find((candidate) => candidate.id === picked) ?? target;
3980
+ continue;
3981
+ }
3982
+ if (readable == false) {
3983
+ output.write(" Not available while the file cannot be read.\n");
3984
+ continue;
3985
+ }
3986
+ try {
3987
+ if (action === "a") {
3988
+ await addOrEditHost(prompter, output, target, entries);
3989
+ continue;
3990
+ }
3991
+ if (action === "e" || action === "r" || action === "c" || action === "p") {
3992
+ const name = await pickHost(prompter, output, names);
3993
+ if (name == null) {
3994
+ continue;
3995
+ }
3996
+ if (action === "e") {
3997
+ await addOrEditHost(prompter, output, target, entries, name);
3998
+ } else if (action === "r") {
3999
+ const remove = await prompter.askYesNo(`Remove ${name} from ${target.location}?`, false);
4000
+ if (remove == true) {
4001
+ reportWrite(output, target.removeEntry(name), "Removed");
4002
+ }
4003
+ } else if (action === "c") {
4004
+ await checkHost(prompter, output, target, name, entries[name]);
4005
+ } else {
4006
+ printHost(output, name, entries[name]);
4007
+ }
4008
+ continue;
4009
+ }
4010
+ output.write(` Unknown choice "${action}".
4011
+ `);
4012
+ } catch (ex) {
4013
+ if (ex instanceof PromptClosedError) {
4014
+ throw ex;
4015
+ }
4016
+ output.write(` Failed: ${errorMessage(ex)}
4017
+
4018
+ `);
4019
+ }
4020
+ }
4021
+ } catch (ex) {
4022
+ if (ex instanceof PromptClosedError) {
4023
+ output.write("\n");
4024
+ return 0;
4025
+ }
4026
+ throw ex;
4027
+ } finally {
4028
+ prompter.close();
2095
4029
  }
2096
- return {
2097
- name: profile.name,
2098
- host: profile.host,
2099
- port: profile.port,
2100
- username: profile.username,
2101
- description: profile.description,
2102
- authMethod,
2103
- readonly: profile.policy.readonly,
2104
- allowSudo: profile.policy.allowSudo,
2105
- allowedPaths: profile.policy.allowedPaths,
2106
- allowCommands: profile.policy.allowCommands
2107
- };
2108
4030
  }
2109
4031
 
2110
4032
  // src/modules/tools/format.ts
@@ -2145,6 +4067,16 @@ function formatHostProfile(profile) {
2145
4067
  if (summary.description != null) {
2146
4068
  lines.push(` ${summary.description}`);
2147
4069
  }
4070
+ const routeParts = [];
4071
+ if (summary.viaProxyCommand == true) {
4072
+ routeParts.push("proxy command");
4073
+ }
4074
+ if (summary.jump != null) {
4075
+ routeParts.push(`jump host ${summary.jump.username}@${summary.jump.host}:${summary.jump.port}`);
4076
+ }
4077
+ if (routeParts.length > 0) {
4078
+ lines.push(` via ${routeParts.join(" \u2192 ")}`);
4079
+ }
2148
4080
  if (summary.allowedPaths.length > 0) {
2149
4081
  lines.push(` file tools limited to: ${summary.allowedPaths.join(", ")} (does not restrict ssh_exec)`);
2150
4082
  }
@@ -2525,7 +4457,7 @@ ${file.content}`);
2525
4457
  const { profile, session: openSession } = resolveProfile(context, { session });
2526
4458
  const resolvedLocalPath = expandHomePath(localPath);
2527
4459
  requirePermittedLocalPath(resolvedLocalPath, "read");
2528
- if (fs__default.default.existsSync(resolvedLocalPath) == false) {
4460
+ if (fs7__default.default.existsSync(resolvedLocalPath) == false) {
2529
4461
  return textResult(`local file not found: ${resolvedLocalPath}`);
2530
4462
  }
2531
4463
  const transferredBytes = await withHostConnection(profile, openSession, async (connection) => {
@@ -2565,7 +4497,7 @@ ${file.content}`);
2565
4497
  const { profile, session: openSession } = resolveProfile(context, { session });
2566
4498
  const resolvedLocalPath = expandHomePath(localPath);
2567
4499
  requirePermittedLocalPath(resolvedLocalPath, "write");
2568
- fs__default.default.mkdirSync(path2__default.default.dirname(resolvedLocalPath), { recursive: true });
4500
+ fs7__default.default.mkdirSync(path__default.default.dirname(resolvedLocalPath), { recursive: true });
2569
4501
  const transferredBytes = await withHostConnection(profile, openSession, async (connection) => {
2570
4502
  return await downloadFile(connection, remotePath, resolvedLocalPath);
2571
4503
  });
@@ -2789,8 +4721,23 @@ function createSshMcpServer() {
2789
4721
 
2790
4722
  // src/cli.ts
2791
4723
  function parseArguments(argv) {
2792
- const parsed = { showHelp: false, showVersion: false, checkOnly: false };
2793
- for (const argument of argv) {
4724
+ const parsed = { showHelp: false, showVersion: false, checkOnly: false, configMode: false };
4725
+ let rest = argv;
4726
+ if (argv[0] === "config") {
4727
+ parsed.configMode = true;
4728
+ rest = argv.slice(1);
4729
+ }
4730
+ for (let index = 0; index < rest.length; index += 1) {
4731
+ const argument = rest[index];
4732
+ if (argument === "--target") {
4733
+ parsed.targetId = rest[index + 1];
4734
+ index += 1;
4735
+ continue;
4736
+ }
4737
+ if (argument.startsWith("--target=") == true) {
4738
+ parsed.targetId = argument.slice("--target=".length);
4739
+ continue;
4740
+ }
2794
4741
  if (argument === "--help" || argument === "-h") {
2795
4742
  parsed.showHelp = true;
2796
4743
  continue;
@@ -2811,10 +4758,18 @@ var HELP_TEXT = [
2811
4758
  "",
2812
4759
  "Usage:",
2813
4760
  " akms-mcp-ssh [--check]",
4761
+ " akms-mcp-ssh config [--target <client>]",
4762
+ "",
4763
+ "Commands:",
4764
+ " config Manage the SSH hosts registered in an MCP client's config \u2014",
4765
+ " list, add, edit, remove, check, print. Asks plain questions,",
4766
+ " so the SSH_* names below never have to be typed.",
2814
4767
  "",
2815
4768
  "Options:",
2816
4769
  " --check Connect to the configured host, report the result, and exit.",
2817
4770
  " Prints the host key fingerprint so it can be pinned.",
4771
+ " --target <id> config: claude-code | codex | claude-desktop | cursor",
4772
+ " (default: the first one installed)",
2818
4773
  " -v, --version Print the version and exit",
2819
4774
  " -h, --help Print this help and exit",
2820
4775
  "",
@@ -2829,6 +4784,11 @@ var HELP_TEXT = [
2829
4784
  ` ${SINGLE_HOST_ENV.NAME} Alias shown to the model; defaults to the hostname`,
2830
4785
  ` ${SINGLE_HOST_ENV.DESCRIPTION} Shown to the model \u2014 say what the host is for`,
2831
4786
  ` ${SINGLE_HOST_ENV.CWD} Directory new sessions start in`,
4787
+ ` ${SINGLE_HOST_ENV.PROXY_COMMAND} Command carrying the SSH stream on its stdin/stdout (OpenSSH ProxyCommand);`,
4788
+ " %h / %p / %r expand to the first hop's host, port and user",
4789
+ ` ${SINGLE_HOST_ENV.JUMP_HOST} Jump host the target is reached through (OpenSSH ProxyJump / -J)`,
4790
+ ` ${SINGLE_HOST_ENV.JUMP_PORT} / ${SINGLE_HOST_ENV.JUMP_USER} / ${SINGLE_HOST_ENV.JUMP_KEY} / ${SINGLE_HOST_ENV.JUMP_PASSPHRASE} / ${SINGLE_HOST_ENV.JUMP_PASSWORD} / ${SINGLE_HOST_ENV.JUMP_HOST_KEY}`,
4791
+ ` Jump host connection; user and key default to ${SINGLE_HOST_ENV.USER} / ${SINGLE_HOST_ENV.KEY}`,
2832
4792
  ` ${SINGLE_HOST_ENV.READONLY} Reject write commands, redirections, uploads (default false)`,
2833
4793
  ` ${SINGLE_HOST_ENV.ALLOW_SUDO} Allow sudo / su / doas (default true)`,
2834
4794
  ` ${SINGLE_HOST_ENV.ALLOW_COMMANDS} Comma-separated allow-list of binaries`,
@@ -2840,60 +4800,14 @@ var HELP_TEXT = [
2840
4800
  "",
2841
4801
  "The server speaks MCP over stdio; run it from an MCP client, not interactively."
2842
4802
  ].join("\n");
2843
- function describeAuth(profile) {
2844
- if (profile.privateKeyPath != null) {
2845
- return `key ${profile.privateKeyPath}`;
2846
- }
2847
- if (profile.password != null) {
2848
- return "password";
2849
- }
2850
- return "ssh agent";
2851
- }
2852
- async function runConnectionCheck(profile) {
4803
+ async function runCheckCommand(profile) {
2853
4804
  if (profile == null) {
2854
- process.stdout.write(`No SSH host is registered \u2014 set ${SINGLE_HOST_ENV.HOST} and ${SINGLE_HOST_ENV.USER}.
4805
+ process.stdout.write(`No SSH host is registered \u2014 set ${SINGLE_HOST_ENV.HOST} and ${SINGLE_HOST_ENV.USER}, or run: akms-mcp-ssh config
2855
4806
  `);
2856
4807
  return 1;
2857
4808
  }
2858
- const endpoint = `${profile.username}@${profile.host}:${profile.port}`;
2859
- const auth = describeAuth(profile);
2860
- process.stdout.write(`Checking ${profile.name} \u2192 ${endpoint}
2861
-
2862
- `);
2863
- const connection = new SshConnection(profile);
2864
- const startedAt = Date.now();
2865
- let connected = false;
2866
- let detail = "";
2867
- try {
2868
- await connection.connect();
2869
- connected = true;
2870
- } catch (ex) {
2871
- detail = String(ex);
2872
- if (ex instanceof Error) {
2873
- detail = ex.message;
2874
- }
2875
- } finally {
2876
- connection.disconnect();
2877
- }
2878
- const durationMs = Date.now() - startedAt;
2879
- if (connected == true) {
2880
- process.stdout.write(` OK ${endpoint} (${auth}, ${durationMs}ms)
2881
- `);
2882
- } else {
2883
- process.stdout.write(` FAILED ${endpoint} (${auth})
2884
- `);
2885
- process.stdout.write(` ${detail}
2886
- `);
2887
- }
2888
- if (connection.hostKeyFingerprint != null) {
2889
- let pinNote = `not pinned \u2014 set ${SINGLE_HOST_ENV.HOST_KEY} to it to detect a changed key`;
2890
- if (profile.hostKeyFingerprint != null) {
2891
- pinNote = "pinned";
2892
- }
2893
- process.stdout.write(` host key ${connection.hostKeyFingerprint} (${pinNote})
2894
- `);
2895
- }
2896
- if (connected == true) {
4809
+ const result = await runConnectionCheck(profile, process.stdout);
4810
+ if (result.connected == true) {
2897
4811
  return 0;
2898
4812
  }
2899
4813
  return 1;
@@ -2911,12 +4825,23 @@ async function main() {
2911
4825
  `);
2912
4826
  return;
2913
4827
  }
4828
+ if (cliArguments.configMode == true) {
4829
+ if (process.env[LOG_LEVEL_ENV] == null) {
4830
+ process.env[LOG_LEVEL_ENV] = "warn";
4831
+ }
4832
+ const exitCode = await runConfigCommand({
4833
+ input: process.stdin,
4834
+ output: process.stdout,
4835
+ targetId: cliArguments.targetId
4836
+ });
4837
+ process.exit(exitCode);
4838
+ }
2914
4839
  if (cliArguments.checkOnly == true && process.env[LOG_LEVEL_ENV] == null) {
2915
- process.env[LOG_LEVEL_ENV] = "silent";
4840
+ process.env[LOG_LEVEL_ENV] = "warn";
2916
4841
  }
2917
4842
  const instance = createSshMcpServer();
2918
4843
  if (cliArguments.checkOnly == true) {
2919
- const exitCode = await runConnectionCheck(instance.profile);
4844
+ const exitCode = await runCheckCommand(instance.profile);
2920
4845
  instance.shutdown();
2921
4846
  process.exit(exitCode);
2922
4847
  }