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

ConnectCliAuthSurface.tsx

198 lines6.7 KB

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