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

SshPasswordPromptDialog.tsx

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