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

DesktopSshPasswordPrompts.ts

332 lines10.3 KB

1import type { DesktopSshPasswordPromptRequest } from "@t3tools/contracts";
2import { DesktopSshPasswordPromptResolutionInputSchema } from "@t3tools/contracts";
3import type { SshPasswordRequest } from "@t3tools/ssh/auth";
4import * as Context from "effect/Context";
5import * as Data from "effect/Data";
6import * as DateTime from "effect/DateTime";
7import * as Deferred from "effect/Deferred";
8import * as Duration from "effect/Duration";
9import * as Effect from "effect/Effect";
10import * as Layer from "effect/Layer";
11import * as Option from "effect/Option";
12import * as Random from "effect/Random";
13import * as Ref from "effect/Ref";
14​
15import * as IpcChannels from "../ipc/channels.ts";
16import * as ElectronWindow from "../electron/ElectronWindow.ts";
17​
18const DEFAULT_SSH_PASSWORD_PROMPT_TIMEOUT_MS = 3 * 60 * 1000;
19const WINDOW_UNAVAILABLE_MESSAGE = "T3 Code window is not available for SSH authentication.";
20​
21type DesktopSshPasswordPromptResolutionInput =
22 typeof DesktopSshPasswordPromptResolutionInputSchema.Type;
23​
24export class DesktopSshPromptUnavailableError extends Data.TaggedError(
25 "DesktopSshPromptUnavailableError",
26)<{
27 readonly reason: string;
28}> {
29 override get message() {
30 return this.reason;
31 }
33​
34export class DesktopSshPromptWindowUnavailableError extends Data.TaggedError(
35 "DesktopSshPromptWindowUnavailableError",
36)<{
37 readonly destination: string;
38}> {
39 override get message() {
40 return WINDOW_UNAVAILABLE_MESSAGE;
41 }
43​
44export class DesktopSshPromptSendError extends Data.TaggedError("DesktopSshPromptSendError")<{
45 readonly requestId: string;
46 readonly destination: string;
47 readonly cause: unknown;
48}> {
49 override get message() {
50 return WINDOW_UNAVAILABLE_MESSAGE;
51 }
53​
54export class DesktopSshPromptTimedOutError extends Data.TaggedError(
55 "DesktopSshPromptTimedOutError",
56)<{
57 readonly requestId: string;
58 readonly destination: string;
59}> {
60 override get message() {
61 return `SSH authentication timed out for ${this.destination}.`;
62 }
64​
65export class DesktopSshPromptCancelledError extends Data.TaggedError(
66 "DesktopSshPromptCancelledError",
67)<{
68 readonly requestId: string;
69 readonly destination: string;
70 readonly reason: string;
71}> {
72 override get message() {
73 return this.reason;
74 }
76​
77export class DesktopSshPromptInvalidRequestIdError extends Data.TaggedError(
78 "DesktopSshPromptInvalidRequestIdError",
79)<{
80 readonly requestId: string;
81}> {
82 override get message() {
83 return "Invalid SSH password prompt id.";
84 }
86​
87export class DesktopSshPromptExpiredError extends Data.TaggedError("DesktopSshPromptExpiredError")<{
88 readonly requestId: string;
89}> {
90 override get message() {
91 return "SSH password prompt expired. Try connecting again.";
92 }
94​
95export type DesktopSshPasswordPromptRequestError =
96 | DesktopSshPromptUnavailableError
97 | DesktopSshPromptWindowUnavailableError
98 | DesktopSshPromptSendError
99 | DesktopSshPromptTimedOutError
100 | DesktopSshPromptCancelledError;
101​
102export type DesktopSshPasswordPromptResolveError =
103 | DesktopSshPromptInvalidRequestIdError
104 | DesktopSshPromptExpiredError;
105​
106export type DesktopSshPasswordPromptError =
107 | DesktopSshPasswordPromptRequestError
108 | DesktopSshPasswordPromptResolveError;
109​
110export function isDesktopSshPasswordPromptCancellation(
111 error: unknown,
112): error is DesktopSshPromptCancelledError | DesktopSshPromptTimedOutError {
113 return (
114 error instanceof DesktopSshPromptCancelledError ||
115 error instanceof DesktopSshPromptTimedOutError
116 );
118​
119export interface DesktopSshPasswordPromptsShape {
120 readonly request: (
121 request: SshPasswordRequest,
122 ) => Effect.Effect<string, DesktopSshPasswordPromptRequestError>;
123 readonly resolve: (
124 input: DesktopSshPasswordPromptResolutionInput,
125 ) => Effect.Effect<void, DesktopSshPasswordPromptResolveError>;
126 readonly cancelPending: (reason: string) => Effect.Effect<void>;
128​
129export class DesktopSshPasswordPrompts extends Context.Service<
130 DesktopSshPasswordPrompts,
131 DesktopSshPasswordPromptsShape
132>()("t3/desktop/SshPasswordPrompts") {}
133​
134interface PendingSshPasswordPrompt {
135 readonly requestId: string;
136 readonly destination: string;
137 readonly deferred: Deferred.Deferred<string, DesktopSshPasswordPromptRequestError>;
139​
140interface LayerOptions {
141 readonly passwordPromptTimeoutMs?: number;
143​
144const removePending = (
145 pendingRef: Ref.Ref<Map<string, PendingSshPasswordPrompt>>,
146 requestId: string,
147) =>
148 Ref.modify(pendingRef, (pending) => {
149 const entry = pending.get(requestId);
150 if (entry === undefined) {
151 return [Option.none<PendingSshPasswordPrompt>(), pending] as const;
152 }
153​
154 const nextPending = new Map(pending);
155 nextPending.delete(requestId);
156 return [Option.some(entry), nextPending] as const;
157 });
158​
159const failPending = (
160 pending: PendingSshPasswordPrompt,
161 error: DesktopSshPasswordPromptRequestError,
162) => Deferred.fail(pending.deferred, error).pipe(Effect.asVoid);
163​
164const make = Effect.fn("desktop.sshPasswordPrompts.make")(function* (options: LayerOptions = {}) {
165 const electronWindow = yield* ElectronWindow.ElectronWindow;
166 const pendingRef = yield* Ref.make(new Map<string, PendingSshPasswordPrompt>());
167 const passwordPromptTimeoutMs =
168 options.passwordPromptTimeoutMs ?? DEFAULT_SSH_PASSWORD_PROMPT_TIMEOUT_MS;
169​
170 const cancelPending = (reason: string): Effect.Effect<void> =>
171 Ref.getAndSet(pendingRef, new Map()).pipe(
172 Effect.flatMap((pending) =>
173 Effect.forEach(
174 pending.values(),
175 (entry) =>
176 failPending(
177 entry,
178 new DesktopSshPromptCancelledError({
179 requestId: entry.requestId,
180 destination: entry.destination,
181 reason,
182 }),
183 ),
184 { discard: true },
185 ),
186 ),
187 Effect.asVoid,
188 );
189​
190 yield* Effect.addFinalizer(() =>
191 cancelPending("SSH password prompt service stopped.").pipe(Effect.ignore),
192 );
193​
194 const resolve = Effect.fn("desktop.sshPasswordPrompts.resolve")(function* (
195 input: DesktopSshPasswordPromptResolutionInput,
196 ): Effect.fn.Return<void, DesktopSshPasswordPromptResolveError> {
197 const requestId = input.requestId.trim();
198 if (requestId.length === 0) {
199 return yield* new DesktopSshPromptInvalidRequestIdError({ requestId: input.requestId });
200 }
201​
202 const pending = yield* removePending(pendingRef, requestId);
203 if (Option.isNone(pending)) {
204 return yield* new DesktopSshPromptExpiredError({ requestId });
205 }
206​
207 const entry = pending.value;
208 if (input.password === null) {
209 yield* failPending(
210 entry,
211 new DesktopSshPromptCancelledError({
212 requestId,
213 destination: entry.destination,
214 reason: `SSH authentication cancelled for ${entry.destination}.`,
215 }),
216 );
217 return;
218 }
219​
220 yield* Deferred.succeed(entry.deferred, input.password).pipe(Effect.asVoid);
221 });
222​
223 const request = Effect.fn("desktop.sshPasswordPrompts.request")(function* (
224 input: SshPasswordRequest,
225 ): Effect.fn.Return<string, DesktopSshPasswordPromptRequestError> {
226 const window = yield* electronWindow.main;
227 if (Option.isNone(window) || window.value.isDestroyed()) {
228 return yield* new DesktopSshPromptWindowUnavailableError({
229 destination: input.destination,
230 });
231 }
232​
233 const requestId = yield* Random.nextUUIDv4;
234 const now = yield* DateTime.now;
235 const expiresAt = DateTime.formatIso(
236 DateTime.add(now, { milliseconds: passwordPromptTimeoutMs }),
237 );
238 const promptRequest: DesktopSshPasswordPromptRequest = {
239 requestId,
240 destination: input.destination,
241 username: input.username,
242 prompt: input.prompt,
243 expiresAt,
244 };
245 const deferred = yield* Deferred.make<string, DesktopSshPasswordPromptRequestError>();
246 const pending: PendingSshPasswordPrompt = {
247 requestId,
248 destination: input.destination,
249 deferred,
250 };
251 yield* Ref.update(pendingRef, (entries) => new Map(entries).set(requestId, pending));
252​
253 const context = yield* Effect.context();
254 const runFork = Effect.runForkWith(context);
255​
256 const cancelOnWindowClosed = () => {
257 runFork(
258 removePending(pendingRef, requestId).pipe(
259 Effect.flatMap((entry) =>
260 Option.match(entry, {
261 onNone: () => Effect.void,
262 onSome: (pending) =>
263 failPending(
264 pending,
265 new DesktopSshPromptCancelledError({
266 requestId,
267 destination: input.destination,
268 reason: "SSH authentication was cancelled because the app window closed.",
269 }),
270 ),
271 }),
272 ),
273 ),
274 );
275 };
276 const cleanup = Effect.sync(() => {
277 if (!window.value.isDestroyed()) {
278 window.value.removeListener("closed", cancelOnWindowClosed);
279 }
280 }).pipe(Effect.andThen(removePending(pendingRef, requestId)), Effect.asVoid);
281 const waitForPassword = Deferred.await(deferred).pipe(
282 Effect.timeoutOption(Duration.millis(passwordPromptTimeoutMs)),
283 Effect.flatMap(
284 Option.match({
285 onNone: () =>
286 Effect.fail(
287 new DesktopSshPromptTimedOutError({
288 requestId,
289 destination: input.destination,
290 }),
291 ),
292 onSome: Effect.succeed,
293 }),
294 ),
295 );
296​
297 return yield* Effect.try({
298 try: () => {
299 if (window.value.isDestroyed()) {
300 throw new Error(WINDOW_UNAVAILABLE_MESSAGE);
301 }
302 window.value.once("closed", cancelOnWindowClosed);
303 window.value.webContents.send(IpcChannels.SSH_PASSWORD_PROMPT_CHANNEL, promptRequest);
304 if (window.value.isDestroyed()) {
305 throw new Error(WINDOW_UNAVAILABLE_MESSAGE);
306 }
307 if (window.value.isMinimized()) {
308 window.value.restore();
309 }
310 if (window.value.isDestroyed()) {
311 throw new Error(WINDOW_UNAVAILABLE_MESSAGE);
312 }
313 window.value.focus();
314 },
315 catch: (cause) =>
316 new DesktopSshPromptSendError({
317 requestId,
318 destination: input.destination,
319 cause,
320 }),
321 }).pipe(Effect.andThen(waitForPassword), Effect.ensuring(cleanup));
322 });
323​
324 return DesktopSshPasswordPrompts.of({
325 request,
326 resolve,
327 cancelPending,
328 });
329});
330​
331export const layer = (options: LayerOptions = {}) =>
332 Layer.effect(DesktopSshPasswordPrompts, make(options));