Open History to see the last commit
1import { readHashParams } from "./remote.ts";
2
3const CONNECT_AUTH_STATE_PARAM = "state";
4const CONNECT_AUTH_CHALLENGE_PARAM = "challenge";
5const CONNECT_AUTH_PORT_PARAM = "port";
6const CONNECT_AUTH_CODE_SEPARATOR = ".";
7const CONNECT_LOOPBACK_CALLBACK_PATH = "/callback";
8
9const CONNECT_AUTHORIZE_PATH = "/connect";
10const CONNECT_CALLBACK_PATH = "/connect/callback";
11
12/**
13 * The CLI prints URLs against this origin and the web bundle uses it to
14 * decide whether it is the hosted deployment — the two must agree, so the
15 * default lives here.
16 */
17export const DEFAULT_HOSTED_APP_URL = "https://app.t3.codes";
18
19/**
20 * Requested at authorize time by the hosted page and honored by the CLI's
21 * token exchange; keep both sides on this single definition.
22 */
23export const CONNECT_OAUTH_SCOPES = ["openid", "profile", "email"] as const;
24
25export interface ConnectAuthorizeRequest {
26 readonly state: string;
27 readonly challenge: string;
28 /**
29 * Present when a loopback CLI initiated the request: the hosted /connect
30 * page then asks Clerk to redirect the authorization code straight to
31 * `http://127.0.0.1:<port>/callback` instead of the hosted callback page.
32 */
33 readonly loopbackPort?: number;
34}
35
36/**
37 * The URL the CLI prints for the user to open in a browser. `state` and
38 * `code_challenge` ride the fragment so they never reach the hosted app's
39 * server or CDN logs; neither is a secret.
40 *
41 * Both CLI flows route through the hosted /connect page rather than hitting
42 * Clerk's /oauth/authorize directly: a signed-out browser sent straight to
43 * /oauth/authorize goes through Clerk's sign-in redirect, which does not
44 * reliably preserve the authorize query parameters (state, response_type,
45 * code_challenge). The hosted page waits for a Clerk session first, then
46 * forwards the request with the parameters intact.
47 */
48export function buildConnectAuthorizeRequestUrl(input: {
49 readonly hostedAppUrl: string;
50 readonly state: string;
51 readonly challenge: string;
52 readonly loopbackPort?: number;
53}): string {
54 const url = new URL(CONNECT_AUTHORIZE_PATH, input.hostedAppUrl);
55 url.hash = new URLSearchParams([
56 [CONNECT_AUTH_STATE_PARAM, input.state],
57 [CONNECT_AUTH_CHALLENGE_PARAM, input.challenge],
58 ...(input.loopbackPort === undefined
59 ? []
60 : [[CONNECT_AUTH_PORT_PARAM, String(input.loopbackPort)] as [string, string]]),
61 ]).toString();
62 return url.toString();
63}
64
65export function readConnectAuthorizeRequest(url: URL): ConnectAuthorizeRequest | null {
66 const params = readHashParams(url);
67 const state = params.get(CONNECT_AUTH_STATE_PARAM)?.trim() ?? "";
68 const challenge = params.get(CONNECT_AUTH_CHALLENGE_PARAM)?.trim() ?? "";
69 if (!state || !challenge) {
70 return null;
71 }
72 const port = params.get(CONNECT_AUTH_PORT_PARAM);
73 if (port === null) {
74 return { state, challenge };
75 }
76 // A present-but-invalid port means the link was corrupted; reject the whole
77 // request rather than silently downgrading a loopback flow to the
78 // out-of-band one, which would strand the waiting CLI.
79 const loopbackPort = parseLoopbackPort(port.trim());
80 if (loopbackPort === null) {
81 return null;
82 }
83 return { state, challenge, loopbackPort };
84}
85
86function parseLoopbackPort(value: string): number | null {
87 if (!/^\d{1,5}$/.test(value)) {
88 return null;
89 }
90 const port = Number(value);
91 return port >= 1 && port <= 65535 ? port : null;
92}
93
94/**
95 * Redirect URI for the CLI's local callback listener. Must stay in sync with
96 * the redirect URI registered on the Clerk CLI OAuth application.
97 */
98export function connectLoopbackRedirectUri(port: number): string {
99 return `http://127.0.0.1:${port}${CONNECT_LOOPBACK_CALLBACK_PATH}`;
100}
101
102export function connectCallbackUrl(hostedAppUrl: string): string {
103 return new URL(CONNECT_CALLBACK_PATH, hostedAppUrl).toString();
104}
105
106export function buildConnectClerkAuthorizeUrl(input: {
107 readonly authorizationEndpoint: string;
108 readonly clientId: string;
109 readonly redirectUri: string;
110 readonly scopes: ReadonlyArray<string>;
111 readonly state: string;
112 readonly challenge: string;
113}): string {
114 const url = new URL(input.authorizationEndpoint);
115 url.searchParams.set("client_id", input.clientId);
116 url.searchParams.set("redirect_uri", input.redirectUri);
117 url.searchParams.set("response_type", "code");
118 url.searchParams.set("scope", input.scopes.join(" "));
119 url.searchParams.set("state", input.state);
120 url.searchParams.set("code_challenge", input.challenge);
121 url.searchParams.set("code_challenge_method", "S256");
122 return url.toString();
123}
124
125export interface ConnectAuthCode {
126 readonly code: string;
127 readonly state: string;
128}
129
130/**
131 * The single blob the hosted callback page displays and the CLI accepts.
132 * Bundling `state` with the authorization code lets the CLI keep the loopback
133 * flow's CSRF check without any backend: it verifies the returned state
134 * matches the one it generated. Clerk authorization codes and the CLI's
135 * base64url states never contain ".".
136 */
137export function encodeConnectAuthCode(input: ConnectAuthCode): string {
138 return `${input.code}${CONNECT_AUTH_CODE_SEPARATOR}${input.state}`;
139}
140
141/**
142 * Validates an out-of-band authorization code against the state of the request this process
143 * generated. Returns the parsed code or a user-facing error message; both
144 * the prompt's live validation and the authoritative post-prompt check go
145 * through here so they cannot drift.
146 */
147export function checkConnectAuthCode(
148 blob: string,
149 expectedState: string,
150): ConnectAuthCode | string {
151 const parsed = parseConnectAuthCode(blob);
152 if (parsed === null) {
153 return "That does not look like a T3 Connect code. Copy the full code.";
154 }
155 if (parsed.state !== expectedState) {
156 return "That code belongs to a different connect request. Open the URL above and try again.";
157 }
158 return parsed;
159}
160
161export function parseConnectAuthCode(blob: string): ConnectAuthCode | null {
162 const trimmed = blob.trim();
163 const separatorIndex = trimmed.lastIndexOf(CONNECT_AUTH_CODE_SEPARATOR);
164 if (separatorIndex <= 0 || separatorIndex === trimmed.length - 1) {
165 return null;
166 }
167 const code = trimmed.slice(0, separatorIndex);
168 const state = trimmed.slice(separatorIndex + 1);
169 return { code, state };
170}