Open History to see the last commit
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;
24}
25
26function formatRemainingSeconds(seconds: number): string {
27 return `${Math.floor(seconds / 60)}:${String(seconds % 60).padStart(2, "0")}`;
28}
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;
35}
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();
43}
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 return (
51 window.desktopBridge?.onSshPasswordPrompt((request) => {
52 setPromptQueue([...promptQueue, request]);
53 }) ?? (() => undefined)
54 );
55}
56
57function subscribePromptQueue(listener: () => void): () => void {
58 promptQueueListeners.add(listener);
59 return () => {
60 promptQueueListeners.delete(listener);
61 };
62}
63
64const readPromptQueue = () => promptQueue;
65
66function removeSshPasswordPrompt(requestId: string) {
67 if (promptQueue[0]?.requestId === requestId) setPromptQueue(promptQueue.slice(1));
68}
69
70export function SshPasswordPromptDialog() {
71 const queue = useSyncExternalStore(subscribePromptQueue, readPromptQueue, readPromptQueue);
72 const currentRequest = queue[0] ?? null;
73
74 if (!currentRequest) {
75 return null;
76 }
77
78 return <ActiveSshPasswordPrompt key={currentRequest.requestId} request={currentRequest} />;
79}
80
81function ActiveSshPasswordPrompt({
82 request,
83}: {
84 readonly request: DesktopSshPasswordPromptRequest;
85}) {
86 const [password, setPassword] = useState("");
87 const [isResponding, setIsResponding] = useState(false);
88 const [responseError, setResponseError] = useState<string | null>(null);
89 const inputRef = useRef<HTMLInputElement | null>(null);
90 const isRespondingRef = useRef(false);
91 const formId = useId();
92
93 const expiresAtMs = Date.parse(request.expiresAt);
94 const now = useNowSecond();
95 const isExpired = useDeadlinePassed(Number.isFinite(expiresAtMs) ? expiresAtMs : null);
96 const remainingMs = Number.isFinite(expiresAtMs)
97 ? isExpired
98 ? 0
99 : Math.max(0, expiresAtMs - now)
100 : null;
101 const remainingSeconds = remainingMs === null ? null : Math.ceil(remainingMs / 1_000);
102 const remainingLabel =
103 remainingSeconds === null ? null : formatRemainingSeconds(remainingSeconds);
104 const visibleResponseError = isExpired
105 ? "This SSH verification prompt expired. Try connecting again."
106 : responseError;
107
108 const respond = async (nextPassword: string | null) => {
109 if (isRespondingRef.current) {
110 return;
111 }
112
113 const requestId = request.requestId;
114 if (nextPassword !== null && isExpired) {
115 setResponseError("This SSH verification prompt expired. Try connecting again.");
116 return;
117 }
118
119 isRespondingRef.current = true;
120 setIsResponding(true);
121 setResponseError(null);
122 const result = await settlePromise(async () =>
123 window.desktopBridge?.resolveSshPasswordPrompt(requestId, nextPassword),
124 );
125 if (AsyncResult.isSuccess(result) || nextPassword === null) {
126 removeSshPasswordPrompt(requestId);
127 } else {
128 setResponseError(getPromptErrorMessage(Cause.squash(result.cause)));
129 }
130 isRespondingRef.current = false;
131 setIsResponding(false);
132 };
133
134 const dismissExpiredPrompt = () => {
135 removeSshPasswordPrompt(request.requestId);
136 };
137
138 const cancelPrompt = () => {
139 if (isExpired) {
140 dismissExpiredPrompt();
141 return;
142 }
143 void respond(null);
144 };
145
146 const target = describeSshTarget(request);
147
148 return (
149 <Dialog
150 open
151 onOpenChange={(open) => {
152 if (!open) {
153 cancelPrompt();
154 }
155 }}
156 >
157 <DialogPopup className="max-w-md" initialFocus={inputRef} showCloseButton={false}>
158 <DialogHeader>
159 <DialogTitle>SSH verification required</DialogTitle>
160 <DialogDescription>
161 Enter the password or verification code required by <code>{target}</code>. T3 Code
162 passes your response to the local SSH process and keeps it in memory to reuse for this
163 host. T3 Code does not write it to disk.
164 </DialogDescription>
165 </DialogHeader>
166 <DialogPanel scrollFade={false}>
167 <form
168 className="space-y-3"
169 id={formId}
170 onSubmit={(event) => {
171 event.preventDefault();
172 void respond(password);
173 }}
174 >
175 <div className="space-y-2">
176 <div className="flex items-center justify-between gap-3">
177 <p className="text-sm font-medium text-foreground">{request.prompt}</p>
178 {remainingLabel ? (
179 <span
180 className={
181 isExpired
182 ? "shrink-0 text-xs font-medium text-destructive"
183 : "shrink-0 text-xs text-muted-foreground"
184 }
185 >
186 {isExpired ? "Expired" : remainingLabel}
187 </span>
188 ) : null}
189 </div>
190 <Input
191 ref={inputRef}
192 autoComplete="current-password"
193 disabled={isResponding || isExpired}
194 name="ssh-password"
195 type="password"
196 value={password}
197 onChange={(event) => setPassword(event.target.value)}
198 />
199 </div>
200 {visibleResponseError ? (
201 <p className="text-sm text-destructive">{visibleResponseError}</p>
202 ) : (
203 <p className="text-sm text-muted-foreground">
204 SSH keys may replace a password, but your server can still require a verification
205 code.
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 );
221}