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

PairingRouteSurface.tsx

292 lines9.2 KB

1import type { AuthSessionState } from "@t3tools/contracts";
2import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
3import React, { startTransition, useEffect, useRef, useState, useCallback } from "react";
4​
5import { APP_DISPLAY_NAME } from "../../branding";
6import { connectPairing } from "../../connection/onboarding";
7import {
8 peekPairingTokenFromUrl,
9 stripPairingTokenFromUrl,
10 submitServerAuthCredential,
11} from "../../environments/primary";
12import { readHostedPairingRequest } from "../../hostedPairing";
13import { Button } from "../ui/button";
14import { Input } from "../ui/input";
15import { StandalonePage, StandalonePageHeader } from "../ui/standalone-page";
16import { useAtomCommand } from "../../state/use-atom-command";
17​
18export function PairingPendingSurface() {
19 return (
20 <StandalonePage tone="pairing">
21 <StandalonePageHeader
22 eyebrow={APP_DISPLAY_NAME}
23 title="Pairing with this environment"
24 description="Validating the pairing link and preparing your session."
25 />
26 </StandalonePage>
27 );
29​
30export function PairingRouteSurface({
31 auth,
32 initialErrorMessage,
33 onAuthenticated,
34}: {
35 auth: AuthSessionState["auth"];
36 initialErrorMessage?: string;
37 onAuthenticated: () => void;
38}) {
39 const autoPairTokenRef = useRef<string | null>(peekPairingTokenFromUrl());
40 const [credential, setCredential] = useState(() => autoPairTokenRef.current ?? "");
41 const [errorMessage, setErrorMessage] = useState(initialErrorMessage ?? "");
42 const [isSubmitting, setIsSubmitting] = useState(false);
43 const autoSubmitAttemptedRef = useRef(false);
44​
45 const submitCredential = useCallback(
46 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 [onAuthenticated],
67 );
68​
69 const handleSubmit = useCallback(
70 async (event?: React.SubmitEvent<HTMLFormElement>) => {
71 event?.preventDefault();
72 await submitCredential(credential);
73 },
74 [submitCredential, credential],
75 );
76​
77 useEffect(() => {
78 const token = autoPairTokenRef.current;
79 if (!token || autoSubmitAttemptedRef.current) {
80 return;
81 }
82​
83 autoSubmitAttemptedRef.current = true;
84 stripPairingTokenFromUrl();
85 void submitCredential(token);
86 }, [submitCredential]);
87​
88 return (
89 <StandalonePage tone="pairing">
90 <StandalonePageHeader
91 eyebrow={APP_DISPLAY_NAME}
92 title="Pair with this environment"
93 description={describeAuthGate(auth.bootstrapMethods)}
94 />
95​
96 <form className="mt-6 space-y-4" onSubmit={(event) => void handleSubmit(event)}>
97 <div className="space-y-2">
98 <label className="text-sm font-medium" htmlFor="pairing-token">
99 Pairing token
100 </label>
101 <Input
102 id="pairing-token"
103 autoCapitalize="none"
104 autoComplete="off"
105 autoCorrect="off"
106 disabled={isSubmitting}
107 nativeInput
108 onChange={(event) => setCredential(event.currentTarget.value)}
109 placeholder="Paste a one-time token or pairing secret"
110 spellCheck={false}
111 value={credential}
112 />
113 </div>
114​
115 {errorMessage ? (
116 <div className="rounded-lg border border-destructive/30 bg-destructive/6 px-3 py-2 text-sm text-destructive">
117 {errorMessage}
118 </div>
119 ) : null}
120​
121 <div className="flex flex-wrap gap-2">
122 <Button disabled={isSubmitting} size="sm" type="submit">
123 {isSubmitting ? "Pairing..." : "Continue"}
124 </Button>
125 <Button
126 disabled={isSubmitting}
127 onClick={() => window.location.reload()}
128 size="sm"
129 variant="outline"
130 >
131 Reload app
132 </Button>
133 </div>
134 </form>
135​
136 <div className="mt-6 rounded-lg border border-border/70 bg-background/55 px-3 py-3 text-xs leading-relaxed text-muted-foreground">
137 {describeSupportedMethods(auth.bootstrapMethods)}
138 </div>
139 </StandalonePage>
140 );
142​
143export function HostedPairingRouteSurface() {
144 const connectPairingEnvironment = useAtomCommand(connectPairing, {
145 reportFailure: false,
146 });
147 const hostedPairingRequestRef = useRef(readHostedPairingRequest());
148 const [status, setStatus] = useState<"pairing" | "paired" | "error">(() =>
149 hostedPairingRequestRef.current ? "pairing" : "error",
150 );
151 const [message, setMessage] = useState(() =>
152 hostedPairingRequestRef.current
153 ? "Connecting to this backend."
154 : "This pairing link is missing its backend host or token.",
155 );
156 const [canRetry, setCanRetry] = useState(false);
157 const submitAttemptedRef = useRef(false);
158 const tokenSubmittedRef = useRef(false);
159​
160 const submitHostedPairingRequest = useCallback(async () => {
161 const request = hostedPairingRequestRef.current;
162​
163 if (!request) {
164 setStatus("error");
165 setMessage("This pairing link is missing its backend host or token.");
166 setCanRetry(false);
167 return;
168 }
169​
170 if (tokenSubmittedRef.current) {
171 setStatus("error");
172 setMessage("This one-time pairing token was already submitted. Request a new pairing link.");
173 setCanRetry(false);
174 return;
175 }
176​
177 setStatus("pairing");
178 setMessage("Connecting to this backend.");
179 setCanRetry(false);
180 tokenSubmittedRef.current = true;
181​
182 const result = await connectPairingEnvironment({
183 host: request.host,
184 pairingCode: request.token,
185 });
186 if (result._tag === "Success") {
187 setStatus("paired");
188 setMessage(`${request.label || "The environment"} is saved in this browser.`);
189 return;
190 }
191​
192 tokenSubmittedRef.current = false;
193 setStatus("error");
194 setCanRetry(true);
195 setMessage(
196 `${errorMessageFromUnknown(squashAtomCommandFailure(result))} If the backend accepted this one-time token, request a new pairing link before retrying.`,
197 );
198 }, [connectPairingEnvironment]);
199​
200 useEffect(() => {
201 if (submitAttemptedRef.current) {
202 return;
203 }
204 submitAttemptedRef.current = true;
205​
206 stripPairingTokenFromUrl();
207 void submitHostedPairingRequest();
208 }, [submitHostedPairingRequest]);
209​
210 const request = hostedPairingRequestRef.current;
211​
212 return (
213 <StandalonePage tone="pairing">
214 <StandalonePageHeader
215 eyebrow={APP_DISPLAY_NAME}
216 title={
217 status === "paired"
218 ? "Backend paired"
219 : status === "error"
220 ? "Pairing failed"
221 : "Pairing backend"
222 }
223 description={message}
224 />
225​
226 {request ? (
227 <div className="mt-5 rounded-lg border border-border/70 bg-background/55 px-3 py-3 text-xs leading-relaxed text-muted-foreground">
228 Host: <span className="font-mono text-foreground/80">{request.host}</span>
229 </div>
230 ) : null}
231​
232 {status === "error" ? (
233 <div className="mt-5 rounded-lg border border-destructive/30 bg-destructive/6 px-3 py-2 text-sm text-destructive">
234 Verify the backend is reachable from this browser, supports CORS for hosted clients, and
235 is served over HTTPS when opening this page from HTTPS.
236 </div>
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.";