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

SshPasswordPromptDialog.tsx

221 lines6.9 KB

1import type { DesktopSshPasswordPromptRequest } from "@t3tools/contracts";
2import { useEffect, useId, useRef, useState } from "react";
3​
4import { Button } from "../ui/button";
5import {
6 Dialog,
7 DialogDescription,
8 DialogFooter,
9 DialogHeader,
10 DialogPanel,
11 DialogPopup,
12 DialogTitle,
13} from "../ui/dialog";
14import { Input } from "../ui/input";
15​
16function describeSshTarget(request: DesktopSshPasswordPromptRequest): string {
17 return request.username ? `${request.username}@${request.destination}` : request.destination;
19​
20function formatRemainingSeconds(seconds: number): string {
21 return `${Math.floor(seconds / 60)}:${String(seconds % 60).padStart(2, "0")}`;
23​
24function getPromptErrorMessage(error: unknown): string {
25 const message = error instanceof Error ? error.message : "SSH password prompt failed.";
26 return message.includes("expired") || message.includes("no longer pending")
27 ? "This SSH password prompt expired. Try connecting again."
28 : message;
30​
31export function SshPasswordPromptDialog() {
32 const [queue, setQueue] = useState<readonly DesktopSshPasswordPromptRequest[]>([]);
33 const [password, setPassword] = useState("");
34 const [isResponding, setIsResponding] = useState(false);
35 const [now, setNow] = useState(() => Date.now());
36 const [responseError, setResponseError] = useState<string | null>(null);
37 const currentRequest = queue[0] ?? null;
38 const inputRef = useRef<HTMLInputElement | null>(null);
39 const isRespondingRef = useRef(false);
40 const formId = useId();
41​
42 useEffect(() => {
43 const bridge = window.desktopBridge;
44 if (!bridge?.onSshPasswordPrompt) {
45 return;
46 }
47​
48 return bridge.onSshPasswordPrompt((request) => {
49 setQueue((currentQueue) => [...currentQueue, request]);
50 });
51 }, []);
52​
53 useEffect(() => {
54 setPassword("");
55 setResponseError(null);
56 if (!currentRequest) {
57 return;
58 }
59​
60 setNow(Date.now());
61 const frame = window.requestAnimationFrame(() => {
62 inputRef.current?.focus();
63 inputRef.current?.select();
64 });
65 return () => {
66 window.cancelAnimationFrame(frame);
67 };
68 }, [currentRequest]);
69​
70 useEffect(() => {
71 if (!currentRequest) {
72 return;
73 }
74​
75 const interval = window.setInterval(() => {
76 setNow(Date.now());
77 }, 1_000);
78 return () => {
79 window.clearInterval(interval);
80 };
81 }, [currentRequest]);
82​
83 const expiresAtMs = currentRequest ? Date.parse(currentRequest.expiresAt) : Number.NaN;
84 const remainingMs = Number.isFinite(expiresAtMs) ? Math.max(0, expiresAtMs - now) : null;
85 const isExpired = remainingMs !== null && remainingMs <= 0;
86 const remainingSeconds = remainingMs === null ? null : Math.ceil(remainingMs / 1_000);
87 const remainingLabel =
88 remainingSeconds === null ? null : formatRemainingSeconds(remainingSeconds);
89​
90 useEffect(() => {
91 if (isExpired) {
92 setResponseError("This SSH password prompt expired. Try connecting again.");
93 }
94 }, [isExpired]);
95​
96 const removeCurrentPrompt = (requestId: string) => {
97 setQueue((currentQueue) =>
98 currentQueue[0]?.requestId === requestId ? currentQueue.slice(1) : currentQueue,
99 );
100 setPassword("");
101 setResponseError(null);
102 };
103​
104 const respond = async (nextPassword: string | null) => {
105 if (!currentRequest || isRespondingRef.current) {
106 return;
107 }
108​
109 const requestId = currentRequest.requestId;
110 if (nextPassword !== null && isExpired) {
111 setResponseError("This SSH password prompt expired. Try connecting again.");
112 return;
113 }
114​
115 isRespondingRef.current = true;
116 setIsResponding(true);
117 setResponseError(null);
118 try {
119 await window.desktopBridge?.resolveSshPasswordPrompt(requestId, nextPassword);
120 removeCurrentPrompt(requestId);
121 } catch (error) {
122 if (nextPassword === null) {
123 removeCurrentPrompt(requestId);
124 } else {
125 setResponseError(getPromptErrorMessage(error));
126 }
127 } finally {
128 isRespondingRef.current = false;
129 setIsResponding(false);
130 }
131 };
132​
133 const dismissExpiredPrompt = () => {
134 if (currentRequest) {
135 removeCurrentPrompt(currentRequest.requestId);
136 }
137 };
138​
139 const cancelPrompt = () => {
140 if (isExpired) {
141 dismissExpiredPrompt();
142 return;
143 }
144 void respond(null);
145 };
146​
147 const target = currentRequest ? describeSshTarget(currentRequest) : null;
148​
149 return (
150 <Dialog
151 open={currentRequest !== null}
152 onOpenChange={(open) => {
153 if (!open) {
154 cancelPrompt();
155 }
156 }}
157 >
158 <DialogPopup className="max-w-md" showCloseButton={false}>
159 <DialogHeader>
160 <DialogTitle>SSH Password Required</DialogTitle>
161 <DialogDescription>
162 T3 needs your SSH password to connect to{" "}
163 {target ? <code>{target}</code> : "the remote host"}. The password is passed to the
164 local SSH process for this connection attempt and is not saved by T3 Code.
165 </DialogDescription>
166 </DialogHeader>
167 <DialogPanel className="space-y-3" scrollFade={false}>
168 <form
169 className="space-y-3"
170 id={formId}
171 onSubmit={(event) => {
172 event.preventDefault();
173 void respond(password);
174 }}
175 >
176 <div className="space-y-2">
177 <div className="flex items-center justify-between gap-3">
178 <p className="text-sm font-medium text-foreground">{currentRequest?.prompt}</p>
179 {remainingLabel ? (
180 <span
181 className={
182 isExpired
183 ? "shrink-0 text-xs font-medium text-destructive"
184 : "shrink-0 text-xs text-muted-foreground"
185 }
186 >
187 {isExpired ? "Expired" : remainingLabel}
188 </span>
189 ) : null}
190 </div>
191 <Input
192 ref={inputRef}
193 autoComplete="current-password"
194 disabled={isResponding || isExpired}
195 name="ssh-password"
196 type="password"
197 value={password}
198 onChange={(event) => setPassword(event.target.value)}
199 />
200 </div>
201 {responseError ? (
202 <p className="text-sm text-destructive">{responseError}</p>
203 ) : (
204 <p className="text-sm text-muted-foreground">
205 Use SSH keys to avoid repeated password prompts on new SSH sessions.
206 </p>
207 )}
208 </form>
209 </DialogPanel>
210 <DialogFooter>
211 <Button disabled={isResponding} type="button" variant="outline" onClick={cancelPrompt}>
212 {isExpired ? "Dismiss" : "Cancel"}
213 </Button>
214 <Button disabled={isResponding || isExpired} form={formId} type="submit">
215 Continue
216 </Button>
217 </DialogFooter>
218 </DialogPopup>
219 </Dialog>
220 );