Open History to see the last commit
1import type { DesktopSshEnvironmentTarget } from "@t3tools/contracts";
2import * as HostProcess from "@t3tools/shared/HostProcess";
3import * as Crypto from "effect/Crypto";
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, Crypto.Crypto> {
80 const crypto = yield* Crypto.Crypto;
81 const digest = yield* crypto
82 .digest("SHA-256", encoder.encode(targetConnectionKey(target)))
83 .pipe(Effect.orDie);
84 return Hex.encode(digest).slice(0, 16);
85});
86
87function buildSshHostSpec(target: DesktopSshEnvironmentTarget): string {
88 const destination = target.alias.trim() || target.hostname.trim();
89 if (destination.length === 0) {
90 throw new Error("SSH target is missing its alias/hostname.");
91 }
92 return target.username ? `${target.username}@${destination}` : destination;
93}
94
95export const buildSshHostSpecEffect = (
96 target: DesktopSshEnvironmentTarget,
97): Effect.Effect<string, SshInvalidTargetError> =>
98 Effect.try({
99 try: () => buildSshHostSpec(target),
100 catch: (cause) =>
101 new SshInvalidTargetError({
102 message: cause instanceof Error ? cause.message : "SSH target is invalid.",
103 }),
104 });
105
106export function baseSshArgs(
107 target: DesktopSshEnvironmentTarget,
108 input?: { readonly batchMode?: "yes" | "no" },
109): string[] {
110 return [
111 "-o",
112 `BatchMode=${input?.batchMode ?? "no"}`,
113 "-o",
114 "ConnectTimeout=10",
115 ...(target.port !== null ? ["-p", String(target.port)] : []),
116 ];
117}
118
119export function getLastNonEmptyOutputLine(stdout: string): string | null {
120 return (
121 stdout
122 .trim()
123 .split(/\r?\n/u)
124 .map((entry) => entry.trim())
125 .findLast((entry) => entry.length > 0) ?? null
126 );
127}
128
129const collectProcessOutput = <E>(stream: Stream.Stream<Uint8Array, E>): Effect.Effect<string, E> =>
130 stream.pipe(
131 Stream.decodeText(),
132 Stream.runFold(
133 () => "",
134 (acc, chunk) => acc + chunk,
135 ),
136 );
137
138function redactSshErrorOutput(output: string, keepTail = false): string {
139 const redacted = output.replace(
140 /("(?:access_token|bearerToken|credential|pairingToken|token)"\s*:\s*")[^"]+(")/giu,
141 "$1[redacted]$2",
142 );
143 if (redacted.length <= MAX_SSH_ERROR_OUTPUT_LENGTH) return redacted;
144 return keepTail
145 ? `[truncated]\n${redacted.slice(-MAX_SSH_ERROR_OUTPUT_LENGTH)}`
146 : `${redacted.slice(0, MAX_SSH_ERROR_OUTPUT_LENGTH)}\n[truncated]`;
147}
148
149function normalizeSshErrorMessage(input: {
150 readonly stdout?: string;
151 readonly stderr: string;
152 readonly fallbackMessage: string;
153}): string {
154 const cleanedStderr = input.stderr.trim();
155 if (cleanedStderr.length > 0) {
156 return cleanedStderr;
157 }
158
159 const cleanedStdout = input.stdout?.trim() ?? "";
160 return cleanedStdout.length > 0 ? cleanedStdout : input.fallbackMessage;
161}
162
163export function sshTargetLogFields(target: DesktopSshEnvironmentTarget) {
164 return {
165 alias: target.alias,
166 hostname: target.hostname,
167 username: target.username,
168 port: target.port,
169 };
170}
171
172function stdinStream(input: string | undefined) {
173 return input === undefined ? Stream.empty : Stream.make(encoder.encode(input));
174}
175
176const runSshCommandInScope = Effect.fn("ssh/command.runSshCommand.inScope")(function* (
177 target: DesktopSshEnvironmentTarget,
178 input: RunSshCommandOptions,
179 commandScope: Scope.Scope,
180): Effect.fn.Return<
181 SshCommandResult,
182 SshCommandError | SshInvalidTargetError,
183 ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem | Path.Path
184> {
185 const hostSpec = yield* buildSshHostSpecEffect(target);
186 const environment = yield* buildSshChildEnvironment({
187 ...(input.interactiveAuth === undefined ? {} : { interactiveAuth: input.interactiveAuth }),
188 ...(input.authSecret === undefined ? {} : { authSecret: input.authSecret }),
189 }).pipe(
190 Effect.mapError(
191 (cause) =>
192 new SshCommandError({
193 command: ["ssh"],
194 exitCode: null,
195 stderr: "",
196 message: "Failed to prepare SSH authentication helpers.",
197 cause,
198 }),
199 ),
200 );
201 const args = [
202 ...baseSshArgs(target, {
203 batchMode: input.batchMode ?? (input.interactiveAuth ? "no" : "yes"),
204 }),
205 // Cold installs need a long command budget; a lost connection must fail sooner.
206 "-o",
207 "ServerAliveInterval=15",
208 "-o",
209 "ServerAliveCountMax=3",
210 ...(input.preHostArgs ?? []),
211 "--",
212 hostSpec,
213 ...(input.remoteCommandArgs ?? []),
214 ];
215 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
216 const sshCommand = yield* resolveSshCommand;
217 yield* Effect.logDebug("ssh.command.start", {
218 ...sshTargetLogFields(target),
219 command: [sshCommand, ...args],
220 hasStdin: input.stdin !== undefined,
221 timeoutMs: input.timeoutMs ?? DEFAULT_SSH_COMMAND_TIMEOUT_MS,
222 });
223 const child = yield* spawner
224 .spawn(
225 ChildProcess.make(sshCommand, args, {
226 env: environment,
227 extendEnv: true,
228 stdin: {
229 stream: stdinStream(input.stdin),
230 endOnDone: true,
231 },
232 }),
233 )
234 .pipe(
235 Effect.provideService(Scope.Scope, commandScope),
236 Effect.mapError(
237 (cause) =>
238 new SshCommandError({
239 command: [sshCommand, ...args],
240 exitCode: null,
241 stderr: "",
242 message:
243 cause instanceof Error
244 ? cause.message
245 : `Failed to spawn SSH command for ${hostSpec}.`,
246 cause,
247 }),
248 ),
249 );
250
251 const [stdout, stderr, exitCode] = yield* Effect.all(
252 [
253 collectProcessOutput(child.stdout),
254 collectProcessOutput(child.stderr),
255 child.exitCode.pipe(Effect.map(Number)),
256 ],
257 { concurrency: "unbounded" },
258 ).pipe(
259 Effect.mapError(
260 (cause) =>
261 new SshCommandError({
262 command: ["ssh", ...args],
263 exitCode: null,
264 stderr: "",
265 message:
266 cause instanceof Error ? cause.message : `Failed to run SSH command for ${hostSpec}.`,
267 cause,
268 }),
269 ),
270 );
271
272 if (exitCode !== 0) {
273 const diagnosticStdout = redactSshErrorOutput(stdout, input.keepErrorOutputTail);
274 yield* Effect.logWarning("ssh.command.failed", {
275 ...sshTargetLogFields(target),
276 command: ["ssh", ...args],
277 exitCode,
278 stdout: diagnosticStdout,
279 stderr,
280 });
281 return yield* new SshCommandError({
282 command: ["ssh", ...args],
283 exitCode,
284 stdout: diagnosticStdout,
285 stderr,
286 message: normalizeSshErrorMessage({
287 stdout: diagnosticStdout,
288 stderr,
289 fallbackMessage: `SSH command failed for ${hostSpec} (exit ${exitCode}).`,
290 }),
291 });
292 }
293
294 yield* Effect.logDebug("ssh.command.succeeded", {
295 ...sshTargetLogFields(target),
296 command: ["ssh", ...args],
297 });
298 return { stdout, stderr };
299});
300
301export const runSshCommand = Effect.fn("ssh/command.runSshCommand")(function* (
302 target: DesktopSshEnvironmentTarget,
303 input: RunSshCommandOptions = {},
304): Effect.fn.Return<
305 SshCommandResult,
306 SshCommandError | SshInvalidTargetError,
307 ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem | Path.Path
308> {
309 return yield* Effect.scopedWith((commandScope) =>
310 runSshCommandInScope(target, input, commandScope),
311 ).pipe(
312 Effect.timeoutOption(Duration.millis(input.timeoutMs ?? DEFAULT_SSH_COMMAND_TIMEOUT_MS)),
313 Effect.flatMap((result) =>
314 Option.match(result, {
315 onSome: Effect.succeed,
316 // The enclosing operation owns the span for this inline handler.
317 onNone: Effect.fnUntraced(function* () {
318 yield* Effect.logWarning("ssh.command.timedOut", {
319 ...sshTargetLogFields(target),
320 timeoutMs: input.timeoutMs ?? DEFAULT_SSH_COMMAND_TIMEOUT_MS,
321 remoteCommandArgs: input.remoteCommandArgs ?? [],
322 preHostArgs: input.preHostArgs ?? [],
323 hasStdin: input.stdin !== undefined,
324 });
325 return yield* new SshCommandError({
326 command: ["ssh"],
327 exitCode: null,
328 stderr: "",
329 message: `SSH command timed out after ${input.timeoutMs ?? DEFAULT_SSH_COMMAND_TIMEOUT_MS}ms.`,
330 });
331 }),
332 }),
333 ),
334 );
335});
336
337export const resolveSshTarget = Effect.fn("ssh/command.resolveSshTarget")(function* (
338 alias: string,
339): Effect.fn.Return<
340 DesktopSshEnvironmentTarget,
341 SshCommandError | SshInvalidTargetError,
342 ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem | Path.Path
343> {
344 const trimmedAlias = alias.trim();
345 if (trimmedAlias.length === 0) {
346 return yield* new SshInvalidTargetError({ message: "SSH host alias is required." });
347 }
348
349 yield* Effect.logDebug("ssh.target.resolve.start", { alias: trimmedAlias });
350 return yield* runSshCommand(
351 {
352 alias: trimmedAlias,
353 hostname: trimmedAlias,
354 username: null,
355 port: null,
356 },
357 { preHostArgs: ["-G"] },
358 ).pipe(
359 Effect.map((result) => parseSshResolveOutput(trimmedAlias, result.stdout)),
360 Effect.tap((target) =>
361 Effect.logDebug("ssh.target.resolve.succeeded", sshTargetLogFields(target)),
362 ),
363 Effect.catch((cause) =>
364 Effect.logDebug("ssh.target.resolve.fallback", { alias: trimmedAlias, cause }).pipe(
365 Effect.as({
366 alias: trimmedAlias,
367 hostname: trimmedAlias,
368 username: null,
369 port: null,
370 }),
371 ),
372 ),
373 );
374});