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 = /^\s*([^\s=]+)\s*=?\s*(.*)$/u.exec(line);
20 if (!match) {
21 return null;
22 }
23
24 const directive = match[1]!.toLowerCase();
25 const args: Array<string> = [];
26 const rest = match[2]!;
27 let token: string | null = null;
28 let quote: string | null = null;
29 for (let index = 0; index < rest.length; index += 1) {
30 const char = rest[index]!;
31 const next = rest[index + 1];
32 if (
33 char === "\\" &&
34 (next === '"' || next === "'" || next === "\\" || (quote === null && next === " "))
35 ) {
36 token = (token ?? "") + next;
37 index += 1;
38 } else if (quote !== null) {
39 if (char === quote) {
40 quote = null;
41 } else {
42 token = (token ?? "") + char;
43 }
44 } else if (char === '"' || char === "'") {
45 quote = char;
46 token ??= "";
47 } else if (/\s/u.test(char)) {
48 if (token !== null) {
49 args.push(token);
50 token = null;
51 }
52 } else if (char === "#" && token === null) {
53 break;
54 } else {
55 token = (token ?? "") + char;
56 }
57 }
58 if (quote !== null) {
59 return { directive, args: null };
60 }
61 if (token !== null) {
62 args.push(token);
63 }
64 return { directive, args };
65}
66
67function expandHomePath(input: string, homeDir: string): string {
68 return input.replace(/^~(?=$|\/|\\)/u, homeDir);
69}
70
71const resolveSshConfigIncludePattern = Effect.fnUntraced(function* (
72 includePattern: string,
73 _directory: string,
74 homeDir: string,
75) {
76 const path = yield* Path.Path;
77 const expandedPattern = expandHomePath(includePattern, homeDir);
78 return path.isAbsolute(expandedPattern)
79 ? expandedPattern
80 : path.resolve(path.join(homeDir, ".ssh"), expandedPattern);
81});
82
83function hasSshPattern(value: string): boolean {
84 return value.includes("*") || value.includes("?") || value.startsWith("!");
85}
86
87function escapeRegex(value: string): string {
88 return value.replace(/[.*+?^${}()|[\]\\]/gu, "\\$&");
89}
90
91function globToRegExp(pattern: string): RegExp {
92 return new RegExp(
93 `^${escapeRegex(pattern).replace(/\\\*/gu, ".*").replace(/\\\?/gu, ".")}$`,
94 "u",
95 );
96}
97
98const expandGlob = Effect.fnUntraced(function* (pattern: string) {
99 const fs = yield* FileSystem.FileSystem;
100 const path = yield* Path.Path;
101 if (!pattern.includes("*") && !pattern.includes("?")) {
102 return (yield* fs.exists(pattern)) ? [pattern] : NO_HOSTS;
103 }
104
105 const directory = path.dirname(pattern);
106 const basePattern = path.basename(pattern);
107 if (!(yield* fs.exists(directory))) {
108 return NO_HOSTS;
109 }
110
111 const matcher = globToRegExp(basePattern);
112 const entries = yield* fs.readDirectory(directory);
113 const matchedPaths: string[] = [];
114 for (const entry of entries) {
115 if (!matcher.test(entry)) {
116 continue;
117 }
118 const entryPath = path.join(directory, entry);
119 if (yield* fs.exists(entryPath)) {
120 matchedPaths.push(entryPath);
121 }
122 }
123 return matchedPaths.toSorted();
124});
125
126type HostCondition = ReadonlyArray<string> | null;
127
128interface HostNameRule {
129 readonly conditions: ReadonlyArray<HostCondition>;
130 readonly hostname: string | null;
131}
132
133function matchesHostPatterns(alias: string, patterns: ReadonlyArray<string>): boolean {
134 let matched = false;
135 for (const pattern of patterns) {
136 const negated = pattern.startsWith("!");
137 const hostPattern = negated ? pattern.slice(1) : pattern;
138 const matches =
139 hostPattern === "*" ||
140 (hasSshPattern(hostPattern) ? globToRegExp(hostPattern).test(alias) : hostPattern === alias);
141 if (!matches) continue;
142 if (negated) return false;
143 matched = true;
144 }
145 return matched;
146}
147
148function resolveConfiguredHostname(alias: string, rules: ReadonlyArray<HostNameRule>) {
149 for (const { conditions, hostname } of rules) {
150 if (
151 conditions.some((condition) => condition !== null && !matchesHostPatterns(alias, condition))
152 ) {
153 continue;
154 }
155 // SSH takes the first value; an uncertain earlier value blocks later fallbacks.
156 if (conditions.includes(null) || hostname === null) return null;
157 if (/%(?!h)/u.test(hostname) || hostname.includes("$")) return null;
158 return hostname.replaceAll("%h", alias);
159 }
160 return null;
161}
162
163const collectSshConfigAliasesFromFile = Effect.fnUntraced(function* (
164 filePath: string,
165 visited: Set<string>,
166 homeDir: string,
167 aliases: Set<string>,
168 hostNameRules: Array<HostNameRule>,
169 inheritedConditions: ReadonlyArray<HostCondition>,
170): Effect.fn.Return<void, PlatformError.PlatformError, FileSystem.FileSystem | Path.Path> {
171 const fs = yield* FileSystem.FileSystem;
172 const path = yield* Path.Path;
173 const resolvedPath = path.resolve(filePath);
174 if (visited.has(resolvedPath)) {
175 // Read each file once, but never reuse its rules under a different Include context.
176 hostNameRules.push({ conditions: inheritedConditions, hostname: null });
177 return;
178 }
179 if (!(yield* fs.exists(resolvedPath))) return;
180 visited.add(resolvedPath);
181
182 const directory = path.dirname(resolvedPath);
183 const raw = yield* fs.readFileString(resolvedPath);
184 let condition: HostCondition = ["*"];
185
186 for (const line of raw.split(/\r?\n/u)) {
187 const parsed = parseSshConfigLine(line);
188 if (!parsed) continue;
189 const { directive, args } = parsed;
190 const conditions = [...inheritedConditions, condition];
191
192 if (directive === "host") {
193 condition = args;
194 for (const alias of args ?? []) {
195 if (alias.length > 0 && !hasSshPattern(alias)) aliases.add(alias);
196 }
197 } else if (directive === "match") {
198 condition = null;
199 } else if (directive === "hostname") {
200 hostNameRules.push({ conditions, hostname: args?.length === 1 ? args[0]! : null });
201 } else if (directive === "include") {
202 if (args === null) {
203 hostNameRules.push({ conditions, hostname: null });
204 continue;
205 }
206 for (const includePattern of args) {
207 const resolvedPattern = yield* resolveSshConfigIncludePattern(
208 includePattern,
209 directory,
210 homeDir,
211 );
212 if (
213 /%|\$\{|\[/u.test(includePattern) ||
214 (includePattern.startsWith("~") && !/^~(?=$|\/|\\)/u.test(includePattern)) ||
215 hasSshPattern(path.dirname(resolvedPattern))
216 ) {
217 hostNameRules.push({ conditions, hostname: null });
218 continue;
219 }
220 const includedPaths = yield* expandGlob(resolvedPattern);
221 for (const includedPath of includedPaths) {
222 yield* collectSshConfigAliasesFromFile(
223 includedPath,
224 visited,
225 homeDir,
226 aliases,
227 hostNameRules,
228 conditions,
229 );
230 }
231 }
232 }
233 }
234});
235
236function normalizeKnownHostsHostname(rawHost: string): string {
237 const bracketMatch = /^\[([^\]]+)\]:(\d+)$/u.exec(rawHost);
238 if (bracketMatch?.[1]) {
239 return bracketMatch[1];
240 }
241
242 if (!rawHost.includes(":")) {
243 return rawHost;
244 }
245
246 const firstColonIndex = rawHost.indexOf(":");
247 const lastColonIndex = rawHost.lastIndexOf(":");
248 return firstColonIndex === lastColonIndex ? rawHost.slice(0, lastColonIndex) : rawHost;
249}
250
251export function parseKnownHostsHostnames(raw: string): ReadonlyArray<string> {
252 const hostnames = new Set<string>();
253
254 for (const line of raw.split(/\r?\n/u)) {
255 const trimmed = line.trim();
256 if (trimmed.length === 0 || trimmed.startsWith("#")) {
257 continue;
258 }
259
260 const withoutMarker = trimmed.startsWith("@")
261 ? trimmed.split(/\s+/u).slice(1).join(" ")
262 : trimmed;
263 const [hostField = ""] = withoutMarker.split(/\s+/u);
264 if (hostField.length === 0 || hostField.startsWith("|")) {
265 continue;
266 }
267
268 for (const rawHost of hostField.split(",")) {
269 const host = normalizeKnownHostsHostname(rawHost).trim();
270 if (host.length === 0 || hasSshPattern(host)) {
271 continue;
272 }
273 hostnames.add(host);
274 }
275 }
276
277 return [...hostnames].toSorted((left, right) => left.localeCompare(right));
278}
279
280const readKnownHostsHostnames = Effect.fnUntraced(function* (filePath: string) {
281 const fs = yield* FileSystem.FileSystem;
282 if (!(yield* fs.exists(filePath))) {
283 return NO_HOSTS;
284 }
285 return parseKnownHostsHostnames(yield* fs.readFileString(filePath));
286});
287
288export const discoverSshHosts = Effect.fnUntraced(
289 function* (input: { readonly homeDir?: string }) {
290 const path = yield* Path.Path;
291 const env = yield* Config.all({
292 home: Config.String("HOME").pipe(Config.option),
293 userProfile: Config.String("USERPROFILE").pipe(Config.option),
294 });
295 const homeDir =
296 input?.homeDir ??
297 Option.getOrUndefined(env.home) ??
298 Option.getOrUndefined(env.userProfile) ??
299 "";
300 if (homeDir.trim().length === 0) {
301 return [];
302 }
303
304 const sshDirectory = path.join(homeDir, ".ssh");
305 const configAliases = new Set<string>();
306 const hostNameRules: Array<HostNameRule> = [];
307 yield* collectSshConfigAliasesFromFile(
308 path.join(sshDirectory, "config"),
309 new Set<string>(),
310 homeDir,
311 configAliases,
312 hostNameRules,
313 [],
314 );
315 const knownHosts = yield* readKnownHostsHostnames(path.join(sshDirectory, "known_hosts"));
316 const discovered = new Map<string, DesktopDiscoveredSshHost>();
317
318 const configuredHostnames = new Set<string>();
319 for (const alias of configAliases) {
320 const hostname = resolveConfiguredHostname(alias, hostNameRules);
321 if (hostname !== null) configuredHostnames.add(hostname.toLowerCase());
322 discovered.set(alias, {
323 alias,
324 hostname: hostname ?? alias,
325 username: null,
326 port: null,
327 source: "ssh-config",
328 });
329 }
330
331 for (const hostname of knownHosts) {
332 if (discovered.has(hostname) || configuredHostnames.has(hostname.toLowerCase())) {
333 continue;
334 }
335 discovered.set(hostname, {
336 alias: hostname,
337 hostname,
338 username: null,
339 port: null,
340 source: "known-hosts",
341 });
342 }
343
344 return [...discovered.values()].toSorted((left, right) =>
345 left.alias.localeCompare(right.alias),
346 );
347 },
348 Effect.mapError(
349 (cause) =>
350 new SshHostDiscoveryError({
351 message: "Failed to discover SSH hosts.",
352 cause,
353 }),
354 ),
355);