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

SshPasswordPromptDialog.tsx

221 lines6.8 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 password prompt failed.";
29 return message.includes("expired") || message.includes("no longer pending")
30 ? "This SSH password 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 password 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 password 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 Password Required</DialogTitle>
162 <DialogDescription>
163 T3 needs your SSH password to connect to <code>{target}</code>. The password is passed
164 to the local SSH process for this connection attempt and is not saved by T3 Code.
165 </DialogDescription>
166 </DialogHeader>
167 <DialogPanel 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">{request.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 {visibleResponseError ? (
202 <p className="text-sm text-destructive">{visibleResponseError}</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 );