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

command.ts

379 lines11.6 KB

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