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

PairingRouteSurface.tsx

295 lines9.2 KB

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