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

config.ts

297 lines8.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. A line with an unterminated quote is ignored.
18function splitDirectiveArgs(line: string): ReadonlyArray<string> {
19 const match = /^\s*([^\s=]+)\s*=?\s*(.*)$/u.exec(line);
20 if (!match) {
21 return [];
22 }
23​
24 const args = [match[1]!];
25 const rest = match[2]!;
26 let token: string | null = null;
27 let quote: string | null = null;
28 for (let index = 0; index < rest.length; index += 1) {
29 const char = rest[index]!;
30 const next = rest[index + 1];
31 if (
32 char === "\\" &&
33 (next === '"' || next === "'" || next === "\\" || (quote === null && next === " "))
34 ) {
35 token = (token ?? "") + next;
36 index += 1;
37 } else if (quote !== null) {
38 if (char === quote) {
39 quote = null;
40 } else {
41 token = (token ?? "") + char;
42 }
43 } else if (char === '"' || char === "'") {
44 quote = char;
45 token ??= "";
46 } else if (/\s/u.test(char)) {
47 if (token !== null) {
48 args.push(token);
49 token = null;
50 }
51 } else if (char === "#" && token === null) {
52 break;
53 } else {
54 token = (token ?? "") + char;
55 }
56 }
57 if (quote !== null) {
58 return [];
59 }
60 if (token !== null) {
61 args.push(token);
62 }
63 return args;
65​
66function expandHomePath(input: string, homeDir: string): string {
67 return input.replace(/^~(?=$|\/|\\)/u, homeDir);
69​
70export const resolveSshConfigIncludePattern = Effect.fnUntraced(function* (
71 includePattern: string,
72 _directory: string,
73 homeDir: string,
74) {
75 const path = yield* Path.Path;
76 const expandedPattern = expandHomePath(includePattern, homeDir);
77 return path.isAbsolute(expandedPattern)
78 ? expandedPattern
79 : path.resolve(path.join(homeDir, ".ssh"), expandedPattern);
80});
81​
82function hasSshPattern(value: string): boolean {
83 return value.includes("*") || value.includes("?") || value.startsWith("!");
85​
86function escapeRegex(value: string): string {
87 return value.replace(/[.*+?^${}()|[\]\\]/gu, "\\$&");
89​
90function globToRegExp(pattern: string): RegExp {
91 return new RegExp(
92 `^${escapeRegex(pattern).replace(/\\\*/gu, ".*").replace(/\\\?/gu, ".")}$`,
93 "u",
94 );
96​
97const expandGlob = Effect.fnUntraced(function* (pattern: string) {
98 const fs = yield* FileSystem.FileSystem;
99 const path = yield* Path.Path;
100 if (!pattern.includes("*") && !pattern.includes("?")) {
101 return (yield* fs.exists(pattern)) ? [pattern] : NO_HOSTS;
102 }
103​
104 const directory = path.dirname(pattern);
105 const basePattern = path.basename(pattern);
106 if (!(yield* fs.exists(directory))) {
107 return NO_HOSTS;
108 }
109​
110 const matcher = globToRegExp(basePattern);
111 const entries = yield* fs.readDirectory(directory);
112 const matchedPaths: string[] = [];
113 for (const entry of entries) {
114 if (!matcher.test(entry)) {
115 continue;
116 }
117 const entryPath = path.join(directory, entry);
118 if (yield* fs.exists(entryPath)) {
119 matchedPaths.push(entryPath);
120 }
121 }
122 return matchedPaths.toSorted((left, right) => left.localeCompare(right));
123});
124​
125const collectSshConfigAliasesFromFile = Effect.fnUntraced(function* (
126 filePath: string,
127 visited = new Set<string>(),
128 homeDir: string,
129): Effect.fn.Return<
130 ReadonlyArray<string>,
131 PlatformError.PlatformError,
132 FileSystem.FileSystem | Path.Path
133> {
134 const fs = yield* FileSystem.FileSystem;
135 const path = yield* Path.Path;
136 const resolvedPath = path.resolve(filePath);
137 if (visited.has(resolvedPath) || !(yield* fs.exists(resolvedPath))) {
138 return NO_HOSTS;
139 }
140 visited.add(resolvedPath);
141​
142 const aliases = new Set<string>();
143 const directory = path.dirname(resolvedPath);
144 const raw = yield* fs.readFileString(resolvedPath);
145​
146 for (const line of raw.split(/\r?\n/u)) {
147 const [directive = "", ...rawArgs] = splitDirectiveArgs(line);
148 const normalizedDirective = directive.toLowerCase();
149 if (normalizedDirective === "include") {
150 for (const includePattern of rawArgs) {
151 const resolvedPattern = yield* resolveSshConfigIncludePattern(
152 includePattern,
153 directory,
154 homeDir,
155 );
156 const includedPaths = yield* expandGlob(resolvedPattern);
157 for (const includedPath of includedPaths) {
158 const includedAliases = yield* collectSshConfigAliasesFromFile(
159 includedPath,
160 visited,
161 homeDir,
162 );
163 for (const alias of includedAliases) {
164 aliases.add(alias);
165 }
166 }
167 }
168 continue;
169 }
170​
171 if (normalizedDirective !== "host") {
172 continue;
173 }
174​
175 for (const alias of rawArgs) {
176 if (alias.length === 0 || hasSshPattern(alias)) {
177 continue;
178 }
179 aliases.add(alias);
180 }
181 }
182​
183 return [...aliases].toSorted((left, right) => left.localeCompare(right));
184});
185​
186function normalizeKnownHostsHostname(rawHost: string): string {
187 const bracketMatch = /^\[([^\]]+)\]:(\d+)$/u.exec(rawHost);
188 if (bracketMatch?.[1]) {
189 return bracketMatch[1];
190 }
191​
192 if (!rawHost.includes(":")) {
193 return rawHost;
194 }
195​
196 const firstColonIndex = rawHost.indexOf(":");
197 const lastColonIndex = rawHost.lastIndexOf(":");
198 return firstColonIndex === lastColonIndex ? rawHost.slice(0, lastColonIndex) : rawHost;
200​
201export function parseKnownHostsHostnames(raw: string): ReadonlyArray<string> {
202 const hostnames = new Set<string>();
203​
204 for (const line of raw.split(/\r?\n/u)) {
205 const trimmed = line.trim();
206 if (trimmed.length === 0 || trimmed.startsWith("#")) {
207 continue;
208 }
209​
210 const withoutMarker = trimmed.startsWith("@")
211 ? trimmed.split(/\s+/u).slice(1).join(" ")
212 : trimmed;
213 const [hostField = ""] = withoutMarker.split(/\s+/u);
214 if (hostField.length === 0 || hostField.startsWith("|")) {
215 continue;
216 }
217​
218 for (const rawHost of hostField.split(",")) {
219 const host = normalizeKnownHostsHostname(rawHost).trim();
220 if (host.length === 0 || hasSshPattern(host)) {
221 continue;
222 }
223 hostnames.add(host);
224 }
225 }
226​
227 return [...hostnames].toSorted((left, right) => left.localeCompare(right));
229​
230const readKnownHostsHostnames = Effect.fnUntraced(function* (filePath: string) {
231 const fs = yield* FileSystem.FileSystem;
232 if (!(yield* fs.exists(filePath))) {
233 return NO_HOSTS;
234 }
235 return parseKnownHostsHostnames(yield* fs.readFileString(filePath));
236});
237​
238export const discoverSshHosts = Effect.fnUntraced(
239 function* (input: { readonly homeDir?: string }) {
240 const path = yield* Path.Path;
241 const env = yield* Config.all({
242 home: Config.String("HOME").pipe(Config.option),
243 userProfile: Config.String("USERPROFILE").pipe(Config.option),
244 });
245 const homeDir =
246 input?.homeDir ??
247 Option.getOrUndefined(env.home) ??
248 Option.getOrUndefined(env.userProfile) ??
249 "";
250 if (homeDir.trim().length === 0) {
251 return [];
252 }
253​
254 const sshDirectory = path.join(homeDir, ".ssh");
255 const configAliases = yield* collectSshConfigAliasesFromFile(
256 path.join(sshDirectory, "config"),
257 new Set<string>(),
258 homeDir,
259 );
260 const knownHosts = yield* readKnownHostsHostnames(path.join(sshDirectory, "known_hosts"));
261 const discovered = new Map<string, DesktopDiscoveredSshHost>();
262​
263 for (const alias of configAliases) {
264 discovered.set(alias, {
265 alias,
266 hostname: alias,
267 username: null,
268 port: null,
269 source: "ssh-config",
270 });
271 }
272​
273 for (const hostname of knownHosts) {
274 if (discovered.has(hostname)) {
275 continue;
276 }
277 discovered.set(hostname, {
278 alias: hostname,
279 hostname,
280 username: null,
281 port: null,
282 source: "known-hosts",
283 });
284 }
285​
286 return [...discovered.values()].toSorted((left, right) =>
287 left.alias.localeCompare(right.alias),
288 );
289 },
290 Effect.mapError(
291 (cause) =>
292 new SshHostDiscoveryError({
293 message: "Failed to discover SSH hosts.",
294 cause,
295 }),
296 ),
297);