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