Split SSH helpers into dedicated modules

- Add auth, command, config, and tunnel exports
- Update desktop SSH environment imports
- Add tests for auth and command helpers
This commit is contained in:
Julius Marminge committed 2026-04-28 11:54:58 -07:00
1 parent 20edab789d
commit e4b6dd4efa
11 files changed
+273 -246

No files matched your search

+12 -20
View File
@@ -15,27 +15,28 @@ import type {
DesktopSshPasswordPromptRequest,
ExecutionEnvironmentDescriptor,
} from "@t3tools/contracts";
import { isSshAuthFailure, type SshPasswordRequest } from "@t3tools/ssh/auth";
import {
DEFAULT_REMOTE_PORT,
baseSshArgs,
buildSshHostSpec,
collectSshConfigAliasesFromFile,
discoverSshHosts,
getLastNonEmptyOutputLine,
isSshAuthFailure,
normalizeSshErrorMessage,
parseKnownHostsHostnames,
parseSshResolveOutput,
remoteStateKey,
resolveRemoteT3CliPackageSpec,
resolveSshConfigIncludePattern,
targetConnectionKey,
} from "@t3tools/ssh";
} from "@t3tools/ssh/command";
import {
collectSshConfigAliasesFromFile,
discoverSshHosts,
parseKnownHostsHostnames,
resolveSshConfigIncludePattern,
} from "@t3tools/ssh/config";
import { DEFAULT_REMOTE_PORT, normalizeSshErrorMessage } from "@t3tools/ssh/tunnel";
import { Effect } from "effect";
import { waitForHttpReady } from "./backendReadiness.ts";
export { resolveRemoteT3CliPackageSpec };
export { resolveRemoteT3CliPackageSpec } from "@t3tools/ssh/command";
const REMOTE_PORT_SCAN_WINDOW = 200;
const SSH_ASKPASS_DIR_NAME = "t3code-ssh-askpass";
@@ -84,15 +85,8 @@ interface SshAuthOptions {
readonly interactiveAuth?: boolean;
}
interface DesktopSshPasswordRequest {
readonly destination: string;
readonly username: string | null;
readonly prompt: string;
readonly attempt: number;
}
interface DesktopSshEnvironmentManagerOptions {
readonly passwordProvider?: (request: DesktopSshPasswordRequest) => Promise<string | null>;
readonly passwordProvider?: (request: SshPasswordRequest) => Promise<string | null>;
readonly resolveCliPackageSpec?: () => string;
}
@@ -1042,9 +1036,7 @@ export class DesktopSshEnvironmentBridge {
await this.manager.dispose();
}
private async requestPasswordFromRenderer(
input: DesktopSshPasswordRequest,
): Promise<string | null> {
private async requestPasswordFromRenderer(input: SshPasswordRequest): Promise<string | null> {
const window = this.options.getMainWindow();
if (!window || window.isDestroyed()) {
throw new Error("T3 Code window is not available for SSH authentication.");
+19 -3
View File
@@ -4,9 +4,25 @@
"private": true,
"type": "module",
"exports": {
".": {
"types": "./src/index.ts",
"import": "./src/index.ts"
"./auth": {
"types": "./src/auth.ts",
"import": "./src/auth.ts"
},
"./command": {
"types": "./src/command.ts",
"import": "./src/command.ts"
},
"./config": {
"types": "./src/config.ts",
"import": "./src/config.ts"
},
"./errors": {
"types": "./src/errors.ts",
"import": "./src/errors.ts"
},
"./tunnel": {
"types": "./src/tunnel.ts",
"import": "./src/tunnel.ts"
}
},
"scripts": {
+22
View File
@@ -0,0 +1,22 @@
import { assert, describe, it } from "@effect/vitest";
import { Effect } from "effect";
import { isSshAuthFailure } from "./auth.ts";
describe("ssh auth", () => {
it.effect("detects ssh auth failures from common permission denied messages", () =>
Effect.sync(() => {
assert.equal(
isSshAuthFailure(
new Error(
"[email protected]: 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);
}),
);
});
+18
View File
@@ -0,0 +1,18 @@
export interface SshPasswordRequest {
readonly destination: string;
readonly username: string | null;
readonly prompt: string;
readonly attempt: number;
}
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)
);
}
+91
View File
@@ -0,0 +1,91 @@
import { assert, describe, it } from "@effect/vitest";
import { Effect } from "effect";
import {
baseSshArgs,
getLastNonEmptyOutputLine,
parseSshResolveOutput,
resolveRemoteT3CliPackageSpec,
} from "./command.ts";
describe("ssh command", () => {
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",
}),
"[email protected]",
);
assert.equal(
resolveRemoteT3CliPackageSpec({
appVersion: "0.0.17-nightly.20260415.44",
updateChannel: "nightly",
}),
"[email protected]",
);
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"}',
);
}),
);
});
+88
View File
@@ -0,0 +1,88 @@
import * as Crypto from "node:crypto";
import type { DesktopSshEnvironmentTarget, DesktopUpdateChannel } from "@t3tools/contracts";
const PUBLISHABLE_T3_VERSION_PATTERN = /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/u;
export function parseSshResolveOutput(alias: string, stdout: string): DesktopSshEnvironmentTarget {
const values = new Map<string, string>();
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 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";
}
@@ -6,25 +6,16 @@ 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[] = [];
} from "./config.ts";
function makeTempHomeDir(): string {
const directory = FS.mkdtempSync(Path.join(OS.tmpdir(), "t3-ssh-test-"));
tempDirectories.push(directory);
return directory;
return FS.mkdtempSync(Path.join(OS.tmpdir(), "t3-ssh-test-"));
}
describe("ssh", () => {
describe("ssh config", () => {
it.effect("discovers ssh config hosts across included files", () =>
Effect.acquireUseRelease(
Effect.sync(makeTempHomeDir),
@@ -134,100 +125,4 @@ describe("ssh", () => {
);
}),
);
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",
}),
"[email protected]",
);
assert.equal(
resolveRemoteT3CliPackageSpec({
appVersion: "0.0.17-nightly.20260415.44",
updateChannel: "nightly",
}),
"[email protected]",
);
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(
"[email protected]: 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);
}),
);
});
@@ -1,25 +1,14 @@
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 type { DesktopDiscoveredSshHost } from "@t3tools/contracts";
import { Data, Effect } from "effect";
import { Effect } from "effect";
export const DEFAULT_REMOTE_PORT = 3773;
import { SshHostDiscoveryError } from "./errors.ts";
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("#");
@@ -185,106 +174,6 @@ function readKnownHostsHostnames(filePath: string): ReadonlyArray<string> {
return parseKnownHostsHostnames(FS.readFileSync(filePath, "utf8"));
}
export function parseSshResolveOutput(alias: string, stdout: string): DesktopSshEnvironmentTarget {
const values = new Map<string, string>();
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<readonly DesktopDiscoveredSshHost[], SshHostDiscoveryError> =>
+6
View File
@@ -0,0 +1,6 @@
import { Data } from "effect";
export class SshHostDiscoveryError extends Data.TaggedError("SshHostDiscoveryError")<{
readonly message: string;
readonly cause: unknown;
}> {}
+5 -1
View File
@@ -1 +1,5 @@
export * from "./ssh.ts";
export * from "./auth.ts";
export * from "./command.ts";
export * from "./config.ts";
export * from "./errors.ts";
export * from "./tunnel.ts";
+6
View File
@@ -0,0 +1,6 @@
export const DEFAULT_REMOTE_PORT = 3773;
export function normalizeSshErrorMessage(stderr: string, fallbackMessage: string): string {
const cleaned = stderr.trim();
return cleaned.length > 0 ? cleaned : fallbackMessage;
}