From 20edab789df95babf6eb9ff0793393f922457ed6 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Tue, 28 Apr 2026 11:34:52 -0700 Subject: [PATCH] Extract SSH helpers into shared package - Move SSH parsing and discovery logic into `@t3tools/ssh` - Reuse the shared helpers from the desktop app and release smoke checks - Add coverage for host discovery, parsing, and package spec resolution --- apps/desktop/package.json | 1 + apps/desktop/src/sshEnvironment.ts | 325 ++-------------------------- bun.lock | 18 ++ packages/ssh/package.json | 28 +++ packages/ssh/src/index.ts | 1 + packages/ssh/src/ssh.test.ts | 233 ++++++++++++++++++++ packages/ssh/src/ssh.ts | 335 +++++++++++++++++++++++++++++ packages/ssh/tsconfig.json | 17 ++ scripts/release-smoke.ts | 1 + 9 files changed, 654 insertions(+), 305 deletions(-) create mode 100644 packages/ssh/package.json create mode 100644 packages/ssh/src/index.ts create mode 100644 packages/ssh/src/ssh.test.ts create mode 100644 packages/ssh/src/ssh.ts create mode 100644 packages/ssh/tsconfig.json diff --git a/apps/desktop/package.json b/apps/desktop/package.json index 53bee5f63a..75563de716 100644 --- a/apps/desktop/package.json +++ b/apps/desktop/package.json @@ -24,6 +24,7 @@ "@t3tools/client-runtime": "workspace:*", "@t3tools/contracts": "workspace:*", "@t3tools/shared": "workspace:*", + "@t3tools/ssh": "workspace:*", "@t3tools/tailscale": "workspace:*", "@types/node": "catalog:", "effect-acp": "workspace:*", diff --git a/apps/desktop/src/sshEnvironment.ts b/apps/desktop/src/sshEnvironment.ts index eb57b8b37e..7c6fc68f9a 100644 --- a/apps/desktop/src/sshEnvironment.ts +++ b/apps/desktop/src/sshEnvironment.ts @@ -13,18 +13,34 @@ import type { DesktopSshEnvironmentBootstrap, DesktopSshEnvironmentTarget, DesktopSshPasswordPromptRequest, - DesktopUpdateChannel, ExecutionEnvironmentDescriptor, } from "@t3tools/contracts"; +import { + DEFAULT_REMOTE_PORT, + baseSshArgs, + buildSshHostSpec, + collectSshConfigAliasesFromFile, + discoverSshHosts, + getLastNonEmptyOutputLine, + isSshAuthFailure, + normalizeSshErrorMessage, + parseKnownHostsHostnames, + parseSshResolveOutput, + remoteStateKey, + resolveRemoteT3CliPackageSpec, + resolveSshConfigIncludePattern, + targetConnectionKey, +} from "@t3tools/ssh"; +import { Effect } from "effect"; import { waitForHttpReady } from "./backendReadiness.ts"; -const DEFAULT_REMOTE_PORT = 3773; +export { resolveRemoteT3CliPackageSpec }; + const REMOTE_PORT_SCAN_WINDOW = 200; const SSH_ASKPASS_DIR_NAME = "t3code-ssh-askpass"; const TUNNEL_SHUTDOWN_TIMEOUT_MS = 2_000; const SSH_READY_TIMEOUT_MS = 20_000; -const PUBLISHABLE_T3_VERSION_PATTERN = /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/u; const DISCOVER_SSH_HOSTS_CHANNEL = "desktop:discover-ssh-hosts"; const ENSURE_SSH_ENVIRONMENT_CHANNEL = "desktop:ensure-ssh-environment"; @@ -80,199 +96,6 @@ interface DesktopSshEnvironmentManagerOptions { readonly resolveCliPackageSpec?: () => string; } -const NO_HOSTS = [] as const; - -function stripInlineComment(line: string): string { - const hashIndex = line.indexOf("#"); - return (hashIndex >= 0 ? line.slice(0, hashIndex) : line).trim(); -} - -function splitDirectiveArgs(value: string): ReadonlyArray { - return value - .trim() - .split(/\s+/u) - .map((entry) => entry.trim()) - .filter((entry) => entry.length > 0); -} - -function expandHomePath(input: string, homeDir: string = OS.homedir()): string { - return input.replace(/^~(?=$|\/|\\)/u, homeDir); -} - -function resolveSshConfigIncludePattern( - includePattern: string, - _directory: string, - homeDir: string = OS.homedir(), -): string { - 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, "\\$&"); -} - -function globToRegExp(pattern: string): RegExp { - return new RegExp( - `^${escapeRegex(pattern).replace(/\\\*/gu, ".*").replace(/\\\?/gu, ".")}$`, - "u", - ); -} - -function expandGlob(pattern: string): ReadonlyArray { - if (!pattern.includes("*") && !pattern.includes("?")) { - return FS.existsSync(pattern) ? [pattern] : NO_HOSTS; - } - - const directory = Path.dirname(pattern); - const basePattern = Path.basename(pattern); - if (!FS.existsSync(directory)) { - return NO_HOSTS; - } - - const matcher = globToRegExp(basePattern); - return FS.readdirSync(directory) - .filter((entry) => matcher.test(entry)) - .map((entry) => Path.join(directory, entry)) - .filter((entry) => FS.existsSync(entry)) - .toSorted((left, right) => left.localeCompare(right)); -} - -function collectSshConfigAliasesFromFile( - filePath: string, - visited = new Set(), - homeDir: string = OS.homedir(), -): ReadonlyArray { - const resolvedPath = Path.resolve(filePath); - if (visited.has(resolvedPath) || !FS.existsSync(resolvedPath)) { - return NO_HOSTS; - } - visited.add(resolvedPath); - - const aliases = new Set(); - const directory = Path.dirname(resolvedPath); - const raw = FS.readFileSync(resolvedPath, "utf8"); - - for (const line of raw.split(/\r?\n/u)) { - const stripped = stripInlineComment(line); - if (stripped.length === 0) { - continue; - } - - const [directive = "", ...rawArgs] = splitDirectiveArgs(stripped); - const normalizedDirective = directive.toLowerCase(); - if (normalizedDirective === "include") { - for (const includePattern of rawArgs) { - const resolvedPattern = resolveSshConfigIncludePattern(includePattern, directory, homeDir); - for (const includedPath of expandGlob(resolvedPattern)) { - for (const alias of collectSshConfigAliasesFromFile(includedPath, visited, homeDir)) { - aliases.add(alias); - } - } - } - continue; - } - - if (normalizedDirective !== "host") { - continue; - } - - for (const alias of rawArgs) { - if (alias.length === 0 || hasSshPattern(alias)) { - continue; - } - aliases.add(alias); - } - } - - return [...aliases].toSorted((left, right) => left.localeCompare(right)); -} - -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; -} - -function parseKnownHostsHostnames(raw: string): ReadonlyArray { - const hostnames = new Set(); - - 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)); -} - -function readKnownHostsHostnames(filePath: string): ReadonlyArray { - if (!FS.existsSync(filePath)) { - return NO_HOSTS; - } - - return parseKnownHostsHostnames(FS.readFileSync(filePath, "utf8")); -} - -function parseSshResolveOutput(alias: string, stdout: string): DesktopSshEnvironmentTarget { - const values = new Map(); - for (const line of stdout.split(/\r?\n/u)) { - const trimmed = line.trim(); - if (trimmed.length === 0) { - continue; - } - const [key, ...rest] = trimmed.split(/\s+/u); - if (!key || rest.length === 0 || values.has(key)) { - continue; - } - values.set(key, rest.join(" ").trim()); - } - - const hostname = values.get("hostname")?.trim() || alias; - const username = values.get("user")?.trim() || null; - const rawPort = values.get("port")?.trim() ?? ""; - const parsedPort = Number.parseInt(rawPort, 10); - - return { - alias, - hostname, - username, - port: Number.isInteger(parsedPort) ? parsedPort : null, - }; -} - async function findAvailableLocalPort(): Promise { return await new Promise((resolve, reject) => { const server = Net.createServer(); @@ -296,22 +119,6 @@ async function findAvailableLocalPort(): Promise { }); } -function targetConnectionKey(target: DesktopSshEnvironmentTarget): string { - return `${target.alias}\u0000${target.hostname}\u0000${target.username ?? ""}\u0000${target.port ?? ""}`; -} - -function remoteStateKey(target: DesktopSshEnvironmentTarget): string { - return Crypto.createHash("sha256").update(targetConnectionKey(target)).digest("hex").slice(0, 16); -} - -function buildSshHostSpec(target: DesktopSshEnvironmentTarget): string { - const destination = target.alias.trim() || target.hostname.trim(); - if (destination.length === 0) { - throw new Error("SSH target is missing its alias/hostname."); - } - return target.username ? `${target.username}@${destination}` : destination; -} - function getDefaultSshAskpassDirectory(): string { return Path.join(OS.tmpdir(), SSH_ASKPASS_DIR_NAME); } @@ -450,36 +257,6 @@ function buildSshChildEnvironment(input?: { }; } -function baseSshArgs( - target: DesktopSshEnvironmentTarget, - input?: { readonly batchMode?: "yes" | "no" }, -): string[] { - return [ - "-o", - `BatchMode=${input?.batchMode ?? "no"}`, - "-o", - "ConnectTimeout=10", - ...(target.port !== null ? ["-p", String(target.port)] : []), - ]; -} - -function normalizeSshErrorMessage(stderr: string, fallbackMessage: string): string { - const cleaned = stderr.trim(); - return cleaned.length > 0 ? cleaned : fallbackMessage; -} - -function isSshAuthFailure(error: unknown): boolean { - const message = error instanceof Error ? error.message : String(error); - const normalized = message.toLowerCase(); - return ( - /permission denied \((?:publickey|password|keyboard-interactive|hostbased|gssapi-with-mic)[^)]*\)/u.test( - normalized, - ) || - /authentication failed/u.test(normalized) || - /too many authentication failures/u.test(normalized) - ); -} - async function runSshCommand( target: DesktopSshEnvironmentTarget, input?: { @@ -596,33 +373,6 @@ function buildRemoteLaunchScript(input?: { readonly packageSpec?: string }): str }); } -function getLastNonEmptyOutputLine(stdout: string): string | null { - return ( - stdout - .trim() - .split(/\r?\n/u) - .map((entry) => entry.trim()) - .findLast((entry) => entry.length > 0) ?? null - ); -} - -export function resolveRemoteT3CliPackageSpec(input: { - readonly appVersion: string; - readonly updateChannel: DesktopUpdateChannel; - readonly isDevelopment?: boolean; -}): string { - const appVersion = input.appVersion.trim(); - if (!input.isDevelopment && PUBLISHABLE_T3_VERSION_PATTERN.test(appVersion)) { - return `t3@${appVersion}`; - } - - if (input.isDevelopment) { - return "t3@nightly"; - } - - return input.updateChannel === "nightly" ? "t3@nightly" : "t3@latest"; -} - function buildRemoteT3RunnerScript(input?: { readonly packageSpec?: string }): string { const packageSpec = input?.packageSpec?.trim() || "t3@latest"; return stripTrailingNewlines( @@ -769,40 +519,7 @@ async function stopTunnel(entry: SshTunnelEntry): Promise { export async function discoverDesktopSshHosts(input?: { readonly homeDir?: string; }): Promise { - const homeDir = input?.homeDir ?? OS.homedir(); - const sshDirectory = Path.join(homeDir, ".ssh"); - const configAliases = collectSshConfigAliasesFromFile( - Path.join(sshDirectory, "config"), - new Set(), - homeDir, - ); - const knownHosts = readKnownHostsHostnames(Path.join(sshDirectory, "known_hosts")); - const discovered = new Map(); - - for (const alias of configAliases) { - discovered.set(alias, { - alias, - hostname: alias, - username: null, - port: null, - source: "ssh-config", - }); - } - - for (const hostname of knownHosts) { - if (discovered.has(hostname)) { - 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)); + return await Effect.runPromise(discoverSshHosts(input)); } export class DesktopSshEnvironmentManager { @@ -1369,8 +1086,6 @@ export const __test = { getLastNonEmptyOutputLine, isSshAuthFailure, collectSshConfigAliasesFromFile, - expandHomePath, - normalizeKnownHostsHostname, parseKnownHostsHostnames, parseSshResolveOutput, readSshScriptTemplate, diff --git a/bun.lock b/bun.lock index 9f6acee0aa..13321bc3b2 100644 --- a/bun.lock +++ b/bun.lock @@ -25,6 +25,7 @@ "@t3tools/client-runtime": "workspace:*", "@t3tools/contracts": "workspace:*", "@t3tools/shared": "workspace:*", + "@t3tools/ssh": "workspace:*", "@t3tools/tailscale": "workspace:*", "@types/node": "catalog:", "effect-acp": "workspace:*", @@ -201,6 +202,21 @@ "vitest": "catalog:", }, }, + "packages/ssh": { + "name": "@t3tools/ssh", + "version": "0.0.0-alpha.1", + "dependencies": { + "@t3tools/contracts": "workspace:*", + "effect": "catalog:", + }, + "devDependencies": { + "@effect/language-service": "catalog:", + "@effect/vitest": "catalog:", + "@types/node": "catalog:", + "typescript": "catalog:", + "vitest": "catalog:", + }, + }, "packages/tailscale": { "name": "@t3tools/tailscale", "version": "0.0.0-alpha.1", @@ -758,6 +774,8 @@ "@t3tools/shared": ["@t3tools/shared@workspace:packages/shared"], + "@t3tools/ssh": ["@t3tools/ssh@workspace:packages/ssh"], + "@t3tools/tailscale": ["@t3tools/tailscale@workspace:packages/tailscale"], "@t3tools/web": ["@t3tools/web@workspace:apps/web"], diff --git a/packages/ssh/package.json b/packages/ssh/package.json new file mode 100644 index 0000000000..b32dd4a3af --- /dev/null +++ b/packages/ssh/package.json @@ -0,0 +1,28 @@ +{ + "name": "@t3tools/ssh", + "version": "0.0.0-alpha.1", + "private": true, + "type": "module", + "exports": { + ".": { + "types": "./src/index.ts", + "import": "./src/index.ts" + } + }, + "scripts": { + "prepare": "effect-language-service patch", + "typecheck": "tsc --noEmit", + "test": "vitest run" + }, + "dependencies": { + "@t3tools/contracts": "workspace:*", + "effect": "catalog:" + }, + "devDependencies": { + "@effect/language-service": "catalog:", + "@effect/vitest": "catalog:", + "@types/node": "catalog:", + "typescript": "catalog:", + "vitest": "catalog:" + } +} diff --git a/packages/ssh/src/index.ts b/packages/ssh/src/index.ts new file mode 100644 index 0000000000..c373cc08e8 --- /dev/null +++ b/packages/ssh/src/index.ts @@ -0,0 +1 @@ +export * from "./ssh.ts"; diff --git a/packages/ssh/src/ssh.test.ts b/packages/ssh/src/ssh.test.ts new file mode 100644 index 0000000000..908cc64031 --- /dev/null +++ b/packages/ssh/src/ssh.test.ts @@ -0,0 +1,233 @@ +import * as FS from "node:fs"; +import * as OS from "node:os"; +import * as Path from "node:path"; + +import { assert, describe, it } from "@effect/vitest"; +import { Effect } from "effect"; + +import { + baseSshArgs, + discoverSshHosts, + getLastNonEmptyOutputLine, + isSshAuthFailure, + parseKnownHostsHostnames, + parseSshResolveOutput, + resolveRemoteT3CliPackageSpec, + resolveSshConfigIncludePattern, +} from "./ssh.ts"; + +const tempDirectories: string[] = []; + +function makeTempHomeDir(): string { + const directory = FS.mkdtempSync(Path.join(OS.tmpdir(), "t3-ssh-test-")); + tempDirectories.push(directory); + return directory; +} + +describe("ssh", () => { + it.effect("discovers ssh config hosts across included files", () => + Effect.acquireUseRelease( + Effect.sync(makeTempHomeDir), + (homeDir) => + Effect.gen(function* () { + const sshDir = Path.join(homeDir, ".ssh"); + FS.mkdirSync(Path.join(sshDir, "config.d"), { recursive: true }); + FS.writeFileSync( + Path.join(sshDir, "config"), + ["Host devbox", " HostName devbox.example.com", "Include config.d/*.conf", ""].join( + "\n", + ), + "utf8", + ); + FS.writeFileSync( + Path.join(sshDir, "config.d", "team.conf"), + [ + "Host staging", + " HostName staging.example.com", + "Host *", + " ServerAliveInterval 30", + "", + ].join("\n"), + "utf8", + ); + FS.writeFileSync( + Path.join(sshDir, "known_hosts"), + [ + "known.example.com ssh-ed25519 AAAA", + "|1|hashed|entry ssh-ed25519 AAAA", + "[bastion.example.com]:2222 ssh-ed25519 AAAA", + "", + ].join("\n"), + "utf8", + ); + + const hosts = yield* discoverSshHosts({ homeDir }); + assert.deepEqual(hosts, [ + { + alias: "bastion.example.com", + hostname: "bastion.example.com", + username: null, + port: null, + source: "known-hosts", + }, + { + alias: "devbox", + hostname: "devbox", + username: null, + port: null, + source: "ssh-config", + }, + { + alias: "known.example.com", + hostname: "known.example.com", + username: null, + port: null, + source: "known-hosts", + }, + { + alias: "staging", + hostname: "staging", + username: null, + port: null, + source: "ssh-config", + }, + ]); + }), + (homeDir) => Effect.sync(() => FS.rmSync(homeDir, { recursive: true, force: true })), + ), + ); + + it.effect("parses known_hosts entries without returning hashed hosts", () => + Effect.sync(() => { + assert.deepEqual( + parseKnownHostsHostnames( + [ + "github.com ssh-ed25519 AAAA", + "gitlab.com,gitlab-alias ssh-ed25519 BBBB", + "|1|hashed|entry ssh-ed25519 CCCC", + "@cert-authority *.example.com ssh-ed25519 DDDD", + "[ssh.example.com]:2200 ssh-ed25519 EEEE", + "port.example.com:22 ssh-ed25519 HHHH", + "::1 ssh-ed25519 FFFF", + "2001:db8::1 ssh-ed25519 GGGG", + "", + ].join("\n"), + ), + [ + "::1", + "2001:db8::1", + "github.com", + "gitlab-alias", + "gitlab.com", + "port.example.com", + "ssh.example.com", + ], + ); + }), + ); + + it.effect("expands tilde-prefixed ssh config include patterns", () => + Effect.sync(() => { + assert.equal( + resolveSshConfigIncludePattern("~/.ssh/config.d/*.conf", "/tmp/project", "/tmp/home"), + "/tmp/home/.ssh/config.d/*.conf", + ); + }), + ); + + it.effect("parses resolved ssh config output into a target", () => + Effect.sync(() => { + assert.deepEqual( + parseSshResolveOutput( + "devbox", + ["hostname devbox.example.com", "user julius", "port 2222", ""].join("\n"), + ), + { + alias: "devbox", + hostname: "devbox.example.com", + username: "julius", + port: 2222, + }, + ); + }), + ); + + it.effect("builds interactive ssh args without forcing batch mode", () => + Effect.sync(() => { + assert.deepEqual( + baseSshArgs( + { + alias: "devbox", + hostname: "devbox.example.com", + username: "julius", + port: 2222, + }, + { batchMode: "no" }, + ), + ["-o", "BatchMode=no", "-o", "ConnectTimeout=10", "-p", "2222"], + ); + }), + ); + + it.effect("resolves the remote t3 package spec from the desktop release channel", () => + Effect.sync(() => { + assert.equal( + resolveRemoteT3CliPackageSpec({ + appVersion: "0.0.17", + updateChannel: "latest", + }), + "t3@0.0.17", + ); + assert.equal( + resolveRemoteT3CliPackageSpec({ + appVersion: "0.0.17-nightly.20260415.44", + updateChannel: "nightly", + }), + "t3@0.0.17-nightly.20260415.44", + ); + assert.equal( + resolveRemoteT3CliPackageSpec({ + appVersion: "0.0.0-dev", + updateChannel: "nightly", + isDevelopment: true, + }), + "t3@nightly", + ); + assert.equal( + resolveRemoteT3CliPackageSpec({ + appVersion: "0.0.0-dev", + updateChannel: "latest", + isDevelopment: true, + }), + "t3@nightly", + ); + }), + ); + + it.effect("reads the last non-empty ssh output line", () => + Effect.sync(() => { + assert.equal( + getLastNonEmptyOutputLine( + ["Welcome to the host", "", '{"credential":"pairing-token"}', ""].join("\n"), + ), + '{"credential":"pairing-token"}', + ); + }), + ); + + it.effect("detects ssh auth failures from common permission denied messages", () => + Effect.sync(() => { + assert.equal( + isSshAuthFailure( + new Error( + "julius@100.65.180.100: Permission denied (publickey,password,keyboard-interactive).", + ), + ), + true, + ); + assert.equal(isSshAuthFailure(new Error("Permission denied (publickey).")), true); + assert.equal(isSshAuthFailure(new Error("Connection timed out")), false); + assert.equal(isSshAuthFailure(new Error("mkdir: Permission denied")), false); + }), + ); +}); diff --git a/packages/ssh/src/ssh.ts b/packages/ssh/src/ssh.ts new file mode 100644 index 0000000000..b0f95014bd --- /dev/null +++ b/packages/ssh/src/ssh.ts @@ -0,0 +1,335 @@ +import * as Crypto from "node:crypto"; +import * as FS from "node:fs"; +import * as OS from "node:os"; +import * as Path from "node:path"; + +import type { + DesktopDiscoveredSshHost, + DesktopSshEnvironmentTarget, + DesktopUpdateChannel, +} from "@t3tools/contracts"; + +import { Data, Effect } from "effect"; + +export const DEFAULT_REMOTE_PORT = 3773; + +const NO_HOSTS = [] as const; +const PUBLISHABLE_T3_VERSION_PATTERN = /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/u; + +export class SshHostDiscoveryError extends Data.TaggedError("SshHostDiscoveryError")<{ + readonly message: string; + readonly cause: unknown; +}> {} + +function stripInlineComment(line: string): string { + const hashIndex = line.indexOf("#"); + return (hashIndex >= 0 ? line.slice(0, hashIndex) : line).trim(); +} + +function splitDirectiveArgs(value: string): ReadonlyArray { + return value + .trim() + .split(/\s+/u) + .map((entry) => entry.trim()) + .filter((entry) => entry.length > 0); +} + +function expandHomePath(input: string, homeDir: string = OS.homedir()): string { + return input.replace(/^~(?=$|\/|\\)/u, homeDir); +} + +export function resolveSshConfigIncludePattern( + includePattern: string, + _directory: string, + homeDir: string = OS.homedir(), +): string { + 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, "\\$&"); +} + +function globToRegExp(pattern: string): RegExp { + return new RegExp( + `^${escapeRegex(pattern).replace(/\\\*/gu, ".*").replace(/\\\?/gu, ".")}$`, + "u", + ); +} + +function expandGlob(pattern: string): ReadonlyArray { + if (!pattern.includes("*") && !pattern.includes("?")) { + return FS.existsSync(pattern) ? [pattern] : NO_HOSTS; + } + + const directory = Path.dirname(pattern); + const basePattern = Path.basename(pattern); + if (!FS.existsSync(directory)) { + return NO_HOSTS; + } + + const matcher = globToRegExp(basePattern); + return FS.readdirSync(directory) + .filter((entry) => matcher.test(entry)) + .map((entry) => Path.join(directory, entry)) + .filter((entry) => FS.existsSync(entry)) + .toSorted((left, right) => left.localeCompare(right)); +} + +export function collectSshConfigAliasesFromFile( + filePath: string, + visited = new Set(), + homeDir: string = OS.homedir(), +): ReadonlyArray { + const resolvedPath = Path.resolve(filePath); + if (visited.has(resolvedPath) || !FS.existsSync(resolvedPath)) { + return NO_HOSTS; + } + visited.add(resolvedPath); + + const aliases = new Set(); + const directory = Path.dirname(resolvedPath); + const raw = FS.readFileSync(resolvedPath, "utf8"); + + for (const line of raw.split(/\r?\n/u)) { + const stripped = stripInlineComment(line); + if (stripped.length === 0) { + continue; + } + + const [directive = "", ...rawArgs] = splitDirectiveArgs(stripped); + const normalizedDirective = directive.toLowerCase(); + if (normalizedDirective === "include") { + for (const includePattern of rawArgs) { + const resolvedPattern = resolveSshConfigIncludePattern(includePattern, directory, homeDir); + for (const includedPath of expandGlob(resolvedPattern)) { + for (const alias of collectSshConfigAliasesFromFile(includedPath, visited, homeDir)) { + aliases.add(alias); + } + } + } + continue; + } + + if (normalizedDirective !== "host") { + continue; + } + + for (const alias of rawArgs) { + if (alias.length === 0 || hasSshPattern(alias)) { + continue; + } + aliases.add(alias); + } + } + + return [...aliases].toSorted((left, right) => left.localeCompare(right)); +} + +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 { + const hostnames = new Set(); + + 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)); +} + +function readKnownHostsHostnames(filePath: string): ReadonlyArray { + if (!FS.existsSync(filePath)) { + return NO_HOSTS; + } + + return parseKnownHostsHostnames(FS.readFileSync(filePath, "utf8")); +} + +export function parseSshResolveOutput(alias: string, stdout: string): DesktopSshEnvironmentTarget { + const values = new Map(); + for (const line of stdout.split(/\r?\n/u)) { + const trimmed = line.trim(); + if (trimmed.length === 0) { + continue; + } + const [key, ...rest] = trimmed.split(/\s+/u); + if (!key || rest.length === 0 || values.has(key)) { + continue; + } + values.set(key, rest.join(" ").trim()); + } + + const hostname = values.get("hostname")?.trim() || alias; + const username = values.get("user")?.trim() || null; + const rawPort = values.get("port")?.trim() ?? ""; + const parsedPort = Number.parseInt(rawPort, 10); + + return { + alias, + hostname, + username, + port: Number.isInteger(parsedPort) ? parsedPort : null, + }; +} + +export function targetConnectionKey(target: DesktopSshEnvironmentTarget): string { + return `${target.alias}\u0000${target.hostname}\u0000${target.username ?? ""}\u0000${target.port ?? ""}`; +} + +export function remoteStateKey(target: DesktopSshEnvironmentTarget): string { + return Crypto.createHash("sha256").update(targetConnectionKey(target)).digest("hex").slice(0, 16); +} + +export function buildSshHostSpec(target: DesktopSshEnvironmentTarget): string { + const destination = target.alias.trim() || target.hostname.trim(); + if (destination.length === 0) { + throw new Error("SSH target is missing its alias/hostname."); + } + return target.username ? `${target.username}@${destination}` : destination; +} + +export function baseSshArgs( + target: DesktopSshEnvironmentTarget, + input?: { readonly batchMode?: "yes" | "no" }, +): string[] { + return [ + "-o", + `BatchMode=${input?.batchMode ?? "no"}`, + "-o", + "ConnectTimeout=10", + ...(target.port !== null ? ["-p", String(target.port)] : []), + ]; +} + +export function normalizeSshErrorMessage(stderr: string, fallbackMessage: string): string { + const cleaned = stderr.trim(); + return cleaned.length > 0 ? cleaned : fallbackMessage; +} + +export function isSshAuthFailure(error: unknown): boolean { + const message = error instanceof Error ? error.message : String(error); + const normalized = message.toLowerCase(); + return ( + /permission denied \((?:publickey|password|keyboard-interactive|hostbased|gssapi-with-mic)[^)]*\)/u.test( + normalized, + ) || + /authentication failed/u.test(normalized) || + /too many authentication failures/u.test(normalized) + ); +} + +export function getLastNonEmptyOutputLine(stdout: string): string | null { + return ( + stdout + .trim() + .split(/\r?\n/u) + .map((entry) => entry.trim()) + .findLast((entry) => entry.length > 0) ?? null + ); +} + +export function resolveRemoteT3CliPackageSpec(input: { + readonly appVersion: string; + readonly updateChannel: DesktopUpdateChannel; + readonly isDevelopment?: boolean; +}): string { + const appVersion = input.appVersion.trim(); + if (!input.isDevelopment && PUBLISHABLE_T3_VERSION_PATTERN.test(appVersion)) { + return `t3@${appVersion}`; + } + + if (input.isDevelopment) { + return "t3@nightly"; + } + + return input.updateChannel === "nightly" ? "t3@nightly" : "t3@latest"; +} + +export const discoverSshHosts = (input?: { + readonly homeDir?: string; +}): Effect.Effect => + Effect.try({ + try: () => { + const homeDir = input?.homeDir ?? OS.homedir(); + const sshDirectory = Path.join(homeDir, ".ssh"); + const configAliases = collectSshConfigAliasesFromFile( + Path.join(sshDirectory, "config"), + new Set(), + homeDir, + ); + const knownHosts = readKnownHostsHostnames(Path.join(sshDirectory, "known_hosts")); + const discovered = new Map(); + + for (const alias of configAliases) { + discovered.set(alias, { + alias, + hostname: alias, + username: null, + port: null, + source: "ssh-config", + }); + } + + for (const hostname of knownHosts) { + if (discovered.has(hostname)) { + 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), + ); + }, + catch: (cause) => + new SshHostDiscoveryError({ + message: "Failed to discover SSH hosts.", + cause, + }), + }); diff --git a/packages/ssh/tsconfig.json b/packages/ssh/tsconfig.json new file mode 100644 index 0000000000..2f8e6d4df6 --- /dev/null +++ b/packages/ssh/tsconfig.json @@ -0,0 +1,17 @@ +{ + "extends": "../../tsconfig.base.json", + "compilerOptions": { + "plugins": [ + { + "name": "@effect/language-service", + "diagnosticSeverity": { + "importFromBarrel": "error", + "anyUnknownInErrorContext": "warning", + "instanceOfSchema": "warning", + "deterministicKeys": "warning" + } + } + ] + }, + "include": ["src"] +} diff --git a/scripts/release-smoke.ts b/scripts/release-smoke.ts index 8260edde7f..27308134f1 100644 --- a/scripts/release-smoke.ts +++ b/scripts/release-smoke.ts @@ -24,6 +24,7 @@ const workspaceFiles = [ "packages/client-runtime/package.json", "packages/contracts/package.json", "packages/shared/package.json", + "packages/ssh/package.json", "packages/tailscale/package.json", "packages/effect-acp/package.json", "packages/effect-codex-app-server/package.json",