The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 21, 03:37 UTC
| 1 | import type { DesktopDiscoveredSshHost } from "@t3tools/contracts"; |
| 2 | |
| 3 | import * as Config from "effect/Config"; |
| 4 | import * as Effect from "effect/Effect"; |
| 5 | import * as FileSystem from "effect/FileSystem"; |
| 6 | import * as Option from "effect/Option"; |
| 7 | import * as Path from "effect/Path"; |
| 8 | import * as PlatformError from "effect/PlatformError"; |
| 9 | |
| 10 | import { SshHostDiscoveryError } from "./errors.ts"; |
| 11 | |
| 12 | const 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. |
| 18 | function 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 }; |
| 67 | } |
| 68 | |
| 69 | function expandHomePath(input: string, homeDir: string): string { |
| 70 | return input.replace(/^~(?=$|\/|\\)/u, () => homeDir); |
| 71 | } |
| 72 | |
| 73 | const 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 | |
| 85 | function hasSshPattern(value: string): boolean { |
| 86 | return value.includes("*") || value.includes("?") || value.startsWith("!"); |
| 87 | } |
| 88 | |
| 89 | function escapeRegex(value: string): string { |
| 90 | return value.replace(/[.*+?^${}()|[\]\\]/gu, "\\$&"); |
| 91 | } |
| 92 | |
| 93 | const utf8 = new TextEncoder(); |
| 94 | |
| 95 | function globBytes(value: string): string { |
| 96 | return Array.from(utf8.encode(value), (byte) => String.fromCharCode(byte)).join(""); |
| 97 | } |
| 98 | |
| 99 | // OpenSSH matches Include globs and Host patterns on UTF-8 bytes, so `?` consumes one byte. |
| 100 | function globMatcher(pattern: string): (value: string) => boolean { |
| 101 | const regex = new RegExp( |
| 102 | `^${escapeRegex(globBytes(pattern)).replace(/\\\*/gu, "[^]*").replace(/\\\?/gu, ".")}$`, |
| 103 | "u", |
| 104 | ); |
| 105 | return (value) => regex.test(globBytes(value)); |
| 106 | } |
| 107 | |
| 108 | function hasGlobWildcard(value: string): boolean { |
| 109 | return value.includes("*") || value.includes("?"); |
| 110 | } |
| 111 | |
| 112 | const expandGlob = Effect.fnUntraced(function* ( |
| 113 | pattern: string, |
| 114 | ): Effect.fn.Return< |
| 115 | ReadonlyArray<string>, |
| 116 | PlatformError.PlatformError, |
| 117 | FileSystem.FileSystem | Path.Path |
| 118 | > { |
| 119 | const fs = yield* FileSystem.FileSystem; |
| 120 | const path = yield* Path.Path; |
| 121 | if (!hasGlobWildcard(pattern)) { |
| 122 | return (yield* fs.exists(pattern)) ? [pattern] : NO_HOSTS; |
| 123 | } |
| 124 | |
| 125 | const directoryPattern = path.dirname(pattern); |
| 126 | const basePattern = path.basename(pattern); |
| 127 | const directoryIsGlob = hasGlobWildcard(directoryPattern); |
| 128 | const directories = directoryIsGlob ? yield* expandGlob(directoryPattern) : [directoryPattern]; |
| 129 | |
| 130 | const matches = globMatcher(basePattern); |
| 131 | const matchedPaths: string[] = []; |
| 132 | for (const directory of directories) { |
| 133 | if (!(yield* fs.exists(directory))) continue; |
| 134 | if ((yield* fs.stat(directory)).type !== "Directory") continue; |
| 135 | // Like OpenSSH's glob, a wildcard-matched directory we cannot read matches nothing. |
| 136 | const entries = directoryIsGlob |
| 137 | ? yield* fs.readDirectory(directory).pipe(Effect.orElseSucceed(() => NO_HOSTS)) |
| 138 | : yield* fs.readDirectory(directory); |
| 139 | for (const entry of entries) { |
| 140 | if (entry.startsWith(".") && !basePattern.startsWith(".")) continue; |
| 141 | if (!matches(entry)) { |
| 142 | continue; |
| 143 | } |
| 144 | const entryPath = path.join(directory, entry); |
| 145 | if (yield* fs.exists(entryPath)) { |
| 146 | matchedPaths.push(entryPath); |
| 147 | } |
| 148 | } |
| 149 | } |
| 150 | // OpenSSH's glob sorts matches by UTF-8 bytes, not UTF-16 code units. |
| 151 | return matchedPaths.toSorted((left, right) => { |
| 152 | const leftBytes = globBytes(left); |
| 153 | const rightBytes = globBytes(right); |
| 154 | return leftBytes < rightBytes ? -1 : leftBytes > rightBytes ? 1 : 0; |
| 155 | }); |
| 156 | }); |
| 157 | |
| 158 | type HostCondition = ReadonlyArray<string> | null; |
| 159 | |
| 160 | interface HostRule { |
| 161 | readonly conditions: ReadonlyArray<HostCondition>; |
| 162 | // null: an unreadable Include that may set any directive. |
| 163 | readonly directive: "hostname" | "port" | null; |
| 164 | readonly value: string | null; |
| 165 | } |
| 166 | |
| 167 | function matchesHostPatterns(alias: string, patterns: ReadonlyArray<string>): boolean { |
| 168 | let matched = false; |
| 169 | for (const pattern of patterns) { |
| 170 | const negated = pattern.startsWith("!"); |
| 171 | const hostPattern = negated ? pattern.slice(1) : pattern; |
| 172 | const matches = |
| 173 | hostPattern === "*" || |
| 174 | (hasSshPattern(hostPattern) ? globMatcher(hostPattern)(alias) : hostPattern === alias); |
| 175 | if (!matches) continue; |
| 176 | if (negated) return false; |
| 177 | matched = true; |
| 178 | } |
| 179 | return matched; |
| 180 | } |
| 181 | |
| 182 | function resolveConfiguredValue( |
| 183 | alias: string, |
| 184 | directive: "hostname" | "port", |
| 185 | rules: ReadonlyArray<HostRule>, |
| 186 | ) { |
| 187 | for (const rule of rules) { |
| 188 | if ( |
| 189 | (rule.directive !== null && rule.directive !== directive) || |
| 190 | rule.conditions.some( |
| 191 | (condition) => condition !== null && !matchesHostPatterns(alias, condition), |
| 192 | ) |
| 193 | ) { |
| 194 | continue; |
| 195 | } |
| 196 | // SSH takes the first value; an uncertain earlier value blocks later fallbacks. |
| 197 | if (rule.conditions.includes(null) || rule.value === null) return null; |
| 198 | return rule.value; |
| 199 | } |
| 200 | return undefined; |
| 201 | } |
| 202 | |
| 203 | function resolveConfiguredHostname(alias: string, rules: ReadonlyArray<HostRule>) { |
| 204 | const hostname = resolveConfiguredValue(alias, "hostname", rules) ?? null; |
| 205 | if (hostname === null || /%(?!h)/u.test(hostname) || hostname.includes("$")) return null; |
| 206 | return hostname.replaceAll("%h", alias); |
| 207 | } |
| 208 | |
| 209 | // "*" when the port is uncertain, so the alias still covers every known_hosts port. |
| 210 | function resolveConfiguredPort(alias: string, rules: ReadonlyArray<HostRule>) { |
| 211 | const port = resolveConfiguredValue(alias, "port", rules); |
| 212 | return port === undefined ? "22" : (port ?? "*"); |
| 213 | } |
| 214 | |
| 215 | const collectSshConfigAliasesFromFile = Effect.fnUntraced(function* ( |
| 216 | filePath: string, |
| 217 | visited: Set<string>, |
| 218 | homeDir: string, |
| 219 | aliases: Set<string>, |
| 220 | hostNameRules: Array<HostRule>, |
| 221 | inheritedConditions: ReadonlyArray<HostCondition>, |
| 222 | ): Effect.fn.Return<void, PlatformError.PlatformError, FileSystem.FileSystem | Path.Path> { |
| 223 | const fs = yield* FileSystem.FileSystem; |
| 224 | const path = yield* Path.Path; |
| 225 | const resolvedPath = path.resolve(filePath); |
| 226 | if (visited.has(resolvedPath)) { |
| 227 | // Read each file once, but never reuse its rules under a different Include context. |
| 228 | hostNameRules.push({ conditions: inheritedConditions, directive: null, value: null }); |
| 229 | return; |
| 230 | } |
| 231 | if (!(yield* fs.exists(resolvedPath))) return; |
| 232 | if ((yield* fs.stat(resolvedPath)).type === "Directory") return; |
| 233 | visited.add(resolvedPath); |
| 234 | |
| 235 | const directory = path.dirname(resolvedPath); |
| 236 | const raw = yield* fs.readFileString(resolvedPath); |
| 237 | let condition: HostCondition = ["*"]; |
| 238 | |
| 239 | for (const line of raw.split(/\r?\n/u)) { |
| 240 | const parsed = parseSshConfigLine(line); |
| 241 | if (!parsed) continue; |
| 242 | const { directive, args } = parsed; |
| 243 | const conditions = [...inheritedConditions, condition]; |
| 244 | |
| 245 | if (directive === "host") { |
| 246 | condition = args; |
| 247 | for (const alias of args ?? []) { |
| 248 | if (alias.length > 0 && !hasSshPattern(alias)) aliases.add(alias); |
| 249 | } |
| 250 | } else if (directive === "match") { |
| 251 | condition = null; |
| 252 | } else if (directive === "hostname") { |
| 253 | hostNameRules.push({ |
| 254 | conditions, |
| 255 | directive: "hostname", |
| 256 | value: args?.length === 1 ? args[0]! : null, |
| 257 | }); |
| 258 | } else if (directive === "port") { |
| 259 | const port = args?.length === 1 ? Number(args[0]) : Number.NaN; |
| 260 | hostNameRules.push({ |
| 261 | conditions, |
| 262 | directive: "port", |
| 263 | value: Number.isInteger(port) && port >= 1 && port <= 65535 ? String(port) : null, |
| 264 | }); |
| 265 | } else if (directive === "include") { |
| 266 | if (args === null) { |
| 267 | hostNameRules.push({ conditions, directive: null, value: null }); |
| 268 | continue; |
| 269 | } |
| 270 | for (const includePattern of args) { |
| 271 | const resolvedPattern = yield* resolveSshConfigIncludePattern( |
| 272 | includePattern, |
| 273 | directory, |
| 274 | homeDir, |
| 275 | ); |
| 276 | if ( |
| 277 | /%|\$\{|\[/u.test(includePattern) || |
| 278 | (includePattern.startsWith("~") && !/^~(?=$|\/|\\)/u.test(includePattern)) |
| 279 | ) { |
| 280 | hostNameRules.push({ conditions, directive: null, value: null }); |
| 281 | continue; |
| 282 | } |
| 283 | const includedPaths = yield* expandGlob(resolvedPattern); |
| 284 | for (const includedPath of includedPaths) { |
| 285 | yield* collectSshConfigAliasesFromFile( |
| 286 | includedPath, |
| 287 | visited, |
| 288 | homeDir, |
| 289 | aliases, |
| 290 | hostNameRules, |
| 291 | conditions, |
| 292 | ); |
| 293 | } |
| 294 | } |
| 295 | } |
| 296 | } |
| 297 | }); |
| 298 | |
| 299 | interface KnownHost { |
| 300 | readonly hostname: string; |
| 301 | readonly port: number | null; |
| 302 | } |
| 303 | |
| 304 | function parseKnownHostsHost(rawHost: string): KnownHost | null { |
| 305 | const bracketMatch = /^\[([^\]]+)\]:(\d+)$/u.exec(rawHost); |
| 306 | if (bracketMatch?.[1]) { |
| 307 | const port = Number(bracketMatch[2]); |
| 308 | return port >= 1 && port <= 65535 ? { hostname: bracketMatch[1], port } : null; |
| 309 | } |
| 310 | |
| 311 | if (!rawHost.includes(":")) { |
| 312 | return { hostname: rawHost, port: null }; |
| 313 | } |
| 314 | |
| 315 | const firstColonIndex = rawHost.indexOf(":"); |
| 316 | const lastColonIndex = rawHost.lastIndexOf(":"); |
| 317 | return { |
| 318 | hostname: firstColonIndex === lastColonIndex ? rawHost.slice(0, lastColonIndex) : rawHost, |
| 319 | port: null, |
| 320 | }; |
| 321 | } |
| 322 | |
| 323 | export function parseKnownHosts(raw: string): ReadonlyArray<KnownHost> { |
| 324 | const hosts = new Map<string, KnownHost>(); |
| 325 | |
| 326 | for (const line of raw.split(/\r?\n/u)) { |
| 327 | const trimmed = line.trim(); |
| 328 | if (trimmed.length === 0 || trimmed.startsWith("#")) { |
| 329 | continue; |
| 330 | } |
| 331 | |
| 332 | const withoutMarker = trimmed.startsWith("@") |
| 333 | ? trimmed.split(/\s+/u).slice(1).join(" ") |
| 334 | : trimmed; |
| 335 | const [hostField = ""] = withoutMarker.split(/\s+/u); |
| 336 | if (hostField.length === 0 || hostField.startsWith("|")) { |
| 337 | continue; |
| 338 | } |
| 339 | |
| 340 | for (const rawHost of hostField.split(",")) { |
| 341 | const parsed = parseKnownHostsHost(rawHost.trim()); |
| 342 | if (parsed === null) continue; |
| 343 | const hostname = parsed.hostname.trim(); |
| 344 | if (hostname.length === 0 || hasSshPattern(hostname)) { |
| 345 | continue; |
| 346 | } |
| 347 | hosts.set(`${hostname}\u0000${parsed.port ?? ""}`, { hostname, port: parsed.port }); |
| 348 | } |
| 349 | } |
| 350 | |
| 351 | return [...hosts.values()].toSorted( |
| 352 | (left, right) => |
| 353 | left.hostname.localeCompare(right.hostname) || (left.port ?? 0) - (right.port ?? 0), |
| 354 | ); |
| 355 | } |
| 356 | |
| 357 | const readKnownHosts = Effect.fnUntraced(function* (filePath: string) { |
| 358 | const fs = yield* FileSystem.FileSystem; |
| 359 | if (!(yield* fs.exists(filePath))) { |
| 360 | return []; |
| 361 | } |
| 362 | return parseKnownHosts(yield* fs.readFileString(filePath)); |
| 363 | }); |
| 364 | |
| 365 | export const discoverSshHosts = Effect.fnUntraced( |
| 366 | function* (input: { readonly homeDir?: string }) { |
| 367 | const path = yield* Path.Path; |
| 368 | const env = yield* Config.all({ |
| 369 | home: Config.String("HOME").pipe(Config.option), |
| 370 | userProfile: Config.String("USERPROFILE").pipe(Config.option), |
| 371 | }); |
| 372 | const homeDir = |
| 373 | input?.homeDir ?? |
| 374 | Option.getOrUndefined(env.home) ?? |
| 375 | Option.getOrUndefined(env.userProfile) ?? |
| 376 | ""; |
| 377 | if (homeDir.trim().length === 0) { |
| 378 | return []; |
| 379 | } |
| 380 | |
| 381 | const sshDirectory = path.join(homeDir, ".ssh"); |
| 382 | const configAliases = new Set<string>(); |
| 383 | const hostNameRules: Array<HostRule> = []; |
| 384 | yield* collectSshConfigAliasesFromFile( |
| 385 | path.join(sshDirectory, "config"), |
| 386 | new Set<string>(), |
| 387 | homeDir, |
| 388 | configAliases, |
| 389 | hostNameRules, |
| 390 | [], |
| 391 | ); |
| 392 | const knownHosts = yield* readKnownHosts(path.join(sshDirectory, "known_hosts")); |
| 393 | const discovered = new Map<string, DesktopDiscoveredSshHost>(); |
| 394 | |
| 395 | const configuredNames = new Set<string>(); |
| 396 | const configuredDestinations = new Set<string>(); |
| 397 | for (const alias of configAliases) { |
| 398 | const hostname = resolveConfiguredHostname(alias, hostNameRules); |
| 399 | const port = resolveConfiguredPort(alias, hostNameRules); |
| 400 | for (const name of hostname === null ? [alias] : [alias, hostname]) { |
| 401 | configuredNames.add(name.toLowerCase()); |
| 402 | configuredDestinations.add(`${name.toLowerCase()}\u0000${port}`); |
| 403 | } |
| 404 | discovered.set(alias, { |
| 405 | alias, |
| 406 | hostname: hostname ?? alias, |
| 407 | username: null, |
| 408 | port: null, |
| 409 | source: "ssh-config", |
| 410 | }); |
| 411 | } |
| 412 | |
| 413 | for (const { hostname, port } of knownHosts) { |
| 414 | const name = hostname.toLowerCase(); |
| 415 | // A port-less entry connects as `ssh <host>`, so a matching alias's Port applies to it. |
| 416 | if ( |
| 417 | port === null |
| 418 | ? configuredNames.has(name) |
| 419 | : configuredDestinations.has(`${name}\u0000${port}`) || |
| 420 | configuredDestinations.has(`${name}\u0000*`) |
| 421 | ) { |
| 422 | continue; |
| 423 | } |
| 424 | discovered.set(`${hostname}\u0000${port ?? ""}`, { |
| 425 | alias: hostname, |
| 426 | hostname, |
| 427 | username: null, |
| 428 | port, |
| 429 | source: "known-hosts", |
| 430 | }); |
| 431 | } |
| 432 | |
| 433 | return [...discovered.values()].toSorted((left, right) => |
| 434 | left.alias.localeCompare(right.alias), |
| 435 | ); |
| 436 | }, |
| 437 | Effect.mapError( |
| 438 | (cause) => |
| 439 | new SshHostDiscoveryError({ |
| 440 | message: "Failed to discover SSH hosts.", |
| 441 | cause, |
| 442 | }), |
| 443 | ), |
| 444 | ); |