Open History to see the last commit
1import * as NodeCrypto from "node:crypto";
2
3import type { DesktopSshEnvironmentTarget, DesktopUpdateChannel } from "@t3tools/contracts";
4import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
5import * as Duration from "effect/Duration";
6import * as Effect from "effect/Effect";
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/unstable/process";
13
14import { buildSshChildEnvironment, type SshAuthOptions } from "./auth.ts";
15import { SshCommandError, SshInvalidTargetError } from "./errors.ts";
16
17const PUBLISHABLE_T3_VERSION_PATTERN = /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/u;
18const DEFAULT_SSH_COMMAND_TIMEOUT_MS = 60_000;
19const MAX_SSH_ERROR_OUTPUT_LENGTH = 4_000;
20
21/**
22 * ssh is a real executable everywhere (`ssh.exe` on Windows), so it is always
23 * spawned directly — cmd.exe shell mode would re-tokenize arguments such as
24 * identity-file paths containing spaces.
25 */
26const sshCommandForPlatform = (platform: NodeJS.Platform): string =>
27 platform === "win32" ? "ssh.exe" : "ssh";
28
29export const resolveSshCommand = Effect.map(HostProcessPlatform, sshCommandForPlatform);
30
31const encoder = new TextEncoder();
32
33export interface SshCommandResult {
34 readonly stdout: string;
35 readonly stderr: string;
36}
37
38export interface RunSshCommandOptions extends SshAuthOptions {
39 readonly preHostArgs?: ReadonlyArray<string>;
40 readonly remoteCommandArgs?: ReadonlyArray<string>;
41 readonly stdin?: string;
42 readonly timeoutMs?: number;
43}
44
45export function parseSshResolveOutput(alias: string, stdout: string): DesktopSshEnvironmentTarget {
46 const values = new Map<string, string>();
47 for (const line of stdout.split(/\r?\n/u)) {
48 const trimmed = line.trim();
49 if (trimmed.length === 0) {
50 continue;
51 }
52 const [key, ...rest] = trimmed.split(/\s+/u);
53 if (!key || rest.length === 0 || values.has(key)) {
54 continue;
55 }
56 values.set(key, rest.join(" ").trim());
57 }
58
59 const hostname = values.get("hostname")?.trim() || alias;
60 const username = values.get("user")?.trim() || null;
61 const rawPort = values.get("port")?.trim() ?? "";
62 const parsedPort = Number.parseInt(rawPort, 10);
63
64 return {
65 alias,
66 hostname,
67 username,
68 port: Number.isInteger(parsedPort) ? parsedPort : null,
69 };
70}
71
72export function targetConnectionKey(target: DesktopSshEnvironmentTarget): string {
73 return `${target.alias}\u0000${target.hostname}\u0000${target.username ?? ""}\u0000${target.port ?? ""}`;
74}
75
76export function remoteStateKey(target: DesktopSshEnvironmentTarget): string {
77 return NodeCrypto.createHash("sha256")
78 .update(targetConnectionKey(target))
79 .digest("hex")
80 .slice(0, 16);
81}
82
83export function buildSshHostSpec(target: DesktopSshEnvironmentTarget): string {
84 const destination = target.alias.trim() || target.hostname.trim();
85 if (destination.length === 0) {
86 throw new Error("SSH target is missing its alias/hostname.");
87 }
88 return target.username ? `${target.username}@${destination}` : destination;
89}
90
91export const buildSshHostSpecEffect = (
92 target: DesktopSshEnvironmentTarget,
93): Effect.Effect<string, SshInvalidTargetError> =>
94 Effect.try({
95 try: () => buildSshHostSpec(target),
96 catch: (cause) =>
97 new SshInvalidTargetError({
98 message: cause instanceof Error ? cause.message : "SSH target is invalid.",
99 }),
100 });
101
102export function baseSshArgs(
103 target: DesktopSshEnvironmentTarget,
104 input?: { readonly batchMode?: "yes" | "no" },
105): string[] {
106 return [
107 "-o",
108 `BatchMode=${input?.batchMode ?? "no"}`,
109 "-o",
110 "ConnectTimeout=10",
111 ...(target.port !== null ? ["-p", String(target.port)] : []),
112 ];
113}
114
115export function getLastNonEmptyOutputLine(stdout: string): string | null {
116 return (
117 stdout
118 .trim()
119 .split(/\r?\n/u)
120 .map((entry) => entry.trim())
121 .findLast((entry) => entry.length > 0) ?? null
122 );
123}
124
125export const collectProcessOutput = <E>(
126 stream: Stream.Stream<Uint8Array, E>,
127): 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 hostSpec,
204 ...(input.remoteCommandArgs ?? []),
205 ];
206 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
207 const sshCommand = yield* resolveSshCommand;
208 yield* Effect.logDebug("ssh.command.start", {
209 ...sshTargetLogFields(target),
210 command: [sshCommand, ...args],
211 hasStdin: input.stdin !== undefined,
212 timeoutMs: input.timeoutMs ?? DEFAULT_SSH_COMMAND_TIMEOUT_MS,
213 });
214 const child = yield* spawner
215 .spawn(
216 ChildProcess.make(sshCommand, args, {
217 env: environment,
218 extendEnv: true,
219 stdin: {
220 stream: stdinStream(input.stdin),
221 endOnDone: true,
222 },
223 }),
224 )
225 .pipe(
226 Effect.provideService(Scope.Scope, commandScope),
227 Effect.mapError(
228 (cause) =>
229 new SshCommandError({
230 command: [sshCommand, ...args],
231 exitCode: null,
232 stderr: "",
233 message:
234 cause instanceof Error
235 ? cause.message
236 : `Failed to spawn SSH command for ${hostSpec}.`,
237 cause,
238 }),
239 ),
240 );
241
242 const [stdout, stderr, exitCode] = yield* Effect.all(
243 [
244 collectProcessOutput(child.stdout),
245 collectProcessOutput(child.stderr),
246 child.exitCode.pipe(Effect.map(Number)),
247 ],
248 { concurrency: "unbounded" },
249 ).pipe(
250 Effect.mapError(
251 (cause) =>
252 new SshCommandError({
253 command: ["ssh", ...args],
254 exitCode: null,
255 stderr: "",
256 message:
257 cause instanceof Error ? cause.message : `Failed to run SSH command for ${hostSpec}.`,
258 cause,
259 }),
260 ),
261 );
262
263 if (exitCode !== 0) {
264 const diagnosticStdout = redactSshErrorOutput(stdout);
265 yield* Effect.logWarning("ssh.command.failed", {
266 ...sshTargetLogFields(target),
267 command: ["ssh", ...args],
268 exitCode,
269 stdout: diagnosticStdout,
270 stderr,
271 });
272 return yield* new SshCommandError({
273 command: ["ssh", ...args],
274 exitCode,
275 stdout: diagnosticStdout,
276 stderr,
277 message: normalizeSshErrorMessage({
278 stdout: diagnosticStdout,
279 stderr,
280 fallbackMessage: `SSH command failed for ${hostSpec} (exit ${exitCode}).`,
281 }),
282 });
283 }
284
285 yield* Effect.logDebug("ssh.command.succeeded", {
286 ...sshTargetLogFields(target),
287 command: ["ssh", ...args],
288 });
289 return { stdout, stderr };
290});
291
292export const runSshCommand = Effect.fn("ssh/command.runSshCommand")(function* (
293 target: DesktopSshEnvironmentTarget,
294 input: RunSshCommandOptions = {},
295): Effect.fn.Return<
296 SshCommandResult,
297 SshCommandError | SshInvalidTargetError,
298 ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem | Path.Path
299> {
300 return yield* Effect.scopedWith((commandScope) =>
301 runSshCommandInScope(target, input, commandScope),
302 ).pipe(
303 Effect.timeoutOption(Duration.millis(input.timeoutMs ?? DEFAULT_SSH_COMMAND_TIMEOUT_MS)),
304 Effect.flatMap((result) =>
305 Option.match(result, {
306 onSome: Effect.succeed,
307 onNone: () =>
308 Effect.gen(function* () {
309 yield* Effect.logWarning("ssh.command.timedOut", {
310 ...sshTargetLogFields(target),
311 timeoutMs: input.timeoutMs ?? DEFAULT_SSH_COMMAND_TIMEOUT_MS,
312 remoteCommandArgs: input.remoteCommandArgs ?? [],
313 preHostArgs: input.preHostArgs ?? [],
314 hasStdin: input.stdin !== undefined,
315 });
316 return yield* new SshCommandError({
317 command: ["ssh"],
318 exitCode: null,
319 stderr: "",
320 message: `SSH command timed out after ${input.timeoutMs ?? DEFAULT_SSH_COMMAND_TIMEOUT_MS}ms.`,
321 });
322 }),
323 }),
324 ),
325 );
326});
327
328export const resolveSshTarget = Effect.fn("ssh/command.resolveSshTarget")(function* (
329 alias: string,
330): Effect.fn.Return<
331 DesktopSshEnvironmentTarget,
332 SshCommandError | SshInvalidTargetError,
333 ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem | Path.Path
334> {
335 const trimmedAlias = alias.trim();
336 if (trimmedAlias.length === 0) {
337 return yield* new SshInvalidTargetError({ message: "SSH host alias is required." });
338 }
339
340 yield* Effect.logDebug("ssh.target.resolve.start", { alias: trimmedAlias });
341 return yield* runSshCommand(
342 {
343 alias: trimmedAlias,
344 hostname: trimmedAlias,
345 username: null,
346 port: null,
347 },
348 { preHostArgs: ["-G"] },
349 ).pipe(
350 Effect.map((result) => parseSshResolveOutput(trimmedAlias, result.stdout)),
351 Effect.tap((target) =>
352 Effect.logDebug("ssh.target.resolve.succeeded", sshTargetLogFields(target)),
353 ),
354 Effect.catch((cause) =>
355 Effect.logDebug("ssh.target.resolve.fallback", { alias: trimmedAlias, cause }).pipe(
356 Effect.as({
357 alias: trimmedAlias,
358 hostname: trimmedAlias,
359 username: null,
360 port: null,
361 }),
362 ),
363 ),
364 );
365});
366
367export function resolveRemoteT3CliPackageSpec(input: {
368 readonly appVersion: string;
369 readonly updateChannel: DesktopUpdateChannel;
370 readonly isDevelopment?: boolean;
371}): string {
372 const appVersion = input.appVersion.trim();
373 if (!input.isDevelopment && PUBLISHABLE_T3_VERSION_PATTERN.test(appVersion)) {
374 return `t3@${appVersion}`;
375 }
376
377 if (input.isDevelopment) {
378 return "t3@nightly";
379 }
380
381 return input.updateChannel === "nightly" ? "t3@nightly" : "t3@latest";
382}