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