sshConfigAlias.ts 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708
  1. /* eslint-disable max-lines -- SSH config alias 解析链路包含扫描、回退和受控执行,暂集中在同一文件。 */
  2. import { spawn } from "node:child_process";
  3. import { existsSync } from "node:fs";
  4. import { glob, readFile } from "node:fs/promises";
  5. import { homedir } from "node:os";
  6. import { delimiter, dirname, isAbsolute, join, resolve } from "node:path";
  7. import type { SSHConfigAliasOption } from "@zcode/shared";
  8. const CACHE_TTL_MS = 30_000;
  9. const MAX_ALIAS_COUNT = 200;
  10. const SSH_G_TIMEOUT_MS = 1_500;
  11. const SSH_G_CONCURRENCY = 3;
  12. const MAX_INCLUDE_DEPTH = 8;
  13. interface ParsedDirective {
  14. key: string;
  15. value: string;
  16. }
  17. interface ParsedBlock {
  18. patterns: string[];
  19. directives: ParsedDirective[];
  20. source: string;
  21. fromHostDirective: boolean;
  22. }
  23. interface AliasMeta {
  24. alias: string;
  25. source: string;
  26. }
  27. let aliasCache: {
  28. expiresAt: number;
  29. options: SSHConfigAliasOption[];
  30. } | null = null;
  31. function cloneAliasOptions(options: SSHConfigAliasOption[]): SSHConfigAliasOption[] {
  32. return options.map((option) => ({ ...option }));
  33. }
  34. function isConnectableAliasPattern(pattern: string): boolean {
  35. const trimmed = pattern.trim();
  36. if (!trimmed) {
  37. return false;
  38. }
  39. if (trimmed === "*" || trimmed.startsWith("!")) {
  40. return false;
  41. }
  42. return !/[?*[\\\]]/.test(trimmed);
  43. }
  44. function stripInlineComment(line: string): string {
  45. let quote: "'" | '"' | null = null;
  46. let escaped = false;
  47. for (let i = 0; i < line.length; i += 1) {
  48. const char = line.charAt(i);
  49. if (escaped) {
  50. escaped = false;
  51. continue;
  52. }
  53. if (char === "\\") {
  54. escaped = true;
  55. continue;
  56. }
  57. if (quote) {
  58. if (char === quote) {
  59. quote = null;
  60. }
  61. continue;
  62. }
  63. if (char === "'" || char === '"') {
  64. quote = char;
  65. continue;
  66. }
  67. if (char === "#") {
  68. return line.slice(0, i);
  69. }
  70. }
  71. return line;
  72. }
  73. function splitSshTokens(line: string): string[] {
  74. const tokens: string[] = [];
  75. let current = "";
  76. let quote: "'" | '"' | null = null;
  77. for (let i = 0; i < line.length; i += 1) {
  78. const char = line.charAt(i);
  79. if (quote) {
  80. if (char === "\\") {
  81. const nextChar = line.charAt(i + 1);
  82. if (!nextChar) {
  83. current += "\\";
  84. continue;
  85. }
  86. if (nextChar === quote || nextChar === "\\") {
  87. current += nextChar;
  88. i += 1;
  89. continue;
  90. }
  91. current += "\\";
  92. continue;
  93. }
  94. if (char === quote) {
  95. quote = null;
  96. continue;
  97. }
  98. current += char;
  99. continue;
  100. }
  101. if (char === "'" || char === '"') {
  102. quote = char;
  103. continue;
  104. }
  105. if (/\s/.test(char)) {
  106. if (current.length > 0) {
  107. tokens.push(current);
  108. current = "";
  109. }
  110. continue;
  111. }
  112. if (char === "\\") {
  113. const nextChar = line.charAt(i + 1);
  114. if (!nextChar) {
  115. current += "\\";
  116. continue;
  117. }
  118. if (
  119. /\s/.test(nextChar) ||
  120. nextChar === "\\" ||
  121. nextChar === "'" ||
  122. nextChar === '"' ||
  123. nextChar === "#"
  124. ) {
  125. current += nextChar;
  126. i += 1;
  127. continue;
  128. }
  129. // SSH config 在 Windows 下常见 `C:\Users\...` 这类路径。
  130. // 不能把任意 `\` 都当成转义前缀:反斜杠会被吞掉,私钥/Include 路径失效。
  131. // 这里仅在“确实用于转义分隔符/引号”时解义,其余场景保留字面反斜杠。
  132. current += "\\";
  133. continue;
  134. }
  135. current += char;
  136. }
  137. if (current.length > 0) {
  138. tokens.push(current);
  139. }
  140. return tokens;
  141. }
  142. function hasGlobPattern(value: string): boolean {
  143. // Windows 绝对路径天然包含 `\`,但这不代表 Include 是 glob。
  144. // 这里只识别 SSH Include 真正的 glob 元字符:`* ? [ ]`。
  145. return /[*?[\]]/.test(value);
  146. }
  147. function expandHomeToken(rawPath: string): string {
  148. const trimmed = rawPath.trim();
  149. if (!trimmed) {
  150. return trimmed;
  151. }
  152. const home = homedir();
  153. const withHomeVariable = trimmed.replace(/^%d(?=$|[\\/])/, home);
  154. if (withHomeVariable === "~") {
  155. return home;
  156. }
  157. if (withHomeVariable.startsWith("~/") || withHomeVariable.startsWith("~\\")) {
  158. return join(home, withHomeVariable.slice(2));
  159. }
  160. return withHomeVariable;
  161. }
  162. async function resolveIncludeTargets(includeTokens: string[], baseDir: string): Promise<string[]> {
  163. const results: string[] = [];
  164. const visited = new Set<string>();
  165. for (const token of includeTokens) {
  166. const expanded = expandHomeToken(token);
  167. if (!expanded) {
  168. continue;
  169. }
  170. const absolutePattern = isAbsolute(expanded) ? expanded : resolve(baseDir, expanded);
  171. if (!hasGlobPattern(absolutePattern)) {
  172. if (existsSync(absolutePattern) && !visited.has(absolutePattern)) {
  173. visited.add(absolutePattern);
  174. results.push(absolutePattern);
  175. }
  176. continue;
  177. }
  178. try {
  179. for await (const match of glob(absolutePattern)) {
  180. const resolvedMatch = resolve(match);
  181. if (visited.has(resolvedMatch)) {
  182. continue;
  183. }
  184. visited.add(resolvedMatch);
  185. results.push(resolvedMatch);
  186. }
  187. } catch {
  188. // include 展开失败时按空集合处理,避免单个坏配置阻塞整体加载。
  189. }
  190. }
  191. return results;
  192. }
  193. async function parseConfigBlocks(
  194. configPath: string,
  195. visited: Set<string>,
  196. depth: number,
  197. ): Promise<ParsedBlock[]> {
  198. const normalizedPath = resolve(configPath);
  199. if (visited.has(normalizedPath) || depth > MAX_INCLUDE_DEPTH) {
  200. return [];
  201. }
  202. visited.add(normalizedPath);
  203. let content = "";
  204. try {
  205. content = await readFile(normalizedPath, "utf8");
  206. } catch {
  207. return [];
  208. }
  209. const blocks: ParsedBlock[] = [];
  210. let currentBlock: ParsedBlock = {
  211. patterns: ["*"],
  212. directives: [],
  213. source: normalizedPath,
  214. fromHostDirective: false,
  215. };
  216. blocks.push(currentBlock);
  217. const lines = content.split(/\r?\n/);
  218. for (const line of lines) {
  219. const stripped = stripInlineComment(line).trim();
  220. if (!stripped) {
  221. continue;
  222. }
  223. const tokens = splitSshTokens(stripped);
  224. if (tokens.length === 0) {
  225. continue;
  226. }
  227. const rawKey = tokens[0];
  228. if (!rawKey) {
  229. continue;
  230. }
  231. const key = rawKey.toLowerCase();
  232. if (key === "include") {
  233. const includeTokens = tokens.slice(1);
  234. const includePaths = await resolveIncludeTargets(includeTokens, dirname(normalizedPath));
  235. for (const includePath of includePaths) {
  236. const includeBlocks = await parseConfigBlocks(includePath, visited, depth + 1);
  237. blocks.push(...includeBlocks);
  238. }
  239. continue;
  240. }
  241. if (key === "host") {
  242. currentBlock = {
  243. patterns: tokens.slice(1),
  244. directives: [],
  245. source: normalizedPath,
  246. fromHostDirective: true,
  247. };
  248. blocks.push(currentBlock);
  249. continue;
  250. }
  251. if (tokens.length < 2) {
  252. continue;
  253. }
  254. currentBlock.directives.push({
  255. key,
  256. value: tokens.slice(1).join(" "),
  257. });
  258. }
  259. return blocks;
  260. }
  261. function buildAliasMetas(blocks: ParsedBlock[]): AliasMeta[] {
  262. const aliases: AliasMeta[] = [];
  263. const seenAliases = new Set<string>();
  264. for (const block of blocks) {
  265. if (!block.fromHostDirective || block.patterns.length !== 1) {
  266. continue;
  267. }
  268. const alias = block.patterns[0]?.trim();
  269. if (!alias || !isConnectableAliasPattern(alias) || seenAliases.has(alias)) {
  270. continue;
  271. }
  272. seenAliases.add(alias);
  273. aliases.push({
  274. alias,
  275. source: block.source,
  276. });
  277. if (aliases.length >= MAX_ALIAS_COUNT) {
  278. break;
  279. }
  280. }
  281. return aliases;
  282. }
  283. function matchHostPattern(pattern: string, alias: string): boolean {
  284. if (pattern === "*") {
  285. return true;
  286. }
  287. if (!/[*?]/.test(pattern)) {
  288. return pattern === alias;
  289. }
  290. const regexBody = Array.from(pattern, (char) => {
  291. if (char === "*") {
  292. return ".*";
  293. }
  294. if (char === "?") {
  295. return ".";
  296. }
  297. // Teleport 会生成 `Host *.teleport-*.example.com` 这类 SSH glob。
  298. // 特殊字符(含 `*`)必须先转义,否则会拼出 `^*...` 非法正则并让 alias 枚举整体失败。
  299. return char.replace(/[\\^$.*+?()[\]{}|]/g, "\\$&");
  300. }).join("");
  301. const regex = new RegExp(`^${regexBody}$`);
  302. return regex.test(alias);
  303. }
  304. function blockMatchesAlias(patterns: string[], alias: string): boolean {
  305. let matchedPositive = false;
  306. for (const rawPattern of patterns) {
  307. const pattern = rawPattern.trim();
  308. if (!pattern) {
  309. continue;
  310. }
  311. if (pattern.startsWith("!")) {
  312. const negatePattern = pattern.slice(1);
  313. if (negatePattern && matchHostPattern(negatePattern, alias)) {
  314. return false;
  315. }
  316. continue;
  317. }
  318. if (matchHostPattern(pattern, alias)) {
  319. matchedPositive = true;
  320. }
  321. }
  322. return matchedPositive;
  323. }
  324. function toValidPort(rawPort: string): number | undefined {
  325. const parsedPort = Number.parseInt(rawPort, 10);
  326. if (!Number.isInteger(parsedPort) || parsedPort <= 0 || parsedPort > 65_535) {
  327. return undefined;
  328. }
  329. return parsedPort;
  330. }
  331. function normalizeIdentityPath(rawValue: string): string | undefined {
  332. const expanded = expandHomeToken(rawValue).trim();
  333. return expanded.length > 0 ? expanded : undefined;
  334. }
  335. function buildFallbackOptions(
  336. blocks: ParsedBlock[],
  337. aliasMetas: AliasMeta[],
  338. ): SSHConfigAliasOption[] {
  339. return aliasMetas.map((meta) => {
  340. let host: string | undefined;
  341. let port: number | undefined;
  342. let username: string | undefined;
  343. let privateKeyPath: string | undefined;
  344. for (const block of blocks) {
  345. if (!blockMatchesAlias(block.patterns, meta.alias)) {
  346. continue;
  347. }
  348. for (const directive of block.directives) {
  349. switch (directive.key) {
  350. case "hostname":
  351. if (!host) {
  352. const normalizedHost = directive.value.trim();
  353. host = normalizedHost.length > 0 ? normalizedHost : undefined;
  354. }
  355. break;
  356. case "port":
  357. if (port == null) {
  358. port = toValidPort(directive.value.trim());
  359. }
  360. break;
  361. case "user":
  362. if (!username) {
  363. const normalizedUser = directive.value.trim();
  364. username = normalizedUser.length > 0 ? normalizedUser : undefined;
  365. }
  366. break;
  367. case "identityfile":
  368. if (!privateKeyPath) {
  369. privateKeyPath = normalizeIdentityPath(directive.value);
  370. }
  371. break;
  372. default:
  373. break;
  374. }
  375. }
  376. }
  377. return {
  378. alias: meta.alias,
  379. host: host ?? meta.alias,
  380. port,
  381. username,
  382. privateKeyPath,
  383. source: meta.source,
  384. };
  385. });
  386. }
  387. function findExecutableFromPath(binaryName: string): string | null {
  388. const rawPath = process.env["PATH"];
  389. if (!rawPath) {
  390. return null;
  391. }
  392. for (const entry of rawPath.split(delimiter)) {
  393. const trimmed = entry.trim();
  394. if (!trimmed) {
  395. continue;
  396. }
  397. const fullPath = join(trimmed, binaryName);
  398. if (existsSync(fullPath)) {
  399. return fullPath;
  400. }
  401. }
  402. return null;
  403. }
  404. function resolveSshExecutablePath(): string | null {
  405. if (process.platform !== "win32") {
  406. return findExecutableFromPath("ssh");
  407. }
  408. const fromPath = findExecutableFromPath("ssh.exe");
  409. if (fromPath) {
  410. return fromPath;
  411. }
  412. const windowsDir = process.env["WINDIR"]?.trim() || "C:\\Windows";
  413. const programFiles = process.env["ProgramFiles"]?.trim() || "C:\\Program Files";
  414. const programFilesX86 = process.env["ProgramFiles(x86)"]?.trim() || "C:\\Program Files (x86)";
  415. const candidates = [
  416. join(windowsDir, "System32", "OpenSSH", "ssh.exe"),
  417. join(programFiles, "OpenSSH", "ssh.exe"),
  418. join(programFiles, "Git", "usr", "bin", "ssh.exe"),
  419. join(programFilesX86, "Git", "usr", "bin", "ssh.exe"),
  420. ];
  421. return candidates.find((candidate) => existsSync(candidate)) ?? null;
  422. }
  423. async function runSshConfigQuery(params: {
  424. sshExecutablePath: string;
  425. configPath: string;
  426. alias: string;
  427. }): Promise<string | null> {
  428. const { sshExecutablePath, configPath, alias } = params;
  429. return await new Promise((resolvePromise) => {
  430. let finished = false;
  431. let stdout = "";
  432. const child = spawn(sshExecutablePath, ["-G", "-F", configPath, "-o", "BatchMode=yes", alias], {
  433. stdio: ["ignore", "pipe", "ignore"],
  434. windowsHide: true,
  435. env: {
  436. ...process.env,
  437. SSH_ASKPASS_REQUIRE: "never",
  438. SSH_ASKPASS: "",
  439. DISPLAY: "",
  440. },
  441. });
  442. const timeoutId = setTimeout(() => {
  443. if (finished) {
  444. return;
  445. }
  446. finished = true;
  447. child.kill();
  448. resolvePromise(null);
  449. }, SSH_G_TIMEOUT_MS);
  450. child.stdout.on("data", (chunk: Buffer | string) => {
  451. if (finished) {
  452. return;
  453. }
  454. stdout += chunk.toString();
  455. if (stdout.length > 128_000) {
  456. stdout = stdout.slice(0, 128_000);
  457. }
  458. });
  459. child.on("error", () => {
  460. if (finished) {
  461. return;
  462. }
  463. finished = true;
  464. clearTimeout(timeoutId);
  465. resolvePromise(null);
  466. });
  467. child.on("close", (code) => {
  468. if (finished) {
  469. return;
  470. }
  471. finished = true;
  472. clearTimeout(timeoutId);
  473. resolvePromise(code === 0 ? stdout : null);
  474. });
  475. });
  476. }
  477. function parseSshGOutput(output: string): Omit<SSHConfigAliasOption, "alias"> {
  478. let host: string | undefined;
  479. let port: number | undefined;
  480. let username: string | undefined;
  481. for (const line of output.split(/\r?\n/)) {
  482. const trimmed = line.trim();
  483. if (!trimmed) {
  484. continue;
  485. }
  486. const match = /^(\S+)\s+(.*)$/.exec(trimmed);
  487. if (!match) {
  488. continue;
  489. }
  490. const rawKey = match[1];
  491. const rawValue = match[2];
  492. if (!rawKey || rawValue == null) {
  493. continue;
  494. }
  495. const key = rawKey.toLowerCase();
  496. const value = rawValue.trim();
  497. switch (key) {
  498. case "hostname":
  499. if (!host && value.length > 0) {
  500. host = value;
  501. }
  502. break;
  503. case "port":
  504. if (port == null) {
  505. port = toValidPort(value);
  506. }
  507. break;
  508. case "user":
  509. if (!username && value.length > 0) {
  510. username = value;
  511. }
  512. break;
  513. default:
  514. break;
  515. }
  516. }
  517. return {
  518. host,
  519. port,
  520. username,
  521. };
  522. }
  523. async function mapWithConcurrency<T, R>(
  524. items: T[],
  525. concurrency: number,
  526. mapper: (item: T, index: number) => Promise<R>,
  527. ): Promise<R[]> {
  528. if (items.length === 0) {
  529. return [];
  530. }
  531. const safeConcurrency = Math.max(1, Math.min(concurrency, items.length));
  532. const results = Array.from({ length: items.length }) as R[];
  533. const entries = items.map((item, index) => ({ item, index }));
  534. let cursor = 0;
  535. async function worker(): Promise<void> {
  536. while (true) {
  537. const index = cursor;
  538. cursor += 1;
  539. if (index >= entries.length) {
  540. return;
  541. }
  542. const entry = entries[index];
  543. if (!entry) {
  544. continue;
  545. }
  546. results[entry.index] = await mapper(entry.item, entry.index);
  547. }
  548. }
  549. await Promise.all(
  550. Array.from({ length: safeConcurrency }, async () => {
  551. await worker();
  552. }),
  553. );
  554. return results;
  555. }
  556. export async function listSSHConfigAliasesFromLocalConfig(): Promise<SSHConfigAliasOption[]> {
  557. const now = Date.now();
  558. if (aliasCache && aliasCache.expiresAt > now) {
  559. return cloneAliasOptions(aliasCache.options);
  560. }
  561. const rootConfigPath = join(homedir(), ".ssh", "config");
  562. if (!existsSync(rootConfigPath)) {
  563. aliasCache = {
  564. expiresAt: now + CACHE_TTL_MS,
  565. options: [],
  566. };
  567. return [];
  568. }
  569. const blocks = await parseConfigBlocks(rootConfigPath, new Set<string>(), 0);
  570. const aliasMetas = buildAliasMetas(blocks);
  571. if (aliasMetas.length === 0) {
  572. aliasCache = {
  573. expiresAt: now + CACHE_TTL_MS,
  574. options: [],
  575. };
  576. return [];
  577. }
  578. const fallbackOptions = buildFallbackOptions(blocks, aliasMetas);
  579. const fallbackByAlias = new Map(fallbackOptions.map((option) => [option.alias, option] as const));
  580. const sshExecutablePath = resolveSshExecutablePath();
  581. const options =
  582. sshExecutablePath == null
  583. ? fallbackOptions
  584. : await mapWithConcurrency(aliasMetas, SSH_G_CONCURRENCY, async (meta) => {
  585. const fallbackOption = fallbackByAlias.get(meta.alias) ?? {
  586. alias: meta.alias,
  587. host: meta.alias,
  588. source: meta.source,
  589. };
  590. const sshOutput = await runSshConfigQuery({
  591. sshExecutablePath,
  592. configPath: rootConfigPath,
  593. alias: meta.alias,
  594. });
  595. if (!sshOutput) {
  596. return fallbackOption;
  597. }
  598. const parsed = parseSshGOutput(sshOutput);
  599. return {
  600. alias: meta.alias,
  601. host: parsed.host ?? fallbackOption.host ?? meta.alias,
  602. port: parsed.port ?? fallbackOption.port,
  603. username: parsed.username ?? fallbackOption.username,
  604. // `ssh -G` 会返回默认 identityfile(例如 ~/.ssh/id_rsa),
  605. // 即使 alias 并未显式配置 IdentityFile。之前直接采用该值,会把“密码登录”误判成“密钥登录”。
  606. // 因此 privateKeyPath 只信任 ssh config 显式解析结果,不再使用 `ssh -G` 的 identityfile。
  607. privateKeyPath: fallbackOption.privateKeyPath,
  608. source: meta.source,
  609. } satisfies SSHConfigAliasOption;
  610. });
  611. aliasCache = {
  612. expiresAt: now + CACHE_TTL_MS,
  613. options,
  614. };
  615. return cloneAliasOptions(options);
  616. }