Open History to see the last commit
1import {
2 buildConnectClerkAuthorizeUrl,
3 connectCallbackUrl,
4 connectLoopbackRedirectUri,
5 CONNECT_OAUTH_SCOPES,
6 type ConnectAuthorizeRequest,
7} from "@t3tools/shared/connectAuth";
8import { clerkFrontendApiUrlFromPublishableKey } from "@t3tools/shared/relayAuth";
9
10import { configuredHostedAppUrl, isHostedStaticApp } from "../hostedPairing";
11import { hasCloudPublicConfig, resolveCloudPublicConfig, trimNonEmpty } from "./publicConfig";
12
13const CONNECT_CLI_AUTH_STATE_STORAGE_KEY = "t3code-connect-cli-auth-state";
14
15export function resolveConnectCliOAuthClientId(): string | null {
16 return trimNonEmpty(import.meta.env.VITE_CLERK_CLI_OAUTH_CLIENT_ID as string | undefined);
17}
18
19export function hasConnectCliAuthConfig(): boolean {
20 return Boolean(
21 resolveCloudPublicConfig().clerkPublishableKey && resolveConnectCliOAuthClientId(),
22 );
23}
24
25/**
26 * Gate for the /connect routes: the CLI handshake only exists on the hosted
27 * deployment (the same bundle ships inside local instances) and needs the
28 * Clerk CLI OAuth client configured at build time.
29 */
30export function connectCliAuthRoutesEnabled(): boolean {
31 return isHostedStaticApp() && hasCloudPublicConfig() && hasConnectCliAuthConfig();
32}
33
34/**
35 * Builds the Clerk authorize URL for a CLI-initiated connect request. The
36 * state is mirrored into sessionStorage so the callback page can verify the
37 * response matches a request this browser actually started.
38 *
39 * A request carrying a loopback port came from a CLI with a local callback
40 * listener: the authorization code must return to `127.0.0.1` directly, so
41 * the hosted callback page never sees it. Clerk enforces its registered
42 * redirect URI allowlist either way.
43 */
44export function buildConnectCliClerkAuthorizeUrl(request: ConnectAuthorizeRequest): string | null {
45 const { clerkPublishableKey } = resolveCloudPublicConfig();
46 const clientId = resolveConnectCliOAuthClientId();
47 if (!clerkPublishableKey || !clientId) {
48 return null;
49 }
50 return buildConnectClerkAuthorizeUrl({
51 authorizationEndpoint: `${clerkFrontendApiUrlFromPublishableKey(clerkPublishableKey)}/oauth/authorize`,
52 clientId,
53 redirectUri:
54 request.loopbackPort === undefined
55 ? connectCallbackUrl(configuredHostedAppUrl())
56 : connectLoopbackRedirectUri(request.loopbackPort),
57 scopes: CONNECT_OAUTH_SCOPES,
58 state: request.state,
59 challenge: request.challenge,
60 });
61}
62
63/**
64 * Where Clerk sends the browser once the sign-in modal on /connect completes.
65 * It has to be the authorize endpoint rather than this page: /connect carries
66 * the CLI request in its fragment, so navigating back to the same URL is a
67 * same-document fragment navigation the browser never reloads — and Clerk
68 * treats any post-sign-in navigation as a page unload and skips the state emit
69 * that would otherwise re-render the surface, so the session never arrives
70 * either. Falls back to the current URL when the authorize URL cannot be
71 * built, which only happens on a deployment without the CLI OAuth config.
72 */
73export function connectCliSignInRedirectUrl(
74 request: ConnectAuthorizeRequest,
75 currentHref: string,
76): string {
77 return buildConnectCliClerkAuthorizeUrl(request) ?? currentHref;
78}
79
80export function rememberConnectCliAuthState(state: string): void {
81 try {
82 window.sessionStorage.setItem(CONNECT_CLI_AUTH_STATE_STORAGE_KEY, state);
83 } catch {
84 // Session storage can be unavailable (e.g. blocked). The callback page
85 // then falls back to trusting the state Clerk echoed back.
86 }
87}
88
89/**
90 * Read-only on purpose: this runs during render, where a removal would be
91 * consumed by React's double-invoked/discarded renders (StrictMode) and
92 * silently disable the state check. The value is not a secret and is
93 * overwritten by the next /connect visit.
94 */
95export function readConnectCliAuthState(): string | null {
96 try {
97 return window.sessionStorage.getItem(CONNECT_CLI_AUTH_STATE_STORAGE_KEY);
98 } catch {
99 return null;
100 }
101}
102
103export interface ConnectCliCallbackResult {
104 readonly code: string;
105 readonly state: string;
106}
107
108export function readConnectCliCallbackResult(
109 url: URL = new URL(window.location.href),
110): ConnectCliCallbackResult | null {
111 const code = url.searchParams.get("code")?.trim() ?? "";
112 const state = url.searchParams.get("state")?.trim() ?? "";
113 if (!code || !state) {
114 return null;
115 }
116 return { code, state };
117}