The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import type { |
| 2 | DesktopDiscoveredSshHost, |
| 3 | DesktopSshEnvironmentBootstrap, |
| 4 | DesktopSshEnvironmentTarget, |
| 5 | } from "@t3tools/contracts"; |
| 6 | import { CLI_RELEASE_BASE_URL_ENV } from "@t3tools/shared/cliRelease"; |
| 7 | import * as NetService from "@t3tools/shared/Net"; |
| 8 | import * as SshAuth from "@t3tools/ssh/auth"; |
| 9 | import { resolveSshTarget } from "@t3tools/ssh/command"; |
| 10 | import { discoverSshHosts } from "@t3tools/ssh/config"; |
| 11 | import { |
| 12 | SshCommandError, |
| 13 | SshHostDiscoveryError, |
| 14 | SshInvalidTargetError, |
| 15 | SshLaunchError, |
| 16 | SshPairingError, |
| 17 | SshPasswordPromptError, |
| 18 | SshReadinessError, |
| 19 | } from "@t3tools/ssh/errors"; |
| 20 | import * as SshTunnel from "@t3tools/ssh/tunnel"; |
| 21 | import * as Context from "effect/Context"; |
| 22 | import type * as Digest from "effect/crypto/Digest"; |
| 23 | import * as SecureRandom from "effect/crypto/SecureRandom"; |
| 24 | import * as Effect from "effect/Effect"; |
| 25 | import * as FileSystem from "effect/FileSystem"; |
| 26 | import * as Layer from "effect/Layer"; |
| 27 | import * as Path from "effect/Path"; |
| 28 | import * as Schema from "effect/Schema"; |
| 29 | import * as HttpClient from "effect/http/HttpClient"; |
| 30 | import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner"; |
| 31 | import * as Option from "effect/Option"; |
| 32 | import serverPackageJson from "../../../server/package.json" with { type: "json" }; |
| 33 | |
| 34 | import type * as DesktopEnvironment from "../app/DesktopEnvironment.ts"; |
| 35 | |
| 36 | import * as DesktopSshPasswordPrompts from "./DesktopSshPasswordPrompts.ts"; |
| 37 | |
| 38 | export type DesktopSshEnvironmentRuntimeServices = |
| 39 | | ChildProcessSpawner.ChildProcessSpawner |
| 40 | | Digest.Digest |
| 41 | | FileSystem.FileSystem |
| 42 | | Path.Path |
| 43 | | HttpClient.HttpClient |
| 44 | | NetService.NetService; |
| 45 | |
| 46 | export type DesktopSshEnvironmentOperationError = |
| 47 | | SshCommandError |
| 48 | | SshInvalidTargetError |
| 49 | | SshLaunchError |
| 50 | | SshPairingError |
| 51 | | SshReadinessError |
| 52 | | SshPasswordPromptError |
| 53 | | NetService.NetError; |
| 54 | |
| 55 | export type DesktopSshEnvironmentDiscoverError = SshHostDiscoveryError; |
| 56 | |
| 57 | export class DesktopSshEnvironment extends Context.Service< |
| 58 | DesktopSshEnvironment, |
| 59 | { |
| 60 | readonly discoverHosts: (input?: { |
| 61 | readonly homeDir?: string; |
| 62 | }) => Effect.Effect<readonly DesktopDiscoveredSshHost[], DesktopSshEnvironmentDiscoverError>; |
| 63 | readonly resolveHost: ( |
| 64 | alias: string, |
| 65 | ) => Effect.Effect<DesktopSshEnvironmentTarget, SshCommandError | SshInvalidTargetError>; |
| 66 | readonly ensureEnvironment: ( |
| 67 | target: DesktopSshEnvironmentTarget, |
| 68 | options?: { readonly issuePairingToken?: boolean }, |
| 69 | ) => Effect.Effect<DesktopSshEnvironmentBootstrap, DesktopSshEnvironmentOperationError>; |
| 70 | readonly disconnectEnvironment: ( |
| 71 | target: DesktopSshEnvironmentTarget, |
| 72 | ) => Effect.Effect<void, DesktopSshEnvironmentOperationError>; |
| 73 | readonly closeAllTunnels: Effect.Effect<void>; |
| 74 | } |
| 75 | >()("@t3tools/desktop/ssh/DesktopSshEnvironment") {} |
| 76 | |
| 77 | export interface DesktopSshEnvironmentLayerOptions { |
| 78 | readonly resolveCliRunner?: Effect.Effect<SshTunnel.RemoteT3RunnerOptions>; |
| 79 | readonly resolveLauncherId?: Effect.Effect<string | null>; |
| 80 | } |
| 81 | |
| 82 | export const resolveDesktopSshCliRunner = ( |
| 83 | environment: DesktopEnvironment.DesktopEnvironment["Service"], |
| 84 | env: NodeJS.ProcessEnv, |
| 85 | ): SshTunnel.RemoteT3RunnerOptions => { |
| 86 | const devRemoteEntryPath = Option.getOrUndefined(environment.devRemoteT3ServerEntryPath); |
| 87 | if (environment.isDevelopment && devRemoteEntryPath !== undefined) { |
| 88 | return { |
| 89 | nodeScriptPath: devRemoteEntryPath, |
| 90 | nodeEngineRange: serverPackageJson.engines.node, |
| 91 | }; |
| 92 | } |
| 93 | const releaseBaseUrl = env[CLI_RELEASE_BASE_URL_ENV]?.trim() || undefined; |
| 94 | return { |
| 95 | archiveVersion: environment.appVersion, |
| 96 | ...(releaseBaseUrl === undefined ? {} : { releaseBaseUrl }), |
| 97 | }; |
| 98 | }; |
| 99 | |
| 100 | // Remote servers record this ID as their owner, so it has to outlive restarts, |
| 101 | // updates and edits to a saved connection. Without a stored one there is none. |
| 102 | export const readOrCreateLauncherId = Effect.fn("desktop.ssh.readOrCreateLauncherId")( |
| 103 | function* (filePath: string) { |
| 104 | const fileSystem = yield* FileSystem.FileSystem; |
| 105 | const random = yield* SecureRandom.SecureRandom; |
| 106 | // Any other read failure may hide a stored ID, which a new one would overwrite. |
| 107 | const stored = yield* fileSystem.readFileString(filePath).pipe( |
| 108 | Effect.catchIf( |
| 109 | (cause) => cause.reason._tag === "NotFound", |
| 110 | () => Effect.succeed(""), |
| 111 | ), |
| 112 | ); |
| 113 | if (/^[0-9a-f]{32}$/u.test(stored.trim())) return stored.trim(); |
| 114 | const launcherId = (yield* random.uuidV4()).replace(/-/g, ""); |
| 115 | yield* fileSystem.writeFileString(filePath, `${launcherId}\n`); |
| 116 | return launcherId; |
| 117 | }, |
| 118 | Effect.orElseSucceed(() => null), |
| 119 | ); |
| 120 | |
| 121 | function discoverDesktopSshHostsEffect(input?: { readonly homeDir?: string }) { |
| 122 | return discoverSshHosts(input ?? {}); |
| 123 | } |
| 124 | |
| 125 | const isSshPasswordPromptError = Schema.is(SshPasswordPromptError); |
| 126 | |
| 127 | export function isDesktopSshPasswordPromptCancellation( |
| 128 | error: unknown, |
| 129 | ): error is SshPasswordPromptError { |
| 130 | return ( |
| 131 | isSshPasswordPromptError(error) && |
| 132 | DesktopSshPasswordPrompts.isDesktopSshPasswordPromptCancellation(error.cause) |
| 133 | ); |
| 134 | } |
| 135 | |
| 136 | function unexpectedPasswordPromptError(error: never): never { |
| 137 | throw new Error(`Unhandled desktop SSH password prompt error: ${String(error)}`); |
| 138 | } |
| 139 | |
| 140 | function toSshPasswordPromptError( |
| 141 | cause: DesktopSshPasswordPrompts.DesktopSshPasswordPromptRequestError, |
| 142 | ): SshPasswordPromptError { |
| 143 | let message: string; |
| 144 | switch (cause._tag) { |
| 145 | case "DesktopSshPromptRequestIdGenerationError": |
| 146 | message = "Secure randomness is unavailable."; |
| 147 | break; |
| 148 | case "DesktopSshPromptWindowUnavailableError": |
| 149 | case "DesktopSshPromptPresentationError": |
| 150 | message = "T3 Code window is not available for SSH authentication."; |
| 151 | break; |
| 152 | case "DesktopSshPromptTimedOutError": |
| 153 | message = `SSH authentication timed out for ${cause.destination}.`; |
| 154 | break; |
| 155 | case "DesktopSshPromptCancelledError": |
| 156 | message = `SSH authentication cancelled for ${cause.destination}.`; |
| 157 | break; |
| 158 | case "DesktopSshPromptWindowClosedError": |
| 159 | message = "SSH authentication was cancelled because the app window closed."; |
| 160 | break; |
| 161 | case "DesktopSshPromptServiceStoppedError": |
| 162 | message = "SSH password prompt service stopped."; |
| 163 | break; |
| 164 | default: |
| 165 | return unexpectedPasswordPromptError(cause); |
| 166 | } |
| 167 | return new SshPasswordPromptError({ message, cause }); |
| 168 | } |
| 169 | |
| 170 | const makePasswordPrompt = ( |
| 171 | prompts: DesktopSshPasswordPrompts.DesktopSshPasswordPrompts["Service"], |
| 172 | ): SshAuth.SshPasswordPrompt["Service"] => ({ |
| 173 | isAvailable: true, |
| 174 | request: (request: SshAuth.SshPasswordRequest) => |
| 175 | prompts.request(request).pipe(Effect.mapError(toSshPasswordPromptError)), |
| 176 | }); |
| 177 | |
| 178 | /** @public */ |
| 179 | export const make = Effect.gen(function* () { |
| 180 | const manager = yield* SshTunnel.SshEnvironmentManager; |
| 181 | const prompts = yield* DesktopSshPasswordPrompts.DesktopSshPasswordPrompts; |
| 182 | const runtimeContext = yield* Effect.context<DesktopSshEnvironmentRuntimeServices>(); |
| 183 | const passwordPrompt = SshAuth.SshPasswordPrompt.of(makePasswordPrompt(prompts)); |
| 184 | |
| 185 | return DesktopSshEnvironment.of({ |
| 186 | discoverHosts: Effect.fn("desktop.ssh.discoverHosts")(function* (input) { |
| 187 | return yield* discoverDesktopSshHostsEffect(input); |
| 188 | }, Effect.provide(runtimeContext)), |
| 189 | resolveHost: Effect.fn("desktop.ssh.resolveHost")(function* (alias) { |
| 190 | return yield* resolveSshTarget(alias.trim()); |
| 191 | }, Effect.provide(runtimeContext)), |
| 192 | ensureEnvironment: Effect.fn("desktop.ssh.ensureEnvironment")( |
| 193 | function* (target, ensureOptions) { |
| 194 | return yield* manager.ensureEnvironment(target, ensureOptions); |
| 195 | }, |
| 196 | Effect.provideService(SshAuth.SshPasswordPrompt, passwordPrompt), |
| 197 | Effect.provide(runtimeContext), |
| 198 | ), |
| 199 | disconnectEnvironment: Effect.fn("desktop.ssh.disconnectEnvironment")( |
| 200 | function* (target) { |
| 201 | return yield* manager.disconnectEnvironment(target); |
| 202 | }, |
| 203 | Effect.provideService(SshAuth.SshPasswordPrompt, passwordPrompt), |
| 204 | Effect.provide(runtimeContext), |
| 205 | ), |
| 206 | closeAllTunnels: manager.closeAllTunnels, |
| 207 | }); |
| 208 | }); |
| 209 | |
| 210 | export const layer = (options: DesktopSshEnvironmentLayerOptions = {}) => |
| 211 | Layer.effect(DesktopSshEnvironment, make).pipe( |
| 212 | Layer.provide( |
| 213 | SshTunnel.SshEnvironmentManager.layer({ |
| 214 | ...(options.resolveCliRunner === undefined |
| 215 | ? {} |
| 216 | : { resolveCliRunner: options.resolveCliRunner }), |
| 217 | ...(options.resolveLauncherId === undefined |
| 218 | ? {} |
| 219 | : { resolveLauncherId: options.resolveLauncherId }), |
| 220 | }), |
| 221 | ), |
| 222 | ); |