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

DesktopSshPasswordPrompts.ts

473 lines15.1 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 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.TaggedErrorClass<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 }
55​
56export class DesktopSshPromptWindowUnavailableError extends Schema.TaggedErrorClass<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 }
69​
70export class DesktopSshPromptPresentationError extends Schema.TaggedErrorClass<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 }
83​
84export class DesktopSshPromptTimedOutError extends Schema.TaggedErrorClass<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 }
95​
96export class DesktopSshPromptCancelledError extends Schema.TaggedErrorClass<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 }
107​
108export class DesktopSshPromptWindowClosedError extends Schema.TaggedErrorClass<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 }
119​
120export class DesktopSshPromptServiceStoppedError extends Schema.TaggedErrorClass<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 }
131​
132export class DesktopSshPromptInvalidRequestIdError extends Schema.TaggedErrorClass<DesktopSshPromptInvalidRequestIdError>()(
133 "DesktopSshPromptInvalidRequestIdError",
134 {
135 requestId: Schema.String,
136 },
137) {
138 override get message(): string {
139 return "Invalid SSH password prompt id.";
140 }
142​
143export class DesktopSshPromptExpiredError extends Schema.TaggedErrorClass<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 }
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>;
200​
201export interface DesktopSshPasswordPromptsOptions {
202 readonly passwordPromptTimeoutMs?: number;
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​
225export const make = Effect.fn("desktop.sshPasswordPrompts.make")(function* (
226 options: DesktopSshPasswordPromptsOptions = {},
227) {
228 const electronWindow = yield* ElectronWindow.ElectronWindow;
229 const crypto = yield* Crypto.Crypto;
230 const pendingRef = yield* Ref.make(new Map<string, PendingSshPasswordPrompt>());
231 const passwordPromptTimeoutMs =
232 options.passwordPromptTimeoutMs ?? DEFAULT_SSH_PASSWORD_PROMPT_TIMEOUT_MS;
233​
234 const cancelPending = () =>
235 Ref.getAndSet(pendingRef, new Map()).pipe(
236 Effect.flatMap((pending) =>
237 Effect.forEach(
238 pending.values(),
239 (entry) =>
240 failPending(
241 entry,
242 new DesktopSshPromptServiceStoppedError({
243 requestId: entry.requestId,
244 destination: entry.destination,
245 }),
246 ),
247 { discard: true },
248 ),
249 ),
250 Effect.asVoid,
251 );
252​
253 yield* Effect.addFinalizer(() => cancelPending().pipe(Effect.ignore));
254​
255 const resolve: DesktopSshPasswordPrompts["Service"]["resolve"] = Effect.fn(
256 "desktop.sshPasswordPrompts.resolve",
257 )(function* (input) {
258 const requestId = input.requestId.trim();
259 if (requestId.length === 0) {
260 return yield* new DesktopSshPromptInvalidRequestIdError({ requestId: input.requestId });
261 }
262​
263 const pending = yield* removePending(pendingRef, requestId);
264 if (Option.isNone(pending)) {
265 return yield* new DesktopSshPromptExpiredError({ requestId });
266 }
267​
268 const entry = pending.value;
269 if (input.password === null) {
270 yield* failPending(
271 entry,
272 new DesktopSshPromptCancelledError({
273 requestId,
274 destination: entry.destination,
275 }),
276 );
277 return;
278 }
279​
280 yield* Deferred.succeed(entry.deferred, input.password).pipe(Effect.asVoid);
281 });
282​
283 const request: DesktopSshPasswordPrompts["Service"]["request"] = Effect.fn(
284 "desktop.sshPasswordPrompts.request",
285 )(function* (input) {
286 const window = yield* electronWindow.main;
287 if (Option.isNone(window)) {
288 return yield* new DesktopSshPromptWindowUnavailableError({
289 destination: input.destination,
290 requestId: null,
291 stage: "before-request",
292 });
293 }
294​
295 const unavailableBeforeRequest = yield* Effect.try({
296 try: () => window.value.isDestroyed(),
297 catch: (cause) =>
298 new DesktopSshPromptPresentationError({
299 requestId: null,
300 destination: input.destination,
301 operation: "check-window-before-request",
302 cause,
303 }),
304 });
305 if (unavailableBeforeRequest) {
306 return yield* new DesktopSshPromptWindowUnavailableError({
307 destination: input.destination,
308 requestId: null,
309 stage: "before-request",
310 });
311 }
312​
313 const requestId = yield* crypto.randomUUIDv4.pipe(
314 Effect.mapError(
315 (cause) =>
316 new DesktopSshPromptRequestIdGenerationError({
317 destination: input.destination,
318 cause,
319 }),
320 ),
321 );
322 const now = yield* DateTime.now;
323 const expiresAt = DateTime.formatIso(
324 DateTime.add(now, { milliseconds: passwordPromptTimeoutMs }),
325 );
326 const promptRequest: DesktopSshPasswordPromptRequest = {
327 requestId,
328 destination: input.destination,
329 username: input.username,
330 prompt: input.prompt,
331 expiresAt,
332 };
333 const deferred = yield* Deferred.make<string, DesktopSshPasswordPromptRequestError>();
334 const pending: PendingSshPasswordPrompt = {
335 requestId,
336 destination: input.destination,
337 deferred,
338 };
339 yield* Ref.update(pendingRef, (entries) => new Map(entries).set(requestId, pending));
340​
341 const context = yield* Effect.context();
342 const runFork = Effect.runForkWith(context);
343​
344 const cancelOnWindowClosed = () => {
345 runFork(
346 removePending(pendingRef, requestId).pipe(
347 Effect.flatMap((entry) =>
348 Option.match(entry, {
349 onNone: () => Effect.void,
350 onSome: (pending) =>
351 failPending(
352 pending,
353 new DesktopSshPromptWindowClosedError({
354 requestId,
355 destination: input.destination,
356 }),
357 ),
358 }),
359 ),
360 ),
361 );
362 };
363 const runPresentationOperation = <A>(
364 operation: DesktopSshPromptPresentationOperation,
365 evaluate: () => A,
366 ) =>
367 Effect.try({
368 try: evaluate,
369 catch: (cause) =>
370 new DesktopSshPromptPresentationError({
371 requestId,
372 destination: input.destination,
373 operation,
374 cause,
375 }),
376 });
377 const cleanup = runPresentationOperation("remove-window-close-listener", () => {
378 if (!window.value.isDestroyed()) {
379 window.value.removeListener("closed", cancelOnWindowClosed);
380 }
381 }).pipe(Effect.orDie, Effect.ensuring(removePending(pendingRef, requestId)), Effect.asVoid);
382 const waitForPassword = Deferred.await(deferred).pipe(
383 Effect.timeoutOption(Duration.millis(passwordPromptTimeoutMs)),
384 Effect.flatMap(
385 Option.match({
386 onNone: () =>
387 Effect.fail(
388 new DesktopSshPromptTimedOutError({
389 requestId,
390 destination: input.destination,
391 }),
392 ),
393 onSome: Effect.succeed,
394 }),
395 ),
396 );
397 const preferSubmittedPassword = (error: DesktopSshPasswordPromptRequestError) =>
398 Deferred.poll(deferred).pipe(
399 Effect.flatMap(
400 Option.match({
401 onSome: (completion) => completion,
402 onNone: () =>
403 Ref.get(pendingRef).pipe(
404 Effect.flatMap((entries) =>
405 entries.has(requestId) ? Effect.fail(error) : Deferred.await(deferred),
406 ),
407 ),
408 }),
409 ),
410 );
411​
412 return yield* Effect.gen(function* () {
413 const unavailableBeforePresentation = yield* runPresentationOperation(
414 "check-window-before-presentation",
415 () => window.value.isDestroyed(),
416 );
417 if (unavailableBeforePresentation) {
418 return yield* new DesktopSshPromptWindowUnavailableError({
419 destination: input.destination,
420 requestId,
421 stage: "before-presentation",
422 });
423 }
424 yield* runPresentationOperation("register-window-close-listener", () =>
425 window.value.once("closed", cancelOnWindowClosed),
426 );
427 return yield* Effect.gen(function* () {
428 yield* runPresentationOperation("send-prompt-request", () =>
429 window.value.webContents.send(SSH_PASSWORD_PROMPT_CHANNEL, promptRequest),
430 );
431 yield* Effect.yieldNow;
432 const unavailableAfterSend = yield* runPresentationOperation(
433 "check-window-after-send",
434 () => window.value.isDestroyed(),
435 );
436 if (unavailableAfterSend) {
437 return yield* new DesktopSshPromptWindowUnavailableError({
438 destination: input.destination,
439 requestId,
440 stage: "after-send",
441 });
442 }
443 const minimized = yield* runPresentationOperation("check-window-minimized", () =>
444 window.value.isMinimized(),
445 );
446 if (minimized) {
447 yield* runPresentationOperation("restore-window", () => window.value.restore());
448 }
449 const unavailableAfterRestore = yield* runPresentationOperation(
450 "check-window-after-restore",
451 () => window.value.isDestroyed(),
452 );
453 if (unavailableAfterRestore) {
454 return yield* new DesktopSshPromptWindowUnavailableError({
455 destination: input.destination,
456 requestId,
457 stage: "after-restore",
458 });
459 }
460 yield* runPresentationOperation("focus-window", () => window.value.focus());
461 return yield* waitForPassword;
462 }).pipe(Effect.catch(preferSubmittedPassword));
463 }).pipe(Effect.ensuring(cleanup));
464 });
465​
466 return DesktopSshPasswordPrompts.of({
467 request,
468 resolve,
469 });
470});
471​
472export const layer = (options: DesktopSshPasswordPromptsOptions = {}) =>
473 Layer.effect(DesktopSshPasswordPrompts, make(options));