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

connectCliAuth.ts

100 lines3.5 KB

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);
18​
19export function hasConnectCliAuthConfig(): boolean {
20 return Boolean(
21 resolveCloudPublicConfig().clerkPublishableKey && resolveConnectCliOAuthClientId(),
22 );
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();
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 });
62​
63export function rememberConnectCliAuthState(state: string): void {
64 try {
65 window.sessionStorage.setItem(CONNECT_CLI_AUTH_STATE_STORAGE_KEY, state);
66 } catch {
67 // Session storage can be unavailable (e.g. blocked). The callback page
68 // then falls back to trusting the state Clerk echoed back.
69 }
71​
72/**
73 * Read-only on purpose: this runs during render, where a removal would be
74 * consumed by React's double-invoked/discarded renders (StrictMode) and
75 * silently disable the state check. The value is not a secret and is
76 * overwritten by the next /connect visit.
77 */
78export function readConnectCliAuthState(): string | null {
79 try {
80 return window.sessionStorage.getItem(CONNECT_CLI_AUTH_STATE_STORAGE_KEY);
81 } catch {
82 return null;
83 }
85​
86export interface ConnectCliCallbackResult {
87 readonly code: string;
88 readonly state: string;
90​
91export function readConnectCliCallbackResult(
92 url: URL = new URL(window.location.href),
93): ConnectCliCallbackResult | null {
94 const code = url.searchParams.get("code")?.trim() ?? "";
95 const state = url.searchParams.get("state")?.trim() ?? "";
96 if (!code || !state) {
97 return null;
98 }
99 return { code, state };