Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

command.ts

367 lines11.2 KB

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