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

command.ts

364 lines11.0 KB

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