Open History to see the last commit
1import type { DesktopDiscoveredSshHost } from "@t3tools/contracts";
2
3import * as Config from "effect/Config";
4import * as Effect from "effect/Effect";
5import * as FileSystem from "effect/FileSystem";
6import * as Option from "effect/Option";
7import * as Path from "effect/Path";
8import * as PlatformError from "effect/PlatformError";
9
10import { SshHostDiscoveryError } from "./errors.ts";
11
12const NO_HOSTS: ReadonlyArray<string> = [] as const;
13
14// Mirrors OpenSSH readconf: the keyword may be followed by one optional "=",
15// then the arguments are split like misc.c argv_split() with quotes, the
16// escapes \\ \" \' and unquoted "\ ", and "#" starting a comment only at
17// the start of a token. Invalid quoting leaves hostname resolution uncertain.
18function parseSshConfigLine(line: string) {
19 const match = /^[ \t\r]*([^ \t\r=]+)[ \t\r]*=?[ \t\r]*(.*)$/su.exec(
20 line.replace(/[ \t\r\f]+$/u, ""),
21 );
22 if (!match) {
23 return null;
24 }
25
26 const directive = match[1]!.toLowerCase();
27 const args: Array<string> = [];
28 const rest = match[2]!;
29 let token: string | null = null;
30 let quote: string | null = null;
31 for (let index = 0; index < rest.length; index += 1) {
32 const char = rest[index]!;
33 const next = rest[index + 1];
34 if (
35 char === "\\" &&
36 (next === '"' || next === "'" || next === "\\" || (quote === null && next === " "))
37 ) {
38 token = (token ?? "") + next;
39 index += 1;
40 } else if (quote !== null) {
41 if (char === quote) {
42 quote = null;
43 } else {
44 token = (token ?? "") + char;
45 }
46 } else if (char === '"' || char === "'") {
47 quote = char;
48 token ??= "";
49 } else if (/[ \t]/u.test(char)) {
50 if (token !== null) {
51 args.push(token);
52 token = null;
53 }
54 } else if (char === "#" && token === null) {
55 break;
56 } else {
57 token = (token ?? "") + char;
58 }
59 }
60 if (quote !== null) {
61 return { directive, args: null };
62 }
63 if (token !== null) {
64 args.push(token);
65 }
66 return { directive, args };
67}
68
69function expandHomePath(input: string, homeDir: string): string {
70 return input.replace(/^~(?=$|\/|\\)/u, () => homeDir);
71}
72
73const resolveSshConfigIncludePattern = Effect.fnUntraced(function* (
74 includePattern: string,
75 _directory: string,
76 homeDir: string,
77) {
78 const path = yield* Path.Path;
79 const expandedPattern = expandHomePath(includePattern, homeDir);
80 return path.isAbsolute(expandedPattern)
81 ? expandedPattern
82 : path.resolve(path.join(homeDir, ".ssh"), expandedPattern);
83});
84
85function hasSshPattern(value: string): boolean {
86 return value.includes("*") || value.includes("?") || value.startsWith("!");
87}
88
89function escapeRegex(value: string): string {
90 return value.replace(/[.*+?^${}()|[\]\\]/gu, "\\$&");
91}
92
93const utf8 = new TextEncoder();
94
95// OpenSSH's glob matches UTF-8 bytes, so `?` consumes one byte of a filename.
96function globBytes(value: string): string {
97 return Array.from(utf8.encode(value), (byte) => String.fromCharCode(byte)).join("");
98}
99
100function globToRegExp(pattern: string): RegExp {
101 return new RegExp(
102 `^${escapeRegex(pattern).replace(/\\\*/gu, "[^]*").replace(/\\\?/gu, ".")}$`,
103 "u",
104 );
105}
106
107function hasGlobWildcard(value: string): boolean {
108 return value.includes("*") || value.includes("?");
109}
110
111const expandGlob = Effect.fnUntraced(function* (
112 pattern: string,
113): Effect.fn.Return<
114 ReadonlyArray<string>,
115 PlatformError.PlatformError,
116 FileSystem.FileSystem | Path.Path
117> {
118 const fs = yield* FileSystem.FileSystem;
119 const path = yield* Path.Path;
120 if (!hasGlobWildcard(pattern)) {
121 return (yield* fs.exists(pattern)) ? [pattern] : NO_HOSTS;
122 }
123
124 const directoryPattern = path.dirname(pattern);
125 const basePattern = path.basename(pattern);
126 const directoryIsGlob = hasGlobWildcard(directoryPattern);
127 const directories = directoryIsGlob ? yield* expandGlob(directoryPattern) : [directoryPattern];
128
129 const matcher = globToRegExp(globBytes(basePattern));
130 const matchedPaths: string[] = [];
131 for (const directory of directories) {
132 if (!(yield* fs.exists(directory))) continue;
133 if ((yield* fs.stat(directory)).type !== "Directory") continue;
134 // Like OpenSSH's glob, a wildcard-matched directory we cannot read matches nothing.
135 const entries = directoryIsGlob
136 ? yield* fs.readDirectory(directory).pipe(Effect.orElseSucceed(() => NO_HOSTS))
137 : yield* fs.readDirectory(directory);
138 for (const entry of entries) {
139 if (entry.startsWith(".") && !basePattern.startsWith(".")) continue;
140 if (!matcher.test(globBytes(entry))) {
141 continue;
142 }
143 const entryPath = path.join(directory, entry);
144 if (yield* fs.exists(entryPath)) {
145 matchedPaths.push(entryPath);
146 }
147 }
148 }
149 return matchedPaths.toSorted();
150});
151
152type HostCondition = ReadonlyArray<string> | null;
153
154interface HostRule {
155 readonly conditions: ReadonlyArray<HostCondition>;
156 // null: an unreadable Include that may set any directive.
157 readonly directive: "hostname" | "port" | null;
158 readonly value: string | null;
159}
160
161function matchesHostPatterns(alias: string, patterns: ReadonlyArray<string>): boolean {
162 let matched = false;
163 for (const pattern of patterns) {
164 const negated = pattern.startsWith("!");
165 const hostPattern = negated ? pattern.slice(1) : pattern;
166 const matches =
167 hostPattern === "*" ||
168 (hasSshPattern(hostPattern) ? globToRegExp(hostPattern).test(alias) : hostPattern === alias);
169 if (!matches) continue;
170 if (negated) return false;
171 matched = true;
172 }
173 return matched;
174}
175
176function resolveConfiguredValue(
177 alias: string,
178 directive: "hostname" | "port",
179 rules: ReadonlyArray<HostRule>,
180) {
181 for (const rule of rules) {
182 if (
183 (rule.directive !== null && rule.directive !== directive) ||
184 rule.conditions.some(
185 (condition) => condition !== null && !matchesHostPatterns(alias, condition),
186 )
187 ) {
188 continue;
189 }
190 // SSH takes the first value; an uncertain earlier value blocks later fallbacks.
191 if (rule.conditions.includes(null) || rule.value === null) return null;
192 return rule.value;
193 }
194 return undefined;
195}
196
197function resolveConfiguredHostname(alias: string, rules: ReadonlyArray<HostRule>) {
198 const hostname = resolveConfiguredValue(alias, "hostname", rules) ?? null;
199 if (hostname === null || /%(?!h)/u.test(hostname) || hostname.includes("$")) return null;
200 return hostname.replaceAll("%h", alias);
201}
202
203// "*" when the port is uncertain, so the alias still covers every known_hosts port.
204function resolveConfiguredPort(alias: string, rules: ReadonlyArray<HostRule>) {
205 const port = resolveConfiguredValue(alias, "port", rules);
206 return port === undefined ? "22" : (port ?? "*");
207}
208
209const collectSshConfigAliasesFromFile = Effect.fnUntraced(function* (
210 filePath: string,
211 visited: Set<string>,
212 homeDir: string,
213 aliases: Set<string>,
214 hostNameRules: Array<HostRule>,
215 inheritedConditions: ReadonlyArray<HostCondition>,
216): Effect.fn.Return<void, PlatformError.PlatformError, FileSystem.FileSystem | Path.Path> {
217 const fs = yield* FileSystem.FileSystem;
218 const path = yield* Path.Path;
219 const resolvedPath = path.resolve(filePath);
220 if (visited.has(resolvedPath)) {
221 // Read each file once, but never reuse its rules under a different Include context.
222 hostNameRules.push({ conditions: inheritedConditions, directive: null, value: null });
223 return;
224 }
225 if (!(yield* fs.exists(resolvedPath))) return;
226 if ((yield* fs.stat(resolvedPath)).type === "Directory") return;
227 visited.add(resolvedPath);
228
229 const directory = path.dirname(resolvedPath);
230 const raw = yield* fs.readFileString(resolvedPath);
231 let condition: HostCondition = ["*"];
232
233 for (const line of raw.split(/\r?\n/u)) {
234 const parsed = parseSshConfigLine(line);
235 if (!parsed) continue;
236 const { directive, args } = parsed;
237 const conditions = [...inheritedConditions, condition];
238
239 if (directive === "host") {
240 condition = args;
241 for (const alias of args ?? []) {
242 if (alias.length > 0 && !hasSshPattern(alias)) aliases.add(alias);
243 }
244 } else if (directive === "match") {
245 condition = null;
246 } else if (directive === "hostname") {
247 hostNameRules.push({
248 conditions,
249 directive: "hostname",
250 value: args?.length === 1 ? args[0]! : null,
251 });
252 } else if (directive === "port") {
253 const port = args?.length === 1 ? Number(args[0]) : Number.NaN;
254 hostNameRules.push({
255 conditions,
256 directive: "port",
257 value: Number.isInteger(port) && port >= 1 && port <= 65535 ? String(port) : null,
258 });
259 } else if (directive === "include") {
260 if (args === null) {
261 hostNameRules.push({ conditions, directive: null, value: null });
262 continue;
263 }
264 for (const includePattern of args) {
265 const resolvedPattern = yield* resolveSshConfigIncludePattern(
266 includePattern,
267 directory,
268 homeDir,
269 );
270 if (
271 /%|\$\{|\[/u.test(includePattern) ||
272 (includePattern.startsWith("~") && !/^~(?=$|\/|\\)/u.test(includePattern))
273 ) {
274 hostNameRules.push({ conditions, directive: null, value: null });
275 continue;
276 }
277 const includedPaths = yield* expandGlob(resolvedPattern);
278 for (const includedPath of includedPaths) {
279 yield* collectSshConfigAliasesFromFile(
280 includedPath,
281 visited,
282 homeDir,
283 aliases,
284 hostNameRules,
285 conditions,
286 );
287 }
288 }
289 }
290 }
291});
292
293interface KnownHost {
294 readonly hostname: string;
295 readonly port: number | null;
296}
297
298function parseKnownHostsHost(rawHost: string): KnownHost | null {
299 const bracketMatch = /^\[([^\]]+)\]:(\d+)$/u.exec(rawHost);
300 if (bracketMatch?.[1]) {
301 const port = Number(bracketMatch[2]);
302 return port >= 1 && port <= 65535 ? { hostname: bracketMatch[1], port } : null;
303 }
304
305 if (!rawHost.includes(":")) {
306 return { hostname: rawHost, port: null };
307 }
308
309 const firstColonIndex = rawHost.indexOf(":");
310 const lastColonIndex = rawHost.lastIndexOf(":");
311 return {
312 hostname: firstColonIndex === lastColonIndex ? rawHost.slice(0, lastColonIndex) : rawHost,
313 port: null,
314 };
315}
316
317export function parseKnownHosts(raw: string): ReadonlyArray<KnownHost> {
318 const hosts = new Map<string, KnownHost>();
319
320 for (const line of raw.split(/\r?\n/u)) {
321 const trimmed = line.trim();
322 if (trimmed.length === 0 || trimmed.startsWith("#")) {
323 continue;
324 }
325
326 const withoutMarker = trimmed.startsWith("@")
327 ? trimmed.split(/\s+/u).slice(1).join(" ")
328 : trimmed;
329 const [hostField = ""] = withoutMarker.split(/\s+/u);
330 if (hostField.length === 0 || hostField.startsWith("|")) {
331 continue;
332 }
333
334 for (const rawHost of hostField.split(",")) {
335 const parsed = parseKnownHostsHost(rawHost.trim());
336 if (parsed === null) continue;
337 const hostname = parsed.hostname.trim();
338 if (hostname.length === 0 || hasSshPattern(hostname)) {
339 continue;
340 }
341 hosts.set(`${hostname}\u0000${parsed.port ?? ""}`, { hostname, port: parsed.port });
342 }
343 }
344
345 return [...hosts.values()].toSorted(
346 (left, right) =>
347 left.hostname.localeCompare(right.hostname) || (left.port ?? 0) - (right.port ?? 0),
348 );
349}
350
351const readKnownHosts = Effect.fnUntraced(function* (filePath: string) {
352 const fs = yield* FileSystem.FileSystem;
353 if (!(yield* fs.exists(filePath))) {
354 return [];
355 }
356 return parseKnownHosts(yield* fs.readFileString(filePath));
357});
358
359export const discoverSshHosts = Effect.fnUntraced(
360 function* (input: { readonly homeDir?: string }) {
361 const path = yield* Path.Path;
362 const env = yield* Config.all({
363 home: Config.String("HOME").pipe(Config.option),
364 userProfile: Config.String("USERPROFILE").pipe(Config.option),
365 });
366 const homeDir =
367 input?.homeDir ??
368 Option.getOrUndefined(env.home) ??
369 Option.getOrUndefined(env.userProfile) ??
370 "";
371 if (homeDir.trim().length === 0) {
372 return [];
373 }
374
375 const sshDirectory = path.join(homeDir, ".ssh");
376 const configAliases = new Set<string>();
377 const hostNameRules: Array<HostRule> = [];
378 yield* collectSshConfigAliasesFromFile(
379 path.join(sshDirectory, "config"),
380 new Set<string>(),
381 homeDir,
382 configAliases,
383 hostNameRules,
384 [],
385 );
386 const knownHosts = yield* readKnownHosts(path.join(sshDirectory, "known_hosts"));
387 const discovered = new Map<string, DesktopDiscoveredSshHost>();
388
389 const configuredNames = new Set<string>();
390 const configuredDestinations = new Set<string>();
391 for (const alias of configAliases) {
392 const hostname = resolveConfiguredHostname(alias, hostNameRules);
393 const port = resolveConfiguredPort(alias, hostNameRules);
394 for (const name of hostname === null ? [alias] : [alias, hostname]) {
395 configuredNames.add(name.toLowerCase());
396 configuredDestinations.add(`${name.toLowerCase()}\u0000${port}`);
397 }
398 discovered.set(alias, {
399 alias,
400 hostname: hostname ?? alias,
401 username: null,
402 port: null,
403 source: "ssh-config",
404 });
405 }
406
407 for (const { hostname, port } of knownHosts) {
408 const name = hostname.toLowerCase();
409 // A port-less entry connects as `ssh <host>`, so a matching alias's Port applies to it.
410 if (
411 port === null
412 ? configuredNames.has(name)
413 : configuredDestinations.has(`${name}\u0000${port}`) ||
414 configuredDestinations.has(`${name}\u0000*`)
415 ) {
416 continue;
417 }
418 discovered.set(`${hostname}\u0000${port ?? ""}`, {
419 alias: hostname,
420 hostname,
421 username: null,
422 port,
423 source: "known-hosts",
424 });
425 }
426
427 return [...discovered.values()].toSorted((left, right) =>
428 left.alias.localeCompare(right.alias),
429 );
430 },
431 Effect.mapError(
432 (cause) =>
433 new SshHostDiscoveryError({
434 message: "Failed to discover SSH hosts.",
435 cause,
436 }),
437 ),
438);