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

SshPasswordPromptDialog.tsx

228 lines7.6 KB

1import { settlePromise } from "@t3tools/client-runtime/state/runtime";
2import type { DesktopSshPasswordPromptRequest } from "@t3tools/contracts";
3import * as AsyncResult from "effect/reactivity/AsyncResult";
4import * as Cause from "effect/Cause";
5import { useId, useRef, useState, useSyncExternalStore } from "react";
6​
7import { useDeadlinePassed } from "../../hooks/useDeadline";
8import { useNowSecond } from "../../hooks/useNowSecond";
9​
10import { Button } from "../ui/button";
11import {
12 Dialog,
13 DialogDescription,
14 DialogFooter,
15 DialogHeader,
16 DialogPanel,
17 DialogPopup,
18 DialogTitle,
19} from "../ui/dialog";
20import { Input } from "../ui/input";
21​
22function describeSshTarget(request: DesktopSshPasswordPromptRequest): string {
23 return request.username ? `${request.username}@${request.destination}` : request.destination;
25​
26function formatRemainingSeconds(seconds: number): string {
27 return `${Math.floor(seconds / 60)}:${String(seconds % 60).padStart(2, "0")}`;
29​
30function getPromptErrorMessage(error: unknown): string {
31 const message = error instanceof Error ? error.message : "SSH verification prompt failed.";
32 return message.includes("expired") || message.includes("no longer pending")
33 ? "This SSH verification prompt expired. Try connecting again."
34 : message;
36​
37let promptQueue: readonly DesktopSshPasswordPromptRequest[] = [];
38const promptQueueListeners = new Set<() => void>();
39​
40function setPromptQueue(next: readonly DesktopSshPasswordPromptRequest[]) {
41 promptQueue = next;
42 for (const listener of promptQueueListeners) listener();
44​
45/**
46 * Queues the desktop's SSH password prompts for the life of the page, so a prompt
47 * that arrives while no dialog is mounted still waits for one.
48 */
49export function startSshPasswordPromptQueue(): () => void {
50 const bridge = window.desktopBridge;
51 if (!bridge) return () => undefined;
52 const stopPrompts = bridge.onSshPasswordPrompt((request) => {
53 if (promptQueue.some((queued) => queued.requestId === request.requestId)) return;
54 setPromptQueue([...promptQueue, request]);
55 });
56 const stopSettled = bridge.onSshPasswordPromptSettled(removeSshPasswordPrompt);
57 return () => {
58 stopPrompts();
59 stopSettled();
60 };
62​
63function subscribePromptQueue(listener: () => void): () => void {
64 promptQueueListeners.add(listener);
65 return () => {
66 promptQueueListeners.delete(listener);
67 };
69​
70const readPromptQueue = () => promptQueue;
71​
72function removeSshPasswordPrompt(requestId: string) {
73 if (!promptQueue.some((request) => request.requestId === requestId)) return;
74 setPromptQueue(promptQueue.filter((request) => request.requestId !== requestId));
76​
77export function SshPasswordPromptDialog() {
78 const queue = useSyncExternalStore(subscribePromptQueue, readPromptQueue, readPromptQueue);
79 const currentRequest = queue[0] ?? null;
80​
81 if (!currentRequest) {
82 return null;
83 }
84​
85 return <ActiveSshPasswordPrompt key={currentRequest.requestId} request={currentRequest} />;
87​
88function ActiveSshPasswordPrompt({
89 request,
90}: {
91 readonly request: DesktopSshPasswordPromptRequest;
92}) {
93 const [password, setPassword] = useState("");
94 const [isResponding, setIsResponding] = useState(false);
95 const [responseError, setResponseError] = useState<string | null>(null);
96 const inputRef = useRef<HTMLInputElement | null>(null);
97 const isRespondingRef = useRef(false);
98 const formId = useId();
99​
100 const expiresAtMs = Date.parse(request.expiresAt);
101 const now = useNowSecond();
102 const isExpired = useDeadlinePassed(Number.isFinite(expiresAtMs) ? expiresAtMs : null);
103 const remainingMs = Number.isFinite(expiresAtMs)
104 ? isExpired
105 ? 0
106 : Math.max(0, expiresAtMs - now)
107 : null;
108 const remainingSeconds = remainingMs === null ? null : Math.ceil(remainingMs / 1_000);
109 const remainingLabel =
110 remainingSeconds === null ? null : formatRemainingSeconds(remainingSeconds);
111 const visibleResponseError = isExpired
112 ? "This SSH verification prompt expired. Try connecting again."
113 : responseError;
114​
115 const respond = async (nextPassword: string | null) => {
116 if (isRespondingRef.current) {
117 return;
118 }
119​
120 const requestId = request.requestId;
121 if (nextPassword !== null && isExpired) {
122 setResponseError("This SSH verification prompt expired. Try connecting again.");
123 return;
124 }
125​
126 isRespondingRef.current = true;
127 setIsResponding(true);
128 setResponseError(null);
129 const result = await settlePromise(async () =>
130 window.desktopBridge?.resolveSshPasswordPrompt(requestId, nextPassword),
131 );
132 if (AsyncResult.isSuccess(result) || nextPassword === null) {
133 removeSshPasswordPrompt(requestId);
134 } else {
135 setResponseError(getPromptErrorMessage(Cause.squash(result.cause)));
136 }
137 isRespondingRef.current = false;
138 setIsResponding(false);
139 };
140​
141 const dismissExpiredPrompt = () => {
142 removeSshPasswordPrompt(request.requestId);
143 };
144​
145 const cancelPrompt = () => {
146 if (isExpired) {
147 dismissExpiredPrompt();
148 return;
149 }
150 void respond(null);
151 };
152​
153 const target = describeSshTarget(request);
154​
155 return (
156 <Dialog
157 open
158 onOpenChange={(open) => {
159 if (!open) {
160 cancelPrompt();
161 }
162 }}
163 >
164 <DialogPopup className="max-w-md" initialFocus={inputRef} showCloseButton={false}>
165 <DialogHeader>
166 <DialogTitle>SSH verification required</DialogTitle>
167 <DialogDescription>
168 Enter the password or verification code required by <code>{target}</code>. T3 Code
169 passes your response to the local SSH process and keeps it in memory to reuse for this
170 host. T3 Code does not write it to disk.
171 </DialogDescription>
172 </DialogHeader>
173 <DialogPanel scrollFade={false}>
174 <form
175 className="space-y-3"
176 id={formId}
177 onSubmit={(event) => {
178 event.preventDefault();
179 void respond(password);
180 }}
181 >
182 <div className="space-y-2">
183 <div className="flex items-center justify-between gap-3">
184 <p className="text-sm font-medium text-foreground">{request.prompt}</p>
185 {remainingLabel ? (
186 <span
187 className={
188 isExpired
189 ? "shrink-0 text-xs font-medium text-destructive"
190 : "shrink-0 text-xs text-muted-foreground"
191 }
192 >
193 {isExpired ? "Expired" : remainingLabel}
194 </span>
195 ) : null}
196 </div>
197 <Input
198 ref={inputRef}
199 autoComplete="current-password"
200 disabled={isResponding || isExpired}
201 name="ssh-password"
202 type="password"
203 value={password}
204 onChange={(event) => setPassword(event.target.value)}
205 />
206 </div>
207 {visibleResponseError ? (
208 <p className="text-sm text-destructive">{visibleResponseError}</p>
209 ) : (
210 <p className="text-sm text-muted-foreground">
211 SSH keys may replace a password, but your server can still require a verification
212 code.
213 </p>
214 )}
215 </form>
216 </DialogPanel>
217 <DialogFooter>
218 <Button disabled={isResponding} type="button" variant="outline" onClick={cancelPrompt}>
219 {isExpired ? "Dismiss" : "Cancel"}
220 </Button>
221 <Button disabled={isResponding || isExpired} form={formId} type="submit">
222 Continue
223 </Button>
224 </DialogFooter>
225 </DialogPopup>
226 </Dialog>
227 );