sailfork / t3code-github / packages/ ssh/ src/ config.ts

import type { DesktopDiscoveredSshHost } from "@t3tools/contracts";

import * as Config from "effect/Config";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Option from "effect/Option";
import * as Path from "effect/Path";
import * as PlatformError from "effect/PlatformError";

import { SshHostDiscoveryError } from "./errors.ts";

const NO_HOSTS: ReadonlyArray<string> = [] as const;

// Mirrors OpenSSH readconf: the keyword may be followed by one optional "=",
// then the arguments are split like misc.c argv_split() with quotes, the
// escapes \\ \" \' and unquoted "\ ", and "#" starting a comment only at
// the start of a token. Invalid quoting leaves hostname resolution uncertain.
function parseSshConfigLine(line: string) {
  const match = /^\s*([^\s=]+)\s*=?\s*(.*)$/u.exec(line);
  if (!match) {
    return null;
  }

  const directive = match[1]!.toLowerCase();
  const args: Array<string> = [];
  const rest = match[2]!;
  let token: string | null = null;
  let quote: string | null = null;
  for (let index = 0; index < rest.length; index += 1) {
    const char = rest[index]!;
    const next = rest[index + 1];
    if (
      char === "\\" &&
      (next === '"' || next === "'" || next === "\\" || (quote === null && next === " "))
    ) {
      token = (token ?? "") + next;
      index += 1;
    } else if (quote !== null) {
      if (char === quote) {
        quote = null;
      } else {
        token = (token ?? "") + char;
      }
    } else if (char === '"' || char === "'") {
      quote = char;
      token ??= "";
    } else if (/\s/u.test(char)) {
      if (token !== null) {
        args.push(token);
        token = null;
      }
    } else if (char === "#" && token === null) {
      break;
    } else {
      token = (token ?? "") + char;
    }
  }
  if (quote !== null) {
    return { directive, args: null };
  }
  if (token !== null) {
    args.push(token);
  }
  return { directive, args };
}

function expandHomePath(input: string, homeDir: string): string {
  return input.replace(/^~(?=$|\/|\\)/u, homeDir);
}

const resolveSshConfigIncludePattern = Effect.fnUntraced(function* (
  includePattern: string,
  _directory: string,
  homeDir: string,
) {
  const path = yield* Path.Path;
  const expandedPattern = expandHomePath(includePattern, homeDir);
  return path.isAbsolute(expandedPattern)
    ? expandedPattern
    : path.resolve(path.join(homeDir, ".ssh"), expandedPattern);
});

function hasSshPattern(value: string): boolean {
  return value.includes("*") || value.includes("?") || value.startsWith("!");
}

function escapeRegex(value: string): string {
  return value.replace(/[.*+?^${}()|[\]\\]/gu, "\\

Loading Sailfork

amp;"); } function globToRegExp(pattern: string): RegExp { return new RegExp( `^${escapeRegex(pattern).replace(/\\\*/gu, ".*").replace(/\\\?/gu, ".")} packages/ssh/src/config.ts at main · sailfork/t3code-github · Sailfork
, "u", ); } const expandGlob = Effect.fnUntraced(function* (pattern: string) { const fs = yield* FileSystem.FileSystem; const path = yield* Path.Path; if (!pattern.includes("*") && !pattern.includes("?")) { return (yield* fs.exists(pattern)) ? [pattern] : NO_HOSTS; } const directory = path.dirname(pattern); const basePattern = path.basename(pattern); if (!(yield* fs.exists(directory))) { return NO_HOSTS; } const matcher = globToRegExp(basePattern); const entries = yield* fs.readDirectory(directory); const matchedPaths: string[] = []; for (const entry of entries) { if (entry.startsWith(".") && !basePattern.startsWith(".")) continue; if (!matcher.test(entry)) { continue; } const entryPath = path.join(directory, entry); if (yield* fs.exists(entryPath)) { matchedPaths.push(entryPath); } } return matchedPaths.toSorted(); }); type HostCondition = ReadonlyArray<string> | null; interface HostNameRule { readonly conditions: ReadonlyArray<HostCondition>; readonly hostname: string | null; } function matchesHostPatterns(alias: string, patterns: ReadonlyArray<string>): boolean { let matched = false; for (const pattern of patterns) { const negated = pattern.startsWith("!"); const hostPattern = negated ? pattern.slice(1) : pattern; const matches = hostPattern === "*" || (hasSshPattern(hostPattern) ? globToRegExp(hostPattern).test(alias) : hostPattern === alias); if (!matches) continue; if (negated) return false; matched = true; } return matched; } function resolveConfiguredHostname(alias: string, rules: ReadonlyArray<HostNameRule>) { for (const { conditions, hostname } of rules) { if ( conditions.some((condition) => condition !== null && !matchesHostPatterns(alias, condition)) ) { continue; } // SSH takes the first value; an uncertain earlier value blocks later fallbacks. if (conditions.includes(null) || hostname === null) return null; if (/%(?!h)/u.test(hostname) || hostname.includes("$")) return null; return hostname.replaceAll("%h", alias); } return null; } const collectSshConfigAliasesFromFile = Effect.fnUntraced(function* ( filePath: string, visited: Set<string>, homeDir: string, aliases: Set<string>, hostNameRules: Array<HostNameRule>, inheritedConditions: ReadonlyArray<HostCondition>, ): Effect.fn.Return<void, PlatformError.PlatformError, FileSystem.FileSystem | Path.Path> { const fs = yield* FileSystem.FileSystem; const path = yield* Path.Path; const resolvedPath = path.resolve(filePath); if (visited.has(resolvedPath)) { // Read each file once, but never reuse its rules under a different Include context. hostNameRules.push({ conditions: inheritedConditions, hostname: null }); return; } if (!(yield* fs.exists(resolvedPath))) return; if ((yield* fs.stat(resolvedPath)).type === "Directory") return; visited.add(resolvedPath); const directory = path.dirname(resolvedPath); const raw = yield* fs.readFileString(resolvedPath); let condition: HostCondition = ["*"]; for (const line of raw.split(/\r?\n/u)) { const parsed = parseSshConfigLine(line); if (!parsed) continue; const { directive, args } = parsed; const conditions = [...inheritedConditions, condition]; if (directive === "host") { condition = args; for (const alias of args ?? []) { if (alias.length > 0 && !hasSshPattern(alias)) aliases.add(alias); } } else if (directive === "match") { condition = null; } else if (directive === "hostname") { hostNameRules.push({ conditions, hostname: args?.length === 1 ? args[0]! : null }); } else if (directive === "include") { if (args === null) { hostNameRules.push({ conditions, hostname: null }); continue; } for (const includePattern of args) { const resolvedPattern = yield* resolveSshConfigIncludePattern( includePattern, directory, homeDir, ); if ( /%|\$\{|\[/u.test(includePattern) || (includePattern.startsWith("~") && !/^~(?=$|\/|\\)/u.test(includePattern)) || hasSshPattern(path.dirname(resolvedPattern)) ) { hostNameRules.push({ conditions, hostname: null }); continue; } const includedPaths = yield* expandGlob(resolvedPattern); for (const includedPath of includedPaths) { yield* collectSshConfigAliasesFromFile( includedPath, visited, homeDir, aliases, hostNameRules, conditions, ); } } } } }); function normalizeKnownHostsHostname(rawHost: string): string { const bracketMatch = /^\[([^\]]+)\]:(\d+)$/u.exec(rawHost); if (bracketMatch?.[1]) { return bracketMatch[1]; } if (!rawHost.includes(":")) { return rawHost; } const firstColonIndex = rawHost.indexOf(":"); const lastColonIndex = rawHost.lastIndexOf(":"); return firstColonIndex === lastColonIndex ? rawHost.slice(0, lastColonIndex) : rawHost; } export function parseKnownHostsHostnames(raw: string): ReadonlyArray<string> { const hostnames = new Set<string>(); for (const line of raw.split(/\r?\n/u)) { const trimmed = line.trim(); if (trimmed.length === 0 || trimmed.startsWith("#")) { continue; } const withoutMarker = trimmed.startsWith("@") ? trimmed.split(/\s+/u).slice(1).join(" ") : trimmed; const [hostField = ""] = withoutMarker.split(/\s+/u); if (hostField.length === 0 || hostField.startsWith("|")) { continue; } for (const rawHost of hostField.split(",")) { const host = normalizeKnownHostsHostname(rawHost).trim(); if (host.length === 0 || hasSshPattern(host)) { continue; } hostnames.add(host); } } return [...hostnames].toSorted((left, right) => left.localeCompare(right)); } const readKnownHostsHostnames = Effect.fnUntraced(function* (filePath: string) { const fs = yield* FileSystem.FileSystem; if (!(yield* fs.exists(filePath))) { return NO_HOSTS; } return parseKnownHostsHostnames(yield* fs.readFileString(filePath)); }); export const discoverSshHosts = Effect.fnUntraced( function* (input: { readonly homeDir?: string }) { const path = yield* Path.Path; const env = yield* Config.all({ home: Config.String("HOME").pipe(Config.option), userProfile: Config.String("USERPROFILE").pipe(Config.option), }); const homeDir = input?.homeDir ?? Option.getOrUndefined(env.home) ?? Option.getOrUndefined(env.userProfile) ?? ""; if (homeDir.trim().length === 0) { return []; } const sshDirectory = path.join(homeDir, ".ssh"); const configAliases = new Set<string>(); const hostNameRules: Array<HostNameRule> = []; yield* collectSshConfigAliasesFromFile( path.join(sshDirectory, "config"), new Set<string>(), homeDir, configAliases, hostNameRules, [], ); const knownHosts = yield* readKnownHostsHostnames(path.join(sshDirectory, "known_hosts")); const discovered = new Map<string, DesktopDiscoveredSshHost>(); const configuredHostnames = new Set<string>(); for (const alias of configAliases) { const hostname = resolveConfiguredHostname(alias, hostNameRules); if (hostname !== null) configuredHostnames.add(hostname.toLowerCase()); discovered.set(alias, { alias, hostname: hostname ?? alias, username: null, port: null, source: "ssh-config", }); } for (const hostname of knownHosts) { if (discovered.has(hostname) || configuredHostnames.has(hostname.toLowerCase())) { continue; } discovered.set(hostname, { alias: hostname, hostname, username: null, port: null, source: "known-hosts", }); } return [...discovered.values()].toSorted((left, right) => left.alias.localeCompare(right.alias), ); }, Effect.mapError( (cause) => new SshHostDiscoveryError({ message: "Failed to discover SSH hosts.", cause, }), ), );
packages/ssh/src/config.ts at main · sailfork/t3code-github · Sailfork
,\n \"u\",\n );\n}\n\nconst expandGlob = Effect.fnUntraced(function* (pattern: string) {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n if (!pattern.includes(\"*\") && !pattern.includes(\"?\")) {\n return (yield* fs.exists(pattern)) ? [pattern] : NO_HOSTS;\n }\n\n const directory = path.dirname(pattern);\n const basePattern = path.basename(pattern);\n if (!(yield* fs.exists(directory))) {\n return NO_HOSTS;\n }\n\n const matcher = globToRegExp(basePattern);\n const entries = yield* fs.readDirectory(directory);\n const matchedPaths: string[] = [];\n for (const entry of entries) {\n if (entry.startsWith(\".\") && !basePattern.startsWith(\".\")) continue;\n if (!matcher.test(entry)) {\n continue;\n }\n const entryPath = path.join(directory, entry);\n if (yield* fs.exists(entryPath)) {\n matchedPaths.push(entryPath);\n }\n }\n return matchedPaths.toSorted();\n});\n\ntype HostCondition = ReadonlyArray\u003cstring> | null;\n\ninterface HostNameRule {\n readonly conditions: ReadonlyArray\u003cHostCondition>;\n readonly hostname: string | null;\n}\n\nfunction matchesHostPatterns(alias: string, patterns: ReadonlyArray\u003cstring>): boolean {\n let matched = false;\n for (const pattern of patterns) {\n const negated = pattern.startsWith(\"!\");\n const hostPattern = negated ? pattern.slice(1) : pattern;\n const matches =\n hostPattern === \"*\" ||\n (hasSshPattern(hostPattern) ? globToRegExp(hostPattern).test(alias) : hostPattern === alias);\n if (!matches) continue;\n if (negated) return false;\n matched = true;\n }\n return matched;\n}\n\nfunction resolveConfiguredHostname(alias: string, rules: ReadonlyArray\u003cHostNameRule>) {\n for (const { conditions, hostname } of rules) {\n if (\n conditions.some((condition) => condition !== null && !matchesHostPatterns(alias, condition))\n ) {\n continue;\n }\n // SSH takes the first value; an uncertain earlier value blocks later fallbacks.\n if (conditions.includes(null) || hostname === null) return null;\n if (/%(?!h)/u.test(hostname) || hostname.includes(\"$\")) return null;\n return hostname.replaceAll(\"%h\", alias);\n }\n return null;\n}\n\nconst collectSshConfigAliasesFromFile = Effect.fnUntraced(function* (\n filePath: string,\n visited: Set\u003cstring>,\n homeDir: string,\n aliases: Set\u003cstring>,\n hostNameRules: Array\u003cHostNameRule>,\n inheritedConditions: ReadonlyArray\u003cHostCondition>,\n): Effect.fn.Return\u003cvoid, PlatformError.PlatformError, FileSystem.FileSystem | Path.Path> {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const resolvedPath = path.resolve(filePath);\n if (visited.has(resolvedPath)) {\n // Read each file once, but never reuse its rules under a different Include context.\n hostNameRules.push({ conditions: inheritedConditions, hostname: null });\n return;\n }\n if (!(yield* fs.exists(resolvedPath))) return;\n if ((yield* fs.stat(resolvedPath)).type === \"Directory\") return;\n visited.add(resolvedPath);\n\n const directory = path.dirname(resolvedPath);\n const raw = yield* fs.readFileString(resolvedPath);\n let condition: HostCondition = [\"*\"];\n\n for (const line of raw.split(/\\r?\\n/u)) {\n const parsed = parseSshConfigLine(line);\n if (!parsed) continue;\n const { directive, args } = parsed;\n const conditions = [...inheritedConditions, condition];\n\n if (directive === \"host\") {\n condition = args;\n for (const alias of args ?? []) {\n if (alias.length > 0 && !hasSshPattern(alias)) aliases.add(alias);\n }\n } else if (directive === \"match\") {\n condition = null;\n } else if (directive === \"hostname\") {\n hostNameRules.push({ conditions, hostname: args?.length === 1 ? args[0]! : null });\n } else if (directive === \"include\") {\n if (args === null) {\n hostNameRules.push({ conditions, hostname: null });\n continue;\n }\n for (const includePattern of args) {\n const resolvedPattern = yield* resolveSshConfigIncludePattern(\n includePattern,\n directory,\n homeDir,\n );\n if (\n /%|\\$\\{|\\[/u.test(includePattern) ||\n (includePattern.startsWith(\"~\") && !/^~(?=$|\\/|\\\\)/u.test(includePattern)) ||\n hasSshPattern(path.dirname(resolvedPattern))\n ) {\n hostNameRules.push({ conditions, hostname: null });\n continue;\n }\n const includedPaths = yield* expandGlob(resolvedPattern);\n for (const includedPath of includedPaths) {\n yield* collectSshConfigAliasesFromFile(\n includedPath,\n visited,\n homeDir,\n aliases,\n hostNameRules,\n conditions,\n );\n }\n }\n }\n }\n});\n\nfunction normalizeKnownHostsHostname(rawHost: string): string {\n const bracketMatch = /^\\[([^\\]]+)\\]:(\\d+)$/u.exec(rawHost);\n if (bracketMatch?.[1]) {\n return bracketMatch[1];\n }\n\n if (!rawHost.includes(\":\")) {\n return rawHost;\n }\n\n const firstColonIndex = rawHost.indexOf(\":\");\n const lastColonIndex = rawHost.lastIndexOf(\":\");\n return firstColonIndex === lastColonIndex ? rawHost.slice(0, lastColonIndex) : rawHost;\n}\n\nexport function parseKnownHostsHostnames(raw: string): ReadonlyArray\u003cstring> {\n const hostnames = new Set\u003cstring>();\n\n for (const line of raw.split(/\\r?\\n/u)) {\n const trimmed = line.trim();\n if (trimmed.length === 0 || trimmed.startsWith(\"#\")) {\n continue;\n }\n\n const withoutMarker = trimmed.startsWith(\"@\")\n ? trimmed.split(/\\s+/u).slice(1).join(\" \")\n : trimmed;\n const [hostField = \"\"] = withoutMarker.split(/\\s+/u);\n if (hostField.length === 0 || hostField.startsWith(\"|\")) {\n continue;\n }\n\n for (const rawHost of hostField.split(\",\")) {\n const host = normalizeKnownHostsHostname(rawHost).trim();\n if (host.length === 0 || hasSshPattern(host)) {\n continue;\n }\n hostnames.add(host);\n }\n }\n\n return [...hostnames].toSorted((left, right) => left.localeCompare(right));\n}\n\nconst readKnownHostsHostnames = Effect.fnUntraced(function* (filePath: string) {\n const fs = yield* FileSystem.FileSystem;\n if (!(yield* fs.exists(filePath))) {\n return NO_HOSTS;\n }\n return parseKnownHostsHostnames(yield* fs.readFileString(filePath));\n});\n\nexport const discoverSshHosts = Effect.fnUntraced(\n function* (input: { readonly homeDir?: string }) {\n const path = yield* Path.Path;\n const env = yield* Config.all({\n home: Config.String(\"HOME\").pipe(Config.option),\n userProfile: Config.String(\"USERPROFILE\").pipe(Config.option),\n });\n const homeDir =\n input?.homeDir ??\n Option.getOrUndefined(env.home) ??\n Option.getOrUndefined(env.userProfile) ??\n \"\";\n if (homeDir.trim().length === 0) {\n return [];\n }\n\n const sshDirectory = path.join(homeDir, \".ssh\");\n const configAliases = new Set\u003cstring>();\n const hostNameRules: Array\u003cHostNameRule> = [];\n yield* collectSshConfigAliasesFromFile(\n path.join(sshDirectory, \"config\"),\n new Set\u003cstring>(),\n homeDir,\n configAliases,\n hostNameRules,\n [],\n );\n const knownHosts = yield* readKnownHostsHostnames(path.join(sshDirectory, \"known_hosts\"));\n const discovered = new Map\u003cstring, DesktopDiscoveredSshHost>();\n\n const configuredHostnames = new Set\u003cstring>();\n for (const alias of configAliases) {\n const hostname = resolveConfiguredHostname(alias, hostNameRules);\n if (hostname !== null) configuredHostnames.add(hostname.toLowerCase());\n discovered.set(alias, {\n alias,\n hostname: hostname ?? alias,\n username: null,\n port: null,\n source: \"ssh-config\",\n });\n }\n\n for (const hostname of knownHosts) {\n if (discovered.has(hostname) || configuredHostnames.has(hostname.toLowerCase())) {\n continue;\n }\n discovered.set(hostname, {\n alias: hostname,\n hostname,\n username: null,\n port: null,\n source: \"known-hosts\",\n });\n }\n\n return [...discovered.values()].toSorted((left, right) =>\n left.alias.localeCompare(right.alias),\n );\n },\n Effect.mapError(\n (cause) =>\n new SshHostDiscoveryError({\n message: \"Failed to discover SSH hosts.\",\n cause,\n }),\n ),\n);\n","preview":null,"history":null,"version":"e87acd578def147430fd640f418466c29cb3facf"},"/_session?shell=1":null}