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
163function 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 ...(input.preHostArgs ?? []),
206 "--",
207 hostSpec,
208 ...(input.remoteCommandArgs ?? []),
209 ];
210 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
211 const sshCommand = yield* resolveSshCommand;
212 yield* Effect.logDebug("ssh.command.start", {
213 ...sshTargetLogFields(target),
214 command: [sshCommand, ...args],
215 hasStdin: input.stdin !== undefined,
216 timeoutMs: input.timeoutMs ?? DEFAULT_SSH_COMMAND_TIMEOUT_MS,
217 });
218 const child = yield* spawner
219 .spawn(
220 ChildProcess.make(sshCommand, args, {
221 env: environment,
222 extendEnv: true,
223 stdin: {
224 stream: stdinStream(input.stdin),
225 endOnDone: true,
226 },
227 }),
228 )
229 .pipe(
230 Effect.provideService(Scope.Scope, commandScope),
231 Effect.mapError(
232 (cause) =>
233 new SshCommandError({
234 command: [sshCommand, ...args],
235 exitCode: null,
236 stderr: "",
237 message:
238 cause instanceof Error
239 ? cause.message
240 : `Failed to spawn SSH command for ${hostSpec}.`,
241 cause,
242 }),
243 ),
244 );
245
246 const [stdout, stderr, exitCode] = yield* Effect.all(
247 [
248 collectProcessOutput(child.stdout),
249 collectProcessOutput(child.stderr),
250 child.exitCode.pipe(Effect.map(Number)),
251 ],
252 { concurrency: "unbounded" },
253 ).pipe(
254 Effect.mapError(
255 (cause) =>
256 new SshCommandError({
257 command: ["ssh", ...args],
258 exitCode: null,
259 stderr: "",
260 message:
261 cause instanceof Error ? cause.message : `Failed to run SSH command for ${hostSpec}.`,
262 cause,
263 }),
264 ),
265 );
266
267 if (exitCode !== 0) {
268 const diagnosticStdout = redactSshErrorOutput(stdout, input.keepErrorOutputTail);
269 yield* Effect.logWarning("ssh.command.failed", {
270 ...sshTargetLogFields(target),
271 command: ["ssh", ...args],
272 exitCode,
273 stdout: diagnosticStdout,
274 stderr,
275 });
276 return yield* new SshCommandError({
277 command: ["ssh", ...args],
278 exitCode,
279 stdout: diagnosticStdout,
280 stderr,
281 message: normalizeSshErrorMessage({
282 stdout: diagnosticStdout,
283 stderr,
284 fallbackMessage: `SSH command failed for ${hostSpec} (exit ${exitCode}).`,
285 }),
286 });
287 }
288
289 yield* Effect.logDebug("ssh.command.succeeded", {
290 ...sshTargetLogFields(target),
291 command: ["ssh", ...args],
292 });
293 return { stdout, stderr };
294});
295
296export const runSshCommand = Effect.fn("ssh/command.runSshCommand")(function* (
297 target: DesktopSshEnvironmentTarget,
298 input: RunSshCommandOptions = {},
299): Effect.fn.Return<
300 SshCommandResult,
301 SshCommandError | SshInvalidTargetError,
302 ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem | Path.Path
303> {
304 return yield* Effect.scopedWith((commandScope) =>
305 runSshCommandInScope(target, input, commandScope),
306 ).pipe(
307 Effect.timeoutOption(Duration.millis(input.timeoutMs ?? DEFAULT_SSH_COMMAND_TIMEOUT_MS)),
308 Effect.flatMap((result) =>
309 Option.match(result, {
310 onSome: Effect.succeed,
311 onNone: () =>
312 Effect.gen(function* () {
313 yield* Effect.logWarning("ssh.command.timedOut", {
314 ...sshTargetLogFields(target),
315 timeoutMs: input.timeoutMs ?? DEFAULT_SSH_COMMAND_TIMEOUT_MS,
316 remoteCommandArgs: input.remoteCommandArgs ?? [],
317 preHostArgs: input.preHostArgs ?? [],
318 hasStdin: input.stdin !== undefined,
319 });
320 return yield* new SshCommandError({
321 command: ["ssh"],
322 exitCode: null,
323 stderr: "",
324 message: `SSH command timed out after ${input.timeoutMs ?? DEFAULT_SSH_COMMAND_TIMEOUT_MS}ms.`,
325 });
326 }),
327 }),
328 ),
329 );
330});
331
332export const resolveSshTarget = Effect.fn("ssh/command.resolveSshTarget")(function* (
333 alias: string,
334): Effect.fn.Return<
335 DesktopSshEnvironmentTarget,
336 SshCommandError | SshInvalidTargetError,
337 ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem | Path.Path
338> {
339 const trimmedAlias = alias.trim();
340 if (trimmedAlias.length === 0) {
341 return yield* new SshInvalidTargetError({ message: "SSH host alias is required." });
342 }
343
344 yield* Effect.logDebug("ssh.target.resolve.start", { alias: trimmedAlias });
345 return yield* runSshCommand(
346 {
347 alias: trimmedAlias,
348 hostname: trimmedAlias,
349 username: null,
350 port: null,
351 },
352 { preHostArgs: ["-G"] },
353 ).pipe(
354 Effect.map((result) => parseSshResolveOutput(trimmedAlias, result.stdout)),
355 Effect.tap((target) =>
356 Effect.logDebug("ssh.target.resolve.succeeded", sshTargetLogFields(target)),
357 ),
358 Effect.catch((cause) =>
359 Effect.logDebug("ssh.target.resolve.fallback", { alias: trimmedAlias, cause }).pipe(
360 Effect.as({
361 alias: trimmedAlias,
362 hostname: trimmedAlias,
363 username: null,
364 port: null,
365 }),
366 ),
367 ),
368 );
369});