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

ConnectCliAuthSurface.tsx

209 lines7.0 KB

1import { useAuth, useClerk, useUser } from "@clerk/react";
2import { encodeConnectAuthCode, readConnectAuthorizeRequest } from "@t3tools/shared/connectAuth";
3import { useCallback, useEffect, useRef, useState } from "react";
4​
5import {
6 buildConnectCliClerkAuthorizeUrl,
7 connectCliSignInRedirectUrl,
8 readConnectCliAuthState,
9 readConnectCliCallbackResult,
10 rememberConnectCliAuthState,
11} from "../../cloud/connectCliAuth";
12import { isElectron } from "../../env";
13import { useCopyToClipboard } from "../../hooks/useCopyToClipboard";
14import { AuthSurfaceShell } from "../auth/AuthSurfaceShell";
15import { resolveClerkSignInProps } from "../clerk/authRedirect";
16import { Button } from "../ui/button";
17​
18function ConnectCliAuthMessage({
19 eyebrow,
20 title,
21 description,
22}: {
23 readonly eyebrow?: string;
24 readonly title: string;
25 readonly description: string;
26}) {
27 return (
28 <>
29 {eyebrow ? (
30 <p className="text-[10px] font-semibold tracking-[0.18em] text-blue-600 uppercase dark:text-blue-400">
31 {eyebrow}
32 </p>
33 ) : null}
34 <h1 className="mt-2 text-2xl font-semibold tracking-tight sm:text-3xl">{title}</h1>
35 <p className="mt-2 text-sm leading-relaxed text-muted-foreground">{description}</p>
36 </>
37 );
39​
40const invalidLinkMessage = {
41 eyebrow: "Authorization request",
42 title: "This connect link is incomplete",
43 description:
44 "The link is missing its authorization request. Re-run `t3 connect` in your terminal and open the freshly printed URL.",
45} as const;
46​
47/**
48 * /connect: the URL the CLI prints for both flows. Waits for a Clerk session,
49 * then forwards the CLI's PKCE request to Clerk's authorize endpoint — with a
50 * loopback redirect URI when the request carries a port, so the code returns
51 * straight to the waiting CLI, and the hosted callback page otherwise.
52 */
53export function ConnectCliAuthorizeSurface() {
54 const [request] = useState(() => readConnectAuthorizeRequest(new URL(window.location.href)));
55 const clerk = useClerk();
56 const { isLoaded, isSignedIn } = useAuth();
57 const signInOpened = useRef(false);
58 const redirecting = useRef(false);
59​
60 const openSignIn = useCallback(() => {
61 if (!request) {
62 return;
63 }
64 // Clerk redirects to the authorize endpoint itself once sign-in completes,
65 // so the callback's state check has to be armed before handing off.
66 rememberConnectCliAuthState(request.state);
67 clerk.openSignIn(
68 resolveClerkSignInProps(
69 connectCliSignInRedirectUrl(request, window.location.href),
70 isElectron,
71 ),
72 );
73 }, [clerk, request]);
74​
75 useEffect(() => {
76 if (!request || !isLoaded || redirecting.current) {
77 return;
78 }
79 if (!isSignedIn) {
80 if (!signInOpened.current) {
81 signInOpened.current = true;
82 openSignIn();
83 }
84 return;
85 }
86 const authorizeUrl = buildConnectCliClerkAuthorizeUrl(request);
87 if (!authorizeUrl) {
88 return;
89 }
90 redirecting.current = true;
91 rememberConnectCliAuthState(request.state);
92 window.location.assign(authorizeUrl);
93 }, [isLoaded, isSignedIn, openSignIn, request]);
94​
95 if (!request) {
96 return (
97 <AuthSurfaceShell>
98 <ConnectCliAuthMessage {...invalidLinkMessage} />
99 </AuthSurfaceShell>
100 );
101 }
102​
103 return (
104 <AuthSurfaceShell>
105 <ConnectCliAuthMessage
106 eyebrow={
107 request.loopbackPort === undefined
108 ? "Step 1 of 2 · Browser authorization"
109 : "Browser authorization"
110 }
111 title="Connecting your terminal"
112 description={
113 isSignedIn
114 ? "Redirecting to authorize T3 Connect for your CLI…"
115 : "Sign in to continue authorizing T3 Connect for your CLI."
116 }
117 />
118 {isLoaded && !isSignedIn ? (
119 <div className="mt-6">
120 <Button type="button" onClick={openSignIn}>
121 Sign in
122 </Button>
123 </div>
124 ) : null}
125 </AuthSurfaceShell>
126 );
128​
129/**
130 * /connect/callback: Clerk's redirect target. Shows the one-time code the
131 * user enters in the waiting terminal.
132 */
133export function ConnectCliCallbackSurface() {
134 const [result] = useState(readConnectCliCallbackResult);
135 const [expectedState] = useState(readConnectCliAuthState);
136 const { user } = useUser();
137 const { copyToClipboard, isCopied } = useCopyToClipboard({ target: "authentication code" });
138​
139 if (!result) {
140 return (
141 <AuthSurfaceShell>
142 <ConnectCliAuthMessage
143 eyebrow="Step 2 of 2 · Terminal handoff"
144 title="Authorization did not complete"
145 description="No authorization code was returned. Re-run `t3 connect` in your terminal and try again."
146 />
147 </AuthSurfaceShell>
148 );
149 }
150​
151 // Fail closed: the legitimate callback always lands in the same browser
152 // that visited /connect (which recorded the state), so a missing or
153 // mismatched state means this page was reached some other way — the CSRF
154 // shape the state parameter exists to stop. Refuse to display a code.
155 if (expectedState === null || expectedState !== result.state) {
156 return (
157 <AuthSurfaceShell>
158 <ConnectCliAuthMessage
159 eyebrow="Step 2 of 2 · Terminal handoff"
160 title="This code belongs to a different request"
161 description="This authorization response does not match a connect request started in this browser. Re-run `t3 connect` in your terminal and open the freshly printed URL in this browser."
162 />
163 </AuthSurfaceShell>
164 );
165 }
166​
167 const accountLabel = user?.primaryEmailAddress?.emailAddress ?? user?.username ?? null;
168 const authCode = encodeConnectAuthCode(result);
169​
170 return (
171 <AuthSurfaceShell>
172 <ConnectCliAuthMessage
173 eyebrow="Step 2 of 2 · Terminal handoff"
174 title="Almost connected"
175 description={
176 accountLabel
177 ? `Enter this code in your waiting terminal to connect it as ${accountLabel}.`
178 : "Enter this code in your waiting terminal to finish connecting."
179 }
180 />
181​
182 <div className="mt-6 overflow-hidden rounded-xl border border-border/80 bg-background/65">
183 <div className="flex items-center justify-between border-b border-border/70 px-4 py-2.5">
184 <span className="text-[10px] font-semibold tracking-[0.16em] text-muted-foreground uppercase">
185 One-time authorization code
186 </span>
187 <span className="font-mono text-[10px] text-muted-foreground">expires shortly</span>
188 </div>
189 <code
190 className="block p-4 font-mono text-sm leading-relaxed break-all select-all"
191 data-testid="connect-auth-code"
192 >
193 {authCode}
194 </code>
195 </div>
196​
197 <div className="mt-4 flex items-center gap-3">
198 <Button type="button" onClick={() => copyToClipboard(authCode)}>
199 {isCopied ? "Copied!" : "Copy authorization code"}
200 </Button>
201 </div>
202​
203 <p className="mt-6 text-xs leading-relaxed text-muted-foreground">
204 Only enter this code in a terminal session you started yourself. Anyone holding it can link
205 their machine to your T3 Connect account while it is valid.
206 </p>
207 </AuthSurfaceShell>
208 );