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

command.ts

343 lines10.3 KB

1import * as Crypto from "node:crypto";
2​
3import type { DesktopSshEnvironmentTarget, DesktopUpdateChannel } from "@t3tools/contracts";
4import * as Duration from "effect/Duration";
5import * as Effect from "effect/Effect";
6import * as FileSystem from "effect/FileSystem";
7import * as Option from "effect/Option";
8import * as Path from "effect/Path";
9import * as Scope from "effect/Scope";
10import * as Stream from "effect/Stream";
11import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
12​
13import { buildSshChildEnvironment, type SshAuthOptions } from "./auth.ts";
14import { SshCommandError, SshInvalidTargetError } from "./errors.ts";
15​
16const PUBLISHABLE_T3_VERSION_PATTERN = /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/u;
17const DEFAULT_SSH_COMMAND_TIMEOUT_MS = 60_000;
18​
19const encoder = new TextEncoder();
20​
21export interface SshCommandResult {
22 readonly stdout: string;
23 readonly stderr: string;
25​
26export interface RunSshCommandOptions extends SshAuthOptions {
27 readonly preHostArgs?: ReadonlyArray<string>;
28 readonly remoteCommandArgs?: ReadonlyArray<string>;
29 readonly stdin?: string;
30 readonly timeoutMs?: number;
32​
33export function parseSshResolveOutput(alias: string, stdout: string): DesktopSshEnvironmentTarget {
34 const values = new Map<string, string>();
35 for (const line of stdout.split(/\r?\n/u)) {
36 const trimmed = line.trim();
37 if (trimmed.length === 0) {
38 continue;
39 }
40 const [key, ...rest] = trimmed.split(/\s+/u);
41 if (!key || rest.length === 0 || values.has(key)) {
42 continue;
43 }
44 values.set(key, rest.join(" ").trim());
45 }
46​
47 const hostname = values.get("hostname")?.trim() || alias;
48 const username = values.get("user")?.trim() || null;
49 const rawPort = values.get("port")?.trim() ?? "";
50 const parsedPort = Number.parseInt(rawPort, 10);
51​
52 return {
53 alias,
54 hostname,
55 username,
56 port: Number.isInteger(parsedPort) ? parsedPort : null,
57 };
59​
60export function targetConnectionKey(target: DesktopSshEnvironmentTarget): string {
61 return `${target.alias}\u0000${target.hostname}\u0000${target.username ?? ""}\u0000${target.port ?? ""}`;
63​
64export function remoteStateKey(target: DesktopSshEnvironmentTarget): string {
65 return Crypto.createHash("sha256").update(targetConnectionKey(target)).digest("hex").slice(0, 16);
67​
68export function buildSshHostSpec(target: DesktopSshEnvironmentTarget): string {
69 const destination = target.alias.trim() || target.hostname.trim();
70 if (destination.length === 0) {
71 throw new Error("SSH target is missing its alias/hostname.");
72 }
73 return target.username ? `${target.username}@${destination}` : destination;
75​
76export const buildSshHostSpecEffect = (
77 target: DesktopSshEnvironmentTarget,
78): Effect.Effect<string, SshInvalidTargetError> =>
79 Effect.try({
80 try: () => buildSshHostSpec(target),
81 catch: (cause) =>
82 new SshInvalidTargetError({
83 message: cause instanceof Error ? cause.message : "SSH target is invalid.",
84 }),
85 });
86​
87export function baseSshArgs(
88 target: DesktopSshEnvironmentTarget,
89 input?: { readonly batchMode?: "yes" | "no" },
90): string[] {
91 return [
92 "-o",
93 `BatchMode=${input?.batchMode ?? "no"}`,
94 "-o",
95 "ConnectTimeout=10",
96 ...(target.port !== null ? ["-p", String(target.port)] : []),
97 ];
99​
100export function getLastNonEmptyOutputLine(stdout: string): string | null {
101 return (
102 stdout
103 .trim()
104 .split(/\r?\n/u)
105 .map((entry) => entry.trim())
106 .findLast((entry) => entry.length > 0) ?? null
107 );
109​
110export const collectProcessOutput = <E>(
111 stream: Stream.Stream<Uint8Array, E>,
112): Effect.Effect<string, E> =>
113 stream.pipe(
114 Stream.decodeText(),
115 Stream.runFold(
116 () => "",
117 (acc, chunk) => acc + chunk,
118 ),
119 );
120​
121function normalizeSshErrorMessage(stderr: string, fallbackMessage: string): string {
122 const cleaned = stderr.trim();
123 return cleaned.length > 0 ? cleaned : fallbackMessage;
125​
126function sshTargetLogFields(target: DesktopSshEnvironmentTarget) {
127 return {
128 alias: target.alias,
129 hostname: target.hostname,
130 username: target.username,
131 port: target.port,
132 };
134​
135function stdinStream(input: string | undefined) {
136 return input === undefined ? Stream.empty : Stream.make(encoder.encode(input));
138​
139const runSshCommandInScope = Effect.fn("ssh/command.runSshCommand.inScope")(function* (
140 target: DesktopSshEnvironmentTarget,
141 input: RunSshCommandOptions,
142 commandScope: Scope.Scope,
143): Effect.fn.Return<
144 SshCommandResult,
145 SshCommandError | SshInvalidTargetError,
146 ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem | Path.Path
147> {
148 const hostSpec = yield* buildSshHostSpecEffect(target);
149 const environment = yield* buildSshChildEnvironment({
150 ...(input.interactiveAuth === undefined ? {} : { interactiveAuth: input.interactiveAuth }),
151 ...(input.authSecret === undefined ? {} : { authSecret: input.authSecret }),
152 }).pipe(
153 Effect.mapError(
154 (cause) =>
155 new SshCommandError({
156 command: ["ssh"],
157 exitCode: null,
158 stderr: "",
159 message: "Failed to prepare SSH authentication helpers.",
160 cause,
161 }),
162 ),
163 );
164 const args = [
165 ...baseSshArgs(target, {
166 batchMode: input.batchMode ?? (input.interactiveAuth ? "no" : "yes"),
167 }),
168 ...(input.preHostArgs ?? []),
169 hostSpec,
170 ...(input.remoteCommandArgs ?? []),
171 ];
172 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
173 yield* Effect.logDebug("ssh.command.start", {
174 ...sshTargetLogFields(target),
175 command: ["ssh", ...args],
176 hasStdin: input.stdin !== undefined,
177 timeoutMs: input.timeoutMs ?? DEFAULT_SSH_COMMAND_TIMEOUT_MS,
178 });
179 const child = yield* spawner
180 .spawn(
181 ChildProcess.make("ssh", args, {
182 env: environment,
183 shell: process.platform === "win32",
184 stdin: {
185 stream: stdinStream(input.stdin),
186 endOnDone: true,
187 },
188 }),
189 )
190 .pipe(
191 Effect.provideService(Scope.Scope, commandScope),
192 Effect.mapError(
193 (cause) =>
194 new SshCommandError({
195 command: ["ssh", ...args],
196 exitCode: null,
197 stderr: "",
198 message:
199 cause instanceof Error
200 ? cause.message
201 : `Failed to spawn SSH command for ${hostSpec}.`,
202 cause,
203 }),
204 ),
205 );
206​
207 const [stdout, stderr, exitCode] = yield* Effect.all(
208 [
209 collectProcessOutput(child.stdout),
210 collectProcessOutput(child.stderr),
211 child.exitCode.pipe(Effect.map(Number)),
212 ],
213 { concurrency: "unbounded" },
214 ).pipe(
215 Effect.mapError(
216 (cause) =>
217 new SshCommandError({
218 command: ["ssh", ...args],
219 exitCode: null,
220 stderr: "",
221 message:
222 cause instanceof Error ? cause.message : `Failed to run SSH command for ${hostSpec}.`,
223 cause,
224 }),
225 ),
226 );
227​
228 if (exitCode !== 0) {
229 yield* Effect.logWarning("ssh.command.failed", {
230 ...sshTargetLogFields(target),
231 command: ["ssh", ...args],
232 exitCode,
233 stderr,
234 });
235 return yield* new SshCommandError({
236 command: ["ssh", ...args],
237 exitCode,
238 stderr,
239 message: normalizeSshErrorMessage(
240 stderr,
241 `SSH command failed for ${hostSpec} (exit ${exitCode}).`,
242 ),
243 });
244 }
245​
246 yield* Effect.logDebug("ssh.command.succeeded", {
247 ...sshTargetLogFields(target),
248 command: ["ssh", ...args],
249 });
250 return { stdout, stderr };
251});
252​
253export const runSshCommand = Effect.fn("ssh/command.runSshCommand")(function* (
254 target: DesktopSshEnvironmentTarget,
255 input: RunSshCommandOptions = {},
256): Effect.fn.Return<
257 SshCommandResult,
258 SshCommandError | SshInvalidTargetError,
259 ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem | Path.Path
260> {
261 return yield* Effect.scopedWith((commandScope) =>
262 runSshCommandInScope(target, input, commandScope),
263 ).pipe(
264 Effect.timeoutOption(Duration.millis(input.timeoutMs ?? DEFAULT_SSH_COMMAND_TIMEOUT_MS)),
265 Effect.flatMap((result) =>
266 Option.match(result, {
267 onSome: Effect.succeed,
268 onNone: () =>
269 Effect.gen(function* () {
270 yield* Effect.logWarning("ssh.command.timedOut", {
271 ...sshTargetLogFields(target),
272 timeoutMs: input.timeoutMs ?? DEFAULT_SSH_COMMAND_TIMEOUT_MS,
273 remoteCommandArgs: input.remoteCommandArgs ?? [],
274 preHostArgs: input.preHostArgs ?? [],
275 hasStdin: input.stdin !== undefined,
276 });
277 return yield* new SshCommandError({
278 command: ["ssh"],
279 exitCode: null,
280 stderr: "",
281 message: `SSH command timed out after ${input.timeoutMs ?? DEFAULT_SSH_COMMAND_TIMEOUT_MS}ms.`,
282 });
283 }),
284 }),
285 ),
286 );
287});
288​
289export const resolveSshTarget = Effect.fn("ssh/command.resolveSshTarget")(function* (
290 alias: string,
291): Effect.fn.Return<
292 DesktopSshEnvironmentTarget,
293 SshCommandError | SshInvalidTargetError,
294 ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem | Path.Path
295> {
296 const trimmedAlias = alias.trim();
297 if (trimmedAlias.length === 0) {
298 return yield* new SshInvalidTargetError({ message: "SSH host alias is required." });
299 }
300​
301 yield* Effect.logDebug("ssh.target.resolve.start", { alias: trimmedAlias });
302 return yield* runSshCommand(
303 {
304 alias: trimmedAlias,
305 hostname: trimmedAlias,
306 username: null,
307 port: null,
308 },
309 { preHostArgs: ["-G"] },
310 ).pipe(
311 Effect.map((result) => parseSshResolveOutput(trimmedAlias, result.stdout)),
312 Effect.tap((target) =>
313 Effect.logDebug("ssh.target.resolve.succeeded", sshTargetLogFields(target)),
314 ),
315 Effect.catch((cause) =>
316 Effect.logDebug("ssh.target.resolve.fallback", { alias: trimmedAlias, cause }).pipe(
317 Effect.as({
318 alias: trimmedAlias,
319 hostname: trimmedAlias,
320 username: null,
321 port: null,
322 }),
323 ),
324 ),
325 );
326});
327​
328export function resolveRemoteT3CliPackageSpec(input: {
329 readonly appVersion: string;
330 readonly updateChannel: DesktopUpdateChannel;
331 readonly isDevelopment?: boolean;
332}): string {
333 const appVersion = input.appVersion.trim();
334 if (!input.isDevelopment && PUBLISHABLE_T3_VERSION_PATTERN.test(appVersion)) {
335 return `t3@${appVersion}`;
336 }
337​
338 if (input.isDevelopment) {
339 return "t3@nightly";
340 }
341​
342 return input.updateChannel === "nightly" ? "t3@nightly" : "t3@latest";