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
150function normalizeSshErrorMessage(input: {
151 readonly stdout?: string;
152 readonly stderr: string;
153 readonly fallbackMessage: string;
154}): string {
155 const cleanedStderr = input.stderr.trim();
156 if (cleanedStderr.length > 0) {
157 return cleanedStderr;
158 }
159
160 const cleanedStdout = input.stdout?.trim() ?? "";
161 return cleanedStdout.length > 0 ? cleanedStdout : input.fallbackMessage;
162}
163
164export function sshTargetLogFields(target: DesktopSshEnvironmentTarget) {
165 return {
166 alias: target.alias,
167 hostname: target.hostname,
168 username: target.username,
169 port: target.port,
170 };
171}
172
173function stdinStream(input: string | undefined) {
174 return input === undefined ? Stream.empty : Stream.make(encoder.encode(input));
175}
176
177const runSshCommandInScope = Effect.fn("ssh/command.runSshCommand.inScope")(function* (
178 target: DesktopSshEnvironmentTarget,
179 input: RunSshCommandOptions,
180 commandScope: Scope.Scope,
181): Effect.fn.Return<
182 SshCommandResult,
183 SshCommandError | SshInvalidTargetError,
184 ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem | Path.Path
185> {
186 const hostSpec = yield* buildSshHostSpecEffect(target);
187 const environment = yield* buildSshChildEnvironment({
188 ...(input.interactiveAuth === undefined ? {} : { interactiveAuth: input.interactiveAuth }),
189 ...(input.authSecret === undefined ? {} : { authSecret: input.authSecret }),
190 }).pipe(
191 Effect.mapError(
192 (cause) =>
193 new SshCommandError({
194 command: ["ssh"],
195 exitCode: null,
196 stderr: "",
197 message: "Failed to prepare SSH authentication helpers.",
198 cause,
199 }),
200 ),
201 );
202 const args = [
203 ...baseSshArgs(target, {
204 batchMode: input.batchMode ?? (input.interactiveAuth ? "no" : "yes"),
205 }),
206 // Cold installs need a long command budget; a lost connection must fail sooner.
207 "-o",
208 "ServerAliveInterval=15",
209 "-o",
210 "ServerAliveCountMax=3",
211 ...(input.preHostArgs ?? []),
212 "--",
213 hostSpec,
214 ...(input.remoteCommandArgs ?? []),
215 ];
216 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
217 const sshCommand = yield* resolveSshCommand;
218 yield* Effect.logDebug("ssh.command.start", {
219 ...sshTargetLogFields(target),
220 command: [sshCommand, ...args],
221 hasStdin: input.stdin !== undefined,
222 timeoutMs: input.timeoutMs ?? DEFAULT_SSH_COMMAND_TIMEOUT_MS,
223 });
224 const child = yield* spawner
225 .spawn(
226 ChildProcess.make(sshCommand, args, {
227 env: environment,
228 extendEnv: true,
229 stdin: {
230 stream: stdinStream(input.stdin),
231 endOnDone: true,
232 },
233 }),
234 )
235 .pipe(
236 Effect.provideService(Scope.Scope, commandScope),
237 Effect.mapError(
238 (cause) =>
239 new SshCommandError({
240 command: [sshCommand, ...args],
241 exitCode: null,
242 stderr: "",
243 message:
244 cause instanceof Error
245 ? cause.message
246 : `Failed to spawn SSH command for ${hostSpec}.`,
247 cause,
248 }),
249 ),
250 );
251
252 const [stdout, stderr, exitCode] = yield* Effect.all(
253 [
254 collectProcessOutput(child.stdout),
255 collectProcessOutput(child.stderr),
256 child.exitCode.pipe(Effect.map(Number)),
257 ],
258 { concurrency: "unbounded" },
259 ).pipe(
260 Effect.mapError(
261 (cause) =>
262 new SshCommandError({
263 command: ["ssh", ...args],
264 exitCode: null,
265 stderr: "",
266 message:
267 cause instanceof Error ? cause.message : `Failed to run SSH command for ${hostSpec}.`,
268 cause,
269 }),
270 ),
271 );
272
273 if (exitCode !== 0) {
274 const diagnosticStdout = redactSshErrorOutput(stdout, input.keepErrorOutputTail);
275 yield* Effect.logWarning("ssh.command.failed", {
276 ...sshTargetLogFields(target),
277 command: ["ssh", ...args],
278 exitCode,
279 stdout: diagnosticStdout,
280 stderr,
281 });
282 return yield* new SshCommandError({
283 command: ["ssh", ...args],
284 exitCode,
285 stdout: diagnosticStdout,
286 stderr,
287 message: normalizeSshErrorMessage({
288 stdout: diagnosticStdout,
289 stderr,
290 fallbackMessage: `SSH command failed for ${hostSpec} (exit ${exitCode}).`,
291 }),
292 });
293 }
294
295 yield* Effect.logDebug("ssh.command.succeeded", {
296 ...sshTargetLogFields(target),
297 command: ["ssh", ...args],
298 });
299 return { stdout, stderr };
300});
301
302export const runSshCommand = Effect.fn("ssh/command.runSshCommand")(function* (
303 target: DesktopSshEnvironmentTarget,
304 input: RunSshCommandOptions = {},
305): Effect.fn.Return<
306 SshCommandResult,
307 SshCommandError | SshInvalidTargetError,
308 ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem | Path.Path
309> {
310 return yield* Effect.scopedWith((commandScope) =>
311 runSshCommandInScope(target, input, commandScope),
312 ).pipe(
313 Effect.timeoutOption(Duration.millis(input.timeoutMs ?? DEFAULT_SSH_COMMAND_TIMEOUT_MS)),
314 Effect.flatMap((result) =>
315 Option.match(result, {
316 onSome: Effect.succeed,
317 // The enclosing operation owns the span for this inline handler.
318 onNone: Effect.fnUntraced(function* () {
319 yield* Effect.logWarning("ssh.command.timedOut", {
320 ...sshTargetLogFields(target),
321 timeoutMs: input.timeoutMs ?? DEFAULT_SSH_COMMAND_TIMEOUT_MS,
322 remoteCommandArgs: input.remoteCommandArgs ?? [],
323 preHostArgs: input.preHostArgs ?? [],
324 hasStdin: input.stdin !== undefined,
325 });
326 return yield* new SshCommandError({
327 command: ["ssh"],
328 exitCode: null,
329 stderr: "",
330 message: `SSH command timed out after ${input.timeoutMs ?? DEFAULT_SSH_COMMAND_TIMEOUT_MS}ms.`,
331 });
332 }),
333 }),
334 ),
335 );
336});
337
338export const resolveSshTarget = Effect.fn("ssh/command.resolveSshTarget")(function* (
339 alias: string,
340): Effect.fn.Return<
341 DesktopSshEnvironmentTarget,
342 SshCommandError | SshInvalidTargetError,
343 ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem | Path.Path
344> {
345 const trimmedAlias = alias.trim();
346 if (trimmedAlias.length === 0) {
347 return yield* new SshInvalidTargetError({ message: "SSH host alias is required." });
348 }
349
350 yield* Effect.logDebug("ssh.target.resolve.start", { alias: trimmedAlias });
351 return yield* runSshCommand(
352 {
353 alias: trimmedAlias,
354 hostname: trimmedAlias,
355 username: null,
356 port: null,
357 },
358 { preHostArgs: ["-G"] },
359 ).pipe(
360 Effect.map((result) => parseSshResolveOutput(trimmedAlias, result.stdout)),
361 Effect.tap((target) =>
362 Effect.logDebug("ssh.target.resolve.succeeded", sshTargetLogFields(target)),
363 ),
364 Effect.catch((cause) =>
365 Effect.logDebug("ssh.target.resolve.fallback", { alias: trimmedAlias, cause }).pipe(
366 Effect.as({
367 alias: trimmedAlias,
368 hostname: trimmedAlias,
369 username: null,
370 port: null,
371 }),
372 ),
373 ),
374 );
375});