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

command.ts

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