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

config.ts

259 lines7.3 KB

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