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

config.ts

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