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 // T3 always supplies its own remote command or only forwards ports, so a host
117 // alias's RemoteCommand or RequestTTY must not hijack the session.
118 "-o",
119 "RemoteCommand=none",
120 "-o",
121 "RequestTTY=no",
122 ...(target.port !== null ? ["-p", String(target.port)] : []),
123 ];
124}
125
126export function getLastNonEmptyOutputLine(stdout: string): string | null {
127 return (
128 stdout
129 .trim()
130 .split(/\r?\n/u)
131 .map((entry) => entry.trim())
132 .findLast((entry) => entry.length > 0) ?? null
133 );
134}
135
136interface SshCommandOutput {
137 stdout: string;
138 stderr: string;
139}
140
141// Appends as chunks arrive so a timeout can still report what was printed.
142const collectProcessOutput = <E>(
143 stream: Stream.Stream<Uint8Array, E>,
144 output: SshCommandOutput,
145 key: keyof SshCommandOutput,
146): Effect.Effect<void, E> =>
147 stream.pipe(
148 Stream.decodeText(),
149 Stream.runForEach((chunk) =>
150 Effect.sync(() => {
151 output[key] += chunk;
152 }),
153 ),
154 );
155
156function redactSshErrorOutput(output: string, keepTail = false): string {
157 const redacted = output.replace(
158 /("(?:access_token|bearerToken|credential|pairingToken|token)"\s*:\s*")[^"]+(")/giu,
159 "$1[redacted]$2",
160 );
161 if (redacted.length <= MAX_SSH_ERROR_OUTPUT_LENGTH) return redacted;
162 return keepTail
163 ? `[truncated]\n${redacted.slice(-MAX_SSH_ERROR_OUTPUT_LENGTH)}`
164 : `${redacted.slice(0, MAX_SSH_ERROR_OUTPUT_LENGTH)}\n[truncated]`;
165}
166
167export function shellSingleQuote(value: string): string {
168 return `'${value.replaceAll("'", "'\\''")}'`;
169}
170
171const SAFE_SHELL_ARG = /^[\w@%+=:,./-]+$/u;
172
173// cmd.exe and PowerShell both read double quotes, but not POSIX single quotes.
174function terminalArg(value: string, platform: NodeJS.Platform): string {
175 if (SAFE_SHELL_ARG.test(value)) return value;
176 return platform === "win32" ? `"${value}"` : shellSingleQuote(value);
177}
178
179// ssh prints this for unknown and changed host keys when it cannot ask. The app
180// never answers host key prompts, so the user checks the fingerprint in a terminal.
181function hostKeyVerificationMessage(input: {
182 readonly target: DesktopSshEnvironmentTarget;
183 readonly hostSpec: string;
184 readonly stderr: string;
185 readonly platform: NodeJS.Platform;
186}): string | null {
187 const { target, hostSpec, stderr, platform } = input;
188 if (!stderr.includes("Host key verification failed")) return null;
189 const command = [
190 "ssh",
191 ...(target.port !== null ? ["-p", String(target.port)] : []),
192 ...(hostSpec.startsWith("-") ? ["--"] : []),
193 hostSpec,
194 ]
195 .map((arg) => terminalArg(arg, platform))
196 .join(" ");
197 const guidance = stderr.includes("REMOTE HOST IDENTIFICATION HAS CHANGED")
198 ? `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.`
199 : `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.`;
200 return `${guidance}\n\n${stderr.trim()}`;
201}
202
203function normalizeSshErrorMessage(input: {
204 readonly stdout?: string;
205 readonly stderr: string;
206 readonly fallbackMessage: string;
207}): string {
208 const cleanedStderr = input.stderr.trim();
209 if (cleanedStderr.length > 0) {
210 return cleanedStderr;
211 }
212
213 const cleanedStdout = input.stdout?.trim() ?? "";
214 return cleanedStdout.length > 0 ? cleanedStdout : input.fallbackMessage;
215}
216
217export function sshTargetLogFields(target: DesktopSshEnvironmentTarget) {
218 return {
219 alias: target.alias,
220 hostname: target.hostname,
221 username: target.username,
222 port: target.port,
223 };
224}
225
226function stdinStream(input: string | undefined) {
227 return input === undefined ? Stream.empty : Stream.make(encoder.encode(input));
228}
229
230const runSshCommandInScope = Effect.fn("ssh/command.runSshCommand.inScope")(function* (
231 target: DesktopSshEnvironmentTarget,
232 input: RunSshCommandOptions,
233 commandScope: Scope.Scope,
234 output: SshCommandOutput,
235): Effect.fn.Return<
236 SshCommandResult,
237 SshCommandError | SshInvalidTargetError,
238 ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem | Path.Path
239> {
240 const hostSpec = yield* buildSshHostSpecEffect(target);
241 const environment = yield* buildSshChildEnvironment({
242 ...(input.interactiveAuth === undefined ? {} : { interactiveAuth: input.interactiveAuth }),
243 ...(input.authSecret === undefined ? {} : { authSecret: input.authSecret }),
244 }).pipe(
245 Effect.mapError(
246 (cause) =>
247 new SshCommandError({
248 command: ["ssh"],
249 exitCode: null,
250 stderr: "",
251 message: "Failed to prepare SSH authentication helpers.",
252 cause,
253 }),
254 ),
255 );
256 const args = [
257 ...baseSshArgs(target, {
258 batchMode: input.batchMode ?? (input.interactiveAuth ? "no" : "yes"),
259 }),
260 // Cold installs need a long command budget; a lost connection must fail sooner.
261 "-o",
262 "ServerAliveInterval=15",
263 "-o",
264 "ServerAliveCountMax=3",
265 ...(input.preHostArgs ?? []),
266 "--",
267 hostSpec,
268 ...(input.remoteCommandArgs ?? []),
269 ];
270 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
271 const sshCommand = yield* resolveSshCommand;
272 yield* Effect.logDebug("ssh.command.start", {
273 ...sshTargetLogFields(target),
274 command: [sshCommand, ...args],
275 hasStdin: input.stdin !== undefined,
276 timeoutMs: input.timeoutMs ?? DEFAULT_SSH_COMMAND_TIMEOUT_MS,
277 });
278 const child = yield* spawner
279 .spawn(
280 ChildProcess.make(sshCommand, args, {
281 env: environment,
282 extendEnv: true,
283 forceKillAfter: "1 second",
284 stdin: {
285 stream: stdinStream(input.stdin),
286 endOnDone: true,
287 },
288 }),
289 )
290 .pipe(
291 Effect.provideService(Scope.Scope, commandScope),
292 Effect.mapError(
293 (cause) =>
294 new SshCommandError({
295 command: [sshCommand, ...args],
296 exitCode: null,
297 stderr: "",
298 message:
299 cause instanceof Error
300 ? cause.message
301 : `Failed to spawn SSH command for ${hostSpec}.`,
302 cause,
303 }),
304 ),
305 );
306
307 const [, , exitCode] = yield* Effect.all(
308 [
309 collectProcessOutput(child.stdout, output, "stdout"),
310 collectProcessOutput(child.stderr, output, "stderr"),
311 child.exitCode.pipe(Effect.map(Number)),
312 ],
313 { concurrency: "unbounded" },
314 ).pipe(
315 Effect.mapError(
316 (cause) =>
317 new SshCommandError({
318 command: ["ssh", ...args],
319 exitCode: null,
320 stderr: "",
321 message:
322 cause instanceof Error ? cause.message : `Failed to run SSH command for ${hostSpec}.`,
323 cause,
324 }),
325 ),
326 );
327
328 const { stdout, stderr } = output;
329 if (exitCode !== 0) {
330 const diagnosticStdout = redactSshErrorOutput(stdout, input.keepErrorOutputTail);
331 yield* Effect.logWarning("ssh.command.failed", {
332 ...sshTargetLogFields(target),
333 command: ["ssh", ...args],
334 exitCode,
335 stdout: diagnosticStdout,
336 stderr,
337 });
338 return yield* new SshCommandError({
339 command: ["ssh", ...args],
340 exitCode,
341 stdout: diagnosticStdout,
342 stderr,
343 message:
344 hostKeyVerificationMessage({
345 target,
346 hostSpec,
347 stderr,
348 platform: yield* HostProcess.Platform,
349 }) ??
350 normalizeSshErrorMessage({
351 stdout: diagnosticStdout,
352 stderr,
353 fallbackMessage: `SSH command failed for ${hostSpec} (exit ${exitCode}).`,
354 }),
355 });
356 }
357
358 yield* Effect.logDebug("ssh.command.succeeded", {
359 ...sshTargetLogFields(target),
360 command: ["ssh", ...args],
361 });
362 return { stdout, stderr };
363});
364
365export const runSshCommand = Effect.fn("ssh/command.runSshCommand")(function* (
366 target: DesktopSshEnvironmentTarget,
367 input: RunSshCommandOptions = {},
368): Effect.fn.Return<
369 SshCommandResult,
370 SshCommandError | SshInvalidTargetError,
371 ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem | Path.Path
372> {
373 const output: SshCommandOutput = { stdout: "", stderr: "" };
374 return yield* Effect.scopedWith((commandScope) =>
375 runSshCommandInScope(target, input, commandScope, output),
376 ).pipe(
377 Effect.timeoutOption(Duration.millis(input.timeoutMs ?? DEFAULT_SSH_COMMAND_TIMEOUT_MS)),
378 Effect.flatMap((result) =>
379 Option.match(result, {
380 onSome: Effect.succeed,
381 // The enclosing operation owns the span for this inline handler.
382 onNone: Effect.fnUntraced(function* () {
383 const diagnosticStdout = redactSshErrorOutput(output.stdout, input.keepErrorOutputTail);
384 const { stderr } = output;
385 yield* Effect.logWarning("ssh.command.timedOut", {
386 ...sshTargetLogFields(target),
387 timeoutMs: input.timeoutMs ?? DEFAULT_SSH_COMMAND_TIMEOUT_MS,
388 remoteCommandArgs: input.remoteCommandArgs ?? [],
389 preHostArgs: input.preHostArgs ?? [],
390 hasStdin: input.stdin !== undefined,
391 stdout: diagnosticStdout,
392 stderr,
393 });
394 return yield* new SshCommandError({
395 command: ["ssh"],
396 exitCode: null,
397 stdout: diagnosticStdout,
398 stderr,
399 message: `SSH command timed out after ${input.timeoutMs ?? DEFAULT_SSH_COMMAND_TIMEOUT_MS}ms.`,
400 });
401 }),
402 }),
403 ),
404 );
405});
406
407export const resolveSshTarget = Effect.fn("ssh/command.resolveSshTarget")(function* (
408 alias: string,
409): Effect.fn.Return<
410 DesktopSshEnvironmentTarget,
411 SshCommandError | SshInvalidTargetError,
412 ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem | Path.Path
413> {
414 const trimmedAlias = alias.trim();
415 if (trimmedAlias.length === 0) {
416 return yield* new SshInvalidTargetError({ message: "SSH host alias is required." });
417 }
418
419 yield* Effect.logDebug("ssh.target.resolve.start", { alias: trimmedAlias });
420 return yield* runSshCommand(
421 {
422 alias: trimmedAlias,
423 hostname: trimmedAlias,
424 username: null,
425 port: null,
426 },
427 { preHostArgs: ["-G"] },
428 ).pipe(
429 Effect.map((result) => parseSshResolveOutput(trimmedAlias, result.stdout)),
430 Effect.tap((target) =>
431 Effect.logDebug("ssh.target.resolve.succeeded", sshTargetLogFields(target)),
432 ),
433 Effect.catch((cause) =>
434 Effect.logDebug("ssh.target.resolve.fallback", { alias: trimmedAlias, cause }).pipe(
435 Effect.as({
436 alias: trimmedAlias,
437 hostname: trimmedAlias,
438 username: null,
439 port: null,
440 }),
441 ),
442 ),
443 );
444});