The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 21, 03:37 UTC
| 1 | import type { DesktopSshEnvironmentTarget } from "@t3tools/contracts"; |
| 2 | import * as HostProcess from "@t3tools/shared/HostProcess"; |
| 3 | import * as Digest from "effect/crypto/Digest"; |
| 4 | import * as Duration from "effect/Duration"; |
| 5 | import * as Effect from "effect/Effect"; |
| 6 | import * as Hex from "effect/encoding/Hex"; |
| 7 | import * as FileSystem from "effect/FileSystem"; |
| 8 | import * as Option from "effect/Option"; |
| 9 | import * as Path from "effect/Path"; |
| 10 | import * as Scope from "effect/Scope"; |
| 11 | import * as Stream from "effect/Stream"; |
| 12 | import { ChildProcess, ChildProcessSpawner } from "effect/process"; |
| 13 | |
| 14 | import { buildSshChildEnvironment, type SshAuthOptions } from "./auth.ts"; |
| 15 | import { SshCommandError, SshInvalidTargetError } from "./errors.ts"; |
| 16 | |
| 17 | const DEFAULT_SSH_COMMAND_TIMEOUT_MS = 60_000; |
| 18 | const 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 | */ |
| 25 | const sshCommandForPlatform = (platform: NodeJS.Platform): string => |
| 26 | platform === "win32" ? "ssh.exe" : "ssh"; |
| 27 | |
| 28 | export const resolveSshCommand = Effect.map(HostProcess.Platform, sshCommandForPlatform); |
| 29 | |
| 30 | const encoder = new TextEncoder(); |
| 31 | |
| 32 | export interface SshCommandResult { |
| 33 | readonly stdout: string; |
| 34 | readonly stderr: string; |
| 35 | } |
| 36 | |
| 37 | export interface RunSshCommandOptions extends SshAuthOptions { |
| 38 | readonly preHostArgs?: ReadonlyArray<string>; |
| 39 | readonly remoteCommandArgs?: ReadonlyArray<string>; |
| 40 | readonly stdin?: string; |
| 41 | readonly timeoutMs?: number; |
| 42 | /** Keep the end of long failed-command stdout, where the final cause usually is. */ |
| 43 | readonly keepErrorOutputTail?: boolean; |
| 44 | } |
| 45 | |
| 46 | function parseSshConfigOutput(stdout: string): Map<string, string> { |
| 47 | const values = new Map<string, string>(); |
| 48 | for (const line of stdout.split(/\r?\n/u)) { |
| 49 | const trimmed = line.trim(); |
| 50 | if (trimmed.length === 0) { |
| 51 | continue; |
| 52 | } |
| 53 | const [key, ...rest] = trimmed.split(/\s+/u); |
| 54 | if (!key || rest.length === 0 || values.has(key)) { |
| 55 | continue; |
| 56 | } |
| 57 | values.set(key, rest.join(" ").trim()); |
| 58 | } |
| 59 | return values; |
| 60 | } |
| 61 | |
| 62 | export function parseSshResolveOutput(alias: string, stdout: string): DesktopSshEnvironmentTarget { |
| 63 | const values = parseSshConfigOutput(stdout); |
| 64 | |
| 65 | const hostname = values.get("hostname")?.trim() || alias; |
| 66 | const username = values.get("user")?.trim() || null; |
| 67 | const rawPort = values.get("port")?.trim() ?? ""; |
| 68 | const parsedPort = Number.parseInt(rawPort, 10); |
| 69 | |
| 70 | return { |
| 71 | alias, |
| 72 | hostname, |
| 73 | username, |
| 74 | port: Number.isInteger(parsedPort) ? parsedPort : null, |
| 75 | }; |
| 76 | } |
| 77 | |
| 78 | export function targetConnectionKey(target: DesktopSshEnvironmentTarget): string { |
| 79 | return `${target.alias}\u0000${target.hostname}\u0000${target.username ?? ""}\u0000${target.port ?? ""}`; |
| 80 | } |
| 81 | |
| 82 | export const remoteStateKey = Effect.fn("ssh/command.remoteStateKey")(function* ( |
| 83 | target: DesktopSshEnvironmentTarget, |
| 84 | ): Effect.fn.Return<string, never, Digest.Digest> { |
| 85 | const digestService = yield* Digest.Digest; |
| 86 | const digest = yield* digestService.digest( |
| 87 | Digest.sha256, |
| 88 | encoder.encode(targetConnectionKey(target)), |
| 89 | ); |
| 90 | return Hex.encode(digest).slice(0, 16); |
| 91 | }); |
| 92 | |
| 93 | function buildSshHostSpec(target: DesktopSshEnvironmentTarget): string { |
| 94 | const destination = target.alias.trim() || target.hostname.trim(); |
| 95 | if (destination.length === 0) { |
| 96 | throw new Error("SSH target is missing its alias/hostname."); |
| 97 | } |
| 98 | return target.username ? `${target.username}@${destination}` : destination; |
| 99 | } |
| 100 | |
| 101 | export const buildSshHostSpecEffect = ( |
| 102 | target: DesktopSshEnvironmentTarget, |
| 103 | ): Effect.Effect<string, SshInvalidTargetError> => |
| 104 | Effect.try({ |
| 105 | try: () => buildSshHostSpec(target), |
| 106 | catch: (cause) => |
| 107 | new SshInvalidTargetError({ |
| 108 | message: cause instanceof Error ? cause.message : "SSH target is invalid.", |
| 109 | }), |
| 110 | }); |
| 111 | |
| 112 | export function baseSshArgs( |
| 113 | target: DesktopSshEnvironmentTarget, |
| 114 | input?: { readonly batchMode?: "yes" | "no" }, |
| 115 | ): string[] { |
| 116 | return [ |
| 117 | "-o", |
| 118 | `BatchMode=${input?.batchMode ?? "no"}`, |
| 119 | "-o", |
| 120 | "ConnectTimeout=10", |
| 121 | // T3 always supplies its own remote command or only forwards ports, so a host |
| 122 | // alias's RemoteCommand or RequestTTY must not hijack the session. |
| 123 | "-o", |
| 124 | "RemoteCommand=none", |
| 125 | "-o", |
| 126 | "RequestTTY=no", |
| 127 | ...(target.port !== null ? ["-p", String(target.port)] : []), |
| 128 | ]; |
| 129 | } |
| 130 | |
| 131 | // `-F none` keeps the user's configured forwards out of T3's requests, and ProxyCommand=false |
| 132 | // fails closed instead of dialing the host directly once the master is gone. |
| 133 | export function controlMasterArgs(controlPath: string): string[] { |
| 134 | return ["-F", "none", "-o", `ControlPath=${controlPath}`, "-o", "ProxyCommand=false"]; |
| 135 | } |
| 136 | |
| 137 | export function getLastNonEmptyOutputLine(stdout: string): string | null { |
| 138 | return ( |
| 139 | stdout |
| 140 | .trim() |
| 141 | .split(/\r?\n/u) |
| 142 | .map((entry) => entry.trim()) |
| 143 | .findLast((entry) => entry.length > 0) ?? null |
| 144 | ); |
| 145 | } |
| 146 | |
| 147 | interface SshCommandOutput { |
| 148 | stdout: string; |
| 149 | stderr: string; |
| 150 | } |
| 151 | |
| 152 | // Appends as chunks arrive so a timeout can still report what was printed. |
| 153 | const collectProcessOutput = <E>( |
| 154 | stream: Stream.Stream<Uint8Array, E>, |
| 155 | output: SshCommandOutput, |
| 156 | key: keyof SshCommandOutput, |
| 157 | ): Effect.Effect<void, E> => |
| 158 | stream.pipe( |
| 159 | Stream.decodeText(), |
| 160 | Stream.runForEach((chunk) => |
| 161 | Effect.sync(() => { |
| 162 | output[key] += chunk; |
| 163 | }), |
| 164 | ), |
| 165 | ); |
| 166 | |
| 167 | function redactSshErrorOutput(output: string, keepTail = false): string { |
| 168 | const redacted = output.replace( |
| 169 | /("(?:access_token|bearerToken|credential|pairingToken|token)"\s*:\s*")[^"]+(")/giu, |
| 170 | "$1[redacted]$2", |
| 171 | ); |
| 172 | if (redacted.length <= MAX_SSH_ERROR_OUTPUT_LENGTH) return redacted; |
| 173 | return keepTail |
| 174 | ? `[truncated]\n${redacted.slice(-MAX_SSH_ERROR_OUTPUT_LENGTH)}` |
| 175 | : `${redacted.slice(0, MAX_SSH_ERROR_OUTPUT_LENGTH)}\n[truncated]`; |
| 176 | } |
| 177 | |
| 178 | export function shellSingleQuote(value: string): string { |
| 179 | return `'${value.replaceAll("'", "'\\''")}'`; |
| 180 | } |
| 181 | |
| 182 | const SAFE_SHELL_ARG = /^[\w@%+=:,./-]+$/u; |
| 183 | |
| 184 | // cmd.exe and PowerShell both read double quotes, but not POSIX single quotes. |
| 185 | function terminalArg(value: string, platform: NodeJS.Platform): string { |
| 186 | if (SAFE_SHELL_ARG.test(value)) return value; |
| 187 | return platform === "win32" ? `"${value}"` : shellSingleQuote(value); |
| 188 | } |
| 189 | |
| 190 | // ssh prints this for unknown and changed host keys when it cannot ask. The app |
| 191 | // never answers host key prompts, so the user checks the fingerprint in a terminal. |
| 192 | function hostKeyVerificationMessage(input: { |
| 193 | readonly target: DesktopSshEnvironmentTarget; |
| 194 | readonly hostSpec: string; |
| 195 | readonly stderr: string; |
| 196 | readonly platform: NodeJS.Platform; |
| 197 | }): string | null { |
| 198 | const { target, hostSpec, stderr, platform } = input; |
| 199 | if (!stderr.includes("Host key verification failed")) return null; |
| 200 | const command = [ |
| 201 | "ssh", |
| 202 | ...(target.port !== null ? ["-p", String(target.port)] : []), |
| 203 | ...(hostSpec.startsWith("-") ? ["--"] : []), |
| 204 | hostSpec, |
| 205 | ] |
| 206 | .map((arg) => terminalArg(arg, platform)) |
| 207 | .join(" "); |
| 208 | const guidance = stderr.includes("REMOTE HOST IDENTIFICATION HAS CHANGED") |
| 209 | ? `The host key for ${hostSpec} has changed since it was trusted. Only if you expect this change, remove the old key with the \`ssh-keygen -R\` command in the output below, run \`${command}\` in a terminal, check that the new host key fingerprint is the one you expect, then try again.` |
| 210 | : `SSH could not verify the host key for ${hostSpec}. Run \`${command}\` in a terminal, check that the host key fingerprint is the one you expect, then try again.`; |
| 211 | return `${guidance}\n\n${stderr.trim()}`; |
| 212 | } |
| 213 | |
| 214 | function normalizeSshErrorMessage(input: { |
| 215 | readonly stdout?: string; |
| 216 | readonly stderr: string; |
| 217 | readonly fallbackMessage: string; |
| 218 | }): string { |
| 219 | const cleanedStderr = input.stderr.trim(); |
| 220 | if (cleanedStderr.length > 0) { |
| 221 | return cleanedStderr; |
| 222 | } |
| 223 | |
| 224 | const cleanedStdout = input.stdout?.trim() ?? ""; |
| 225 | return cleanedStdout.length > 0 ? cleanedStdout : input.fallbackMessage; |
| 226 | } |
| 227 | |
| 228 | export function sshTargetLogFields(target: DesktopSshEnvironmentTarget) { |
| 229 | return { |
| 230 | alias: target.alias, |
| 231 | hostname: target.hostname, |
| 232 | username: target.username, |
| 233 | port: target.port, |
| 234 | }; |
| 235 | } |
| 236 | |
| 237 | function stdinStream(input: string | undefined) { |
| 238 | return input === undefined ? Stream.empty : Stream.make(encoder.encode(input)); |
| 239 | } |
| 240 | |
| 241 | const runSshCommandInScope = Effect.fn("ssh/command.runSshCommand.inScope")(function* ( |
| 242 | target: DesktopSshEnvironmentTarget, |
| 243 | input: RunSshCommandOptions, |
| 244 | commandScope: Scope.Scope, |
| 245 | output: SshCommandOutput, |
| 246 | ): Effect.fn.Return< |
| 247 | SshCommandResult, |
| 248 | SshCommandError | SshInvalidTargetError, |
| 249 | ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem | Path.Path |
| 250 | > { |
| 251 | const hostSpec = yield* buildSshHostSpecEffect(target); |
| 252 | const environment = yield* buildSshChildEnvironment({ |
| 253 | ...(input.interactiveAuth === undefined ? {} : { interactiveAuth: input.interactiveAuth }), |
| 254 | ...(input.authSecret === undefined ? {} : { authSecret: input.authSecret }), |
| 255 | }).pipe( |
| 256 | Effect.mapError( |
| 257 | (cause) => |
| 258 | new SshCommandError({ |
| 259 | command: ["ssh"], |
| 260 | exitCode: null, |
| 261 | stderr: "", |
| 262 | message: "Failed to prepare SSH authentication helpers.", |
| 263 | cause, |
| 264 | }), |
| 265 | ), |
| 266 | ); |
| 267 | const args = [ |
| 268 | ...baseSshArgs(target, { |
| 269 | batchMode: input.batchMode ?? (input.interactiveAuth ? "no" : "yes"), |
| 270 | }), |
| 271 | // Cold installs need a long command budget; a lost connection must fail sooner. |
| 272 | "-o", |
| 273 | "ServerAliveInterval=15", |
| 274 | "-o", |
| 275 | "ServerAliveCountMax=3", |
| 276 | ...(input.preHostArgs ?? []), |
| 277 | "--", |
| 278 | hostSpec, |
| 279 | ...(input.remoteCommandArgs ?? []), |
| 280 | ]; |
| 281 | const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; |
| 282 | const sshCommand = yield* resolveSshCommand; |
| 283 | yield* Effect.logDebug("ssh.command.start", { |
| 284 | ...sshTargetLogFields(target), |
| 285 | command: [sshCommand, ...args], |
| 286 | hasStdin: input.stdin !== undefined, |
| 287 | timeoutMs: input.timeoutMs ?? DEFAULT_SSH_COMMAND_TIMEOUT_MS, |
| 288 | }); |
| 289 | const child = yield* spawner |
| 290 | .spawn( |
| 291 | ChildProcess.make(sshCommand, args, { |
| 292 | env: environment, |
| 293 | extendEnv: true, |
| 294 | forceKillAfter: "1 second", |
| 295 | stdin: { |
| 296 | stream: stdinStream(input.stdin), |
| 297 | endOnDone: true, |
| 298 | }, |
| 299 | }), |
| 300 | ) |
| 301 | .pipe( |
| 302 | Effect.provideService(Scope.Scope, commandScope), |
| 303 | Effect.mapError( |
| 304 | (cause) => |
| 305 | new SshCommandError({ |
| 306 | command: [sshCommand, ...args], |
| 307 | exitCode: null, |
| 308 | stderr: "", |
| 309 | message: |
| 310 | cause instanceof Error |
| 311 | ? cause.message |
| 312 | : `Failed to spawn SSH command for ${hostSpec}.`, |
| 313 | cause, |
| 314 | }), |
| 315 | ), |
| 316 | ); |
| 317 | |
| 318 | const [, , exitCode] = yield* Effect.all( |
| 319 | [ |
| 320 | collectProcessOutput(child.stdout, output, "stdout"), |
| 321 | collectProcessOutput(child.stderr, output, "stderr"), |
| 322 | child.exitCode.pipe(Effect.map(Number)), |
| 323 | ], |
| 324 | { concurrency: "unbounded" }, |
| 325 | ).pipe( |
| 326 | Effect.mapError( |
| 327 | (cause) => |
| 328 | new SshCommandError({ |
| 329 | command: ["ssh", ...args], |
| 330 | exitCode: null, |
| 331 | stderr: "", |
| 332 | message: |
| 333 | cause instanceof Error ? cause.message : `Failed to run SSH command for ${hostSpec}.`, |
| 334 | cause, |
| 335 | }), |
| 336 | ), |
| 337 | ); |
| 338 | |
| 339 | const { stdout, stderr } = output; |
| 340 | if (exitCode !== 0) { |
| 341 | const diagnosticStdout = redactSshErrorOutput(stdout, input.keepErrorOutputTail); |
| 342 | yield* Effect.logWarning("ssh.command.failed", { |
| 343 | ...sshTargetLogFields(target), |
| 344 | command: ["ssh", ...args], |
| 345 | exitCode, |
| 346 | stdout: diagnosticStdout, |
| 347 | stderr, |
| 348 | }); |
| 349 | return yield* new SshCommandError({ |
| 350 | command: ["ssh", ...args], |
| 351 | exitCode, |
| 352 | stdout: diagnosticStdout, |
| 353 | stderr, |
| 354 | message: |
| 355 | hostKeyVerificationMessage({ |
| 356 | target, |
| 357 | hostSpec, |
| 358 | stderr, |
| 359 | platform: yield* HostProcess.Platform, |
| 360 | }) ?? |
| 361 | normalizeSshErrorMessage({ |
| 362 | stdout: diagnosticStdout, |
| 363 | stderr, |
| 364 | fallbackMessage: `SSH command failed for ${hostSpec} (exit ${exitCode}).`, |
| 365 | }), |
| 366 | }); |
| 367 | } |
| 368 | |
| 369 | yield* Effect.logDebug("ssh.command.succeeded", { |
| 370 | ...sshTargetLogFields(target), |
| 371 | command: ["ssh", ...args], |
| 372 | }); |
| 373 | return { stdout, stderr }; |
| 374 | }); |
| 375 | |
| 376 | export const runSshCommand = Effect.fn("ssh/command.runSshCommand")(function* ( |
| 377 | target: DesktopSshEnvironmentTarget, |
| 378 | input: RunSshCommandOptions = {}, |
| 379 | ): Effect.fn.Return< |
| 380 | SshCommandResult, |
| 381 | SshCommandError | SshInvalidTargetError, |
| 382 | ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem | Path.Path |
| 383 | > { |
| 384 | const output: SshCommandOutput = { stdout: "", stderr: "" }; |
| 385 | return yield* Effect.scopedWith((commandScope) => |
| 386 | runSshCommandInScope(target, input, commandScope, output), |
| 387 | ).pipe( |
| 388 | Effect.timeoutOption(Duration.millis(input.timeoutMs ?? DEFAULT_SSH_COMMAND_TIMEOUT_MS)), |
| 389 | Effect.flatMap((result) => |
| 390 | Option.match(result, { |
| 391 | onSome: Effect.succeed, |
| 392 | // The enclosing operation owns the span for this inline handler. |
| 393 | onNone: Effect.fnUntraced(function* () { |
| 394 | const diagnosticStdout = redactSshErrorOutput(output.stdout, input.keepErrorOutputTail); |
| 395 | const { stderr } = output; |
| 396 | yield* Effect.logWarning("ssh.command.timedOut", { |
| 397 | ...sshTargetLogFields(target), |
| 398 | timeoutMs: input.timeoutMs ?? DEFAULT_SSH_COMMAND_TIMEOUT_MS, |
| 399 | remoteCommandArgs: input.remoteCommandArgs ?? [], |
| 400 | preHostArgs: input.preHostArgs ?? [], |
| 401 | hasStdin: input.stdin !== undefined, |
| 402 | stdout: diagnosticStdout, |
| 403 | stderr, |
| 404 | }); |
| 405 | return yield* new SshCommandError({ |
| 406 | command: ["ssh"], |
| 407 | exitCode: null, |
| 408 | stdout: diagnosticStdout, |
| 409 | stderr, |
| 410 | message: `SSH command timed out after ${input.timeoutMs ?? DEFAULT_SSH_COMMAND_TIMEOUT_MS}ms.`, |
| 411 | }); |
| 412 | }), |
| 413 | }), |
| 414 | ), |
| 415 | ); |
| 416 | }); |
| 417 | |
| 418 | export const resolveSshTarget = Effect.fn("ssh/command.resolveSshTarget")(function* ( |
| 419 | alias: string, |
| 420 | ): Effect.fn.Return< |
| 421 | DesktopSshEnvironmentTarget, |
| 422 | SshCommandError | SshInvalidTargetError, |
| 423 | ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem | Path.Path |
| 424 | > { |
| 425 | const trimmedAlias = alias.trim(); |
| 426 | if (trimmedAlias.length === 0) { |
| 427 | return yield* new SshInvalidTargetError({ message: "SSH host alias is required." }); |
| 428 | } |
| 429 | |
| 430 | yield* Effect.logDebug("ssh.target.resolve.start", { alias: trimmedAlias }); |
| 431 | return yield* runSshCommand( |
| 432 | { |
| 433 | alias: trimmedAlias, |
| 434 | hostname: trimmedAlias, |
| 435 | username: null, |
| 436 | port: null, |
| 437 | }, |
| 438 | { preHostArgs: ["-G"] }, |
| 439 | ).pipe( |
| 440 | Effect.map((result) => parseSshResolveOutput(trimmedAlias, result.stdout)), |
| 441 | Effect.tap((target) => |
| 442 | Effect.logDebug("ssh.target.resolve.succeeded", sshTargetLogFields(target)), |
| 443 | ), |
| 444 | Effect.catch((cause) => |
| 445 | Effect.logDebug("ssh.target.resolve.fallback", { alias: trimmedAlias, cause }).pipe( |
| 446 | Effect.as({ |
| 447 | alias: trimmedAlias, |
| 448 | hostname: trimmedAlias, |
| 449 | username: null, |
| 450 | port: null, |
| 451 | }), |
| 452 | ), |
| 453 | ), |
| 454 | ); |
| 455 | }); |
| 456 | |
| 457 | /** The control path of the user's signed-in ControlMaster for `target`, or null when none is live. */ |
| 458 | export const findLiveControlPath = Effect.fn("ssh/command.findLiveControlPath")(function* ( |
| 459 | target: DesktopSshEnvironmentTarget, |
| 460 | ): Effect.fn.Return< |
| 461 | string | null, |
| 462 | never, |
| 463 | ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem | Path.Path |
| 464 | > { |
| 465 | const resolved = yield* runSshCommand(target, { preHostArgs: ["-G"] }).pipe(Effect.option); |
| 466 | const controlPath = Option.isSome(resolved) |
| 467 | ? parseSshConfigOutput(resolved.value.stdout).get("controlpath") |
| 468 | : undefined; |
| 469 | if (controlPath === undefined || controlPath === "none") { |
| 470 | return null; |
| 471 | } |
| 472 | return yield* runSshCommand(target, { |
| 473 | preHostArgs: [...controlMasterArgs(controlPath), "-O", "check"], |
| 474 | }).pipe( |
| 475 | Effect.as(controlPath), |
| 476 | Effect.orElseSucceed(() => null), |
| 477 | ); |
| 478 | }); |