@akms/mcp-ssh 0.0.3 → 0.1.1

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.js CHANGED
@@ -1,9 +1,11 @@
1
1
  #!/usr/bin/env node
2
2
  import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
3
- import os from 'os';
4
- import path2 from 'path';
3
+ import fs6 from 'fs';
4
+ import os5 from 'os';
5
+ import path from 'path';
6
+ import { spawnSync, spawn } from 'child_process';
5
7
  import { createHash } from 'crypto';
6
- import fs from 'fs';
8
+ import { Duplex } from 'stream';
7
9
  import { StringDecoder } from 'string_decoder';
8
10
  import ssh2 from 'ssh2';
9
11
  import { setInterval, clearInterval } from 'timers';
@@ -23,7 +25,8 @@ var SESSION_SWEEP_INTERVAL_MS = 6e4;
23
25
  var CWD_MARKER = "__AKMS_SSH_CWD__";
24
26
  var MAX_DIRECTORY_ENTRIES = 1e3;
25
27
  var SERVER_NAME = "akms-mcp-ssh";
26
- var SERVER_VERSION = "0.0.3";
28
+ var PACKAGE_NAME = "@akms/mcp-ssh";
29
+ var SERVER_VERSION = "0.1.1";
27
30
 
28
31
  // src/_defs/command-rules.ts
29
32
  var CRITICAL_PATH_PATTERN = new RegExp(
@@ -445,6 +448,22 @@ var SINGLE_HOST_ENV = {
445
448
  DESCRIPTION: "SSH_DESCRIPTION",
446
449
  /** Directory new sessions start in. */
447
450
  CWD: "SSH_CWD",
451
+ /**
452
+ * Command whose stdin/stdout carry the SSH stream, like OpenSSH's `ProxyCommand`.
453
+ * `%h` / `%p` / `%r` expand to the first hop's host, port and user.
454
+ */
455
+ PROXY_COMMAND: "SSH_PROXY_COMMAND",
456
+ /** Presence of this variable routes the connection through a jump host. */
457
+ JUMP_HOST: "SSH_JUMP_HOST",
458
+ JUMP_PORT: "SSH_JUMP_PORT",
459
+ /** Defaults to `SSH_USER`. */
460
+ JUMP_USER: "SSH_JUMP_USER",
461
+ /** Path to the jump host's private key file; defaults to `SSH_KEY`. */
462
+ JUMP_KEY: "SSH_JUMP_KEY",
463
+ JUMP_PASSPHRASE: "SSH_JUMP_PASSPHRASE",
464
+ JUMP_PASSWORD: "SSH_JUMP_PASSWORD",
465
+ /** Pinned jump host key, `SHA256:…`. */
466
+ JUMP_HOST_KEY: "SSH_JUMP_HOST_KEY",
448
467
  READONLY: "SSH_READONLY",
449
468
  ALLOW_SUDO: "SSH_ALLOW_SUDO",
450
469
  /** Comma-separated binary names. */
@@ -571,20 +590,38 @@ function formatBytes(bytes) {
571
590
  const megabytes = bytes / (1024 * 1024);
572
591
  return `${megabytes.toFixed(1)} MB`;
573
592
  }
593
+ function findExecutable(name) {
594
+ const searchPath = process.env.PATH ?? "";
595
+ const directories = searchPath.split(path.delimiter).filter((directory) => directory !== "");
596
+ let suffixes = [""];
597
+ if (process.platform === "win32") {
598
+ const pathExt = process.env.PATHEXT ?? ".COM;.EXE;.BAT;.CMD";
599
+ suffixes = pathExt.split(";").filter((suffix) => suffix !== "");
600
+ }
601
+ for (const directory of directories) {
602
+ for (const suffix of suffixes) {
603
+ const candidate = path.join(directory, `${name}${suffix}`);
604
+ if (fs6.existsSync(candidate) == true && fs6.statSync(candidate).isFile() == true) {
605
+ return candidate;
606
+ }
607
+ }
608
+ }
609
+ return null;
610
+ }
574
611
  function expandHomePath(inputPath) {
575
612
  let expanded = inputPath;
576
613
  if (inputPath === "~") {
577
- expanded = os.homedir();
614
+ expanded = os5.homedir();
578
615
  } else if (inputPath.startsWith("~/") == true || inputPath.startsWith("~\\") == true) {
579
- expanded = path2.join(os.homedir(), inputPath.slice(2));
616
+ expanded = path.join(os5.homedir(), inputPath.slice(2));
580
617
  }
581
- return path2.resolve(expanded);
618
+ return path.resolve(expanded);
582
619
  }
583
620
  function isAbsoluteRemotePath(remotePath) {
584
621
  return remotePath.startsWith("/");
585
622
  }
586
623
  function normalizeRemotePath(remotePath) {
587
- return path2.posix.normalize(remotePath);
624
+ return path.posix.normalize(remotePath);
588
625
  }
589
626
  function isRemotePathWithin(candidate, allowedPrefix) {
590
627
  const normalizedCandidate = normalizeRemotePath(candidate);
@@ -597,6 +634,195 @@ function isRemotePathWithin(candidate, allowedPrefix) {
597
634
  }
598
635
  return normalizedCandidate.startsWith(`${normalizedPrefix}/`);
599
636
  }
637
+ function readEnv(env, name) {
638
+ const value = env[name];
639
+ if (value == null) {
640
+ return void 0;
641
+ }
642
+ const trimmed = value.trim();
643
+ if (trimmed === "") {
644
+ return void 0;
645
+ }
646
+ return trimmed;
647
+ }
648
+ function readBooleanEnv(env, name) {
649
+ const value = readEnv(env, name);
650
+ if (value == null) {
651
+ return void 0;
652
+ }
653
+ const normalized = value.toLowerCase();
654
+ if (TRUTHY_ENV_VALUES.includes(normalized) == true) {
655
+ return true;
656
+ }
657
+ if (FALSY_ENV_VALUES.includes(normalized) == false) {
658
+ throw new Error(`${name} must be one of ${[...TRUTHY_ENV_VALUES, ...FALSY_ENV_VALUES].join(", ")} (got "${value}")`);
659
+ }
660
+ return false;
661
+ }
662
+ function readIntegerEnv(env, name) {
663
+ const value = readEnv(env, name);
664
+ if (value == null) {
665
+ return void 0;
666
+ }
667
+ const parsed = Number(value);
668
+ if (Number.isInteger(parsed) == false || parsed <= 0) {
669
+ throw new Error(`${name} must be a positive integer (got "${value}")`);
670
+ }
671
+ return parsed;
672
+ }
673
+ function readListEnv(env, name) {
674
+ const value = readEnv(env, name);
675
+ if (value == null) {
676
+ return void 0;
677
+ }
678
+ const items = value.split(",").map((item) => item.trim()).filter((item) => item !== "");
679
+ if (items.length === 0) {
680
+ return void 0;
681
+ }
682
+ return items;
683
+ }
684
+ function compileDenyPatterns(sources) {
685
+ return sources.map((source) => {
686
+ try {
687
+ return new RegExp(source, "i");
688
+ } catch (ex) {
689
+ const _logger = $logger.child({ context: "compileDenyPatterns" });
690
+ _logger.error(ex, "denyPatterns entry is not a valid regular expression");
691
+ let detail = String(ex);
692
+ if (ex instanceof Error) {
693
+ detail = ex.message;
694
+ }
695
+ throw new Error(`${SINGLE_HOST_ENV.DENY_PATTERNS} has an invalid entry /${source}/: ${detail}`);
696
+ }
697
+ });
698
+ }
699
+ function loadHostProfile(env = process.env) {
700
+ const host = readEnv(env, SINGLE_HOST_ENV.HOST);
701
+ if (host == null) {
702
+ const _startupLogger = $logger.child({ context: "loadHostProfile" });
703
+ _startupLogger.warn("no host is registered; set the connection variables and restart", {
704
+ env_vars: [SINGLE_HOST_ENV.HOST, SINGLE_HOST_ENV.USER]
705
+ });
706
+ return null;
707
+ }
708
+ const username = readEnv(env, SINGLE_HOST_ENV.USER);
709
+ if (username == null) {
710
+ throw new Error(`${SINGLE_HOST_ENV.HOST} is set, so ${SINGLE_HOST_ENV.USER} is required`);
711
+ }
712
+ const name = readEnv(env, SINGLE_HOST_ENV.NAME) ?? host;
713
+ const _logger = $logger.child({ context: "loadHostProfile", profile: name });
714
+ const allowCommands = readListEnv(env, SINGLE_HOST_ENV.ALLOW_COMMANDS) ?? [];
715
+ if (allowCommands.length > 0 && allowCommands.includes("pwd") == false) {
716
+ allowCommands.push("pwd");
717
+ }
718
+ const policy = {
719
+ readonly: readBooleanEnv(env, SINGLE_HOST_ENV.READONLY) ?? false,
720
+ allowSudo: readBooleanEnv(env, SINGLE_HOST_ENV.ALLOW_SUDO) ?? true,
721
+ execTimeoutMs: readIntegerEnv(env, SINGLE_HOST_ENV.EXEC_TIMEOUT_MS) ?? DEFAULT_EXEC_TIMEOUT_MS,
722
+ connectTimeoutMs: readIntegerEnv(env, SINGLE_HOST_ENV.CONNECT_TIMEOUT_MS) ?? DEFAULT_CONNECT_TIMEOUT_MS,
723
+ maxOutputCharacters: readIntegerEnv(env, SINGLE_HOST_ENV.MAX_OUTPUT_CHARACTERS) ?? DEFAULT_MAX_OUTPUT_CHARACTERS,
724
+ maxReadFileBytes: readIntegerEnv(env, SINGLE_HOST_ENV.MAX_READ_FILE_BYTES) ?? DEFAULT_MAX_READ_FILE_BYTES,
725
+ allowCommands,
726
+ denyPatterns: compileDenyPatterns(readListEnv(env, SINGLE_HOST_ENV.DENY_PATTERNS) ?? []),
727
+ allowedPaths: readListEnv(env, SINGLE_HOST_ENV.ALLOWED_PATHS) ?? []
728
+ };
729
+ const profile = {
730
+ name,
731
+ host,
732
+ port: readIntegerEnv(env, SINGLE_HOST_ENV.PORT) ?? DEFAULT_SSH_PORT,
733
+ username,
734
+ description: readEnv(env, SINGLE_HOST_ENV.DESCRIPTION),
735
+ passphrase: readEnv(env, SINGLE_HOST_ENV.PASSPHRASE),
736
+ password: readEnv(env, SINGLE_HOST_ENV.PASSWORD),
737
+ hostKeyFingerprint: readEnv(env, SINGLE_HOST_ENV.HOST_KEY),
738
+ defaultCwd: readEnv(env, SINGLE_HOST_ENV.CWD),
739
+ policy
740
+ };
741
+ const keyPath = readEnv(env, SINGLE_HOST_ENV.KEY);
742
+ if (keyPath != null) {
743
+ const expandedKeyPath = expandHomePath(keyPath);
744
+ profile.privateKeyPath = expandedKeyPath;
745
+ if (fs6.existsSync(expandedKeyPath) == false) {
746
+ _logger.warn(`${SINGLE_HOST_ENV.KEY} does not exist; connections will fail`, {
747
+ private_key_path: expandedKeyPath
748
+ });
749
+ }
750
+ }
751
+ profile.proxyCommand = readEnv(env, SINGLE_HOST_ENV.PROXY_COMMAND);
752
+ const jumpHost = readEnv(env, SINGLE_HOST_ENV.JUMP_HOST);
753
+ if (jumpHost == null) {
754
+ const strayJumpVariables = [
755
+ SINGLE_HOST_ENV.JUMP_PORT,
756
+ SINGLE_HOST_ENV.JUMP_USER,
757
+ SINGLE_HOST_ENV.JUMP_KEY,
758
+ SINGLE_HOST_ENV.JUMP_PASSPHRASE,
759
+ SINGLE_HOST_ENV.JUMP_PASSWORD,
760
+ SINGLE_HOST_ENV.JUMP_HOST_KEY
761
+ ].filter((variable) => readEnv(env, variable) != null);
762
+ if (strayJumpVariables.length > 0) {
763
+ throw new Error(`${strayJumpVariables.join(", ")} is set, so ${SINGLE_HOST_ENV.JUMP_HOST} is required`);
764
+ }
765
+ } else {
766
+ profile.jump = {
767
+ host: jumpHost,
768
+ port: readIntegerEnv(env, SINGLE_HOST_ENV.JUMP_PORT) ?? DEFAULT_SSH_PORT,
769
+ username: readEnv(env, SINGLE_HOST_ENV.JUMP_USER) ?? username,
770
+ password: readEnv(env, SINGLE_HOST_ENV.JUMP_PASSWORD),
771
+ hostKeyFingerprint: readEnv(env, SINGLE_HOST_ENV.JUMP_HOST_KEY)
772
+ };
773
+ const jumpKeyPath = readEnv(env, SINGLE_HOST_ENV.JUMP_KEY);
774
+ if (jumpKeyPath != null) {
775
+ profile.jump.privateKeyPath = expandHomePath(jumpKeyPath);
776
+ profile.jump.passphrase = readEnv(env, SINGLE_HOST_ENV.JUMP_PASSPHRASE);
777
+ if (fs6.existsSync(profile.jump.privateKeyPath) == false) {
778
+ _logger.warn(`${SINGLE_HOST_ENV.JUMP_KEY} does not exist; connections will fail`, {
779
+ private_key_path: profile.jump.privateKeyPath
780
+ });
781
+ }
782
+ } else {
783
+ profile.jump.privateKeyPath = profile.privateKeyPath;
784
+ profile.jump.passphrase = readEnv(env, SINGLE_HOST_ENV.JUMP_PASSPHRASE) ?? profile.passphrase;
785
+ }
786
+ }
787
+ _logger.info("host profile loaded", {
788
+ host,
789
+ port: profile.port,
790
+ username,
791
+ readonly: policy.readonly,
792
+ jump_host: profile.jump?.host,
793
+ via_proxy_command: profile.proxyCommand != null
794
+ });
795
+ return profile;
796
+ }
797
+ function toHostSummary(profile) {
798
+ let authMethod = "agent";
799
+ if (profile.privateKeyPath != null) {
800
+ authMethod = "privateKey";
801
+ } else if (profile.password != null) {
802
+ authMethod = "password";
803
+ }
804
+ const summary = {
805
+ name: profile.name,
806
+ host: profile.host,
807
+ port: profile.port,
808
+ username: profile.username,
809
+ description: profile.description,
810
+ authMethod,
811
+ viaProxyCommand: profile.proxyCommand != null,
812
+ readonly: profile.policy.readonly,
813
+ allowSudo: profile.policy.allowSudo,
814
+ allowedPaths: profile.policy.allowedPaths,
815
+ allowCommands: profile.policy.allowCommands
816
+ };
817
+ if (profile.jump != null) {
818
+ summary.jump = {
819
+ host: profile.jump.host,
820
+ port: profile.jump.port,
821
+ username: profile.jump.username
822
+ };
823
+ }
824
+ return summary;
825
+ }
600
826
 
601
827
  // src/modules/guard/command-guard.ts
602
828
  var WRAPPER_BINARY_SET = new Set(COMMAND_WRAPPER_BINARIES);
@@ -1034,20 +1260,20 @@ function inspectRemotePath(remotePath, policy, access) {
1034
1260
  function toRealPath(inputPath) {
1035
1261
  const _logger = $logger.child({ context: "toRealPath" });
1036
1262
  try {
1037
- return fs.realpathSync.native(inputPath);
1263
+ return fs6.realpathSync.native(inputPath);
1038
1264
  } catch (ex) {
1039
1265
  _logger.debug("path does not resolve, falling back to its parent directory", {
1040
1266
  reason: ex instanceof Error ? ex.name : "unknown"
1041
1267
  });
1042
1268
  }
1043
1269
  try {
1044
- const parentRealPath = fs.realpathSync.native(path2.dirname(inputPath));
1045
- return path2.join(parentRealPath, path2.basename(inputPath));
1270
+ const parentRealPath = fs6.realpathSync.native(path.dirname(inputPath));
1271
+ return path.join(parentRealPath, path.basename(inputPath));
1046
1272
  } catch (ex) {
1047
1273
  _logger.debug("parent directory does not resolve either, comparing lexically", {
1048
1274
  reason: ex instanceof Error ? ex.name : "unknown"
1049
1275
  });
1050
- return path2.resolve(inputPath);
1276
+ return path.resolve(inputPath);
1051
1277
  }
1052
1278
  }
1053
1279
  function toComparablePath(inputPath) {
@@ -1127,42 +1353,56 @@ function resolveAgentPath() {
1127
1353
  }
1128
1354
  return void 0;
1129
1355
  }
1130
- function readPrivateKey(profile, keyPath) {
1356
+ function readPrivateKey(label, keyPath) {
1131
1357
  const cached = PRIVATE_KEY_CACHE.get(keyPath);
1132
1358
  if (cached != null) {
1133
1359
  return cached;
1134
1360
  }
1135
1361
  try {
1136
- const contents = fs.readFileSync(keyPath);
1362
+ const contents = fs6.readFileSync(keyPath);
1137
1363
  PRIVATE_KEY_CACHE.set(keyPath, contents);
1138
1364
  return contents;
1139
1365
  } catch (ex) {
1140
- const _logger = $logger.child({ context: "readPrivateKey", profile: profile.name });
1141
- _logger.error(ex, "cannot read the profile's private key file");
1142
- throw new Error(`cannot read the private key configured for profile '${profile.name}' (see the server log for the path)`);
1366
+ const _logger = $logger.child({ context: "readPrivateKey", profile: label });
1367
+ _logger.error(ex, "cannot read the private key file");
1368
+ throw new Error(`cannot read the private key configured for '${label}' (see the server log for the path)`);
1369
+ }
1370
+ }
1371
+ function applyAuth(connectConfig, credentials, label) {
1372
+ if (credentials.privateKeyPath != null) {
1373
+ connectConfig.privateKey = readPrivateKey(label, credentials.privateKeyPath);
1374
+ }
1375
+ if (credentials.passphrase != null) {
1376
+ connectConfig.passphrase = credentials.passphrase;
1377
+ }
1378
+ if (credentials.password != null) {
1379
+ connectConfig.password = credentials.password;
1380
+ }
1381
+ if (connectConfig.privateKey == null && connectConfig.password == null) {
1382
+ connectConfig.agent = resolveAgentPath();
1143
1383
  }
1144
1384
  }
1145
1385
  function toHostKeyFingerprint(hostKey) {
1146
1386
  const digest = createHash("sha256").update(hostKey).digest("base64").replace(/=+$/, "");
1147
1387
  return `SHA256:${digest}`;
1148
1388
  }
1149
- function buildHostVerifier(profile, onHostKeySeen) {
1389
+ function buildHostVerifier(hop, onHostKeySeen) {
1150
1390
  return (hostKey) => {
1151
1391
  const fingerprint = toHostKeyFingerprint(hostKey);
1152
1392
  onHostKeySeen(fingerprint);
1153
- const _logger = $logger.child({ context: "hostVerifier", profile: profile.name, host: profile.host });
1154
- if (profile.hostKeyFingerprint == null) {
1155
- _logger.info("host key accepted unpinned; add hostKeyFingerprint to the profile to pin it", {
1393
+ const _logger = $logger.child({ context: "hostVerifier", profile: hop.label, host: hop.host });
1394
+ if (hop.pinnedFingerprint == null) {
1395
+ _logger.info("host key accepted unpinned; pin the fingerprint in the profile to detect a changed key", {
1156
1396
  host_key_fingerprint: fingerprint
1157
1397
  });
1158
1398
  return true;
1159
1399
  }
1160
- if (profile.hostKeyFingerprint === fingerprint) {
1400
+ if (hop.pinnedFingerprint === fingerprint) {
1161
1401
  _logger.debug("host key matches the pinned fingerprint");
1162
1402
  return true;
1163
1403
  }
1164
1404
  _logger.error(null, "host key does not match the pinned fingerprint", {
1165
- expected: profile.hostKeyFingerprint,
1405
+ expected: hop.pinnedFingerprint,
1166
1406
  actual: fingerprint
1167
1407
  });
1168
1408
  return false;
@@ -1175,21 +1415,152 @@ function buildConnectConfig(profile, onHostKeySeen) {
1175
1415
  username: profile.username,
1176
1416
  readyTimeout: profile.policy.connectTimeoutMs,
1177
1417
  keepaliveInterval: KEEPALIVE_INTERVAL_MS,
1178
- hostVerifier: buildHostVerifier(profile, onHostKeySeen)
1418
+ hostVerifier: buildHostVerifier(
1419
+ { label: profile.name, host: profile.host, pinnedFingerprint: profile.hostKeyFingerprint },
1420
+ onHostKeySeen
1421
+ )
1179
1422
  };
1180
- if (profile.privateKeyPath != null) {
1181
- connectConfig.privateKey = readPrivateKey(profile, profile.privateKeyPath);
1182
- }
1183
- if (profile.passphrase != null) {
1184
- connectConfig.passphrase = profile.passphrase;
1423
+ applyAuth(connectConfig, profile, profile.name);
1424
+ return connectConfig;
1425
+ }
1426
+ function expandProxyCommand(template, hop) {
1427
+ return template.replace(/%[hpr%]/g, (token) => {
1428
+ if (token === "%h") {
1429
+ return hop.host;
1430
+ }
1431
+ if (token === "%p") {
1432
+ return String(hop.port);
1433
+ }
1434
+ if (token === "%r") {
1435
+ return hop.username;
1436
+ }
1437
+ return "%";
1438
+ });
1439
+ }
1440
+ function openProxyCommand(profile, hop) {
1441
+ const command = expandProxyCommand(profile.proxyCommand ?? "", hop);
1442
+ const _logger = $logger.child({ context: "openProxyCommand", profile: profile.name });
1443
+ _logger.debug("starting the proxy command", { command });
1444
+ const child = spawn(command, { shell: true, stdio: ["pipe", "pipe", "pipe"], windowsHide: true });
1445
+ const stderrDecoder = new StringDecoder("utf8");
1446
+ child.stderr.on("data", (chunk) => {
1447
+ const text = stderrDecoder.write(chunk).trim();
1448
+ if (text !== "") {
1449
+ _logger.warn("proxy command stderr", { text });
1450
+ }
1451
+ });
1452
+ child.on("exit", (code, signal) => {
1453
+ _logger.debug("proxy command exited", { exit_code: code, signal });
1454
+ });
1455
+ const sock = Duplex.from({ readable: child.stdout, writable: child.stdin });
1456
+ sock.on("error", (error) => {
1457
+ _logger.debug("proxy command stream error", { error_message: error.message });
1458
+ });
1459
+ child.on("error", (error) => {
1460
+ sock.destroy(error);
1461
+ });
1462
+ let closed = false;
1463
+ return {
1464
+ sock,
1465
+ close: () => {
1466
+ if (closed == true) {
1467
+ return;
1468
+ }
1469
+ closed = true;
1470
+ if (child.exitCode != null || child.signalCode != null) {
1471
+ return;
1472
+ }
1473
+ if (process.platform === "win32" && child.pid != null) {
1474
+ const killer = spawn("taskkill", ["/pid", String(child.pid), "/T", "/F"], { stdio: "ignore", windowsHide: true });
1475
+ killer.on("error", (error) => {
1476
+ _logger.error(error, "failed to kill the proxy command's process tree");
1477
+ });
1478
+ return;
1479
+ }
1480
+ child.kill();
1481
+ }
1482
+ };
1483
+ }
1484
+ function openJumpTransport(profile, jump, proxy, onHostKeySeen) {
1485
+ const label = `${profile.name} jump host`;
1486
+ const endpoint = `${jump.username}@${jump.host}:${jump.port}`;
1487
+ const _logger = $logger.child({ context: "openJumpTransport", profile: profile.name, jump_host: jump.host });
1488
+ const jumpConfig = {
1489
+ host: jump.host,
1490
+ port: jump.port,
1491
+ username: jump.username,
1492
+ readyTimeout: profile.policy.connectTimeoutMs,
1493
+ keepaliveInterval: KEEPALIVE_INTERVAL_MS,
1494
+ hostVerifier: buildHostVerifier(
1495
+ { label, host: jump.host, pinnedFingerprint: jump.hostKeyFingerprint },
1496
+ onHostKeySeen
1497
+ )
1498
+ };
1499
+ applyAuth(jumpConfig, jump, label);
1500
+ if (proxy != null) {
1501
+ jumpConfig.sock = proxy.sock;
1502
+ }
1503
+ return new Promise((resolve, reject) => {
1504
+ const jumpClient = new Client();
1505
+ let settled = false;
1506
+ jumpClient.on("error", (error) => {
1507
+ if (settled == false) {
1508
+ settled = true;
1509
+ jumpClient.destroy();
1510
+ reject(new Error(`jump host ${endpoint}: ${error.message}`));
1511
+ return;
1512
+ }
1513
+ _logger.error(error, "jump host connection error after ready");
1514
+ });
1515
+ jumpClient.on("close", () => {
1516
+ _logger.debug("jump host connection closed");
1517
+ proxy?.close();
1518
+ if (settled == false) {
1519
+ settled = true;
1520
+ reject(new Error(`jump host ${endpoint}: connection closed before the handshake completed`));
1521
+ }
1522
+ });
1523
+ jumpClient.once("ready", () => {
1524
+ if (settled == true) {
1525
+ return;
1526
+ }
1527
+ jumpClient.forwardOut("127.0.0.1", 0, profile.host, profile.port, (error, stream) => {
1528
+ if (settled == true) {
1529
+ return;
1530
+ }
1531
+ settled = true;
1532
+ if (error != null) {
1533
+ jumpClient.end();
1534
+ reject(new Error(`jump host ${endpoint} refused the forward to ${profile.host}:${profile.port}: ${error.message}`));
1535
+ return;
1536
+ }
1537
+ _logger.info("jump host connected, target channel forwarded");
1538
+ resolve({
1539
+ sock: stream,
1540
+ close: () => {
1541
+ jumpClient.end();
1542
+ }
1543
+ });
1544
+ });
1545
+ });
1546
+ jumpClient.connect(jumpConfig);
1547
+ });
1548
+ }
1549
+ async function openTransport(profile, onJumpHostKeySeen) {
1550
+ let proxy = null;
1551
+ if (profile.proxyCommand != null) {
1552
+ proxy = openProxyCommand(profile, profile.jump ?? profile);
1185
1553
  }
1186
- if (profile.password != null) {
1187
- connectConfig.password = profile.password;
1554
+ if (profile.jump == null) {
1555
+ return proxy;
1188
1556
  }
1189
- if (connectConfig.privateKey == null && connectConfig.password == null) {
1190
- connectConfig.agent = resolveAgentPath();
1557
+ try {
1558
+ const jumpTransport = await openJumpTransport(profile, profile.jump, proxy, onJumpHostKeySeen);
1559
+ return jumpTransport;
1560
+ } catch (ex) {
1561
+ proxy?.close();
1562
+ throw ex;
1191
1563
  }
1192
- return connectConfig;
1193
1564
  }
1194
1565
  function buildRemoteCommand(command, cwd, trackCwd) {
1195
1566
  const lines = [];
@@ -1231,6 +1602,7 @@ var SshConnection = class {
1231
1602
  /** Set when the peer closed a previously established connection. */
1232
1603
  this.droppedAfterReady = false;
1233
1604
  this.observedFingerprint = null;
1605
+ this.observedJumpFingerprint = null;
1234
1606
  }
1235
1607
  get isConnected() {
1236
1608
  return this.client != null;
@@ -1239,6 +1611,10 @@ var SshConnection = class {
1239
1611
  get hostKeyFingerprint() {
1240
1612
  return this.observedFingerprint;
1241
1613
  }
1614
+ /** Host key the jump host presented; null without a jump host or before its handshake. */
1615
+ get jumpHostKeyFingerprint() {
1616
+ return this.observedJumpFingerprint;
1617
+ }
1242
1618
  /** True when a connection was established and then lost, so shell state is gone. */
1243
1619
  get wasDropped() {
1244
1620
  return this.droppedAfterReady;
@@ -1246,8 +1622,11 @@ var SshConnection = class {
1246
1622
  /**
1247
1623
  * Opens the connection, or joins the in-flight attempt when one is already running.
1248
1624
  *
1625
+ * With a proxy command or a jump host the carrier is opened first and handed to ssh2
1626
+ * as the socket; it is torn down with the target connection, whichever side closes.
1627
+ *
1249
1628
  * @throws {Error} If the connection was closed, authentication fails, the host is
1250
- * unreachable, or the handshake times out.
1629
+ * unreachable, the handshake times out, or the carrier cannot be opened.
1251
1630
  */
1252
1631
  async connect() {
1253
1632
  if (this.disposed == true) {
@@ -1270,43 +1649,66 @@ var SshConnection = class {
1270
1649
  const connectConfig = buildConnectConfig(this.profile, (fingerprint) => {
1271
1650
  this.observedFingerprint = fingerprint;
1272
1651
  });
1273
- this.connecting = new Promise((resolve, reject) => {
1274
- const client = new Client();
1275
- this.pendingClient = client;
1276
- let settled = false;
1277
- client.on("error", (error) => {
1278
- if (settled == false) {
1652
+ this.connecting = (async () => {
1653
+ const transport = await openTransport(this.profile, (fingerprint) => {
1654
+ this.observedJumpFingerprint = fingerprint;
1655
+ });
1656
+ if (this.disposed == true) {
1657
+ transport?.close();
1658
+ throw new Error(`ssh connection for '${this.profile.name}' was closed during the handshake`);
1659
+ }
1660
+ if (transport != null) {
1661
+ connectConfig.sock = transport.sock;
1662
+ }
1663
+ await new Promise((resolve, reject) => {
1664
+ const client = new Client();
1665
+ this.pendingClient = client;
1666
+ let settled = false;
1667
+ client.on("error", (error) => {
1668
+ if (settled == false) {
1669
+ settled = true;
1670
+ this.pendingClient = null;
1671
+ client.destroy();
1672
+ reject(error);
1673
+ return;
1674
+ }
1675
+ if (this.client !== client) {
1676
+ _logger.debug("ssh connection error during teardown", { error_message: error.message });
1677
+ return;
1678
+ }
1679
+ _logger.error(error, "ssh connection error after ready");
1680
+ });
1681
+ client.on("close", () => {
1682
+ transport?.close();
1683
+ if (this.client === client) {
1684
+ _logger.debug("ssh connection closed by the peer");
1685
+ this.client = null;
1686
+ this.droppedAfterReady = true;
1687
+ return;
1688
+ }
1689
+ if (settled == false) {
1690
+ settled = true;
1691
+ this.pendingClient = null;
1692
+ reject(new Error("connection closed before the handshake completed"));
1693
+ }
1694
+ });
1695
+ client.once("ready", () => {
1696
+ if (settled == true) {
1697
+ return;
1698
+ }
1279
1699
  settled = true;
1280
1700
  this.pendingClient = null;
1281
- client.destroy();
1282
- reject(error);
1283
- return;
1284
- }
1285
- _logger.error(error, "ssh connection error after ready");
1286
- });
1287
- client.on("close", () => {
1288
- if (this.client === client) {
1289
- _logger.debug("ssh connection closed by the peer");
1290
- this.client = null;
1291
- this.droppedAfterReady = true;
1292
- }
1293
- });
1294
- client.once("ready", () => {
1295
- if (settled == true) {
1296
- return;
1297
- }
1298
- settled = true;
1299
- this.pendingClient = null;
1300
- if (this.disposed == true) {
1301
- client.destroy();
1302
- reject(new Error(`ssh connection for '${this.profile.name}' was closed during the handshake`));
1303
- return;
1304
- }
1305
- this.client = client;
1306
- resolve();
1701
+ if (this.disposed == true) {
1702
+ client.destroy();
1703
+ reject(new Error(`ssh connection for '${this.profile.name}' was closed during the handshake`));
1704
+ return;
1705
+ }
1706
+ this.client = client;
1707
+ resolve();
1708
+ });
1709
+ client.connect(connectConfig);
1307
1710
  });
1308
- client.connect(connectConfig);
1309
- });
1711
+ })();
1310
1712
  try {
1311
1713
  await this.connecting;
1312
1714
  _logger.info("ssh connection established");
@@ -1908,7 +2310,7 @@ async function writeRemoteFile(connection, args) {
1908
2310
  }
1909
2311
  async function uploadFile(connection, localPath, remotePath) {
1910
2312
  requirePermittedPath(connection, remotePath, "write");
1911
- const localStats = fs.statSync(localPath);
2313
+ const localStats = fs6.statSync(localPath);
1912
2314
  if (localStats.isFile() == false) {
1913
2315
  throw new Error(`local path is not a file: ${localPath}`);
1914
2316
  }
@@ -1945,7 +2347,7 @@ async function downloadFile(connection, remotePath, localPath) {
1945
2347
  });
1946
2348
  });
1947
2349
  });
1948
- const localStats = fs.statSync(localPath);
2350
+ const localStats = fs6.statSync(localPath);
1949
2351
  const _logger = $logger.child({
1950
2352
  context: "downloadFile",
1951
2353
  profile: connection.profile.name,
@@ -1955,147 +2357,2123 @@ async function downloadFile(connection, remotePath, localPath) {
1955
2357
  _logger.info("file downloaded", { bytes: localStats.size });
1956
2358
  return localStats.size;
1957
2359
  }
1958
- function readEnv(name) {
1959
- const value = process.env[name];
1960
- if (value == null) {
1961
- return void 0;
2360
+
2361
+ // src/modules/manage/connection-check.ts
2362
+ function describeAuth(profile) {
2363
+ if (profile.privateKeyPath != null) {
2364
+ return `key ${profile.privateKeyPath}`;
1962
2365
  }
1963
- const trimmed = value.trim();
1964
- if (trimmed === "") {
1965
- return void 0;
2366
+ if (profile.password != null) {
2367
+ return "password";
1966
2368
  }
1967
- return trimmed;
2369
+ return "ssh agent";
1968
2370
  }
1969
- function readBooleanEnv(name) {
1970
- const value = readEnv(name);
1971
- if (value == null) {
1972
- return void 0;
1973
- }
1974
- const normalized = value.toLowerCase();
1975
- if (TRUTHY_ENV_VALUES.includes(normalized) == true) {
1976
- return true;
2371
+ async function runConnectionCheck(profile, output) {
2372
+ const endpoint = `${profile.username}@${profile.host}:${profile.port}`;
2373
+ const auth = describeAuth(profile);
2374
+ output.write(`Checking ${profile.name} \u2192 ${endpoint}
2375
+ `);
2376
+ if (profile.proxyCommand != null) {
2377
+ output.write(` via proxy command: ${profile.proxyCommand}
2378
+ `);
1977
2379
  }
1978
- if (FALSY_ENV_VALUES.includes(normalized) == false) {
1979
- throw new Error(`${name} must be one of ${[...TRUTHY_ENV_VALUES, ...FALSY_ENV_VALUES].join(", ")} (got "${value}")`);
2380
+ if (profile.jump != null) {
2381
+ output.write(` via jump host: ${profile.jump.username}@${profile.jump.host}:${profile.jump.port}
2382
+ `);
1980
2383
  }
1981
- return false;
2384
+ output.write("\n");
2385
+ const connection = new SshConnection(profile);
2386
+ const startedAt = Date.now();
2387
+ let connected = false;
2388
+ let detail = "";
2389
+ try {
2390
+ await connection.connect();
2391
+ connected = true;
2392
+ } catch (ex) {
2393
+ detail = String(ex);
2394
+ if (ex instanceof Error) {
2395
+ detail = ex.message;
2396
+ }
2397
+ } finally {
2398
+ connection.disconnect();
2399
+ }
2400
+ const durationMs = Date.now() - startedAt;
2401
+ if (connected == true) {
2402
+ output.write(` OK ${endpoint} (${auth}, ${durationMs}ms)
2403
+ `);
2404
+ } else {
2405
+ output.write(` FAILED ${endpoint} (${auth})
2406
+ `);
2407
+ output.write(` ${detail}
2408
+ `);
2409
+ }
2410
+ if (connection.hostKeyFingerprint != null) {
2411
+ let pinNote = `not pinned \u2014 set ${SINGLE_HOST_ENV.HOST_KEY} to it to detect a changed key`;
2412
+ if (profile.hostKeyFingerprint != null) {
2413
+ pinNote = "pinned";
2414
+ }
2415
+ output.write(` host key ${connection.hostKeyFingerprint} (${pinNote})
2416
+ `);
2417
+ }
2418
+ if (connection.jumpHostKeyFingerprint != null) {
2419
+ let pinNote = `not pinned \u2014 set ${SINGLE_HOST_ENV.JUMP_HOST_KEY} to it to detect a changed key`;
2420
+ if (profile.jump?.hostKeyFingerprint != null) {
2421
+ pinNote = "pinned";
2422
+ }
2423
+ output.write(` jump host key ${connection.jumpHostKeyFingerprint} (${pinNote})
2424
+ `);
2425
+ }
2426
+ return {
2427
+ connected,
2428
+ hostKeyFingerprint: connection.hostKeyFingerprint,
2429
+ jumpHostKeyFingerprint: connection.jumpHostKeyFingerprint
2430
+ };
2431
+ }
2432
+
2433
+ // src/modules/manage/entry.ts
2434
+ var MANAGED_ENV_NAMES = [
2435
+ SINGLE_HOST_ENV.HOST,
2436
+ SINGLE_HOST_ENV.PORT,
2437
+ SINGLE_HOST_ENV.USER,
2438
+ SINGLE_HOST_ENV.KEY,
2439
+ SINGLE_HOST_ENV.PASSPHRASE,
2440
+ SINGLE_HOST_ENV.PASSWORD,
2441
+ SINGLE_HOST_ENV.DESCRIPTION,
2442
+ SINGLE_HOST_ENV.JUMP_HOST,
2443
+ SINGLE_HOST_ENV.JUMP_PORT,
2444
+ SINGLE_HOST_ENV.JUMP_USER,
2445
+ SINGLE_HOST_ENV.PROXY_COMMAND,
2446
+ SINGLE_HOST_ENV.READONLY,
2447
+ SINGLE_HOST_ENV.ALLOWED_PATHS,
2448
+ SINGLE_HOST_ENV.HOST_KEY,
2449
+ SINGLE_HOST_ENV.JUMP_HOST_KEY
2450
+ ];
2451
+ var JUMP_ENV_PREFIX = "SSH_JUMP_";
2452
+ var SERVER_NAME_PATTERN = /^[A-Za-z0-9_-]{1,48}$/;
2453
+ function isOurEntry(entry) {
2454
+ if (entry.args.includes(PACKAGE_NAME) == true) {
2455
+ return true;
2456
+ }
2457
+ const commandBase = entry.command.replace(/\\/g, "/").split("/").pop() ?? "";
2458
+ return commandBase === SERVER_NAME || commandBase.startsWith(`${SERVER_NAME}.`) == true;
2459
+ }
2460
+ function launchCommand() {
2461
+ if (process.platform === "win32") {
2462
+ return { command: "cmd", args: ["/c", "npx", "-y", PACKAGE_NAME] };
2463
+ }
2464
+ return { command: "npx", args: ["-y", PACKAGE_NAME] };
2465
+ }
2466
+ function answersToEntry(answers) {
2467
+ const env = {};
2468
+ env[SINGLE_HOST_ENV.HOST] = answers.host;
2469
+ if (answers.port !== DEFAULT_SSH_PORT) {
2470
+ env[SINGLE_HOST_ENV.PORT] = String(answers.port);
2471
+ }
2472
+ env[SINGLE_HOST_ENV.USER] = answers.username;
2473
+ if (answers.auth === "key" && answers.keyPath != null) {
2474
+ env[SINGLE_HOST_ENV.KEY] = answers.keyPath;
2475
+ if (answers.passphrase != null && answers.passphrase !== "") {
2476
+ env[SINGLE_HOST_ENV.PASSPHRASE] = answers.passphrase;
2477
+ }
2478
+ }
2479
+ if (answers.auth === "password" && answers.password != null) {
2480
+ env[SINGLE_HOST_ENV.PASSWORD] = answers.password;
2481
+ }
2482
+ if (answers.hostKeyFingerprint != null) {
2483
+ env[SINGLE_HOST_ENV.HOST_KEY] = answers.hostKeyFingerprint;
2484
+ }
2485
+ if (answers.description != null && answers.description !== "") {
2486
+ env[SINGLE_HOST_ENV.DESCRIPTION] = answers.description;
2487
+ }
2488
+ if (answers.jumpHost != null) {
2489
+ env[SINGLE_HOST_ENV.JUMP_HOST] = answers.jumpHost;
2490
+ if (answers.jumpPort != null && answers.jumpPort !== DEFAULT_SSH_PORT) {
2491
+ env[SINGLE_HOST_ENV.JUMP_PORT] = String(answers.jumpPort);
2492
+ }
2493
+ if (answers.jumpUser != null && answers.jumpUser !== answers.username) {
2494
+ env[SINGLE_HOST_ENV.JUMP_USER] = answers.jumpUser;
2495
+ }
2496
+ if (answers.jumpHostKeyFingerprint != null) {
2497
+ env[SINGLE_HOST_ENV.JUMP_HOST_KEY] = answers.jumpHostKeyFingerprint;
2498
+ }
2499
+ }
2500
+ if (answers.proxyCommand != null && answers.proxyCommand !== "") {
2501
+ env[SINGLE_HOST_ENV.PROXY_COMMAND] = answers.proxyCommand;
2502
+ }
2503
+ if (answers.readonly == true) {
2504
+ env[SINGLE_HOST_ENV.READONLY] = "true";
2505
+ }
2506
+ if (answers.allowedPaths.length > 0) {
2507
+ env[SINGLE_HOST_ENV.ALLOWED_PATHS] = answers.allowedPaths.join(",");
2508
+ }
2509
+ for (const [name, value] of Object.entries(answers.extraEnv)) {
2510
+ if (MANAGED_ENV_NAMES.includes(name) == true) {
2511
+ continue;
2512
+ }
2513
+ if (answers.jumpHost == null && name.startsWith(JUMP_ENV_PREFIX) == true) {
2514
+ continue;
2515
+ }
2516
+ env[name] = value;
2517
+ }
2518
+ const launch = launchCommand();
2519
+ return {
2520
+ command: launch.command,
2521
+ args: launch.args,
2522
+ env
2523
+ };
2524
+ }
2525
+ function readPort(value) {
2526
+ if (value == null) {
2527
+ return DEFAULT_SSH_PORT;
2528
+ }
2529
+ const parsed = Number(value);
2530
+ if (Number.isInteger(parsed) == false || parsed <= 0) {
2531
+ return DEFAULT_SSH_PORT;
2532
+ }
2533
+ return parsed;
2534
+ }
2535
+ function isTruthy(value) {
2536
+ if (value == null) {
2537
+ return false;
2538
+ }
2539
+ return TRUTHY_ENV_VALUES.includes(value.trim().toLowerCase());
2540
+ }
2541
+ function entryToAnswers(name, entry) {
2542
+ const env = entry.env;
2543
+ const host = env[SINGLE_HOST_ENV.HOST] ?? "";
2544
+ const username = env[SINGLE_HOST_ENV.USER] ?? "";
2545
+ let auth = "agent";
2546
+ if (env[SINGLE_HOST_ENV.KEY] != null) {
2547
+ auth = "key";
2548
+ } else if (env[SINGLE_HOST_ENV.PASSWORD] != null) {
2549
+ auth = "password";
2550
+ }
2551
+ let allowedPaths = [];
2552
+ const allowedPathsValue = env[SINGLE_HOST_ENV.ALLOWED_PATHS];
2553
+ if (allowedPathsValue != null) {
2554
+ allowedPaths = allowedPathsValue.split(",").map((item) => item.trim()).filter((item) => item !== "");
2555
+ }
2556
+ const extraEnv = {};
2557
+ for (const [variable, value] of Object.entries(env)) {
2558
+ if (MANAGED_ENV_NAMES.includes(variable) == false) {
2559
+ extraEnv[variable] = value;
2560
+ }
2561
+ }
2562
+ const answers = {
2563
+ name,
2564
+ host,
2565
+ port: readPort(env[SINGLE_HOST_ENV.PORT]),
2566
+ username,
2567
+ auth,
2568
+ keyPath: env[SINGLE_HOST_ENV.KEY],
2569
+ passphrase: env[SINGLE_HOST_ENV.PASSPHRASE],
2570
+ password: env[SINGLE_HOST_ENV.PASSWORD],
2571
+ description: env[SINGLE_HOST_ENV.DESCRIPTION],
2572
+ proxyCommand: env[SINGLE_HOST_ENV.PROXY_COMMAND],
2573
+ readonly: isTruthy(env[SINGLE_HOST_ENV.READONLY]),
2574
+ allowedPaths,
2575
+ hostKeyFingerprint: env[SINGLE_HOST_ENV.HOST_KEY],
2576
+ extraEnv
2577
+ };
2578
+ const jumpHost = env[SINGLE_HOST_ENV.JUMP_HOST];
2579
+ if (jumpHost != null) {
2580
+ answers.jumpHost = jumpHost;
2581
+ answers.jumpPort = readPort(env[SINGLE_HOST_ENV.JUMP_PORT]);
2582
+ answers.jumpUser = env[SINGLE_HOST_ENV.JUMP_USER] ?? username;
2583
+ answers.jumpHostKeyFingerprint = env[SINGLE_HOST_ENV.JUMP_HOST_KEY];
2584
+ }
2585
+ return answers;
2586
+ }
2587
+ function summarizeEntry(entry) {
2588
+ const env = entry.env;
2589
+ const host = env[SINGLE_HOST_ENV.HOST] ?? "?";
2590
+ const port = env[SINGLE_HOST_ENV.PORT] ?? String(DEFAULT_SSH_PORT);
2591
+ const username = env[SINGLE_HOST_ENV.USER] ?? "?";
2592
+ let auth = "agent";
2593
+ if (env[SINGLE_HOST_ENV.KEY] != null) {
2594
+ auth = "key";
2595
+ } else if (env[SINGLE_HOST_ENV.PASSWORD] != null) {
2596
+ auth = "password";
2597
+ }
2598
+ const notes = [];
2599
+ if (env[SINGLE_HOST_ENV.JUMP_HOST] != null) {
2600
+ notes.push(`jump ${env[SINGLE_HOST_ENV.JUMP_HOST]}`);
2601
+ }
2602
+ if (env[SINGLE_HOST_ENV.PROXY_COMMAND] != null) {
2603
+ notes.push("proxy");
2604
+ }
2605
+ if (isTruthy(env[SINGLE_HOST_ENV.READONLY]) == true) {
2606
+ notes.push("readonly");
2607
+ }
2608
+ if (env[SINGLE_HOST_ENV.ALLOWED_PATHS] != null) {
2609
+ notes.push(`paths ${env[SINGLE_HOST_ENV.ALLOWED_PATHS]}`);
2610
+ }
2611
+ if (env[SINGLE_HOST_ENV.HOST_KEY] != null) {
2612
+ notes.push("pinned");
2613
+ }
2614
+ return {
2615
+ endpoint: `${username}@${host}:${port}`,
2616
+ auth,
2617
+ notes: notes.join(", ")
2618
+ };
2619
+ }
2620
+
2621
+ // src/modules/manage/prompter.ts
2622
+ var PromptClosedError = class extends Error {
2623
+ constructor() {
2624
+ super("input closed before the prompt was answered");
2625
+ this.name = "PromptClosedError";
2626
+ }
2627
+ };
2628
+ var ESC = "\x1B";
2629
+ var KEY_UP = [`${ESC}[A`, `${ESC}OA`, "k"];
2630
+ var KEY_DOWN = [`${ESC}[B`, `${ESC}OB`, "j"];
2631
+ var KEY_HOME = [`${ESC}[H`, `${ESC}OH`, `${ESC}[1~`];
2632
+ var KEY_END = [`${ESC}[F`, `${ESC}OF`, `${ESC}[4~`];
2633
+ var KEY_ENTER = ["\r", "\n"];
2634
+ var KEY_BACKSPACE = ["\x7F", "\b"];
2635
+ var KEY_CTRL_C = "";
2636
+ var KEY_CTRL_D = "";
2637
+ function splitKeys(chunk) {
2638
+ const keys = [];
2639
+ let index = 0;
2640
+ while (index < chunk.length) {
2641
+ const isSequence = chunk[index] === ESC && (chunk[index + 1] === "[" || chunk[index + 1] === "O");
2642
+ if (isSequence == true) {
2643
+ let end = index + 2;
2644
+ while (end < chunk.length && /[0-9;]/.test(chunk[end]) == true) {
2645
+ end += 1;
2646
+ }
2647
+ keys.push(chunk.slice(index, end + 1));
2648
+ index = end + 1;
2649
+ continue;
2650
+ }
2651
+ const codePoint = chunk.codePointAt(index) ?? 0;
2652
+ const character = String.fromCodePoint(codePoint);
2653
+ keys.push(character);
2654
+ index += character.length;
2655
+ }
2656
+ return keys;
2657
+ }
2658
+ function charWidth(codePoint) {
2659
+ if (codePoint < 4352) {
2660
+ return 1;
2661
+ }
2662
+ const isWide = codePoint <= 4447 || codePoint === 9001 || codePoint === 9002 || codePoint >= 11904 && codePoint <= 42191 && codePoint !== 12351 || codePoint >= 44032 && codePoint <= 55203 || codePoint >= 63744 && codePoint <= 64255 || codePoint >= 65072 && codePoint <= 65103 || codePoint >= 65280 && codePoint <= 65376 || codePoint >= 65504 && codePoint <= 65510 || codePoint >= 127744 && codePoint <= 128591 || codePoint >= 129280 && codePoint <= 129535 || codePoint >= 131072 && codePoint <= 262141;
2663
+ if (isWide == true) {
2664
+ return 2;
2665
+ }
2666
+ return 1;
2667
+ }
2668
+ function displayWidth(text) {
2669
+ let width = 0;
2670
+ for (const character of text) {
2671
+ width += charWidth(character.codePointAt(0) ?? 0);
2672
+ }
2673
+ return width;
2674
+ }
2675
+ function padToWidth(text, width) {
2676
+ const missing = width - displayWidth(text);
2677
+ if (missing <= 0) {
2678
+ return text;
2679
+ }
2680
+ return `${text}${" ".repeat(missing)}`;
2681
+ }
2682
+ function groupLabelWidths(items) {
2683
+ const widths = items.map(() => 0);
2684
+ let groupStart = 0;
2685
+ for (let index = 0; index <= items.length; index += 1) {
2686
+ const atBoundary = index === items.length || "value" in items[index] == false;
2687
+ if (atBoundary == false) {
2688
+ continue;
2689
+ }
2690
+ let groupWidth = 0;
2691
+ for (let member = groupStart; member < index; member += 1) {
2692
+ const item = items[member];
2693
+ groupWidth = Math.max(groupWidth, displayWidth(item.label));
2694
+ }
2695
+ for (let member = groupStart; member < index; member += 1) {
2696
+ widths[member] = groupWidth;
2697
+ }
2698
+ groupStart = index + 1;
2699
+ }
2700
+ return widths;
2701
+ }
2702
+ function supportsUnicode() {
2703
+ if (process.platform !== "win32") {
2704
+ return true;
2705
+ }
2706
+ return process.env.WT_SESSION != null || process.env.TERM_PROGRAM === "vscode" || process.env.TERMINAL_EMULATOR === "JetBrains-JediTerm" || process.env.ConEmuTask != null;
2707
+ }
2708
+ function createStyle(enabled) {
2709
+ const paint = (open, close) => {
2710
+ return (text) => {
2711
+ if (enabled == false || text === "") {
2712
+ return text;
2713
+ }
2714
+ return `${ESC}[${open}m${text}${ESC}[${close}m`;
2715
+ };
2716
+ };
2717
+ return {
2718
+ accent: paint(36, 39),
2719
+ success: paint(32, 39),
2720
+ dim: paint(2, 22),
2721
+ bold: paint(1, 22)
2722
+ };
2723
+ }
2724
+ var Prompter = class {
2725
+ constructor(input, output) {
2726
+ this.input = input;
2727
+ this.output = output;
2728
+ this.lineBuffer = "";
2729
+ this.pendingLines = [];
2730
+ this.lineWaiter = null;
2731
+ this.inputEnded = false;
2732
+ /** Set while a key-driven prompt (select, secret) owns the input. */
2733
+ this.keyHandler = null;
2734
+ const ttyInput = input;
2735
+ const ttyOutput = output;
2736
+ this.interactive = ttyInput.isTTY == true && ttyInput.setRawMode != null && ttyOutput.isTTY == true;
2737
+ this.style = createStyle(this.interactive == true && process.env.NO_COLOR == null);
2738
+ if (supportsUnicode() == true) {
2739
+ this.symbols = { question: "?", pointer: "\u276F", tick: "\u2714", rule: "\u2500" };
2740
+ } else {
2741
+ this.symbols = { question: "?", pointer: ">", tick: "\u221A", rule: "-" };
2742
+ }
2743
+ input.setEncoding("utf8");
2744
+ input.on("data", (chunk) => {
2745
+ this.onData(chunk);
2746
+ });
2747
+ input.on("end", () => {
2748
+ this.inputEnded = true;
2749
+ if (this.lineWaiter != null) {
2750
+ const waiter = this.lineWaiter;
2751
+ this.lineWaiter = null;
2752
+ waiter(null);
2753
+ }
2754
+ if (this.keyHandler != null) {
2755
+ this.keyHandler(KEY_CTRL_D);
2756
+ }
2757
+ });
2758
+ }
2759
+ /** Stops reading so the process can exit once the command is done. */
2760
+ close() {
2761
+ if (this.interactive == true) {
2762
+ this.input.setRawMode?.(false);
2763
+ this.output.write(`${ESC}[?25h`);
2764
+ }
2765
+ this.input.pause();
2766
+ }
2767
+ write(text) {
2768
+ this.output.write(text);
2769
+ }
2770
+ /** Styling for callers that print around the prompts; plain text off a TTY. */
2771
+ get paint() {
2772
+ return this.style;
2773
+ }
2774
+ /**
2775
+ * Free-text prompt. Enter accepts `defaultValue` when one is shown.
2776
+ *
2777
+ * @throws {PromptClosedError} If the input closes before a line arrives.
2778
+ */
2779
+ async ask(question, defaultValue) {
2780
+ let suffix = "";
2781
+ if (defaultValue != null && defaultValue !== "") {
2782
+ suffix = ` ${this.style.dim(`(${defaultValue})`)}`;
2783
+ }
2784
+ const prompt = `${this.style.accent(this.symbols.question)} ${this.style.bold(question)}${suffix} `;
2785
+ this.output.write(prompt);
2786
+ const line = await this.readLine();
2787
+ if (line == null) {
2788
+ throw new PromptClosedError();
2789
+ }
2790
+ let answer = line.trim();
2791
+ if (answer === "" && defaultValue != null) {
2792
+ answer = defaultValue;
2793
+ }
2794
+ this.collapseAnswered(prompt, line, question, answer);
2795
+ return answer;
2796
+ }
2797
+ /** Like `ask`, re-asking until something non-empty is entered. */
2798
+ async askRequired(question, defaultValue) {
2799
+ for (; ; ) {
2800
+ const answer = await this.ask(question, defaultValue);
2801
+ if (answer !== "") {
2802
+ return answer;
2803
+ }
2804
+ this.output.write(` ${this.style.dim("A value is required.")}
2805
+ `);
2806
+ }
2807
+ }
2808
+ async askYesNo(question, defaultValue) {
2809
+ let hint = "y/N";
2810
+ if (defaultValue == true) {
2811
+ hint = "Y/n";
2812
+ }
2813
+ for (; ; ) {
2814
+ const prompt = `${this.style.accent(this.symbols.question)} ${this.style.bold(question)} ${this.style.dim(`(${hint})`)} `;
2815
+ this.output.write(prompt);
2816
+ const line = await this.readLine();
2817
+ if (line == null) {
2818
+ throw new PromptClosedError();
2819
+ }
2820
+ const normalized = line.trim().toLowerCase();
2821
+ let answer = null;
2822
+ if (normalized === "") {
2823
+ answer = defaultValue;
2824
+ } else if (normalized === "y" || normalized === "yes") {
2825
+ answer = true;
2826
+ } else if (normalized === "n" || normalized === "no") {
2827
+ answer = false;
2828
+ }
2829
+ if (answer != null) {
2830
+ let shown = "no";
2831
+ if (answer == true) {
2832
+ shown = "yes";
2833
+ }
2834
+ this.collapseAnswered(prompt, line, question, shown);
2835
+ return answer;
2836
+ }
2837
+ this.output.write(` ${this.style.dim("Answer y or n.")}
2838
+ `);
2839
+ }
2840
+ }
2841
+ /**
2842
+ * Picks one of `items`. On a TTY: ↑/↓ (or k/j) move, 1–9 jump, Enter picks, Esc returns
2843
+ * `cancelValue`. Off a TTY: a numbered list, answered by number, key or label.
2844
+ *
2845
+ * @throws {PromptClosedError} On Ctrl+C or when the input closes.
2846
+ */
2847
+ async select(question, items, options) {
2848
+ const choices = items.filter((item) => "value" in item);
2849
+ if (choices.length === 0) {
2850
+ throw new Error("select needs at least one choice");
2851
+ }
2852
+ let startIndex = items.findIndex((item) => "value" in item && item.value === options?.defaultValue);
2853
+ if (startIndex < 0) {
2854
+ startIndex = items.findIndex((item) => "value" in item);
2855
+ }
2856
+ if (this.interactive == true) {
2857
+ const picked2 = await this.selectWithKeys(question, items, startIndex, options?.cancelValue);
2858
+ return picked2;
2859
+ }
2860
+ const picked = await this.selectWithLines(question, items, startIndex);
2861
+ return picked;
2862
+ }
2863
+ /**
2864
+ * Reads a value without echoing it on a TTY. Empty means "none", or "keep" when the
2865
+ * caller says a value already exists.
2866
+ *
2867
+ * @throws {PromptClosedError} On Ctrl+C or when the input closes.
2868
+ */
2869
+ async askSecret(question) {
2870
+ if (this.interactive == false) {
2871
+ const answer = await this.ask(question);
2872
+ return answer;
2873
+ }
2874
+ const prompt = `${this.style.accent(this.symbols.question)} ${this.style.bold(question)} `;
2875
+ this.output.write(prompt);
2876
+ const ttyInput = this.input;
2877
+ return new Promise((resolve, reject) => {
2878
+ let buffer = "";
2879
+ const finish = () => {
2880
+ this.keyHandler = null;
2881
+ ttyInput.setRawMode?.(false);
2882
+ this.output.write(`\r${ESC}[2K`);
2883
+ };
2884
+ this.keyHandler = (key) => {
2885
+ if (key === KEY_CTRL_C || key === KEY_CTRL_D) {
2886
+ finish();
2887
+ reject(new PromptClosedError());
2888
+ return;
2889
+ }
2890
+ if (KEY_ENTER.includes(key) == true) {
2891
+ finish();
2892
+ let shown = this.style.dim("(empty)");
2893
+ if (buffer !== "") {
2894
+ shown = "\u2022".repeat(Math.min(buffer.length, 8));
2895
+ }
2896
+ this.writeAnswered(question, shown);
2897
+ resolve(buffer);
2898
+ return;
2899
+ }
2900
+ if (KEY_BACKSPACE.includes(key) == true) {
2901
+ buffer = Array.from(buffer).slice(0, -1).join("");
2902
+ return;
2903
+ }
2904
+ if (key.startsWith(ESC) == true) {
2905
+ return;
2906
+ }
2907
+ buffer += key;
2908
+ };
2909
+ ttyInput.setRawMode?.(true);
2910
+ });
2911
+ }
2912
+ // ── line mode ──────────────────────────────────────────────────────────
2913
+ readLine() {
2914
+ const queued = this.pendingLines.shift();
2915
+ if (queued != null) {
2916
+ return Promise.resolve(queued);
2917
+ }
2918
+ if (this.inputEnded == true) {
2919
+ return Promise.resolve(null);
2920
+ }
2921
+ return new Promise((resolve) => {
2922
+ this.lineWaiter = resolve;
2923
+ });
2924
+ }
2925
+ onData(chunk) {
2926
+ if (this.keyHandler != null) {
2927
+ for (const key of splitKeys(chunk)) {
2928
+ if (this.keyHandler == null) {
2929
+ break;
2930
+ }
2931
+ this.keyHandler(key);
2932
+ }
2933
+ return;
2934
+ }
2935
+ this.lineBuffer += chunk;
2936
+ let newlineIndex = this.lineBuffer.indexOf("\n");
2937
+ while (newlineIndex >= 0) {
2938
+ const line = this.lineBuffer.slice(0, newlineIndex).replace(/\r$/, "");
2939
+ this.lineBuffer = this.lineBuffer.slice(newlineIndex + 1);
2940
+ if (this.lineWaiter != null) {
2941
+ const waiter = this.lineWaiter;
2942
+ this.lineWaiter = null;
2943
+ waiter(line);
2944
+ } else {
2945
+ this.pendingLines.push(line);
2946
+ }
2947
+ newlineIndex = this.lineBuffer.indexOf("\n");
2948
+ }
2949
+ }
2950
+ async selectWithLines(question, items, startIndex) {
2951
+ const choices = items.filter((item) => "value" in item);
2952
+ const labelWidths = groupLabelWidths(items);
2953
+ this.output.write(`${this.symbols.question} ${question}
2954
+ `);
2955
+ let number = 0;
2956
+ for (let index = 0; index < items.length; index += 1) {
2957
+ const item = items[index];
2958
+ if ("value" in item == false) {
2959
+ this.output.write("\n");
2960
+ continue;
2961
+ }
2962
+ number += 1;
2963
+ let line = ` ${String(number).padStart(2)}) ${padToWidth(item.label, labelWidths[index])}`;
2964
+ if (item.hint != null && item.hint !== "") {
2965
+ line += ` ${item.hint}`;
2966
+ }
2967
+ this.output.write(`${line.trimEnd()}
2968
+ `);
2969
+ }
2970
+ const defaultChoice = items[startIndex];
2971
+ const defaultNumber = choices.indexOf(defaultChoice) + 1;
2972
+ for (; ; ) {
2973
+ this.output.write(`Choice (${defaultNumber}): `);
2974
+ const line = await this.readLine();
2975
+ if (line == null) {
2976
+ throw new PromptClosedError();
2977
+ }
2978
+ const answer = line.trim();
2979
+ if (answer === "") {
2980
+ return defaultChoice.value;
2981
+ }
2982
+ const index = Number(answer);
2983
+ if (Number.isInteger(index) == true && index >= 1 && index <= choices.length) {
2984
+ return choices[index - 1].value;
2985
+ }
2986
+ const lowered = answer.toLowerCase();
2987
+ const matched = choices.find((choice) => {
2988
+ const key = choice.key ?? choice.value;
2989
+ return key.toLowerCase() === lowered || choice.label.toLowerCase() === lowered;
2990
+ });
2991
+ if (matched != null) {
2992
+ return matched.value;
2993
+ }
2994
+ this.output.write(` Pick a number from 1 to ${choices.length}.
2995
+ `);
2996
+ }
2997
+ }
2998
+ // ── TTY rendering ──────────────────────────────────────────────────────
2999
+ columns() {
3000
+ const columns = this.output.columns;
3001
+ if (columns == null || columns < 20) {
3002
+ return 80;
3003
+ }
3004
+ return columns;
3005
+ }
3006
+ /** Joins styled parts, cutting the text (not the styles) once `width` columns are used. */
3007
+ fitLine(parts, width) {
3008
+ let used = 0;
3009
+ let line = "";
3010
+ for (const part of parts) {
3011
+ let text = "";
3012
+ for (const character of part.text) {
3013
+ const characterWidth = charWidth(character.codePointAt(0) ?? 0);
3014
+ if (used + characterWidth > width) {
3015
+ break;
3016
+ }
3017
+ used += characterWidth;
3018
+ text += character;
3019
+ }
3020
+ if (part.paint != null) {
3021
+ line += part.paint(text);
3022
+ } else {
3023
+ line += text;
3024
+ }
3025
+ if (used >= width) {
3026
+ break;
3027
+ }
3028
+ }
3029
+ return line;
3030
+ }
3031
+ /** The one-line record an answered prompt leaves behind on a TTY. */
3032
+ writeAnswered(question, answer) {
3033
+ this.output.write(`${this.style.success(this.symbols.tick)} ${question} ${this.style.dim("\xB7")} ${this.style.accent(answer)}
3034
+ `);
3035
+ }
3036
+ /**
3037
+ * Replaces a cooked-mode prompt and its echoed answer with the one-line record. The
3038
+ * rows are worked out from the widths, since a long answer wraps.
3039
+ */
3040
+ collapseAnswered(prompt, typed, question, answer) {
3041
+ if (this.interactive == false) {
3042
+ return;
3043
+ }
3044
+ const plainPrompt = prompt.replace(/\u001b\[[0-9;]*m/g, "");
3045
+ const used = displayWidth(plainPrompt) + displayWidth(typed);
3046
+ const rows = Math.max(1, Math.ceil(used / this.columns()));
3047
+ this.output.write(`${ESC}[${rows}A\r${ESC}[J`);
3048
+ let shown = answer;
3049
+ if (shown === "") {
3050
+ shown = this.style.dim("(empty)");
3051
+ }
3052
+ this.writeAnswered(question, shown);
3053
+ }
3054
+ selectWithKeys(question, items, startIndex, cancelValue) {
3055
+ const ttyInput = this.input;
3056
+ const selectableIndexes = items.flatMap((item, index) => {
3057
+ if ("value" in item) {
3058
+ return [index];
3059
+ }
3060
+ return [];
3061
+ });
3062
+ const labelWidths = groupLabelWidths(items);
3063
+ const ruleWidth = Math.min(Math.max(...labelWidths), 24);
3064
+ let active = startIndex;
3065
+ let renderedLines = 0;
3066
+ const draw = (lines) => {
3067
+ let text = "";
3068
+ if (renderedLines > 1) {
3069
+ text += `${ESC}[${renderedLines - 1}A`;
3070
+ }
3071
+ text += `\r${ESC}[J${lines.join("\n")}`;
3072
+ this.output.write(text);
3073
+ renderedLines = lines.length;
3074
+ };
3075
+ const buildLines = () => {
3076
+ const width = this.columns() - 1;
3077
+ const lines = [
3078
+ this.fitLine([
3079
+ { text: this.symbols.question, paint: this.style.accent },
3080
+ { text: " " },
3081
+ { text: question, paint: this.style.bold }
3082
+ ], width)
3083
+ ];
3084
+ for (let index = 0; index < items.length; index += 1) {
3085
+ const item = items[index];
3086
+ if ("value" in item == false) {
3087
+ lines.push(this.fitLine([{ text: ` ${this.symbols.rule.repeat(ruleWidth)}`, paint: this.style.dim }], width));
3088
+ continue;
3089
+ }
3090
+ const isActive = index === active;
3091
+ const parts = [];
3092
+ if (isActive == true) {
3093
+ parts.push({ text: `${this.symbols.pointer} `, paint: this.style.accent });
3094
+ parts.push({ text: padToWidth(item.label, labelWidths[index]), paint: this.style.accent });
3095
+ } else {
3096
+ parts.push({ text: " " });
3097
+ parts.push({ text: padToWidth(item.label, labelWidths[index]) });
3098
+ }
3099
+ if (item.hint != null && item.hint !== "") {
3100
+ parts.push({ text: ` ${item.hint}`, paint: this.style.dim });
3101
+ }
3102
+ lines.push(this.fitLine(parts, width));
3103
+ }
3104
+ let footer = "\u2191\u2193 move \xB7 enter select";
3105
+ if (cancelValue != null) {
3106
+ footer += " \xB7 esc back";
3107
+ }
3108
+ lines.push(this.fitLine([{ text: footer, paint: this.style.dim }], width));
3109
+ return lines;
3110
+ };
3111
+ const move = (step) => {
3112
+ const position = selectableIndexes.indexOf(active);
3113
+ const next = (position + step + selectableIndexes.length) % selectableIndexes.length;
3114
+ active = selectableIndexes[next];
3115
+ };
3116
+ return new Promise((resolve, reject) => {
3117
+ const finish = () => {
3118
+ this.keyHandler = null;
3119
+ ttyInput.setRawMode?.(false);
3120
+ draw([]);
3121
+ this.output.write(`${ESC}[?25h`);
3122
+ };
3123
+ this.keyHandler = (key) => {
3124
+ if (key === KEY_CTRL_C || key === KEY_CTRL_D) {
3125
+ finish();
3126
+ reject(new PromptClosedError());
3127
+ return;
3128
+ }
3129
+ if (KEY_ENTER.includes(key) == true) {
3130
+ const picked = items[active];
3131
+ finish();
3132
+ this.writeAnswered(question, picked.label);
3133
+ resolve(picked.value);
3134
+ return;
3135
+ }
3136
+ if (key === ESC) {
3137
+ if (cancelValue == null) {
3138
+ return;
3139
+ }
3140
+ finish();
3141
+ resolve(cancelValue);
3142
+ return;
3143
+ }
3144
+ if (KEY_UP.includes(key) == true) {
3145
+ move(-1);
3146
+ } else if (KEY_DOWN.includes(key) == true) {
3147
+ move(1);
3148
+ } else if (KEY_HOME.includes(key) == true) {
3149
+ active = selectableIndexes[0];
3150
+ } else if (KEY_END.includes(key) == true) {
3151
+ active = selectableIndexes[selectableIndexes.length - 1];
3152
+ } else if (/^[1-9]$/.test(key) == true && Number(key) <= selectableIndexes.length) {
3153
+ active = selectableIndexes[Number(key) - 1];
3154
+ } else {
3155
+ return;
3156
+ }
3157
+ draw(buildLines());
3158
+ };
3159
+ ttyInput.setRawMode?.(true);
3160
+ this.output.write(`${ESC}[?25l`);
3161
+ draw(buildLines());
3162
+ });
3163
+ }
3164
+ };
3165
+ var PREFERRED_KEY_NAMES = ["id_ed25519", "id_ecdsa", "id_rsa"];
3166
+ var NON_KEY_FILE_NAMES = ["config", "known_hosts", "known_hosts.old", "authorized_keys", "environment"];
3167
+ var MAX_KEY_FILE_BYTES = 64 * 1024;
3168
+ var CLEAR_ANSWER = "-";
3169
+ var OTHER_KEY_PATH = "\0other";
3170
+ function findPrivateKeys() {
3171
+ const sshDirectory = path.join(os5.homedir(), ".ssh");
3172
+ let names = [];
3173
+ try {
3174
+ names = fs6.readdirSync(sshDirectory);
3175
+ } catch {
3176
+ return [];
3177
+ }
3178
+ const keys = [];
3179
+ for (const name of names) {
3180
+ if (name.endsWith(".pub") == true || NON_KEY_FILE_NAMES.includes(name) == true) {
3181
+ continue;
3182
+ }
3183
+ const fullPath = path.join(sshDirectory, name);
3184
+ let head = "";
3185
+ try {
3186
+ const stat = fs6.statSync(fullPath);
3187
+ if (stat.isFile() == false || stat.size > MAX_KEY_FILE_BYTES) {
3188
+ continue;
3189
+ }
3190
+ const descriptor = fs6.openSync(fullPath, "r");
3191
+ const buffer = Buffer.alloc(64);
3192
+ const bytesRead = fs6.readSync(descriptor, buffer, 0, buffer.length, 0);
3193
+ fs6.closeSync(descriptor);
3194
+ head = buffer.subarray(0, bytesRead).toString("utf8");
3195
+ } catch {
3196
+ continue;
3197
+ }
3198
+ const isPemKey = head.startsWith("-----BEGIN") == true && head.includes("PRIVATE KEY") == true;
3199
+ const isPuttyKey = head.startsWith("PuTTY-User-Key-File") == true;
3200
+ if (isPemKey == false && isPuttyKey == false) {
3201
+ continue;
3202
+ }
3203
+ let hint = "";
3204
+ try {
3205
+ const publicKey = fs6.readFileSync(`${fullPath}.pub`, "utf8").trim().split(/\s+/);
3206
+ hint = publicKey[0].replace(/^ssh-/, "");
3207
+ if (publicKey.length > 2) {
3208
+ hint += ` \xB7 ${publicKey.slice(2).join(" ")}`;
3209
+ }
3210
+ } catch {
3211
+ }
3212
+ keys.push({ path: `~/.ssh/${name}`, hint });
3213
+ }
3214
+ const rank = (key) => {
3215
+ const index = PREFERRED_KEY_NAMES.indexOf(path.basename(key.path));
3216
+ if (index < 0) {
3217
+ return PREFERRED_KEY_NAMES.length;
3218
+ }
3219
+ return index;
3220
+ };
3221
+ return keys.sort((left, right) => rank(left) - rank(right) || left.path.localeCompare(right.path));
3222
+ }
3223
+ async function askPort(prompter, question, current) {
3224
+ for (; ; ) {
3225
+ const answer = await prompter.ask(question, String(current));
3226
+ const parsed = Number(answer);
3227
+ if (Number.isInteger(parsed) == true && parsed > 0 && parsed <= 65535) {
3228
+ return parsed;
3229
+ }
3230
+ prompter.write(" Enter a port number between 1 and 65535.\n");
3231
+ }
3232
+ }
3233
+ async function askOptional(prompter, question, current) {
3234
+ const answer = await prompter.ask(question, current);
3235
+ if (answer === "" || answer === CLEAR_ANSWER) {
3236
+ return void 0;
3237
+ }
3238
+ return answer;
3239
+ }
3240
+ async function askOptionalSecret(prompter, question, current) {
3241
+ let suffix = "(empty for none)";
3242
+ if (current != null) {
3243
+ suffix = `(enter keeps current, ${CLEAR_ANSWER} clears)`;
3244
+ }
3245
+ const answer = await prompter.askSecret(`${question} ${prompter.paint.dim(suffix)}`);
3246
+ if (answer === CLEAR_ANSWER) {
3247
+ return void 0;
3248
+ }
3249
+ if (answer === "") {
3250
+ return current;
3251
+ }
3252
+ return answer;
3253
+ }
3254
+ async function askKeyPath(prompter, current) {
3255
+ const found = findPrivateKeys();
3256
+ let picked = OTHER_KEY_PATH;
3257
+ if (found.length > 0 || current != null) {
3258
+ const items = [];
3259
+ if (current != null && found.some((key) => key.path === current) == false) {
3260
+ items.push({ value: current, label: current, hint: "current" });
3261
+ }
3262
+ for (const key of found) {
3263
+ items.push({ value: key.path, label: key.path, hint: key.hint });
3264
+ }
3265
+ items.push({ separator: true });
3266
+ items.push({ value: OTHER_KEY_PATH, key: "other", label: "Another path\u2026" });
3267
+ picked = await prompter.select("Private key", items, { defaultValue: current ?? found[0]?.path });
3268
+ }
3269
+ if (picked !== OTHER_KEY_PATH) {
3270
+ return picked;
3271
+ }
3272
+ for (; ; ) {
3273
+ const typed = await prompter.askRequired("Private key path");
3274
+ if (fs6.existsSync(expandHomePath(typed)) == true) {
3275
+ return typed;
3276
+ }
3277
+ prompter.write(` ${expandHomePath(typed)} does not exist.
3278
+ `);
3279
+ const useAnyway = await prompter.askYesNo("Use this path anyway?", false);
3280
+ if (useAnyway == true) {
3281
+ return typed;
3282
+ }
3283
+ }
3284
+ }
3285
+ async function askHostQuestions(prompter, existing) {
3286
+ if (existing != null) {
3287
+ prompter.write(prompter.paint.dim(` Enter keeps the value in brackets; ${CLEAR_ANSWER} clears an optional one.
3288
+
3289
+ `));
3290
+ }
3291
+ const host = await prompter.askRequired("Host (hostname or IP)", existing?.host);
3292
+ const port = await askPort(prompter, "Port", existing?.port ?? DEFAULT_SSH_PORT);
3293
+ const username = await prompter.askRequired("Login user", existing?.username);
3294
+ let name = "";
3295
+ const defaultName = existing?.name ?? `ssh-${host}`.replace(/[^A-Za-z0-9_-]+/g, "-").slice(0, 48);
3296
+ for (; ; ) {
3297
+ name = await prompter.askRequired("Server name the agent sees", defaultName);
3298
+ if (SERVER_NAME_PATTERN.test(name) == true) {
3299
+ break;
3300
+ }
3301
+ prompter.write(" Use letters, digits, '-' and '_' only (max 48) \u2014 the name becomes part of every tool name.\n");
3302
+ }
3303
+ const auth = await prompter.select(
3304
+ "Authentication",
3305
+ [
3306
+ { value: "key", label: "Private key file", hint: "only the path is stored \u2014 recommended" },
3307
+ { value: "password", label: "Password", hint: "stored in the config file as plain text" },
3308
+ { value: "agent", label: "SSH agent", hint: "keys already loaded in ssh-agent" }
3309
+ ],
3310
+ { defaultValue: existing?.auth ?? "key" }
3311
+ );
3312
+ let keyPath;
3313
+ let passphrase;
3314
+ let password;
3315
+ if (auth === "key") {
3316
+ keyPath = await askKeyPath(prompter, existing?.keyPath);
3317
+ passphrase = await askOptionalSecret(prompter, "Key passphrase", existing?.passphrase);
3318
+ }
3319
+ if (auth === "password") {
3320
+ password = await askOptionalSecret(prompter, "Password", existing?.password);
3321
+ if (password == null) {
3322
+ prompter.write(" No password given \u2014 falling back to the ssh agent.\n");
3323
+ }
3324
+ }
3325
+ let currentRoute = "direct";
3326
+ if (existing?.jumpHost != null && existing.proxyCommand != null) {
3327
+ currentRoute = "jump-proxy";
3328
+ } else if (existing?.jumpHost != null) {
3329
+ currentRoute = "jump";
3330
+ } else if (existing?.proxyCommand != null) {
3331
+ currentRoute = "proxy";
3332
+ }
3333
+ const route = await prompter.select(
3334
+ "How is it reached?",
3335
+ [
3336
+ { value: "direct", label: "Directly" },
3337
+ { value: "jump", label: "Through a jump host", hint: "ssh -J" },
3338
+ { value: "proxy", label: "Through a proxy command", hint: "e.g. cloudflared access ssh" },
3339
+ { value: "jump-proxy", label: "Proxy command, then a jump host", hint: "cloudflared to the bastion, then on to the host" }
3340
+ ],
3341
+ { defaultValue: currentRoute }
3342
+ );
3343
+ let jumpHost;
3344
+ let jumpPort;
3345
+ let jumpUser;
3346
+ let proxyCommand;
3347
+ if (route === "jump" || route === "jump-proxy") {
3348
+ jumpHost = await prompter.askRequired("Jump host", existing?.jumpHost);
3349
+ jumpPort = await askPort(prompter, "Jump host port", existing?.jumpPort ?? DEFAULT_SSH_PORT);
3350
+ jumpUser = await prompter.askRequired("Jump host user", existing?.jumpUser ?? username);
3351
+ }
3352
+ if (route === "proxy" || route === "jump-proxy") {
3353
+ prompter.write(prompter.paint.dim(" %h / %p / %r expand to the first hop's host, port and user.\n"));
3354
+ proxyCommand = await prompter.askRequired("Proxy command", existing?.proxyCommand ?? "cloudflared access ssh --hostname %h");
3355
+ }
3356
+ const description = await askOptional(prompter, "Description shown to the agent", existing?.description);
3357
+ const readonly = await prompter.askYesNo("Read-only? (rejects writes, redirections, uploads)", existing?.readonly ?? false);
3358
+ let currentAllowedPaths;
3359
+ if (existing != null && existing.allowedPaths.length > 0) {
3360
+ currentAllowedPaths = existing.allowedPaths.join(",");
3361
+ }
3362
+ let allowedPaths = [];
3363
+ const allowedPathsAnswer = await askOptional(
3364
+ prompter,
3365
+ "Limit file tools to path prefixes (comma-separated, empty = anywhere)",
3366
+ currentAllowedPaths
3367
+ );
3368
+ if (allowedPathsAnswer != null) {
3369
+ allowedPaths = allowedPathsAnswer.split(",").map((item) => item.trim()).filter((item) => item !== "");
3370
+ }
3371
+ let resolvedAuth = auth;
3372
+ if (auth === "password" && password == null) {
3373
+ resolvedAuth = "agent";
3374
+ }
3375
+ const answers = {
3376
+ name,
3377
+ host,
3378
+ port,
3379
+ username,
3380
+ auth: resolvedAuth,
3381
+ keyPath,
3382
+ passphrase,
3383
+ password,
3384
+ description,
3385
+ jumpHost,
3386
+ jumpPort,
3387
+ jumpUser,
3388
+ proxyCommand,
3389
+ readonly,
3390
+ allowedPaths,
3391
+ extraEnv: existing?.extraEnv ?? {}
3392
+ };
3393
+ if (existing != null && existing.host === host && existing.port === port) {
3394
+ answers.hostKeyFingerprint = existing.hostKeyFingerprint;
3395
+ }
3396
+ if (existing != null && existing.jumpHost === jumpHost && existing.jumpPort === jumpPort) {
3397
+ answers.jumpHostKeyFingerprint = existing.jumpHostKeyFingerprint;
3398
+ }
3399
+ return answers;
3400
+ }
3401
+ function toMcpServerEntry(value) {
3402
+ if (typeof value !== "object" || value == null) {
3403
+ return null;
3404
+ }
3405
+ const record = value;
3406
+ if (typeof record.command !== "string") {
3407
+ return null;
3408
+ }
3409
+ let args = [];
3410
+ if (Array.isArray(record.args) == true) {
3411
+ args = record.args.filter((item) => typeof item === "string");
3412
+ }
3413
+ const env = {};
3414
+ if (typeof record.env === "object" && record.env != null) {
3415
+ for (const [key, item] of Object.entries(record.env)) {
3416
+ if (typeof item === "string") {
3417
+ env[key] = item;
3418
+ }
3419
+ }
3420
+ }
3421
+ return { command: record.command, args, env };
3422
+ }
3423
+ function readMcpServersJson(document) {
3424
+ if (typeof document !== "object" || document == null || Array.isArray(document) == true) {
3425
+ throw new Error("the config file is not a JSON object");
3426
+ }
3427
+ const entries = {};
3428
+ const servers = document.mcpServers;
3429
+ if (typeof servers !== "object" || servers == null) {
3430
+ return entries;
3431
+ }
3432
+ for (const [name, value] of Object.entries(servers)) {
3433
+ const entry = toMcpServerEntry(value);
3434
+ if (entry != null) {
3435
+ entries[name] = entry;
3436
+ }
3437
+ }
3438
+ return entries;
3439
+ }
3440
+ function readDocument(filePath) {
3441
+ if (fs6.existsSync(filePath) == false) {
3442
+ return {};
3443
+ }
3444
+ const text = fs6.readFileSync(filePath, "utf8");
3445
+ if (text.trim() === "") {
3446
+ return {};
3447
+ }
3448
+ let document;
3449
+ try {
3450
+ document = JSON.parse(text);
3451
+ } catch (ex) {
3452
+ let detail = String(ex);
3453
+ if (ex instanceof Error) {
3454
+ detail = ex.message;
3455
+ }
3456
+ throw new Error(`${filePath} is not valid JSON: ${detail}`);
3457
+ }
3458
+ if (typeof document !== "object" || document == null || Array.isArray(document) == true) {
3459
+ throw new Error(`${filePath} is not a JSON object`);
3460
+ }
3461
+ return document;
3462
+ }
3463
+ function createJsonFileTarget(options) {
3464
+ const { id, label, filePath } = options;
3465
+ function writeDocument(document) {
3466
+ fs6.mkdirSync(path.dirname(filePath), { recursive: true });
3467
+ fs6.writeFileSync(filePath, `${JSON.stringify(document, null, 4)}
3468
+ `, "utf8");
3469
+ }
3470
+ return {
3471
+ id,
3472
+ label,
3473
+ location: filePath,
3474
+ detected: fs6.existsSync(filePath),
3475
+ readEntries() {
3476
+ const document = readDocument(filePath);
3477
+ return readMcpServersJson(document);
3478
+ },
3479
+ writeEntry(name, entry) {
3480
+ const document = readDocument(filePath);
3481
+ let servers = document.mcpServers;
3482
+ if (typeof servers !== "object" || servers == null || Array.isArray(servers) == true) {
3483
+ servers = {};
3484
+ }
3485
+ servers[name] = entry;
3486
+ document.mcpServers = servers;
3487
+ writeDocument(document);
3488
+ return { status: "written", detail: filePath };
3489
+ },
3490
+ removeEntry(name) {
3491
+ const document = readDocument(filePath);
3492
+ const servers = document.mcpServers;
3493
+ if (typeof servers !== "object" || servers == null || Array.isArray(servers) == true) {
3494
+ return { status: "written", detail: filePath };
3495
+ }
3496
+ delete servers[name];
3497
+ writeDocument(document);
3498
+ return { status: "written", detail: filePath };
3499
+ }
3500
+ };
3501
+ }
3502
+
3503
+ // src/modules/manage/targets/claude-code.ts
3504
+ var CLAUDE_CODE_CONFIG_PATH = path.join(os5.homedir(), ".claude.json");
3505
+ var CMD_META_CHARACTER_PATTERN = /([()\][%!^"`<>&|;, *?])/g;
3506
+ function toClaudeAddJsonPayload(entry) {
3507
+ return JSON.stringify({ type: "stdio", command: entry.command, args: entry.args, env: entry.env });
3508
+ }
3509
+ function formatClaudeAddCommand(name, entry) {
3510
+ const payload = toClaudeAddJsonPayload(entry);
3511
+ return `claude mcp add-json ${name} '${payload}' -s user`;
3512
+ }
3513
+ function escapeCmdArgument(argument) {
3514
+ let escaped = argument.replace(/(\\*)"/g, '$1$1\\"');
3515
+ escaped = escaped.replace(/(\\*)$/, "$1$1");
3516
+ escaped = `"${escaped}"`;
3517
+ escaped = escaped.replace(CMD_META_CHARACTER_PATTERN, "^$1");
3518
+ escaped = escaped.replace(CMD_META_CHARACTER_PATTERN, "^$1");
3519
+ return escaped;
3520
+ }
3521
+ function runCliCommand(executable, args) {
3522
+ const isBatchShim = /\.(cmd|bat)$/i.test(executable) == true;
3523
+ if (process.platform !== "win32" || isBatchShim == false) {
3524
+ const result2 = spawnSync(executable, args, { encoding: "utf8", windowsHide: true });
3525
+ return result2;
3526
+ }
3527
+ const commandLine = [executable.replace(CMD_META_CHARACTER_PATTERN, "^$1"), ...args.map(escapeCmdArgument)].join(" ");
3528
+ const result = spawnSync(process.env.ComSpec ?? "cmd.exe", ["/d", "/s", "/c", `"${commandLine}"`], {
3529
+ encoding: "utf8",
3530
+ windowsHide: true,
3531
+ windowsVerbatimArguments: true
3532
+ });
3533
+ return result;
3534
+ }
3535
+ function runClaude(executable, args) {
3536
+ const result = runCliCommand(executable, args);
3537
+ if (result.error != null) {
3538
+ return { status: "unavailable", detail: `could not run claude: ${result.error.message}` };
3539
+ }
3540
+ if (result.status !== 0) {
3541
+ let output = (result.stderr ?? "").trim();
3542
+ if (output === "") {
3543
+ output = (result.stdout ?? "").trim();
3544
+ }
3545
+ return { status: "unavailable", detail: `claude exited with ${result.status}: ${output}` };
3546
+ }
3547
+ return { status: "written", detail: CLAUDE_CODE_CONFIG_PATH };
3548
+ }
3549
+ function readClaudeEntries() {
3550
+ if (fs6.existsSync(CLAUDE_CODE_CONFIG_PATH) == false) {
3551
+ return {};
3552
+ }
3553
+ const text = fs6.readFileSync(CLAUDE_CODE_CONFIG_PATH, "utf8");
3554
+ let document;
3555
+ try {
3556
+ document = JSON.parse(text);
3557
+ } catch (ex) {
3558
+ let detail = String(ex);
3559
+ if (ex instanceof Error) {
3560
+ detail = ex.message;
3561
+ }
3562
+ throw new Error(`${CLAUDE_CODE_CONFIG_PATH} is not valid JSON: ${detail}`);
3563
+ }
3564
+ return readMcpServersJson(document);
3565
+ }
3566
+ function createClaudeCodeTarget() {
3567
+ const executable = findExecutable("claude");
3568
+ return {
3569
+ id: "claude-code",
3570
+ label: "Claude Code (user scope)",
3571
+ location: CLAUDE_CODE_CONFIG_PATH,
3572
+ detected: executable != null || fs6.existsSync(CLAUDE_CODE_CONFIG_PATH) == true,
3573
+ readEntries: readClaudeEntries,
3574
+ writeEntry(name, entry) {
3575
+ if (executable == null) {
3576
+ return {
3577
+ status: "unavailable",
3578
+ detail: `the claude CLI is not on PATH \u2014 run this yourself:
3579
+ ${formatClaudeAddCommand(name, entry)}`
3580
+ };
3581
+ }
3582
+ const previous = readClaudeEntries()[name];
3583
+ if (previous != null) {
3584
+ const removed = runClaude(executable, ["mcp", "remove", name, "-s", "user"]);
3585
+ if (removed.status === "unavailable") {
3586
+ return removed;
3587
+ }
3588
+ }
3589
+ const added = runClaude(executable, ["mcp", "add-json", name, toClaudeAddJsonPayload(entry), "-s", "user"]);
3590
+ if (added.status === "unavailable" && previous != null) {
3591
+ runClaude(executable, ["mcp", "add-json", name, toClaudeAddJsonPayload(previous), "-s", "user"]);
3592
+ return { status: "unavailable", detail: `${added.detail}
3593
+ the previous entry was restored` };
3594
+ }
3595
+ return added;
3596
+ },
3597
+ removeEntry(name) {
3598
+ if (executable == null) {
3599
+ return {
3600
+ status: "unavailable",
3601
+ detail: `the claude CLI is not on PATH \u2014 run this yourself:
3602
+ claude mcp remove ${name} -s user`
3603
+ };
3604
+ }
3605
+ return runClaude(executable, ["mcp", "remove", name, "-s", "user"]);
3606
+ }
3607
+ };
3608
+ }
3609
+
3610
+ // src/modules/manage/targets/toml-subset.ts
3611
+ var BARE_KEY_PATTERN = /^[A-Za-z0-9_-]+$/;
3612
+ var ANY_HEADER_PATTERN = /^\s*\[/;
3613
+ var SERVER_HEADER_PATTERN = /^\s*\[\s*mcp_servers\s*\.\s*([A-Za-z0-9_-]+|"(?:[^"\\]|\\.)*")\s*((?:\.[^\]]*)?)\]\s*(?:#.*)?$/;
3614
+ var KEY_VALUE_PATTERN = /^\s*([A-Za-z0-9_-]+|"(?:[^"\\]|\\.)*")\s*=\s*(.*)$/;
3615
+ var OWNED_TABLE_KEYS = ["command", "args", "env"];
3616
+ var TomlValueParser = class {
3617
+ constructor(text) {
3618
+ this.text = text;
3619
+ this.position = 0;
3620
+ }
3621
+ parse() {
3622
+ const value = this.parseValue();
3623
+ return value;
3624
+ }
3625
+ skipWhitespace() {
3626
+ while (this.position < this.text.length && /\s/.test(this.text[this.position]) == true) {
3627
+ this.position += 1;
3628
+ }
3629
+ }
3630
+ parseValue() {
3631
+ this.skipWhitespace();
3632
+ const current = this.text[this.position];
3633
+ if (current === '"') {
3634
+ return this.parseBasicString();
3635
+ }
3636
+ if (current === "'") {
3637
+ return this.parseLiteralString();
3638
+ }
3639
+ if (current === "[") {
3640
+ return this.parseArray();
3641
+ }
3642
+ if (current === "{") {
3643
+ return this.parseInlineTable();
3644
+ }
3645
+ throw new Error(`unsupported toml value at offset ${this.position}`);
3646
+ }
3647
+ parseBasicString() {
3648
+ this.position += 1;
3649
+ let result = "";
3650
+ while (this.position < this.text.length) {
3651
+ const current = this.text[this.position];
3652
+ if (current === '"') {
3653
+ this.position += 1;
3654
+ return result;
3655
+ }
3656
+ if (current !== "\\") {
3657
+ result += current;
3658
+ this.position += 1;
3659
+ continue;
3660
+ }
3661
+ const escaped = this.text[this.position + 1];
3662
+ this.position += 2;
3663
+ if (escaped === "n") {
3664
+ result += "\n";
3665
+ } else if (escaped === "t") {
3666
+ result += " ";
3667
+ } else if (escaped === "r") {
3668
+ result += "\r";
3669
+ } else if (escaped === "u" || escaped === "U") {
3670
+ let length = 4;
3671
+ if (escaped === "U") {
3672
+ length = 8;
3673
+ }
3674
+ const hex = this.text.slice(this.position, this.position + length);
3675
+ result += String.fromCodePoint(Number.parseInt(hex, 16));
3676
+ this.position += length;
3677
+ } else {
3678
+ result += escaped;
3679
+ }
3680
+ }
3681
+ throw new Error("unterminated toml string");
3682
+ }
3683
+ parseLiteralString() {
3684
+ const end = this.text.indexOf("'", this.position + 1);
3685
+ if (end < 0) {
3686
+ throw new Error("unterminated toml literal string");
3687
+ }
3688
+ const result = this.text.slice(this.position + 1, end);
3689
+ this.position = end + 1;
3690
+ return result;
3691
+ }
3692
+ parseArray() {
3693
+ this.position += 1;
3694
+ const items = [];
3695
+ for (; ; ) {
3696
+ this.skipWhitespace();
3697
+ if (this.position >= this.text.length) {
3698
+ throw new Error("unterminated toml array");
3699
+ }
3700
+ if (this.text[this.position] === "]") {
3701
+ this.position += 1;
3702
+ return items;
3703
+ }
3704
+ items.push(this.parseValue());
3705
+ this.skipWhitespace();
3706
+ if (this.text[this.position] === ",") {
3707
+ this.position += 1;
3708
+ }
3709
+ }
3710
+ }
3711
+ parseInlineTable() {
3712
+ this.position += 1;
3713
+ const table = {};
3714
+ for (; ; ) {
3715
+ this.skipWhitespace();
3716
+ if (this.position >= this.text.length) {
3717
+ throw new Error("unterminated toml inline table");
3718
+ }
3719
+ if (this.text[this.position] === "}") {
3720
+ this.position += 1;
3721
+ return table;
3722
+ }
3723
+ let key;
3724
+ if (this.text[this.position] === '"') {
3725
+ key = this.parseBasicString();
3726
+ } else {
3727
+ const match = /^[A-Za-z0-9_-]+/.exec(this.text.slice(this.position));
3728
+ if (match == null) {
3729
+ throw new Error(`invalid inline table key at offset ${this.position}`);
3730
+ }
3731
+ key = match[0];
3732
+ this.position += key.length;
3733
+ }
3734
+ this.skipWhitespace();
3735
+ if (this.text[this.position] !== "=") {
3736
+ throw new Error(`expected '=' at offset ${this.position}`);
3737
+ }
3738
+ this.position += 1;
3739
+ table[key] = this.parseValue();
3740
+ this.skipWhitespace();
3741
+ if (this.text[this.position] === ",") {
3742
+ this.position += 1;
3743
+ }
3744
+ }
3745
+ }
3746
+ };
3747
+ function unquoteKey(rawKey) {
3748
+ if (rawKey.startsWith('"') == false) {
3749
+ return rawKey;
3750
+ }
3751
+ const parsed = new TomlValueParser(rawKey).parse();
3752
+ return parsed;
3753
+ }
3754
+ function bracketBalance(text) {
3755
+ let balance = 0;
3756
+ let quote = null;
3757
+ for (let index = 0; index < text.length; index += 1) {
3758
+ const current = text[index];
3759
+ if (quote != null) {
3760
+ if (current === "\\" && quote === '"') {
3761
+ index += 1;
3762
+ } else if (current === quote) {
3763
+ quote = null;
3764
+ }
3765
+ continue;
3766
+ }
3767
+ if (current === '"' || current === "'") {
3768
+ quote = current;
3769
+ } else if (current === "#") {
3770
+ break;
3771
+ } else if (current === "[" || current === "{") {
3772
+ balance += 1;
3773
+ } else if (current === "]" || current === "}") {
3774
+ balance -= 1;
3775
+ }
3776
+ }
3777
+ return balance;
3778
+ }
3779
+ function stripComment(text) {
3780
+ let quote = null;
3781
+ for (let index = 0; index < text.length; index += 1) {
3782
+ const current = text[index];
3783
+ if (quote != null) {
3784
+ if (current === "\\" && quote === '"') {
3785
+ index += 1;
3786
+ } else if (current === quote) {
3787
+ quote = null;
3788
+ }
3789
+ continue;
3790
+ }
3791
+ if (current === '"' || current === "'") {
3792
+ quote = current;
3793
+ } else if (current === "#") {
3794
+ return text.slice(0, index);
3795
+ }
3796
+ }
3797
+ return text;
3798
+ }
3799
+ function readStatements(body) {
3800
+ const statements = [];
3801
+ let index = 0;
3802
+ while (index < body.length) {
3803
+ const match = KEY_VALUE_PATTERN.exec(body[index]);
3804
+ if (match == null) {
3805
+ index += 1;
3806
+ continue;
3807
+ }
3808
+ const start = index;
3809
+ let rawValue = stripComment(match[2]);
3810
+ let balance = bracketBalance(rawValue);
3811
+ index += 1;
3812
+ while (balance > 0 && index < body.length) {
3813
+ const continuation = stripComment(body[index]);
3814
+ rawValue += `
3815
+ ${continuation}`;
3816
+ balance += bracketBalance(continuation);
3817
+ index += 1;
3818
+ }
3819
+ statements.push({ key: unquoteKey(match[1]), rawValue, start, end: index });
3820
+ }
3821
+ return statements;
3822
+ }
3823
+ function splitSections(lines) {
3824
+ const sections = [{ header: null, serverName: null, subPath: "", body: [] }];
3825
+ let balance = 0;
3826
+ for (const line of lines) {
3827
+ const current = sections[sections.length - 1];
3828
+ if (balance > 0) {
3829
+ current.body.push(line);
3830
+ balance += bracketBalance(stripComment(line));
3831
+ continue;
3832
+ }
3833
+ if (ANY_HEADER_PATTERN.test(line) == true) {
3834
+ const serverMatch = SERVER_HEADER_PATTERN.exec(line);
3835
+ let serverName = null;
3836
+ let subPath = "";
3837
+ if (serverMatch != null) {
3838
+ serverName = unquoteKey(serverMatch[1]);
3839
+ subPath = serverMatch[2].replace(/^\./, "").replace(/\s+/g, "");
3840
+ }
3841
+ sections.push({ header: line, serverName, subPath, body: [] });
3842
+ continue;
3843
+ }
3844
+ current.body.push(line);
3845
+ const keyValueMatch = KEY_VALUE_PATTERN.exec(line);
3846
+ if (keyValueMatch != null) {
3847
+ balance = bracketBalance(stripComment(keyValueMatch[2]));
3848
+ }
3849
+ }
3850
+ return sections;
3851
+ }
3852
+ function parseStatementValue(statement) {
3853
+ try {
3854
+ const value = new TomlValueParser(statement.rawValue).parse();
3855
+ return value;
3856
+ } catch {
3857
+ return null;
3858
+ }
3859
+ }
3860
+ function parseMcpServersToml(text) {
3861
+ const sections = splitSections(text.split(/\r?\n/));
3862
+ const entries = {};
3863
+ const envTables = {};
3864
+ for (const section of sections) {
3865
+ if (section.serverName == null) {
3866
+ continue;
3867
+ }
3868
+ if (section.subPath === "env") {
3869
+ const envTable = {};
3870
+ for (const statement of readStatements(section.body)) {
3871
+ const value = parseStatementValue(statement);
3872
+ if (typeof value === "string") {
3873
+ envTable[statement.key] = value;
3874
+ }
3875
+ }
3876
+ envTables[section.serverName] = envTable;
3877
+ continue;
3878
+ }
3879
+ if (section.subPath !== "") {
3880
+ continue;
3881
+ }
3882
+ let command = null;
3883
+ let args = [];
3884
+ const env = {};
3885
+ for (const statement of readStatements(section.body)) {
3886
+ const value = parseStatementValue(statement);
3887
+ if (statement.key === "command" && typeof value === "string") {
3888
+ command = value;
3889
+ } else if (statement.key === "args" && Array.isArray(value) == true) {
3890
+ args = value.filter((item) => typeof item === "string");
3891
+ } else if (statement.key === "env" && value != null && typeof value === "object" && Array.isArray(value) == false) {
3892
+ for (const [key, item] of Object.entries(value)) {
3893
+ if (typeof item === "string") {
3894
+ env[key] = item;
3895
+ }
3896
+ }
3897
+ }
3898
+ }
3899
+ if (command != null) {
3900
+ entries[section.serverName] = { command, args, env };
3901
+ }
3902
+ }
3903
+ for (const [name, envTable] of Object.entries(envTables)) {
3904
+ if (entries[name] != null) {
3905
+ Object.assign(entries[name].env, envTable);
3906
+ }
3907
+ }
3908
+ return entries;
3909
+ }
3910
+ function quoteTomlString(value) {
3911
+ const escaped = value.replace(/\\/g, "\\\\").replace(/"/g, '\\"').replace(/\n/g, "\\n").replace(/\r/g, "\\r").replace(/\t/g, "\\t");
3912
+ return `"${escaped}"`;
3913
+ }
3914
+ function formatTomlKey(key) {
3915
+ if (BARE_KEY_PATTERN.test(key) == true) {
3916
+ return key;
3917
+ }
3918
+ return quoteTomlString(key);
3919
+ }
3920
+ function renderOwnedLines(entry) {
3921
+ return [
3922
+ `command = ${quoteTomlString(entry.command)}`,
3923
+ `args = [${entry.args.map((argument) => quoteTomlString(argument)).join(", ")}]`
3924
+ ];
3925
+ }
3926
+ function renderEnvLines(entry) {
3927
+ return Object.entries(entry.env).map(([key, value]) => `${formatTomlKey(key)} = ${quoteTomlString(value)}`);
3928
+ }
3929
+ function renderMcpServerTable(name, entry) {
3930
+ const tableKey = formatTomlKey(name);
3931
+ const lines = [`[mcp_servers.${tableKey}]`, ...renderOwnedLines(entry)];
3932
+ const envLines = renderEnvLines(entry);
3933
+ if (envLines.length > 0) {
3934
+ lines.push("");
3935
+ lines.push(`[mcp_servers.${tableKey}.env]`);
3936
+ lines.push(...envLines);
3937
+ }
3938
+ return `${lines.join("\n")}
3939
+ `;
3940
+ }
3941
+ function isBlank(line) {
3942
+ return line.trim() === "";
3943
+ }
3944
+ function joinSections(sections, eol) {
3945
+ const lines = [];
3946
+ for (const section of sections) {
3947
+ if (section.header != null) {
3948
+ lines.push(section.header);
3949
+ }
3950
+ lines.push(...section.body);
3951
+ }
3952
+ return lines.join(eol);
3953
+ }
3954
+ function writeMcpServerToml(text, name, entry) {
3955
+ let eol = "\n";
3956
+ if (text.includes("\r\n") == true) {
3957
+ eol = "\r\n";
3958
+ }
3959
+ const sections = splitSections(text.split(/\r?\n/));
3960
+ const isOwn = (section) => section.serverName === name;
3961
+ if (entry == null) {
3962
+ const kept = sections.filter((section) => isOwn(section) == false);
3963
+ const removedText = joinSections(kept, eol);
3964
+ return removedText;
3965
+ }
3966
+ const tableKey = formatTomlKey(name);
3967
+ const envLines = renderEnvLines(entry);
3968
+ const tableIndex = sections.findIndex((section) => isOwn(section) == true && section.subPath === "");
3969
+ if (tableIndex < 0) {
3970
+ const withoutStrayEnv = sections.filter((section) => (isOwn(section) == true && section.subPath === "env") == false);
3971
+ let prefix = joinSections(withoutStrayEnv, eol);
3972
+ if (prefix.trim() === "") {
3973
+ prefix = "";
3974
+ } else {
3975
+ prefix = prefix.replace(/(\r?\n)*$/, "");
3976
+ prefix = `${prefix}${eol}${eol}`;
3977
+ }
3978
+ const block = renderMcpServerTable(name, entry).replace(/\n/g, eol);
3979
+ return `${prefix}${block}`;
3980
+ }
3981
+ const table = sections[tableIndex];
3982
+ const ownedLineIndexes = /* @__PURE__ */ new Set();
3983
+ for (const statement of readStatements(table.body)) {
3984
+ if (OWNED_TABLE_KEYS.includes(statement.key) == true) {
3985
+ for (let index = statement.start; index < statement.end; index += 1) {
3986
+ ownedLineIndexes.add(index);
3987
+ }
3988
+ }
3989
+ }
3990
+ const userLines = table.body.filter((_line, index) => ownedLineIndexes.has(index) == false);
3991
+ let trailingBlankCount = 0;
3992
+ while (trailingBlankCount < userLines.length && isBlank(userLines[userLines.length - 1 - trailingBlankCount]) == true) {
3993
+ trailingBlankCount += 1;
3994
+ }
3995
+ const trailingBlanks = userLines.slice(userLines.length - trailingBlankCount);
3996
+ const userContent = userLines.slice(0, userLines.length - trailingBlankCount);
3997
+ const rebuilt = [];
3998
+ for (let index = 0; index < sections.length; index += 1) {
3999
+ const section = sections[index];
4000
+ if (isOwn(section) == true && section.subPath === "env") {
4001
+ continue;
4002
+ }
4003
+ if (index !== tableIndex) {
4004
+ rebuilt.push(section);
4005
+ continue;
4006
+ }
4007
+ if (envLines.length === 0) {
4008
+ rebuilt.push({ ...section, body: [...renderOwnedLines(entry), ...userContent, ...trailingBlanks] });
4009
+ continue;
4010
+ }
4011
+ rebuilt.push({ ...section, body: [...renderOwnedLines(entry), ...userContent, ""] });
4012
+ rebuilt.push({
4013
+ header: `[mcp_servers.${tableKey}.env]`,
4014
+ serverName: name,
4015
+ subPath: "env",
4016
+ body: [...envLines, ...trailingBlanks]
4017
+ });
4018
+ }
4019
+ const rebuiltText = joinSections(rebuilt, eol);
4020
+ return rebuiltText;
4021
+ }
4022
+
4023
+ // src/modules/manage/targets/codex.ts
4024
+ var CODEX_CONFIG_PATH = path.join(os5.homedir(), ".codex", "config.toml");
4025
+ function createCodexTarget() {
4026
+ function readText() {
4027
+ if (fs6.existsSync(CODEX_CONFIG_PATH) == false) {
4028
+ return "";
4029
+ }
4030
+ return fs6.readFileSync(CODEX_CONFIG_PATH, "utf8");
4031
+ }
4032
+ function writeText(text) {
4033
+ fs6.mkdirSync(path.dirname(CODEX_CONFIG_PATH), { recursive: true });
4034
+ fs6.writeFileSync(CODEX_CONFIG_PATH, text, "utf8");
4035
+ return { status: "written", detail: CODEX_CONFIG_PATH };
4036
+ }
4037
+ return {
4038
+ id: "codex",
4039
+ label: "Codex CLI",
4040
+ location: CODEX_CONFIG_PATH,
4041
+ detected: findExecutable("codex") != null || fs6.existsSync(CODEX_CONFIG_PATH) == true,
4042
+ readEntries() {
4043
+ const text = readText();
4044
+ return parseMcpServersToml(text);
4045
+ },
4046
+ writeEntry(name, entry) {
4047
+ const text = readText();
4048
+ const updated = writeMcpServerToml(text, name, entry);
4049
+ return writeText(updated);
4050
+ },
4051
+ removeEntry(name) {
4052
+ const text = readText();
4053
+ const updated = writeMcpServerToml(text, name, null);
4054
+ return writeText(updated);
4055
+ }
4056
+ };
1982
4057
  }
1983
- function readIntegerEnv(name) {
1984
- const value = readEnv(name);
1985
- if (value == null) {
1986
- return void 0;
4058
+
4059
+ // src/modules/manage/targets/index.ts
4060
+ function claudeDesktopConfigPath() {
4061
+ if (process.platform === "win32") {
4062
+ const appData = process.env.APPDATA ?? path.join(os5.homedir(), "AppData", "Roaming");
4063
+ return path.join(appData, "Claude", "claude_desktop_config.json");
1987
4064
  }
1988
- const parsed = Number(value);
1989
- if (Number.isInteger(parsed) == false || parsed <= 0) {
1990
- throw new Error(`${name} must be a positive integer (got "${value}")`);
4065
+ if (process.platform === "darwin") {
4066
+ return path.join(os5.homedir(), "Library", "Application Support", "Claude", "claude_desktop_config.json");
1991
4067
  }
1992
- return parsed;
4068
+ return path.join(os5.homedir(), ".config", "Claude", "claude_desktop_config.json");
1993
4069
  }
1994
- function readListEnv(name) {
1995
- const value = readEnv(name);
1996
- if (value == null) {
1997
- return void 0;
4070
+ function listConfigTargets() {
4071
+ const targets = [
4072
+ createClaudeCodeTarget(),
4073
+ createCodexTarget(),
4074
+ createJsonFileTarget({ id: "claude-desktop", label: "Claude Desktop", filePath: claudeDesktopConfigPath() }),
4075
+ createJsonFileTarget({ id: "cursor", label: "Cursor", filePath: path.join(os5.homedir(), ".cursor", "mcp.json") })
4076
+ ];
4077
+ const detected = targets.filter((target) => target.detected == true);
4078
+ const others = targets.filter((target) => target.detected == false);
4079
+ return [...detected, ...others];
4080
+ }
4081
+
4082
+ // src/modules/manage/index.ts
4083
+ var SECRET_ENV_NAMES = [
4084
+ SINGLE_HOST_ENV.PASSWORD,
4085
+ SINGLE_HOST_ENV.PASSPHRASE,
4086
+ SINGLE_HOST_ENV.JUMP_PASSWORD,
4087
+ SINGLE_HOST_ENV.JUMP_PASSPHRASE
4088
+ ];
4089
+ var HOST_VALUE_PREFIX = "host:";
4090
+ function errorMessage(error) {
4091
+ if (error instanceof Error) {
4092
+ return error.message;
1998
4093
  }
1999
- const items = value.split(",").map((item) => item.trim()).filter((item) => item !== "");
2000
- if (items.length === 0) {
2001
- return void 0;
4094
+ return String(error);
4095
+ }
4096
+ function maskSecrets(entry) {
4097
+ const env = {};
4098
+ for (const [name, value] of Object.entries(entry.env)) {
4099
+ if (SECRET_ENV_NAMES.includes(name) == true) {
4100
+ env[name] = "********";
4101
+ continue;
4102
+ }
4103
+ env[name] = value;
2002
4104
  }
2003
- return items;
4105
+ return { ...entry, env };
2004
4106
  }
2005
- function compileDenyPatterns(sources) {
2006
- return sources.map((source) => {
2007
- try {
2008
- return new RegExp(source, "i");
2009
- } catch (ex) {
2010
- const _logger = $logger.child({ context: "compileDenyPatterns" });
2011
- _logger.error(ex, "denyPatterns entry is not a valid regular expression");
2012
- let detail = String(ex);
2013
- if (ex instanceof Error) {
2014
- detail = ex.message;
4107
+ function formatForTarget(target, name, entry) {
4108
+ if (target.id === "codex") {
4109
+ return renderMcpServerTable(name, entry);
4110
+ }
4111
+ return `"${name}": ${JSON.stringify(entry, null, 4)}
4112
+ `;
4113
+ }
4114
+ function indent(text) {
4115
+ return text.replace(/\n$/, "").split("\n").map((line) => ` ${line}`).join("\n");
4116
+ }
4117
+ function reportWrite(prompter, result, action) {
4118
+ if (result.status === "written") {
4119
+ prompter.write(` ${prompter.paint.success(action)} ${prompter.paint.dim(result.detail)}
4120
+ `);
4121
+ prompter.write(prompter.paint.dim(" Restart the client (or reconnect it from its MCP menu) to pick up the change.\n\n"));
4122
+ return;
4123
+ }
4124
+ prompter.write(` Not ${action.toLowerCase()}: ${result.detail}
4125
+
4126
+ `);
4127
+ }
4128
+ function profileFromEntry(output, entry) {
4129
+ try {
4130
+ const profile = loadHostProfile(entry.env);
4131
+ if (profile == null) {
4132
+ output.write(" The entry has no host.\n");
4133
+ }
4134
+ return profile;
4135
+ } catch (ex) {
4136
+ output.write(` The server would refuse to start with this entry: ${errorMessage(ex)}
4137
+ `);
4138
+ return null;
4139
+ }
4140
+ }
4141
+ async function verifyAnswers(prompter, output, initial) {
4142
+ let answers = initial;
4143
+ for (; ; ) {
4144
+ const testNow = await prompter.askYesNo("Test the connection now?", true);
4145
+ if (testNow == false) {
4146
+ return answers;
4147
+ }
4148
+ output.write("\n");
4149
+ const profile = profileFromEntry(output, answersToEntry(answers));
4150
+ if (profile != null) {
4151
+ const result = await runConnectionCheck(profile, output);
4152
+ output.write("\n");
4153
+ if (result.connected == true) {
4154
+ if (result.hostKeyFingerprint != null && answers.hostKeyFingerprint == null) {
4155
+ const pin = await prompter.askYesNo("Pin this host key? (a changed key then aborts the connection)", true);
4156
+ if (pin == true) {
4157
+ answers = { ...answers, hostKeyFingerprint: result.hostKeyFingerprint };
4158
+ }
4159
+ }
4160
+ if (result.jumpHostKeyFingerprint != null && answers.jumpHost != null && answers.jumpHostKeyFingerprint == null) {
4161
+ const pin = await prompter.askYesNo("Pin the jump host key too?", true);
4162
+ if (pin == true) {
4163
+ answers = { ...answers, jumpHostKeyFingerprint: result.jumpHostKeyFingerprint };
4164
+ }
4165
+ }
4166
+ return answers;
4167
+ }
4168
+ const hostKeyChanged = result.hostKeyFingerprint != null && answers.hostKeyFingerprint != null && result.hostKeyFingerprint !== answers.hostKeyFingerprint;
4169
+ if (hostKeyChanged == true) {
4170
+ output.write(" The host presented a different key than the pinned one. Re-pin only if you know it was rebuilt.\n");
4171
+ const repin = await prompter.askYesNo(`Pin ${result.hostKeyFingerprint} instead?`, false);
4172
+ if (repin == true) {
4173
+ answers = { ...answers, hostKeyFingerprint: result.hostKeyFingerprint ?? void 0 };
4174
+ continue;
4175
+ }
4176
+ }
4177
+ const jumpKeyChanged = result.jumpHostKeyFingerprint != null && answers.jumpHostKeyFingerprint != null && result.jumpHostKeyFingerprint !== answers.jumpHostKeyFingerprint;
4178
+ if (jumpKeyChanged == true) {
4179
+ output.write(" The jump host presented a different key than the pinned one. Re-pin only if you know it was rebuilt.\n");
4180
+ const repin = await prompter.askYesNo(`Pin ${result.jumpHostKeyFingerprint} instead?`, false);
4181
+ if (repin == true) {
4182
+ answers = { ...answers, jumpHostKeyFingerprint: result.jumpHostKeyFingerprint ?? void 0 };
4183
+ continue;
4184
+ }
2015
4185
  }
2016
- throw new Error(`${SINGLE_HOST_ENV.DENY_PATTERNS} has an invalid entry /${source}/: ${detail}`);
2017
4186
  }
2018
- });
4187
+ const next = await prompter.select(
4188
+ "The check failed. What now?",
4189
+ [
4190
+ { value: "edit", key: "e", label: "Change the answers" },
4191
+ { value: "retry", key: "r", label: "Try again", hint: "e.g. after starting a tunnel" },
4192
+ { value: "write", key: "w", label: "Write it anyway", hint: "the host may be unreachable from here" },
4193
+ { value: "cancel", key: "c", label: "Cancel", hint: "nothing is written" }
4194
+ ],
4195
+ { defaultValue: "edit", cancelValue: "cancel" }
4196
+ );
4197
+ if (next === "cancel") {
4198
+ return null;
4199
+ }
4200
+ if (next === "write") {
4201
+ return answers;
4202
+ }
4203
+ if (next === "edit") {
4204
+ output.write("\n");
4205
+ answers = await askHostQuestions(prompter, answers);
4206
+ }
4207
+ }
2019
4208
  }
2020
- function loadHostProfile() {
2021
- const host = readEnv(SINGLE_HOST_ENV.HOST);
2022
- if (host == null) {
2023
- const _startupLogger = $logger.child({ context: "loadHostProfile" });
2024
- _startupLogger.warn("no host is registered; set the connection variables and restart", {
2025
- env_vars: [SINGLE_HOST_ENV.HOST, SINGLE_HOST_ENV.USER]
2026
- });
2027
- return null;
4209
+ async function addOrEditHost(prompter, output, target, entries, existingName) {
4210
+ let existing;
4211
+ if (existingName != null) {
4212
+ existing = entryToAnswers(existingName, entries[existingName]);
4213
+ output.write(`
4214
+ ${prompter.paint.bold(`Editing ${existingName}`)}
4215
+ `);
4216
+ } else {
4217
+ output.write(`
4218
+ ${prompter.paint.bold("Adding a host")}
4219
+ `);
2028
4220
  }
2029
- const username = readEnv(SINGLE_HOST_ENV.USER);
2030
- if (username == null) {
2031
- throw new Error(`${SINGLE_HOST_ENV.HOST} is set, so ${SINGLE_HOST_ENV.USER} is required`);
4221
+ const asked = await askHostQuestions(prompter, existing);
4222
+ output.write("\n");
4223
+ const answers = await verifyAnswers(prompter, output, asked);
4224
+ if (answers == null) {
4225
+ output.write(" Cancelled \u2014 nothing was written.\n\n");
4226
+ return;
2032
4227
  }
2033
- const name = readEnv(SINGLE_HOST_ENV.NAME) ?? host;
2034
- const _logger = $logger.child({ context: "loadHostProfile", profile: name });
2035
- const allowCommands = readListEnv(SINGLE_HOST_ENV.ALLOW_COMMANDS) ?? [];
2036
- if (allowCommands.length > 0 && allowCommands.includes("pwd") == false) {
2037
- allowCommands.push("pwd");
4228
+ if (answers.name !== existingName && entries[answers.name] != null) {
4229
+ const replace = await prompter.askYesNo(`"${answers.name}" already exists in this file. Replace it?`, false);
4230
+ if (replace == false) {
4231
+ output.write(" Cancelled \u2014 nothing was written.\n\n");
4232
+ return;
4233
+ }
2038
4234
  }
2039
- const policy = {
2040
- readonly: readBooleanEnv(SINGLE_HOST_ENV.READONLY) ?? false,
2041
- allowSudo: readBooleanEnv(SINGLE_HOST_ENV.ALLOW_SUDO) ?? true,
2042
- execTimeoutMs: readIntegerEnv(SINGLE_HOST_ENV.EXEC_TIMEOUT_MS) ?? DEFAULT_EXEC_TIMEOUT_MS,
2043
- connectTimeoutMs: readIntegerEnv(SINGLE_HOST_ENV.CONNECT_TIMEOUT_MS) ?? DEFAULT_CONNECT_TIMEOUT_MS,
2044
- maxOutputCharacters: readIntegerEnv(SINGLE_HOST_ENV.MAX_OUTPUT_CHARACTERS) ?? DEFAULT_MAX_OUTPUT_CHARACTERS,
2045
- maxReadFileBytes: readIntegerEnv(SINGLE_HOST_ENV.MAX_READ_FILE_BYTES) ?? DEFAULT_MAX_READ_FILE_BYTES,
2046
- allowCommands,
2047
- denyPatterns: compileDenyPatterns(readListEnv(SINGLE_HOST_ENV.DENY_PATTERNS) ?? []),
2048
- allowedPaths: readListEnv(SINGLE_HOST_ENV.ALLOWED_PATHS) ?? []
2049
- };
2050
- const profile = {
2051
- name,
2052
- host,
2053
- port: readIntegerEnv(SINGLE_HOST_ENV.PORT) ?? DEFAULT_SSH_PORT,
2054
- username,
2055
- description: readEnv(SINGLE_HOST_ENV.DESCRIPTION),
2056
- passphrase: readEnv(SINGLE_HOST_ENV.PASSPHRASE),
2057
- password: readEnv(SINGLE_HOST_ENV.PASSWORD),
2058
- hostKeyFingerprint: readEnv(SINGLE_HOST_ENV.HOST_KEY),
2059
- defaultCwd: readEnv(SINGLE_HOST_ENV.CWD),
2060
- policy
2061
- };
2062
- const keyPath = readEnv(SINGLE_HOST_ENV.KEY);
2063
- if (keyPath != null) {
2064
- const expandedKeyPath = expandHomePath(keyPath);
2065
- profile.privateKeyPath = expandedKeyPath;
2066
- if (fs.existsSync(expandedKeyPath) == false) {
2067
- _logger.warn(`${SINGLE_HOST_ENV.KEY} does not exist; connections will fail`, {
2068
- private_key_path: expandedKeyPath
2069
- });
4235
+ const entry = answersToEntry(answers);
4236
+ output.write(`
4237
+ ${prompter.paint.dim(`This goes into ${target.location}:`)}
4238
+
4239
+ `);
4240
+ output.write(`${indent(formatForTarget(target, answers.name, maskSecrets(entry)))}
4241
+
4242
+ `);
4243
+ const confirmed = await prompter.askYesNo("Write it?", true);
4244
+ if (confirmed == false) {
4245
+ output.write(" Not written. Pick the host and choose Print to get the entry ready to paste.\n\n");
4246
+ return;
4247
+ }
4248
+ const written = target.writeEntry(answers.name, entry);
4249
+ reportWrite(prompter, written, "Written");
4250
+ if (written.status === "written" && existingName != null && existingName !== answers.name) {
4251
+ const removed = target.removeEntry(existingName);
4252
+ if (removed.status === "unavailable") {
4253
+ output.write(` The old name ${existingName} is still there: ${removed.detail}
4254
+
4255
+ `);
2070
4256
  }
2071
4257
  }
2072
- _logger.info("host profile loaded", {
2073
- host,
2074
- port: profile.port,
2075
- username,
2076
- readonly: policy.readonly
4258
+ }
4259
+ async function checkHost(prompter, output, target, name, entry) {
4260
+ output.write("\n");
4261
+ const profile = profileFromEntry(output, entry);
4262
+ if (profile == null) {
4263
+ output.write("\n");
4264
+ return;
4265
+ }
4266
+ const result = await runConnectionCheck(profile, output);
4267
+ output.write("\n");
4268
+ if (result.connected == false) {
4269
+ return;
4270
+ }
4271
+ const env = { ...entry.env };
4272
+ let changed = false;
4273
+ if (result.hostKeyFingerprint != null && env[SINGLE_HOST_ENV.HOST_KEY] == null) {
4274
+ const pin = await prompter.askYesNo("Pin this host key?", true);
4275
+ if (pin == true) {
4276
+ env[SINGLE_HOST_ENV.HOST_KEY] = result.hostKeyFingerprint;
4277
+ changed = true;
4278
+ }
4279
+ }
4280
+ if (result.jumpHostKeyFingerprint != null && env[SINGLE_HOST_ENV.JUMP_HOST_KEY] == null) {
4281
+ const pin = await prompter.askYesNo("Pin the jump host key too?", true);
4282
+ if (pin == true) {
4283
+ env[SINGLE_HOST_ENV.JUMP_HOST_KEY] = result.jumpHostKeyFingerprint;
4284
+ changed = true;
4285
+ }
4286
+ }
4287
+ if (changed == true) {
4288
+ const written = target.writeEntry(name, { ...entry, env });
4289
+ reportWrite(prompter, written, "Pinned");
4290
+ }
4291
+ }
4292
+ function printHost(prompter, name, entry) {
4293
+ prompter.write(`
4294
+ ${prompter.paint.dim('JSON \u2014 Claude Desktop, Cursor, .mcp.json (inside "mcpServers"):')}
4295
+
4296
+ `);
4297
+ prompter.write(`${indent(`"${name}": ${JSON.stringify(entry, null, 4)}`)}
4298
+
4299
+ `);
4300
+ prompter.write(` ${prompter.paint.dim("TOML \u2014 Codex (~/.codex/config.toml):")}
4301
+
4302
+ `);
4303
+ prompter.write(`${indent(renderMcpServerTable(name, entry))}
4304
+
4305
+ `);
4306
+ prompter.write(` ${prompter.paint.dim("Claude Code CLI (bash / zsh / Git Bash):")}
4307
+
4308
+ `);
4309
+ prompter.write(`${indent(formatClaudeAddCommand(name, entry))}
4310
+
4311
+ `);
4312
+ }
4313
+ function buildHostItems(names, entries) {
4314
+ const nameWidth = Math.max(...names.map((name) => displayWidth(name)));
4315
+ const summaries = names.map((name) => summarizeEntry(entries[name]));
4316
+ const endpointWidth = Math.max(...summaries.map((summary) => displayWidth(summary.endpoint)));
4317
+ return names.map((name, index) => {
4318
+ const summary = summaries[index];
4319
+ const hintParts = [summary.auth];
4320
+ if (summary.notes !== "") {
4321
+ hintParts.push(summary.notes);
4322
+ }
4323
+ return {
4324
+ value: `${HOST_VALUE_PREFIX}${name}`,
4325
+ key: name,
4326
+ label: `${name.padEnd(nameWidth)} ${summary.endpoint.padEnd(endpointWidth)}`,
4327
+ hint: hintParts.join(" \xB7 ")
4328
+ };
2077
4329
  });
2078
- return profile;
2079
4330
  }
2080
- function toHostSummary(profile) {
2081
- let authMethod = "agent";
2082
- if (profile.privateKeyPath != null) {
2083
- authMethod = "privateKey";
2084
- } else if (profile.password != null) {
2085
- authMethod = "password";
4331
+ async function manageHost(prompter, output, target, entries, name) {
4332
+ const action = await prompter.select(
4333
+ name,
4334
+ [
4335
+ { value: "edit", key: "e", label: "Edit", hint: "change the answers, re-check, re-write" },
4336
+ { value: "check", key: "c", label: "Check the connection", hint: "connect now and offer to pin the host key" },
4337
+ { value: "print", key: "p", label: "Print the entry", hint: "JSON, Codex TOML and a claude command, ready to paste" },
4338
+ { value: "remove", key: "r", label: "Remove", hint: `from ${target.label}` },
4339
+ { separator: true },
4340
+ { value: "back", key: "b", label: "Back" }
4341
+ ],
4342
+ { defaultValue: "edit", cancelValue: "back" }
4343
+ );
4344
+ if (action === "edit") {
4345
+ await addOrEditHost(prompter, output, target, entries, name);
4346
+ return;
4347
+ }
4348
+ if (action === "check") {
4349
+ await checkHost(prompter, output, target, name, entries[name]);
4350
+ return;
4351
+ }
4352
+ if (action === "print") {
4353
+ printHost(prompter, name, entries[name]);
4354
+ return;
4355
+ }
4356
+ if (action === "remove") {
4357
+ const remove = await prompter.askYesNo(`Remove ${name} from ${target.location}?`, false);
4358
+ if (remove == true) {
4359
+ reportWrite(prompter, target.removeEntry(name), "Removed");
4360
+ }
4361
+ }
4362
+ }
4363
+ async function runConfigCommand(options) {
4364
+ const { input, output } = options;
4365
+ const targets = options.targets ?? listConfigTargets();
4366
+ let target = targets[0];
4367
+ if (options.targetId != null) {
4368
+ const requested = targets.find((candidate) => candidate.id === options.targetId);
4369
+ if (requested == null) {
4370
+ output.write(`Unknown client "${options.targetId}". One of: ${targets.map((candidate) => candidate.id).join(", ")}
4371
+ `);
4372
+ return 1;
4373
+ }
4374
+ target = requested;
4375
+ }
4376
+ const prompter = new Prompter(input, output);
4377
+ const paint = prompter.paint;
4378
+ try {
4379
+ for (; ; ) {
4380
+ let entries = {};
4381
+ let names = [];
4382
+ let readError = null;
4383
+ try {
4384
+ entries = target.readEntries();
4385
+ names = Object.keys(entries).filter((name) => isOurEntry(entries[name]) == true);
4386
+ } catch (ex) {
4387
+ readError = errorMessage(ex);
4388
+ }
4389
+ output.write(`
4390
+ ${paint.bold(target.label)} ${paint.dim(target.location)}
4391
+ `);
4392
+ if (readError != null) {
4393
+ output.write(` Cannot read it: ${readError}
4394
+ Fix the file by hand, or switch to another client.
4395
+ `);
4396
+ } else {
4397
+ const otherCount = Object.keys(entries).length - names.length;
4398
+ if (otherCount > 0) {
4399
+ output.write(paint.dim(` ${otherCount} other MCP server(s) in this file are not managed here.
4400
+ `));
4401
+ }
4402
+ }
4403
+ output.write("\n");
4404
+ const items = [];
4405
+ if (names.length > 0) {
4406
+ items.push(...buildHostItems(names, entries));
4407
+ items.push({ separator: true });
4408
+ }
4409
+ if (readError == null) {
4410
+ items.push({ value: "add", key: "a", label: "Add a host" });
4411
+ }
4412
+ const otherTargets = targets.filter((candidate) => candidate.id !== target.id);
4413
+ if (otherTargets.length > 0) {
4414
+ const detectedOthers = otherTargets.filter((candidate) => candidate.detected == true).map((candidate) => candidate.label);
4415
+ let switchHint = "";
4416
+ if (detectedOthers.length > 0) {
4417
+ switchHint = `also found: ${detectedOthers.join(", ")}`;
4418
+ }
4419
+ items.push({ value: "switch", key: "t", label: "Switch client", hint: switchHint });
4420
+ }
4421
+ items.push({ value: "quit", key: "q", label: "Quit" });
4422
+ let question = "No SSH hosts here yet";
4423
+ if (names.length === 1) {
4424
+ question = "1 SSH host \u2014 pick it to manage it";
4425
+ } else if (names.length > 1) {
4426
+ question = `${names.length} SSH hosts \u2014 pick one to manage it`;
4427
+ }
4428
+ let defaultValue = "add";
4429
+ if (names.length > 0) {
4430
+ defaultValue = `${HOST_VALUE_PREFIX}${names[0]}`;
4431
+ }
4432
+ const picked = await prompter.select(question, items, { defaultValue, cancelValue: "quit" });
4433
+ if (picked === "quit") {
4434
+ return 0;
4435
+ }
4436
+ if (picked === "switch") {
4437
+ const switched = await prompter.select(
4438
+ "Which client?",
4439
+ targets.map((candidate) => {
4440
+ let hint = candidate.location;
4441
+ if (candidate.detected == false) {
4442
+ hint += " \xB7 not found on this machine";
4443
+ }
4444
+ return { value: candidate.id, label: candidate.label, hint };
4445
+ }),
4446
+ { defaultValue: target.id, cancelValue: target.id }
4447
+ );
4448
+ target = targets.find((candidate) => candidate.id === switched) ?? target;
4449
+ continue;
4450
+ }
4451
+ try {
4452
+ if (picked === "add") {
4453
+ await addOrEditHost(prompter, output, target, entries);
4454
+ continue;
4455
+ }
4456
+ if (picked.startsWith(HOST_VALUE_PREFIX) == true) {
4457
+ await manageHost(prompter, output, target, entries, picked.slice(HOST_VALUE_PREFIX.length));
4458
+ }
4459
+ } catch (ex) {
4460
+ if (ex instanceof PromptClosedError) {
4461
+ throw ex;
4462
+ }
4463
+ output.write(` Failed: ${errorMessage(ex)}
4464
+
4465
+ `);
4466
+ }
4467
+ }
4468
+ } catch (ex) {
4469
+ if (ex instanceof PromptClosedError) {
4470
+ output.write("\n");
4471
+ return 0;
4472
+ }
4473
+ throw ex;
4474
+ } finally {
4475
+ prompter.close();
2086
4476
  }
2087
- return {
2088
- name: profile.name,
2089
- host: profile.host,
2090
- port: profile.port,
2091
- username: profile.username,
2092
- description: profile.description,
2093
- authMethod,
2094
- readonly: profile.policy.readonly,
2095
- allowSudo: profile.policy.allowSudo,
2096
- allowedPaths: profile.policy.allowedPaths,
2097
- allowCommands: profile.policy.allowCommands
2098
- };
2099
4477
  }
2100
4478
 
2101
4479
  // src/modules/tools/format.ts
@@ -2136,6 +4514,16 @@ function formatHostProfile(profile) {
2136
4514
  if (summary.description != null) {
2137
4515
  lines.push(` ${summary.description}`);
2138
4516
  }
4517
+ const routeParts = [];
4518
+ if (summary.viaProxyCommand == true) {
4519
+ routeParts.push("proxy command");
4520
+ }
4521
+ if (summary.jump != null) {
4522
+ routeParts.push(`jump host ${summary.jump.username}@${summary.jump.host}:${summary.jump.port}`);
4523
+ }
4524
+ if (routeParts.length > 0) {
4525
+ lines.push(` via ${routeParts.join(" \u2192 ")}`);
4526
+ }
2139
4527
  if (summary.allowedPaths.length > 0) {
2140
4528
  lines.push(` file tools limited to: ${summary.allowedPaths.join(", ")} (does not restrict ssh_exec)`);
2141
4529
  }
@@ -2516,7 +4904,7 @@ ${file.content}`);
2516
4904
  const { profile, session: openSession } = resolveProfile(context, { session });
2517
4905
  const resolvedLocalPath = expandHomePath(localPath);
2518
4906
  requirePermittedLocalPath(resolvedLocalPath, "read");
2519
- if (fs.existsSync(resolvedLocalPath) == false) {
4907
+ if (fs6.existsSync(resolvedLocalPath) == false) {
2520
4908
  return textResult(`local file not found: ${resolvedLocalPath}`);
2521
4909
  }
2522
4910
  const transferredBytes = await withHostConnection(profile, openSession, async (connection) => {
@@ -2556,7 +4944,7 @@ ${file.content}`);
2556
4944
  const { profile, session: openSession } = resolveProfile(context, { session });
2557
4945
  const resolvedLocalPath = expandHomePath(localPath);
2558
4946
  requirePermittedLocalPath(resolvedLocalPath, "write");
2559
- fs.mkdirSync(path2.dirname(resolvedLocalPath), { recursive: true });
4947
+ fs6.mkdirSync(path.dirname(resolvedLocalPath), { recursive: true });
2560
4948
  const transferredBytes = await withHostConnection(profile, openSession, async (connection) => {
2561
4949
  return await downloadFile(connection, remotePath, resolvedLocalPath);
2562
4950
  });
@@ -2780,8 +5168,23 @@ function createSshMcpServer() {
2780
5168
 
2781
5169
  // src/cli.ts
2782
5170
  function parseArguments(argv) {
2783
- const parsed = { showHelp: false, showVersion: false, checkOnly: false };
2784
- for (const argument of argv) {
5171
+ const parsed = { showHelp: false, showVersion: false, checkOnly: false, configMode: false };
5172
+ let rest = argv;
5173
+ if (argv[0] === "config") {
5174
+ parsed.configMode = true;
5175
+ rest = argv.slice(1);
5176
+ }
5177
+ for (let index = 0; index < rest.length; index += 1) {
5178
+ const argument = rest[index];
5179
+ if (argument === "--target") {
5180
+ parsed.targetId = rest[index + 1];
5181
+ index += 1;
5182
+ continue;
5183
+ }
5184
+ if (argument.startsWith("--target=") == true) {
5185
+ parsed.targetId = argument.slice("--target=".length);
5186
+ continue;
5187
+ }
2785
5188
  if (argument === "--help" || argument === "-h") {
2786
5189
  parsed.showHelp = true;
2787
5190
  continue;
@@ -2802,10 +5205,18 @@ var HELP_TEXT = [
2802
5205
  "",
2803
5206
  "Usage:",
2804
5207
  " akms-mcp-ssh [--check]",
5208
+ " akms-mcp-ssh config [--target <client>]",
5209
+ "",
5210
+ "Commands:",
5211
+ " config Manage the SSH hosts registered in an MCP client's config \u2014",
5212
+ " list, add, edit, remove, check, print. Asks plain questions,",
5213
+ " so the SSH_* names below never have to be typed.",
2805
5214
  "",
2806
5215
  "Options:",
2807
5216
  " --check Connect to the configured host, report the result, and exit.",
2808
5217
  " Prints the host key fingerprint so it can be pinned.",
5218
+ " --target <id> config: claude-code | codex | claude-desktop | cursor",
5219
+ " (default: the first one installed)",
2809
5220
  " -v, --version Print the version and exit",
2810
5221
  " -h, --help Print this help and exit",
2811
5222
  "",
@@ -2820,6 +5231,11 @@ var HELP_TEXT = [
2820
5231
  ` ${SINGLE_HOST_ENV.NAME} Alias shown to the model; defaults to the hostname`,
2821
5232
  ` ${SINGLE_HOST_ENV.DESCRIPTION} Shown to the model \u2014 say what the host is for`,
2822
5233
  ` ${SINGLE_HOST_ENV.CWD} Directory new sessions start in`,
5234
+ ` ${SINGLE_HOST_ENV.PROXY_COMMAND} Command carrying the SSH stream on its stdin/stdout (OpenSSH ProxyCommand);`,
5235
+ " %h / %p / %r expand to the first hop's host, port and user",
5236
+ ` ${SINGLE_HOST_ENV.JUMP_HOST} Jump host the target is reached through (OpenSSH ProxyJump / -J)`,
5237
+ ` ${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}`,
5238
+ ` Jump host connection; user and key default to ${SINGLE_HOST_ENV.USER} / ${SINGLE_HOST_ENV.KEY}`,
2823
5239
  ` ${SINGLE_HOST_ENV.READONLY} Reject write commands, redirections, uploads (default false)`,
2824
5240
  ` ${SINGLE_HOST_ENV.ALLOW_SUDO} Allow sudo / su / doas (default true)`,
2825
5241
  ` ${SINGLE_HOST_ENV.ALLOW_COMMANDS} Comma-separated allow-list of binaries`,
@@ -2831,60 +5247,14 @@ var HELP_TEXT = [
2831
5247
  "",
2832
5248
  "The server speaks MCP over stdio; run it from an MCP client, not interactively."
2833
5249
  ].join("\n");
2834
- function describeAuth(profile) {
2835
- if (profile.privateKeyPath != null) {
2836
- return `key ${profile.privateKeyPath}`;
2837
- }
2838
- if (profile.password != null) {
2839
- return "password";
2840
- }
2841
- return "ssh agent";
2842
- }
2843
- async function runConnectionCheck(profile) {
5250
+ async function runCheckCommand(profile) {
2844
5251
  if (profile == null) {
2845
- process.stdout.write(`No SSH host is registered \u2014 set ${SINGLE_HOST_ENV.HOST} and ${SINGLE_HOST_ENV.USER}.
5252
+ 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
2846
5253
  `);
2847
5254
  return 1;
2848
5255
  }
2849
- const endpoint = `${profile.username}@${profile.host}:${profile.port}`;
2850
- const auth = describeAuth(profile);
2851
- process.stdout.write(`Checking ${profile.name} \u2192 ${endpoint}
2852
-
2853
- `);
2854
- const connection = new SshConnection(profile);
2855
- const startedAt = Date.now();
2856
- let connected = false;
2857
- let detail = "";
2858
- try {
2859
- await connection.connect();
2860
- connected = true;
2861
- } catch (ex) {
2862
- detail = String(ex);
2863
- if (ex instanceof Error) {
2864
- detail = ex.message;
2865
- }
2866
- } finally {
2867
- connection.disconnect();
2868
- }
2869
- const durationMs = Date.now() - startedAt;
2870
- if (connected == true) {
2871
- process.stdout.write(` OK ${endpoint} (${auth}, ${durationMs}ms)
2872
- `);
2873
- } else {
2874
- process.stdout.write(` FAILED ${endpoint} (${auth})
2875
- `);
2876
- process.stdout.write(` ${detail}
2877
- `);
2878
- }
2879
- if (connection.hostKeyFingerprint != null) {
2880
- let pinNote = `not pinned \u2014 set ${SINGLE_HOST_ENV.HOST_KEY} to it to detect a changed key`;
2881
- if (profile.hostKeyFingerprint != null) {
2882
- pinNote = "pinned";
2883
- }
2884
- process.stdout.write(` host key ${connection.hostKeyFingerprint} (${pinNote})
2885
- `);
2886
- }
2887
- if (connected == true) {
5256
+ const result = await runConnectionCheck(profile, process.stdout);
5257
+ if (result.connected == true) {
2888
5258
  return 0;
2889
5259
  }
2890
5260
  return 1;
@@ -2902,12 +5272,23 @@ async function main() {
2902
5272
  `);
2903
5273
  return;
2904
5274
  }
5275
+ if (cliArguments.configMode == true) {
5276
+ if (process.env[LOG_LEVEL_ENV] == null) {
5277
+ process.env[LOG_LEVEL_ENV] = "warn";
5278
+ }
5279
+ const exitCode = await runConfigCommand({
5280
+ input: process.stdin,
5281
+ output: process.stdout,
5282
+ targetId: cliArguments.targetId
5283
+ });
5284
+ process.exit(exitCode);
5285
+ }
2905
5286
  if (cliArguments.checkOnly == true && process.env[LOG_LEVEL_ENV] == null) {
2906
- process.env[LOG_LEVEL_ENV] = "silent";
5287
+ process.env[LOG_LEVEL_ENV] = "warn";
2907
5288
  }
2908
5289
  const instance = createSshMcpServer();
2909
5290
  if (cliArguments.checkOnly == true) {
2910
- const exitCode = await runConnectionCheck(instance.profile);
5291
+ const exitCode = await runCheckCommand(instance.profile);
2911
5292
  instance.shutdown();
2912
5293
  process.exit(exitCode);
2913
5294
  }