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

ConnectCliAuthSurface.tsx

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