Open History to see the last commit
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 Crypto from "effect/Crypto";
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 Ref from "effect/Ref";
13import * as Schema from "effect/Schema";
14
15import * as ElectronWindow from "../electron/ElectronWindow.ts";
16import { SSH_PASSWORD_PROMPT_CHANNEL } from "../ipc/channels.ts";
17
18const DEFAULT_SSH_PASSWORD_PROMPT_TIMEOUT_MS = 3 * 60 * 1000;
19
20type DesktopSshPasswordPromptResolutionInput =
21 typeof DesktopSshPasswordPromptResolutionInputSchema.Type;
22
23const DesktopSshPromptWindowAvailabilityStage = Schema.Literals([
24 "before-request",
25 "before-presentation",
26 "after-send",
27 "after-restore",
28]);
29
30const DesktopSshPromptPresentationOperation = Schema.Literals([
31 "check-window-before-request",
32 "check-window-before-presentation",
33 "register-window-close-listener",
34 "send-prompt-request",
35 "check-window-after-send",
36 "check-window-minimized",
37 "restore-window",
38 "check-window-after-restore",
39 "focus-window",
40 "remove-window-close-listener",
41]);
42type DesktopSshPromptPresentationOperation = typeof DesktopSshPromptPresentationOperation.Type;
43
44export class DesktopSshPromptRequestIdGenerationError extends Schema.TaggedError<DesktopSshPromptRequestIdGenerationError>()(
45 "DesktopSshPromptRequestIdGenerationError",
46 {
47 destination: Schema.String,
48 cause: Schema.Defect(),
49 },
50) {
51 override get message(): string {
52 return "Secure randomness is unavailable.";
53 }
54}
55
56export class DesktopSshPromptWindowUnavailableError extends Schema.TaggedError<DesktopSshPromptWindowUnavailableError>()(
57 "DesktopSshPromptWindowUnavailableError",
58 {
59 destination: Schema.String,
60 requestId: Schema.NullOr(Schema.String),
61 stage: DesktopSshPromptWindowAvailabilityStage,
62 },
63) {
64 override get message(): string {
65 const request = this.requestId === null ? "before a request id was assigned" : this.requestId;
66 return `T3 Code window is unavailable during ${this.stage} for SSH authentication to ${this.destination} (request: ${request}).`;
67 }
68}
69
70export class DesktopSshPromptPresentationError extends Schema.TaggedError<DesktopSshPromptPresentationError>()(
71 "DesktopSshPromptPresentationError",
72 {
73 requestId: Schema.NullOr(Schema.String),
74 destination: Schema.String,
75 operation: DesktopSshPromptPresentationOperation,
76 cause: Schema.Defect(),
77 },
78) {
79 override get message(): string {
80 return `Failed to present SSH password prompt for ${this.destination}.`;
81 }
82}
83
84export class DesktopSshPromptTimedOutError extends Schema.TaggedError<DesktopSshPromptTimedOutError>()(
85 "DesktopSshPromptTimedOutError",
86 {
87 requestId: Schema.String,
88 destination: Schema.String,
89 },
90) {
91 override get message(): string {
92 return `SSH authentication timed out for ${this.destination}.`;
93 }
94}
95
96export class DesktopSshPromptCancelledError extends Schema.TaggedError<DesktopSshPromptCancelledError>()(
97 "DesktopSshPromptCancelledError",
98 {
99 requestId: Schema.String,
100 destination: Schema.String,
101 },
102) {
103 override get message(): string {
104 return `SSH authentication cancelled for ${this.destination}.`;
105 }
106}
107
108export class DesktopSshPromptWindowClosedError extends Schema.TaggedError<DesktopSshPromptWindowClosedError>()(
109 "DesktopSshPromptWindowClosedError",
110 {
111 requestId: Schema.String,
112 destination: Schema.String,
113 },
114) {
115 override get message(): string {
116 return "SSH authentication was cancelled because the app window closed.";
117 }
118}
119
120export class DesktopSshPromptServiceStoppedError extends Schema.TaggedError<DesktopSshPromptServiceStoppedError>()(
121 "DesktopSshPromptServiceStoppedError",
122 {
123 requestId: Schema.String,
124 destination: Schema.String,
125 },
126) {
127 override get message(): string {
128 return "SSH password prompt service stopped.";
129 }
130}
131
132export class DesktopSshPromptInvalidRequestIdError extends Schema.TaggedError<DesktopSshPromptInvalidRequestIdError>()(
133 "DesktopSshPromptInvalidRequestIdError",
134 {
135 requestId: Schema.String,
136 },
137) {
138 override get message(): string {
139 return "Invalid SSH password prompt id.";
140 }
141}
142
143export class DesktopSshPromptExpiredError extends Schema.TaggedError<DesktopSshPromptExpiredError>()(
144 "DesktopSshPromptExpiredError",
145 {
146 requestId: Schema.String,
147 },
148) {
149 override get message(): string {
150 return "SSH password prompt expired. Try connecting again.";
151 }
152}
153
154export type DesktopSshPasswordPromptRequestError =
155 | DesktopSshPromptRequestIdGenerationError
156 | DesktopSshPromptWindowUnavailableError
157 | DesktopSshPromptPresentationError
158 | DesktopSshPromptTimedOutError
159 | DesktopSshPromptCancelledError
160 | DesktopSshPromptWindowClosedError
161 | DesktopSshPromptServiceStoppedError;
162
163export type DesktopSshPasswordPromptResolveError =
164 | DesktopSshPromptInvalidRequestIdError
165 | DesktopSshPromptExpiredError;
166
167export type DesktopSshPasswordPromptError =
168 | DesktopSshPasswordPromptRequestError
169 | DesktopSshPasswordPromptResolveError;
170
171export const DesktopSshPasswordPromptCancellation = Schema.Union([
172 DesktopSshPromptCancelledError,
173 DesktopSshPromptWindowClosedError,
174 DesktopSshPromptServiceStoppedError,
175 DesktopSshPromptTimedOutError,
176]);
177export type DesktopSshPasswordPromptCancellation = typeof DesktopSshPasswordPromptCancellation.Type;
178
179export const isDesktopSshPasswordPromptCancellation = Schema.is(
180 DesktopSshPasswordPromptCancellation,
181);
182
183export class DesktopSshPasswordPrompts extends Context.Service<
184 DesktopSshPasswordPrompts,
185 {
186 readonly request: (
187 request: SshPasswordRequest,
188 ) => Effect.Effect<string, DesktopSshPasswordPromptRequestError>;
189 readonly resolve: (
190 input: DesktopSshPasswordPromptResolutionInput,
191 ) => Effect.Effect<void, DesktopSshPasswordPromptResolveError>;
192 }
193>()("@t3tools/desktop/ssh/DesktopSshPasswordPrompts") {}
194
195interface PendingSshPasswordPrompt {
196 readonly requestId: string;
197 readonly destination: string;
198 readonly deferred: Deferred.Deferred<string, DesktopSshPasswordPromptRequestError>;
199}
200
201export interface DesktopSshPasswordPromptsOptions {
202 readonly passwordPromptTimeoutMs?: number;
203}
204
205const removePending = (
206 pendingRef: Ref.Ref<Map<string, PendingSshPasswordPrompt>>,
207 requestId: string,
208) =>
209 Ref.modify(pendingRef, (pending) => {
210 const entry = pending.get(requestId);
211 if (entry === undefined) {
212 return [Option.none<PendingSshPasswordPrompt>(), pending] as const;
213 }
214
215 const nextPending = new Map(pending);
216 nextPending.delete(requestId);
217 return [Option.some(entry), nextPending] as const;
218 });
219
220const failPending = (
221 pending: PendingSshPasswordPrompt,
222 error: DesktopSshPasswordPromptRequestError,
223) => Deferred.fail(pending.deferred, error).pipe(Effect.asVoid);
224
225/** @public Service construction is part of the canonical Effect module API. */
226export const make = Effect.fn("desktop.sshPasswordPrompts.make")(function* (
227 options: DesktopSshPasswordPromptsOptions = {},
228) {
229 const electronWindow = yield* ElectronWindow.ElectronWindow;
230 const crypto = yield* Crypto.Crypto;
231 const pendingRef = yield* Ref.make(new Map<string, PendingSshPasswordPrompt>());
232 const passwordPromptTimeoutMs =
233 options.passwordPromptTimeoutMs ?? DEFAULT_SSH_PASSWORD_PROMPT_TIMEOUT_MS;
234
235 const cancelPending = () =>
236 Ref.getAndSet(pendingRef, new Map()).pipe(
237 Effect.flatMap((pending) =>
238 Effect.forEach(
239 pending.values(),
240 (entry) =>
241 failPending(
242 entry,
243 new DesktopSshPromptServiceStoppedError({
244 requestId: entry.requestId,
245 destination: entry.destination,
246 }),
247 ),
248 { discard: true },
249 ),
250 ),
251 Effect.asVoid,
252 );
253
254 yield* Effect.addFinalizer(() => cancelPending().pipe(Effect.ignore));
255
256 const resolve: DesktopSshPasswordPrompts["Service"]["resolve"] = Effect.fn(
257 "desktop.sshPasswordPrompts.resolve",
258 )(function* (input) {
259 const requestId = input.requestId.trim();
260 if (requestId.length === 0) {
261 return yield* new DesktopSshPromptInvalidRequestIdError({ requestId: input.requestId });
262 }
263
264 const pending = yield* removePending(pendingRef, requestId);
265 if (Option.isNone(pending)) {
266 return yield* new DesktopSshPromptExpiredError({ requestId });
267 }
268
269 const entry = pending.value;
270 if (input.password === null) {
271 yield* failPending(
272 entry,
273 new DesktopSshPromptCancelledError({
274 requestId,
275 destination: entry.destination,
276 }),
277 );
278 return;
279 }
280
281 yield* Deferred.succeed(entry.deferred, input.password).pipe(Effect.asVoid);
282 });
283
284 const request: DesktopSshPasswordPrompts["Service"]["request"] = Effect.fn(
285 "desktop.sshPasswordPrompts.request",
286 )(function* (input) {
287 const window = yield* electronWindow.main;
288 if (Option.isNone(window)) {
289 return yield* new DesktopSshPromptWindowUnavailableError({
290 destination: input.destination,
291 requestId: null,
292 stage: "before-request",
293 });
294 }
295
296 const unavailableBeforeRequest = yield* Effect.try({
297 try: () => window.value.isDestroyed(),
298 catch: (cause) =>
299 new DesktopSshPromptPresentationError({
300 requestId: null,
301 destination: input.destination,
302 operation: "check-window-before-request",
303 cause,
304 }),
305 });
306 if (unavailableBeforeRequest) {
307 return yield* new DesktopSshPromptWindowUnavailableError({
308 destination: input.destination,
309 requestId: null,
310 stage: "before-request",
311 });
312 }
313
314 const requestId = yield* crypto.randomUUIDv4.pipe(
315 Effect.mapError(
316 (cause) =>
317 new DesktopSshPromptRequestIdGenerationError({
318 destination: input.destination,
319 cause,
320 }),
321 ),
322 );
323 const now = yield* DateTime.now;
324 const expiresAt = DateTime.formatIso(
325 DateTime.add(now, { milliseconds: passwordPromptTimeoutMs }),
326 );
327 const promptRequest: DesktopSshPasswordPromptRequest = {
328 requestId,
329 destination: input.destination,
330 username: input.username,
331 prompt: input.prompt,
332 expiresAt,
333 };
334 const deferred = yield* Deferred.make<string, DesktopSshPasswordPromptRequestError>();
335 const pending: PendingSshPasswordPrompt = {
336 requestId,
337 destination: input.destination,
338 deferred,
339 };
340 yield* Ref.update(pendingRef, (entries) => new Map(entries).set(requestId, pending));
341
342 const context = yield* Effect.context();
343 const runFork = Effect.runForkWith(context);
344
345 const cancelOnWindowClosed = () => {
346 runFork(
347 removePending(pendingRef, requestId).pipe(
348 Effect.flatMap((entry) =>
349 Option.match(entry, {
350 onNone: () => Effect.void,
351 onSome: (pending) =>
352 failPending(
353 pending,
354 new DesktopSshPromptWindowClosedError({
355 requestId,
356 destination: input.destination,
357 }),
358 ),
359 }),
360 ),
361 ),
362 );
363 };
364 const runPresentationOperation = <A>(
365 operation: DesktopSshPromptPresentationOperation,
366 evaluate: () => A,
367 ) =>
368 Effect.try({
369 try: evaluate,
370 catch: (cause) =>
371 new DesktopSshPromptPresentationError({
372 requestId,
373 destination: input.destination,
374 operation,
375 cause,
376 }),
377 });
378 const cleanup = runPresentationOperation("remove-window-close-listener", () => {
379 if (!window.value.isDestroyed()) {
380 window.value.removeListener("closed", cancelOnWindowClosed);
381 }
382 }).pipe(Effect.orDie, Effect.ensuring(removePending(pendingRef, requestId)), Effect.asVoid);
383 const waitForPassword = Deferred.await(deferred).pipe(
384 Effect.timeoutOption(Duration.millis(passwordPromptTimeoutMs)),
385 Effect.flatMap(
386 Option.match({
387 onNone: () =>
388 Effect.fail(
389 new DesktopSshPromptTimedOutError({
390 requestId,
391 destination: input.destination,
392 }),
393 ),
394 onSome: Effect.succeed,
395 }),
396 ),
397 );
398 const preferSubmittedPassword = (error: DesktopSshPasswordPromptRequestError) =>
399 Deferred.poll(deferred).pipe(
400 Effect.flatMap(
401 Option.match({
402 onSome: (completion) => completion,
403 onNone: () =>
404 Ref.get(pendingRef).pipe(
405 Effect.flatMap((entries) =>
406 entries.has(requestId) ? Effect.fail(error) : Deferred.await(deferred),
407 ),
408 ),
409 }),
410 ),
411 );
412
413 return yield* Effect.gen(function* () {
414 const unavailableBeforePresentation = yield* runPresentationOperation(
415 "check-window-before-presentation",
416 () => window.value.isDestroyed(),
417 );
418 if (unavailableBeforePresentation) {
419 return yield* new DesktopSshPromptWindowUnavailableError({
420 destination: input.destination,
421 requestId,
422 stage: "before-presentation",
423 });
424 }
425 yield* runPresentationOperation("register-window-close-listener", () =>
426 window.value.once("closed", cancelOnWindowClosed),
427 );
428 return yield* Effect.gen(function* () {
429 yield* runPresentationOperation("send-prompt-request", () =>
430 window.value.webContents.send(SSH_PASSWORD_PROMPT_CHANNEL, promptRequest),
431 );
432 yield* Effect.yieldNow;
433 const unavailableAfterSend = yield* runPresentationOperation(
434 "check-window-after-send",
435 () => window.value.isDestroyed(),
436 );
437 if (unavailableAfterSend) {
438 return yield* new DesktopSshPromptWindowUnavailableError({
439 destination: input.destination,
440 requestId,
441 stage: "after-send",
442 });
443 }
444 const minimized = yield* runPresentationOperation("check-window-minimized", () =>
445 window.value.isMinimized(),
446 );
447 if (minimized) {
448 yield* runPresentationOperation("restore-window", () => window.value.restore());
449 }
450 const unavailableAfterRestore = yield* runPresentationOperation(
451 "check-window-after-restore",
452 () => window.value.isDestroyed(),
453 );
454 if (unavailableAfterRestore) {
455 return yield* new DesktopSshPromptWindowUnavailableError({
456 destination: input.destination,
457 requestId,
458 stage: "after-restore",
459 });
460 }
461 yield* runPresentationOperation("focus-window", () => window.value.focus());
462 return yield* waitForPassword;
463 }).pipe(Effect.catch(preferSubmittedPassword));
464 }).pipe(Effect.ensuring(cleanup));
465 });
466
467 return DesktopSshPasswordPrompts.of({
468 request,
469 resolve,
470 });
471});
472
473export const layer = (options: DesktopSshPasswordPromptsOptions = {}) =>
474 Layer.effect(DesktopSshPasswordPrompts, make(options));