Open History to see the last commit
1import { Alert, AlertDescription } from "../ui/alert";
2import type { AuthSessionState } from "@t3tools/contracts";
3import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
4import { msg, T, useGT, useMessages, Var } from "gt-react";
5import React, { startTransition, useEffect, useEffectEvent, useRef, useState } from "react";
6
7import { connectPairing } from "../../connection/onboarding";
8import {
9 peekPairingTokenFromUrl,
10 stripPairingTokenFromUrl,
11 submitServerAuthCredential,
12} from "../../environments/primary";
13import { readHostedPairingRequest } from "../../hostedPairing";
14import { resolveRemotePairingTarget } from "@t3tools/shared/remote";
15import { Button } from "../ui/button";
16import { Input } from "../ui/input";
17import { StandalonePage, StandalonePageHeader } from "../ui/standalone-page";
18import { useAtomCommand } from "../../state/use-atom-command";
19import { m, type MessageResolver } from "../../i18n/messages";
20
21export function PairingPendingSurface() {
22 const gt = useGT();
23 return (
24 <StandalonePage>
25 <StandalonePageHeader
26 title={gt("Pairing with this environment")}
27 description={gt("Validating the pairing link and preparing your session.")}
28 />
29 </StandalonePage>
30 );
31}
32
33export function PairingRouteSurface({
34 auth,
35 initialErrorMessage,
36 onAuthenticated,
37}: {
38 auth: AuthSessionState["auth"];
39 initialErrorMessage?: string;
40 onAuthenticated: () => void;
41}) {
42 const gt = useGT();
43 const messages = useMessages();
44 const [autoPairToken] = useState(peekPairingTokenFromUrl);
45 const [credential, setCredential] = useState(autoPairToken ?? "");
46 const [errorMessage, setErrorMessage] = useState(initialErrorMessage ?? "");
47 const [isSubmitting, setIsSubmitting] = useState(false);
48 const autoSubmitAttemptedRef = useRef(false);
49
50 const submitCredential = async (nextCredential: string) => {
51 setIsSubmitting(true);
52 setErrorMessage("");
53
54 const submitError = await submitServerAuthCredential(nextCredential).then(
55 () => null,
56 (error) => errorMessageFromUnknown(error),
57 );
58
59 setIsSubmitting(false);
60
61 if (submitError) {
62 setErrorMessage(submitError);
63 return;
64 }
65
66 startTransition(() => {
67 onAuthenticated();
68 });
69 };
70
71 const handleSubmit = async (event?: React.SubmitEvent<HTMLFormElement>) => {
72 event?.preventDefault();
73 await submitCredential(credential);
74 };
75
76 const autoSubmit = useEffectEvent((token: string) => {
77 void submitCredential(token);
78 });
79
80 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- strips the pairing token from the URL and submits it once when the route carries one
81 useEffect(() => {
82 if (!autoPairToken || autoSubmitAttemptedRef.current) {
83 return;
84 }
85
86 autoSubmitAttemptedRef.current = true;
87 stripPairingTokenFromUrl();
88 autoSubmit(autoPairToken);
89 }, [autoPairToken]);
90
91 return (
92 <StandalonePage>
93 <StandalonePageHeader
94 title={gt("Pair with this environment")}
95 description={describeAuthGate(auth.bootstrapMethods, messages)}
96 />
97
98 <form className="mt-6 space-y-4" onSubmit={(event) => void handleSubmit(event)}>
99 <div className="space-y-2">
100 <label className="text-sm font-medium" htmlFor="pairing-token">
101 <T>Pairing token</T>
102 </label>
103 <Input
104 id="pairing-token"
105 autoCapitalize="none"
106 autoComplete="off"
107 autoCorrect="off"
108 disabled={isSubmitting}
109 nativeInput
110 onChange={(event) => setCredential(event.currentTarget.value)}
111 placeholder={gt("Paste a one-time token or pairing secret")}
112 spellCheck={false}
113 value={credential}
114 />
115 </div>
116
117 {errorMessage ? (
118 <Alert variant="error">
119 <AlertDescription>{errorMessage}</AlertDescription>
120 </Alert>
121 ) : null}
122
123 <div className="flex flex-wrap gap-2">
124 <Button disabled={isSubmitting} size="sm" type="submit">
125 {isSubmitting ? gt("Pairing...") : gt("Continue")}
126 </Button>
127 <Button
128 disabled={isSubmitting}
129 onClick={() => window.location.reload()}
130 size="sm"
131 variant="outline"
132 >
133 <T>Reload app</T>
134 </Button>
135 </div>
136 </form>
137
138 <div className="mt-6 rounded-lg border border-border/70 bg-background/55 px-3 py-3 text-xs leading-relaxed text-muted-foreground">
139 {describeSupportedMethods(auth.bootstrapMethods, messages)}
140 </div>
141 </StandalonePage>
142 );
143}
144
145export function HostedPairingRouteSurface() {
146 const connectPairingEnvironment = useAtomCommand(connectPairing, {
147 reportFailure: false,
148 });
149 const [request] = useState(readHostedPairingRequest);
150 // The origin shows the scheme along with the host.
151 const [origin] = useState(() => {
152 if (!request) return null;
153 try {
154 return new URL(
155 resolveRemotePairingTarget({ host: request.host, pairingCode: request.token }).httpBaseUrl,
156 ).origin;
157 } catch {
158 return null;
159 }
160 });
161 const gt = useGT();
162 const [status, setStatus] = useState<"confirm" | "pairing" | "paired" | "error">(
163 origin ? "confirm" : "error",
164 );
165 const [message, setMessage] = useState(() =>
166 origin
167 ? m(msg("This link adds a backend to this browser. Continue only if you trust it."))
168 : request
169 ? m(msg("This pairing link has an invalid backend host."))
170 : m(msg("This pairing link is missing its backend host or token.")),
171 );
172 const [canRetry, setCanRetry] = useState(false);
173 // Nothing is sent to the link's host until the user confirms.
174 // The token stays in the URL until then: the root route picks this page from it.
175 const tokenSubmittedRef = useRef(false);
176
177 const submitHostedPairingRequest = async () => {
178 if (!request) {
179 setStatus("error");
180 setMessage(gt("This pairing link is missing its backend host or token."));
181 setCanRetry(false);
182 return;
183 }
184
185 if (tokenSubmittedRef.current) {
186 setStatus("error");
187 setMessage(
188 gt("This one-time pairing token was already submitted. Request a new pairing link."),
189 );
190 setCanRetry(false);
191 return;
192 }
193
194 setStatus("pairing");
195 setMessage(gt("Connecting to this backend."));
196 setCanRetry(false);
197 tokenSubmittedRef.current = true;
198 stripPairingTokenFromUrl();
199
200 const result = await connectPairingEnvironment({
201 host: request.host,
202 pairingCode: request.token,
203 });
204 if (result._tag === "Success") {
205 setStatus("paired");
206 setMessage(
207 request.label
208 ? gt("{environment} is saved in this browser.", { environment: request.label })
209 : gt("The environment is saved in this browser."),
210 );
211 return;
212 }
213
214 tokenSubmittedRef.current = false;
215 setStatus("error");
216 setCanRetry(true);
217 setMessage(
218 gt(
219 "{error} If the backend accepted this one-time token, request a new pairing link before retrying.",
220 { error: errorMessageFromUnknown(squashAtomCommandFailure(result)) },
221 ),
222 );
223 };
224
225 return (
226 <StandalonePage>
227 <StandalonePageHeader
228 title={
229 status === "paired"
230 ? gt("Backend paired")
231 : status === "error"
232 ? gt("Pairing failed")
233 : status === "confirm"
234 ? gt("Add this backend?")
235 : gt("Pairing backend")
236 }
237 description={message}
238 />
239
240 {request ? (
241 <div className="mt-5 rounded-lg border border-border/70 bg-background/55 px-3 py-3 text-xs leading-relaxed text-muted-foreground">
242 <T>
243 Host:{" "}
244 <span className="font-mono text-foreground/80">
245 <Var>{origin ?? request.host}</Var>
246 </span>
247 </T>
248 </div>
249 ) : null}
250
251 {status === "error" ? (
252 <Alert variant="error" className="mt-5">
253 <AlertDescription>
254 <T>
255 Verify the backend is reachable from this browser, supports CORS for hosted clients,
256 and is served over HTTPS when opening this page from HTTPS.
257 </T>
258 </AlertDescription>
259 </Alert>
260 ) : null}
261
262 <div className="mt-6 flex flex-wrap gap-2">
263 {status === "confirm" ? (
264 <>
265 <Button size="sm" onClick={() => void submitHostedPairingRequest()}>
266 <T>Add backend</T>
267 </Button>
268 <Button
269 size="sm"
270 variant="outline"
271 onClick={() => {
272 stripPairingTokenFromUrl();
273 window.location.href = "/";
274 }}
275 >
276 <T>Cancel</T>
277 </Button>
278 </>
279 ) : status === "pairing" ? (
280 <Button disabled size="sm">
281 <T>Pairing...</T>
282 </Button>
283 ) : canRetry ? (
284 <Button size="sm" onClick={() => void submitHostedPairingRequest()}>
285 <T>Try again</T>
286 </Button>
287 ) : null}
288 {status === "paired" ? (
289 <Button size="sm" variant="outline" onClick={() => (window.location.href = "/")}>
290 <T>Open app</T>
291 </Button>
292 ) : null}
293 </div>
294 </StandalonePage>
295 );
296}
297
298function errorMessageFromUnknown(error: unknown): string {
299 if (error instanceof Error && error.message.trim().length > 0) {
300 return error.message;
301 }
302
303 if (typeof error === "string" && error.trim().length > 0) {
304 return error;
305 }
306
307 return m(msg("Authentication failed."));
308}
309
310function describeAuthGate(
311 bootstrapMethods: ReadonlyArray<string>,
312 resolve: MessageResolver,
313): string {
314 if (bootstrapMethods.includes("desktop-bootstrap")) {
315 return resolve(
316 msg("This environment expects a trusted pairing credential before the app can connect."),
317 );
318 }
319
320 return resolve(msg("Enter a pairing token to start a session with this environment."));
321}
322
323function describeSupportedMethods(
324 bootstrapMethods: ReadonlyArray<string>,
325 resolve: MessageResolver,
326): string {
327 if (
328 bootstrapMethods.includes("desktop-bootstrap") &&
329 bootstrapMethods.includes("one-time-token")
330 ) {
331 return resolve(
332 msg(
333 "Desktop-managed pairing and one-time pairing tokens are both accepted for this environment.",
334 ),
335 );
336 }
337
338 if (bootstrapMethods.includes("desktop-bootstrap")) {
339 return resolve(
340 msg(
341 "This environment is desktop-managed. Open it from the desktop app or paste a bootstrap credential if one was issued explicitly.",
342 ),
343 );
344 }
345
346 return resolve(
347 msg(
348 "This environment accepts one-time pairing tokens. Pairing links can open this page directly, or you can paste the token here.",
349 ),
350 );
351}