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

PairingRouteSurface.tsx

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