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

connectCliAuth.ts

54 lines2.0 KB

1import {
2 buildConnectClerkAuthorizeUrl,
3 connectLoopbackRedirectUri,
4 CONNECT_OAUTH_SCOPES,
5 type ConnectAuthorizeRequest,
6} from "@t3tools/shared/connectAuth";
7import { clerkFrontendApiUrlFromPublishableKey } from "@t3tools/shared/relayAuth";
8​
9import { isHostedStaticApp } from "../hostedPairing";
10import { hasCloudPublicConfig, resolveCloudPublicConfig, trimNonEmpty } from "./publicConfig";
11​
12function resolveConnectCliOAuthClientId(): string | null {
13 return trimNonEmpty(import.meta.env.VITE_CLERK_CLI_OAUTH_CLIENT_ID as string | undefined);
15​
16export function hasConnectCliAuthConfig(): boolean {
17 return Boolean(
18 resolveCloudPublicConfig().clerkPublishableKey && resolveConnectCliOAuthClientId(),
19 );
21​
22export function connectCliAuthRoutesEnabled(): boolean {
23 return isHostedStaticApp() && hasCloudPublicConfig() && hasConnectCliAuthConfig();
25​
26export function buildConnectCliClerkAuthorizeUrl(request: ConnectAuthorizeRequest): string | null {
27 const { clerkPublishableKey } = resolveCloudPublicConfig();
28 const clientId = resolveConnectCliOAuthClientId();
29 if (!clerkPublishableKey || !clientId) {
30 return null;
31 }
32 return buildConnectClerkAuthorizeUrl({
33 authorizationEndpoint: `${clerkFrontendApiUrlFromPublishableKey(clerkPublishableKey)}/oauth/authorize`,
34 clientId,
35 redirectUri: connectLoopbackRedirectUri(request.loopbackPort),
36 scopes: CONNECT_OAUTH_SCOPES,
37 state: request.state,
38 challenge: request.challenge,
39 });
41​
42/**
43 * It has to be the authorize endpoint rather than this page: /connect carries the CLI request
44 * in its fragment, so navigating back to the same URL is a same-document fragment navigation
45 * the browser never reloads — and Clerk treats any post-sign-in navigation as a page unload and
46 * skips the state emit that would otherwise re-render the surface, so the session never arrives
47 * either.
48 */
49export function connectCliSignInRedirectUrl(
50 request: ConnectAuthorizeRequest,
51 currentHref: string,
52): string {
53 return buildConnectCliClerkAuthorizeUrl(request) ?? currentHref;