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

ConnectCliAuthSurface.tsx

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