Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

config.ts

373 lines11.4 KB

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 };
68​
69function expandHomePath(input: string, homeDir: string): string {
70 return input.replace(/^~(?=$|\/|\\)/u, homeDir);
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("!");
88​
89function escapeRegex(value: string): string {
90 return value.replace(/[.*+?^${}()|[\]\\]/gu, "\\$&");
92​
93function globToRegExp(pattern: string): RegExp {
94 return new RegExp(
95 `^${escapeRegex(pattern).replace(/\\\*/gu, ".*").replace(/\\\?/gu, ".")}$`,
96 "u",
97 );
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;
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;
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;
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​
240interface KnownHost {
241 readonly hostname: string;
242 readonly port: number | null;
244​
245function parseKnownHostsHost(rawHost: string): KnownHost | null {
246 const bracketMatch = /^\[([^\]]+)\]:(\d+)$/u.exec(rawHost);
247 if (bracketMatch?.[1]) {
248 const port = Number(bracketMatch[2]);
249 return port >= 1 && port <= 65535 ? { hostname: bracketMatch[1], port } : null;
250 }
251​
252 if (!rawHost.includes(":")) {
253 return { hostname: rawHost, port: null };
254 }
255​
256 const firstColonIndex = rawHost.indexOf(":");
257 const lastColonIndex = rawHost.lastIndexOf(":");
258 return {
259 hostname: firstColonIndex === lastColonIndex ? rawHost.slice(0, lastColonIndex) : rawHost,
260 port: null,
261 };
263​
264export function parseKnownHosts(raw: string): ReadonlyArray<KnownHost> {
265 const hosts = new Map<string, KnownHost>();
266​
267 for (const line of raw.split(/\r?\n/u)) {
268 const trimmed = line.trim();
269 if (trimmed.length === 0 || trimmed.startsWith("#")) {
270 continue;
271 }
272​
273 const withoutMarker = trimmed.startsWith("@")
274 ? trimmed.split(/\s+/u).slice(1).join(" ")
275 : trimmed;
276 const [hostField = ""] = withoutMarker.split(/\s+/u);
277 if (hostField.length === 0 || hostField.startsWith("|")) {
278 continue;
279 }
280​
281 for (const rawHost of hostField.split(",")) {
282 const parsed = parseKnownHostsHost(rawHost.trim());
283 if (parsed === null) continue;
284 const hostname = parsed.hostname.trim();
285 if (hostname.length === 0 || hasSshPattern(hostname)) {
286 continue;
287 }
288 hosts.set(`${hostname}\u0000${parsed.port ?? ""}`, { hostname, port: parsed.port });
289 }
290 }
291​
292 return [...hosts.values()].toSorted(
293 (left, right) =>
294 left.hostname.localeCompare(right.hostname) || (left.port ?? 0) - (right.port ?? 0),
295 );
297​
298const readKnownHosts = Effect.fnUntraced(function* (filePath: string) {
299 const fs = yield* FileSystem.FileSystem;
300 if (!(yield* fs.exists(filePath))) {
301 return [];
302 }
303 return parseKnownHosts(yield* fs.readFileString(filePath));
304});
305​
306export const discoverSshHosts = Effect.fnUntraced(
307 function* (input: { readonly homeDir?: string }) {
308 const path = yield* Path.Path;
309 const env = yield* Config.all({
310 home: Config.String("HOME").pipe(Config.option),
311 userProfile: Config.String("USERPROFILE").pipe(Config.option),
312 });
313 const homeDir =
314 input?.homeDir ??
315 Option.getOrUndefined(env.home) ??
316 Option.getOrUndefined(env.userProfile) ??
317 "";
318 if (homeDir.trim().length === 0) {
319 return [];
320 }
321​
322 const sshDirectory = path.join(homeDir, ".ssh");
323 const configAliases = new Set<string>();
324 const hostNameRules: Array<HostNameRule> = [];
325 yield* collectSshConfigAliasesFromFile(
326 path.join(sshDirectory, "config"),
327 new Set<string>(),
328 homeDir,
329 configAliases,
330 hostNameRules,
331 [],
332 );
333 const knownHosts = yield* readKnownHosts(path.join(sshDirectory, "known_hosts"));
334 const discovered = new Map<string, DesktopDiscoveredSshHost>();
335​
336 const configuredHostnames = new Set<string>();
337 for (const alias of configAliases) {
338 const hostname = resolveConfiguredHostname(alias, hostNameRules);
339 if (hostname !== null) configuredHostnames.add(hostname.toLowerCase());
340 discovered.set(alias, {
341 alias,
342 hostname: hostname ?? alias,
343 username: null,
344 port: null,
345 source: "ssh-config",
346 });
347 }
348​
349 for (const { hostname, port } of knownHosts) {
350 if (discovered.has(hostname) || configuredHostnames.has(hostname.toLowerCase())) {
351 continue;
352 }
353 discovered.set(`${hostname}\u0000${port ?? ""}`, {
354 alias: hostname,
355 hostname,
356 username: null,
357 port,
358 source: "known-hosts",
359 });
360 }
361​
362 return [...discovered.values()].toSorted((left, right) =>
363 left.alias.localeCompare(right.alias),
364 );
365 },
366 Effect.mapError(
367 (cause) =>
368 new SshHostDiscoveryError({
369 message: "Failed to discover SSH hosts.",
370 cause,
371 }),
372 ),
373);