Open History to see the last commit
1import type { DesktopDiscoveredSshHost } from "@t3tools/contracts";
2
3import * as Effect from "effect/Effect";
4import * as FileSystem from "effect/FileSystem";
5import * as Path from "effect/Path";
6import * as PlatformError from "effect/PlatformError";
7
8import { SshHostDiscoveryError } from "./errors.ts";
9
10const NO_HOSTS: ReadonlyArray<string> = [] as const;
11
12function stripInlineComment(line: string): string {
13 const hashIndex = line.indexOf("#");
14 return (hashIndex >= 0 ? line.slice(0, hashIndex) : line).trim();
15}
16
17function splitDirectiveArgs(value: string): ReadonlyArray<string> {
18 return value
19 .replace(/=(?!=)/gu, " ")
20 .trim()
21 .split(/\s+/u)
22 .map((entry) => entry.trim())
23 .filter((entry) => entry.length > 0);
24}
25
26function expandHomePath(input: string, homeDir: string): string {
27 return input.replace(/^~(?=$|\/|\\)/u, homeDir);
28}
29
30export const resolveSshConfigIncludePattern = Effect.fnUntraced(function* (
31 includePattern: string,
32 _directory: string,
33 homeDir: string,
34) {
35 const path = yield* Path.Path;
36 const expandedPattern = expandHomePath(includePattern, homeDir);
37 return path.isAbsolute(expandedPattern)
38 ? expandedPattern
39 : path.resolve(path.join(homeDir, ".ssh"), expandedPattern);
40});
41
42function hasSshPattern(value: string): boolean {
43 return value.includes("*") || value.includes("?") || value.startsWith("!");
44}
45
46function escapeRegex(value: string): string {
47 return value.replace(/[.*+?^${}()|[\]\\]/gu, "\\$&");
48}
49
50function globToRegExp(pattern: string): RegExp {
51 return new RegExp(
52 `^${escapeRegex(pattern).replace(/\\\*/gu, ".*").replace(/\\\?/gu, ".")}$`,
53 "u",
54 );
55}
56
57const expandGlob = Effect.fnUntraced(function* (pattern: string) {
58 const fs = yield* FileSystem.FileSystem;
59 const path = yield* Path.Path;
60 if (!pattern.includes("*") && !pattern.includes("?")) {
61 return (yield* fs.exists(pattern)) ? [pattern] : NO_HOSTS;
62 }
63
64 const directory = path.dirname(pattern);
65 const basePattern = path.basename(pattern);
66 if (!(yield* fs.exists(directory))) {
67 return NO_HOSTS;
68 }
69
70 const matcher = globToRegExp(basePattern);
71 const entries = yield* fs.readDirectory(directory);
72 const matchedPaths: string[] = [];
73 for (const entry of entries) {
74 if (!matcher.test(entry)) {
75 continue;
76 }
77 const entryPath = path.join(directory, entry);
78 if (yield* fs.exists(entryPath)) {
79 matchedPaths.push(entryPath);
80 }
81 }
82 return matchedPaths.toSorted((left, right) => left.localeCompare(right));
83});
84
85export const collectSshConfigAliasesFromFile = Effect.fnUntraced(function* (
86 filePath: string,
87 visited = new Set<string>(),
88 homeDir: string,
89): Effect.fn.Return<
90 ReadonlyArray<string>,
91 PlatformError.PlatformError,
92 FileSystem.FileSystem | Path.Path
93> {
94 const fs = yield* FileSystem.FileSystem;
95 const path = yield* Path.Path;
96 const resolvedPath = path.resolve(filePath);
97 if (visited.has(resolvedPath) || !(yield* fs.exists(resolvedPath))) {
98 return NO_HOSTS;
99 }
100 visited.add(resolvedPath);
101
102 const aliases = new Set<string>();
103 const directory = path.dirname(resolvedPath);
104 const raw = yield* fs.readFileString(resolvedPath);
105
106 for (const line of raw.split(/\r?\n/u)) {
107 const stripped = stripInlineComment(line);
108 if (stripped.length === 0) {
109 continue;
110 }
111
112 const [directive = "", ...rawArgs] = splitDirectiveArgs(stripped);
113 const normalizedDirective = directive.toLowerCase();
114 if (normalizedDirective === "include") {
115 for (const includePattern of rawArgs) {
116 const resolvedPattern = yield* resolveSshConfigIncludePattern(
117 includePattern,
118 directory,
119 homeDir,
120 );
121 const includedPaths = yield* expandGlob(resolvedPattern);
122 for (const includedPath of includedPaths) {
123 const includedAliases = yield* collectSshConfigAliasesFromFile(
124 includedPath,
125 visited,
126 homeDir,
127 );
128 for (const alias of includedAliases) {
129 aliases.add(alias);
130 }
131 }
132 }
133 continue;
134 }
135
136 if (normalizedDirective !== "host") {
137 continue;
138 }
139
140 for (const alias of rawArgs) {
141 if (alias.length === 0 || hasSshPattern(alias)) {
142 continue;
143 }
144 aliases.add(alias);
145 }
146 }
147
148 return [...aliases].toSorted((left, right) => left.localeCompare(right));
149});
150
151function normalizeKnownHostsHostname(rawHost: string): string {
152 const bracketMatch = /^\[([^\]]+)\]:(\d+)$/u.exec(rawHost);
153 if (bracketMatch?.[1]) {
154 return bracketMatch[1];
155 }
156
157 if (!rawHost.includes(":")) {
158 return rawHost;
159 }
160
161 const firstColonIndex = rawHost.indexOf(":");
162 const lastColonIndex = rawHost.lastIndexOf(":");
163 return firstColonIndex === lastColonIndex ? rawHost.slice(0, lastColonIndex) : rawHost;
164}
165
166export function parseKnownHostsHostnames(raw: string): ReadonlyArray<string> {
167 const hostnames = new Set<string>();
168
169 for (const line of raw.split(/\r?\n/u)) {
170 const trimmed = line.trim();
171 if (trimmed.length === 0 || trimmed.startsWith("#")) {
172 continue;
173 }
174
175 const withoutMarker = trimmed.startsWith("@")
176 ? trimmed.split(/\s+/u).slice(1).join(" ")
177 : trimmed;
178 const [hostField = ""] = withoutMarker.split(/\s+/u);
179 if (hostField.length === 0 || hostField.startsWith("|")) {
180 continue;
181 }
182
183 for (const rawHost of hostField.split(",")) {
184 const host = normalizeKnownHostsHostname(rawHost).trim();
185 if (host.length === 0 || hasSshPattern(host)) {
186 continue;
187 }
188 hostnames.add(host);
189 }
190 }
191
192 return [...hostnames].toSorted((left, right) => left.localeCompare(right));
193}
194
195const readKnownHostsHostnames = Effect.fnUntraced(function* (filePath: string) {
196 const fs = yield* FileSystem.FileSystem;
197 if (!(yield* fs.exists(filePath))) {
198 return NO_HOSTS;
199 }
200 return parseKnownHostsHostnames(yield* fs.readFileString(filePath));
201});
202
203export const discoverSshHosts = Effect.fnUntraced(
204 function* (input: { readonly homeDir?: string }) {
205 const path = yield* Path.Path;
206 const homeDir = input?.homeDir ?? process.env.HOME ?? process.env.USERPROFILE ?? "";
207 if (homeDir.trim().length === 0) {
208 return [];
209 }
210
211 const sshDirectory = path.join(homeDir, ".ssh");
212 const configAliases = yield* collectSshConfigAliasesFromFile(
213 path.join(sshDirectory, "config"),
214 new Set<string>(),
215 homeDir,
216 );
217 const knownHosts = yield* readKnownHostsHostnames(path.join(sshDirectory, "known_hosts"));
218 const discovered = new Map<string, DesktopDiscoveredSshHost>();
219
220 for (const alias of configAliases) {
221 discovered.set(alias, {
222 alias,
223 hostname: alias,
224 username: null,
225 port: null,
226 source: "ssh-config",
227 });
228 }
229
230 for (const hostname of knownHosts) {
231 if (discovered.has(hostname)) {
232 continue;
233 }
234 discovered.set(hostname, {
235 alias: hostname,
236 hostname,
237 username: null,
238 port: null,
239 source: "known-hosts",
240 });
241 }
242
243 return [...discovered.values()].toSorted((left, right) =>
244 left.alias.localeCompare(right.alias),
245 );
246 },
247 Effect.mapError(
248 (cause) =>
249 new SshHostDiscoveryError({
250 message: "Failed to discover SSH hosts.",
251 cause,
252 }),
253 ),
254);