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