Open History to see the last commit
1import type { DesktopSshEnvironmentTarget } from "@t3tools/contracts";
2import * as HostProcess from "@t3tools/shared/HostProcess";
3import * as Digest from "effect/crypto/Digest";
4import * as Duration from "effect/Duration";
5import * as Effect from "effect/Effect";
6import * as Hex from "effect/encoding/Hex";
7import * as FileSystem from "effect/FileSystem";
8import * as Option from "effect/Option";
9import * as Path from "effect/Path";
10import * as Scope from "effect/Scope";
11import * as Stream from "effect/Stream";
12import { ChildProcess, ChildProcessSpawner } from "effect/process";
13
14import { buildSshChildEnvironment, type SshAuthOptions } from "./auth.ts";
15import { SshCommandError, SshInvalidTargetError } from "./errors.ts";
16
17const DEFAULT_SSH_COMMAND_TIMEOUT_MS = 60_000;
18const MAX_SSH_ERROR_OUTPUT_LENGTH = 4_000;
19
20/**
21 * ssh is a real executable everywhere (`ssh.exe` on Windows), so it is always
22 * spawned directly — cmd.exe shell mode would re-tokenize arguments such as
23 * identity-file paths containing spaces.
24 */
25const sshCommandForPlatform = (platform: NodeJS.Platform): string =>
26 platform === "win32" ? "ssh.exe" : "ssh";
27
28export const resolveSshCommand = Effect.map(HostProcess.Platform, sshCommandForPlatform);
29
30const encoder = new TextEncoder();
31
32export interface SshCommandResult {
33 readonly stdout: string;
34 readonly stderr: string;
35}
36
37export interface RunSshCommandOptions extends SshAuthOptions {
38 readonly preHostArgs?: ReadonlyArray<string>;
39 readonly remoteCommandArgs?: ReadonlyArray<string>;
40 readonly stdin?: string;
41 readonly timeoutMs?: number;
42 /** Keep the end of long failed-command stdout, where the final cause usually is. */
43 readonly keepErrorOutputTail?: boolean;
44}
45
46export function parseSshResolveOutput(alias: string, stdout: string): DesktopSshEnvironmentTarget {
47 const values = new Map<string, string>();
48 for (const line of stdout.split(/\r?\n/u)) {
49 const trimmed = line.trim();
50 if (trimmed.length === 0) {
51 continue;
52 }
53 const [key, ...rest] = trimmed.split(/\s+/u);
54 if (!key || rest.length === 0 || values.has(key)) {
55 continue;
56 }
57 values.set(key, rest.join(" ").trim());
58 }
59
60 const hostname = values.get("hostname")?.trim() || alias;
61 const username = values.get("user")?.trim() || null;
62 const rawPort = values.get("port")?.trim() ?? "";
63 const parsedPort = Number.parseInt(rawPort, 10);
64
65 return {
66 alias,
67 hostname,
68 username,
69 port: Number.isInteger(parsedPort) ? parsedPort : null,
70 };
71}
72
73export function targetConnectionKey(target: DesktopSshEnvironmentTarget): string {
74 return `${target.alias}\u0000${target.hostname}\u0000${target.username ?? ""}\u0000${target.port ?? ""}`;
75}
76
77export const remoteStateKey = Effect.fn("ssh/command.remoteStateKey")(function* (
78 target: DesktopSshEnvironmentTarget,
79): Effect.fn.Return<string, never, Digest.Digest> {
80 const digestService = yield* Digest.Digest;
81 const digest = yield* digestService.digest(
82 Digest.sha256,
83 encoder.encode(targetConnectionKey(target)),
84 );
85 return Hex.encode(digest).slice(0, 16);
86});
87
88function buildSshHostSpec(target: DesktopSshEnvironmentTarget): string {
89 const destination = target.alias.trim() || target.hostname.trim();
90 if (destination.length === 0) {
91 throw new Error("SSH target is missing its alias/hostname.");
92 }
93 return target.username ? `${target.username}@${destination}` : destination;
94}
95
96export const buildSshHostSpecEffect = (
97 target: DesktopSshEnvironmentTarget,
98): Effect.Effect<string, SshInvalidTargetError> =>
99 Effect.try({
100 try: () => buildSshHostSpec(target),
101 catch: (cause) =>
102 new SshInvalidTargetError({
103 message: cause instanceof Error ? cause.message : "SSH target is invalid.",
104 }),
105 });
106
107export function baseSshArgs(
108 target: DesktopSshEnvironmentTarget,
109 input?: { readonly batchMode?: "yes" | "no" },
110): string[] {
111 return [
112 "-o",
113 `BatchMode=${input?.batchMode ?? "no"}`,
114 "-o",
115 "ConnectTimeout=10",
116 ...(target.port !== null ? ["-p", String(target.port)] : []),
117 ];
118}
119
120export function getLastNonEmptyOutputLine(stdout: string): string | null {
121 return (
122 stdout
123 .trim()
124 .split(/\r?\n/u)
125 .map((entry) => entry.trim())
126 .findLast((entry) => entry.length > 0) ?? null
127 );
128}
129
130const collectProcessOutput = <E>(stream: Stream.Stream<Uint8Array, E>): Effect.Effect<string, E> =>
131 stream.pipe(
132 Stream.decodeText(),
133 Stream.runFold(
134 () => "",
135 (acc, chunk) => acc + chunk,
136 ),
137 );
138
139function redactSshErrorOutput(output: string, keepTail = false): string {
140 const redacted = output.replace(
141 /("(?:access_token|bearerToken|credential|pairingToken|token)"\s*:\s*")[^"]+(")/giu,
142 "$1[redacted]$2",
143 );
144 if (redacted.length <= MAX_SSH_ERROR_OUTPUT_LENGTH) return redacted;
145 return keepTail
146 ? `[truncated]\n${redacted.slice(-MAX_SSH_ERROR_OUTPUT_LENGTH)}`
147 : `${redacted.slice(0, MAX_SSH_ERROR_OUTPUT_LENGTH)}\n[truncated]`;
148}
149
150export function shellSingleQuote(value: string): string {
151 return `'${value.replaceAll("'", "'\\''")}'`;
152}
153
154const SAFE_SHELL_ARG = /^[\w@%+=:,./-]+$/u;
155
156// cmd.exe and PowerShell both read double quotes, but not POSIX single quotes.
157function terminalArg(value: string, platform: NodeJS.Platform): string {
158 if (SAFE_SHELL_ARG.test(value)) return value;
159 return platform === "win32" ? `"${value}"` : shellSingleQuote(value);
160}
161
162// ssh prints this for unknown and changed host keys when it cannot ask. The app
163// never answers host key prompts, so the user checks the fingerprint in a terminal.
164function hostKeyVerificationMessage(input: {
165 readonly target: DesktopSshEnvironmentTarget;
166 readonly hostSpec: string;
167 readonly stderr: string;
168 readonly platform: NodeJS.Platform;
169}): string | null {
170 const { target, hostSpec, stderr, platform } = input;
171 if (!stderr.includes("Host key verification failed")) return null;
172 const command = [
173 "ssh",
174 ...(target.port !== null ? ["-p", String(target.port)] : []),
175 ...(hostSpec.startsWith("-") ? ["--"] : []),
176 hostSpec,
177 ]
178 .map((arg) => terminalArg(arg, platform))
179 .join(" ");
180 const guidance = stderr.includes("REMOTE HOST IDENTIFICATION HAS CHANGED")
181 ? `The host key for ${hostSpec} has changed since it was trusted. Only if you expect this change, remove the old key with the \`ssh-keygen -R\` command in the output below, run \`${command}\` in a terminal, check that the new host key fingerprint is the one you expect, then try again.`
182 : `SSH could not verify the host key for ${hostSpec}. Run \`${command}\` in a terminal, check that the host key fingerprint is the one you expect, then try again.`;
183 return `${guidance}\n\n${stderr.trim()}`;
184}
185
186function normalizeSshErrorMessage(input: {
187 readonly stdout?: string;
188 readonly stderr: string;
189 readonly fallbackMessage: string;
190}): string {
191 const cleanedStderr = input.stderr.trim();
192 if (cleanedStderr.length > 0) {
193 return cleanedStderr;
194 }
195
196 const cleanedStdout = input.stdout?.trim() ?? "";
197 return cleanedStdout.length > 0 ? cleanedStdout : input.fallbackMessage;
198}
199
200export function sshTargetLogFields(target: DesktopSshEnvironmentTarget) {
201 return {
202 alias: target.alias,
203 hostname: target.hostname,
204 username: target.username,
205 port: target.port,
206 };
207}
208
209function stdinStream(input: string | undefined) {
210 return input === undefined ? Stream.empty : Stream.make(encoder.encode(input));
211}
212
213const runSshCommandInScope = Effect.fn("ssh/command.runSshCommand.inScope")(function* (
214 target: DesktopSshEnvironmentTarget,
215 input: RunSshCommandOptions,
216 commandScope: Scope.Scope,
217): Effect.fn.Return<
218 SshCommandResult,
219 SshCommandError | SshInvalidTargetError,
220 ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem | Path.Path
221> {
222 const hostSpec = yield* buildSshHostSpecEffect(target);
223 const environment = yield* buildSshChildEnvironment({
224 ...(input.interactiveAuth === undefined ? {} : { interactiveAuth: input.interactiveAuth }),
225 ...(input.authSecret === undefined ? {} : { authSecret: input.authSecret }),
226 }).pipe(
227 Effect.mapError(
228 (cause) =>
229 new SshCommandError({
230 command: ["ssh"],
231 exitCode: null,
232 stderr: "",
233 message: "Failed to prepare SSH authentication helpers.",
234 cause,
235 }),
236 ),
237 );
238 const args = [
239 ...baseSshArgs(target, {
240 batchMode: input.batchMode ?? (input.interactiveAuth ? "no" : "yes"),
241 }),
242 // Cold installs need a long command budget; a lost connection must fail sooner.
243 "-o",
244 "ServerAliveInterval=15",
245 "-o",
246 "ServerAliveCountMax=3",
247 ...(input.preHostArgs ?? []),
248 "--",
249 hostSpec,
250 ...(input.remoteCommandArgs ?? []),
251 ];
252 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
253 const sshCommand = yield* resolveSshCommand;
254 yield* Effect.logDebug("ssh.command.start", {
255 ...sshTargetLogFields(target),
256 command: [sshCommand, ...args],
257 hasStdin: input.stdin !== undefined,
258 timeoutMs: input.timeoutMs ?? DEFAULT_SSH_COMMAND_TIMEOUT_MS,
259 });
260 const child = yield* spawner
261 .spawn(
262 ChildProcess.make(sshCommand, args, {
263 env: environment,
264 extendEnv: true,
265 stdin: {
266 stream: stdinStream(input.stdin),
267 endOnDone: true,
268 },
269 }),
270 )
271 .pipe(
272 Effect.provideService(Scope.Scope, commandScope),
273 Effect.mapError(
274 (cause) =>
275 new SshCommandError({
276 command: [sshCommand, ...args],
277 exitCode: null,
278 stderr: "",
279 message:
280 cause instanceof Error
281 ? cause.message
282 : `Failed to spawn SSH command for ${hostSpec}.`,
283 cause,
284 }),
285 ),
286 );
287
288 const [stdout, stderr, exitCode] = yield* Effect.all(
289 [
290 collectProcessOutput(child.stdout),
291 collectProcessOutput(child.stderr),
292 child.exitCode.pipe(Effect.map(Number)),
293 ],
294 { concurrency: "unbounded" },
295 ).pipe(
296 Effect.mapError(
297 (cause) =>
298 new SshCommandError({
299 command: ["ssh", ...args],
300 exitCode: null,
301 stderr: "",
302 message:
303 cause instanceof Error ? cause.message : `Failed to run SSH command for ${hostSpec}.`,
304 cause,
305 }),
306 ),
307 );
308
309 if (exitCode !== 0) {
310 const diagnosticStdout = redactSshErrorOutput(stdout, input.keepErrorOutputTail);
311 yield* Effect.logWarning("ssh.command.failed", {
312 ...sshTargetLogFields(target),
313 command: ["ssh", ...args],
314 exitCode,
315 stdout: diagnosticStdout,
316 stderr,
317 });
318 return yield* new SshCommandError({
319 command: ["ssh", ...args],
320 exitCode,
321 stdout: diagnosticStdout,
322 stderr,
323 message:
324 hostKeyVerificationMessage({
325 target,
326 hostSpec,
327 stderr,
328 platform: yield* HostProcess.Platform,
329 }) ??
330 normalizeSshErrorMessage({
331 stdout: diagnosticStdout,
332 stderr,
333 fallbackMessage: `SSH command failed for ${hostSpec} (exit ${exitCode}).`,
334 }),
335 });
336 }
337
338 yield* Effect.logDebug("ssh.command.succeeded", {
339 ...sshTargetLogFields(target),
340 command: ["ssh", ...args],
341 });
342 return { stdout, stderr };
343});
344
345export const runSshCommand = Effect.fn("ssh/command.runSshCommand")(function* (
346 target: DesktopSshEnvironmentTarget,
347 input: RunSshCommandOptions = {},
348): Effect.fn.Return<
349 SshCommandResult,
350 SshCommandError | SshInvalidTargetError,
351 ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem | Path.Path
352> {
353 return yield* Effect.scopedWith((commandScope) =>
354 runSshCommandInScope(target, input, commandScope),
355 ).pipe(
356 Effect.timeoutOption(Duration.millis(input.timeoutMs ?? DEFAULT_SSH_COMMAND_TIMEOUT_MS)),
357 Effect.flatMap((result) =>
358 Option.match(result, {
359 onSome: Effect.succeed,
360 // The enclosing operation owns the span for this inline handler.
361 onNone: Effect.fnUntraced(function* () {
362 yield* Effect.logWarning("ssh.command.timedOut", {
363 ...sshTargetLogFields(target),
364 timeoutMs: input.timeoutMs ?? DEFAULT_SSH_COMMAND_TIMEOUT_MS,
365 remoteCommandArgs: input.remoteCommandArgs ?? [],
366 preHostArgs: input.preHostArgs ?? [],
367 hasStdin: input.stdin !== undefined,
368 });
369 return yield* new SshCommandError({
370 command: ["ssh"],
371 exitCode: null,
372 stderr: "",
373 message: `SSH command timed out after ${input.timeoutMs ?? DEFAULT_SSH_COMMAND_TIMEOUT_MS}ms.`,
374 });
375 }),
376 }),
377 ),
378 );
379});
380
381export const resolveSshTarget = Effect.fn("ssh/command.resolveSshTarget")(function* (
382 alias: string,
383): Effect.fn.Return<
384 DesktopSshEnvironmentTarget,
385 SshCommandError | SshInvalidTargetError,
386 ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem | Path.Path
387> {
388 const trimmedAlias = alias.trim();
389 if (trimmedAlias.length === 0) {
390 return yield* new SshInvalidTargetError({ message: "SSH host alias is required." });
391 }
392
393 yield* Effect.logDebug("ssh.target.resolve.start", { alias: trimmedAlias });
394 return yield* runSshCommand(
395 {
396 alias: trimmedAlias,
397 hostname: trimmedAlias,
398 username: null,
399 port: null,
400 },
401 { preHostArgs: ["-G"] },
402 ).pipe(
403 Effect.map((result) => parseSshResolveOutput(trimmedAlias, result.stdout)),
404 Effect.tap((target) =>
405 Effect.logDebug("ssh.target.resolve.succeeded", sshTargetLogFields(target)),
406 ),
407 Effect.catch((cause) =>
408 Effect.logDebug("ssh.target.resolve.fallback", { alias: trimmedAlias, cause }).pipe(
409 Effect.as({
410 alias: trimmedAlias,
411 hostname: trimmedAlias,
412 username: null,
413 port: null,
414 }),
415 ),
416 ),
417 );
418});