Open History to see the last commit
1import {
2 connectLoopbackRedirectUri,
3 CONNECT_OAUTH_SCOPES,
4 DEFAULT_HOSTED_APP_URL,
5} from "@t3tools/shared/connectAuth";
6import { clerkFrontendApiUrlFromPublishableKey } from "@t3tools/shared/relayAuth";
7import { normalizeSecureRelayUrl } from "@t3tools/shared/relayUrl";
8import * as Config from "effect/Config";
9import * as ConfigProvider from "effect/ConfigProvider";
10import * as Effect from "effect/Effect";
11import * as Schema from "effect/Schema";
12import * as SchemaIssue from "effect/SchemaIssue";
13
14declare const __T3CODE_BUILD_RELAY_URL__: string | undefined;
15declare const __T3CODE_BUILD_CLERK_PUBLISHABLE_KEY__: string | undefined;
16declare const __T3CODE_BUILD_CLERK_CLI_OAUTH_CLIENT_ID__: string | undefined;
17declare const __T3CODE_BUILD_RELAY_CLIENT_OTLP_TRACES_URL__: string | undefined;
18declare const __T3CODE_BUILD_RELAY_CLIENT_OTLP_TRACES_DATASET__: string | undefined;
19declare const __T3CODE_BUILD_RELAY_CLIENT_OTLP_TRACES_TOKEN__: string | undefined;
20
21const CLOUD_CLI_OAUTH_LOOPBACK_PORT = 34338;
22const CLOUD_CLI_OAUTH_SCOPES = CONNECT_OAUTH_SCOPES;
23
24function validateRelayUrl(value: string) {
25 const relayUrl = normalizeSecureRelayUrl(value);
26 return relayUrl === null
27 ? Effect.fail(
28 new Config.ConfigError(
29 new Schema.SchemaError(
30 new SchemaIssue.InvalidValue({
31 message: "Relay URL must be a secure absolute HTTPS origin.",
32 }),
33 ),
34 ),
35 )
36 : Effect.succeed(relayUrl);
37}
38
39function readBuildTimeValue(value: string | undefined): string {
40 return typeof value === "undefined" ? "" : value.trim();
41}
42
43function normalizeSecureUrl(value: string): string | null {
44 try {
45 const url = new URL(value);
46 return url.protocol === "https:" ? url.toString() : null;
47 } catch {
48 return null;
49 }
50}
51
52const buildTimeRelayUrl =
53 typeof __T3CODE_BUILD_RELAY_URL__ === "undefined"
54 ? ""
55 : (normalizeSecureRelayUrl(__T3CODE_BUILD_RELAY_URL__) ?? "");
56const buildTimeClerkPublishableKey = readBuildTimeValue(
57 typeof __T3CODE_BUILD_CLERK_PUBLISHABLE_KEY__ === "undefined"
58 ? undefined
59 : __T3CODE_BUILD_CLERK_PUBLISHABLE_KEY__,
60);
61const buildTimeClerkCliOAuthClientId = readBuildTimeValue(
62 typeof __T3CODE_BUILD_CLERK_CLI_OAUTH_CLIENT_ID__ === "undefined"
63 ? undefined
64 : __T3CODE_BUILD_CLERK_CLI_OAUTH_CLIENT_ID__,
65);
66const buildTimeRelayClientTracing = {
67 tracesUrl: readBuildTimeValue(
68 typeof __T3CODE_BUILD_RELAY_CLIENT_OTLP_TRACES_URL__ === "undefined"
69 ? undefined
70 : __T3CODE_BUILD_RELAY_CLIENT_OTLP_TRACES_URL__,
71 ),
72 tracesDataset: readBuildTimeValue(
73 typeof __T3CODE_BUILD_RELAY_CLIENT_OTLP_TRACES_DATASET__ === "undefined"
74 ? undefined
75 : __T3CODE_BUILD_RELAY_CLIENT_OTLP_TRACES_DATASET__,
76 ),
77 tracesToken: readBuildTimeValue(
78 typeof __T3CODE_BUILD_RELAY_CLIENT_OTLP_TRACES_TOKEN__ === "undefined"
79 ? undefined
80 : __T3CODE_BUILD_RELAY_CLIENT_OTLP_TRACES_TOKEN__,
81 ),
82} as const;
83
84export function resolveRelayClientTracingConfig(
85 env: Readonly<Record<string, string | undefined>> = process.env,
86 fallback = buildTimeRelayClientTracing,
87) {
88 const tracesUrl = env.T3CODE_RELAY_CLIENT_OTLP_TRACES_URL?.trim() || fallback.tracesUrl;
89 const tracesDataset =
90 env.T3CODE_RELAY_CLIENT_OTLP_TRACES_DATASET?.trim() || fallback.tracesDataset;
91 const tracesToken = env.T3CODE_RELAY_CLIENT_OTLP_TRACES_TOKEN?.trim() || fallback.tracesToken;
92 const normalizedTracesUrl = normalizeSecureUrl(tracesUrl);
93 return normalizedTracesUrl && tracesDataset && tracesToken
94 ? { tracesUrl: normalizedTracesUrl, tracesDataset, tracesToken }
95 : null;
96}
97
98export function makeRelayUrlConfig(fallback = buildTimeRelayUrl) {
99 const runtimeConfig = Config.NonEmptyString("T3CODE_RELAY_URL");
100 return (fallback ? runtimeConfig.pipe(Config.withDefault(fallback)) : runtimeConfig).pipe(
101 Config.mapEffect(validateRelayUrl),
102 );
103}
104
105export const relayUrlConfig = makeRelayUrlConfig();
106
107/**
108 * Hosted app origin used for out-of-band OAuth on headless
109 * machines. Overridable so staging/nightly builds can point their CLIs at a
110 * matching hosted deployment.
111 */
112export const hostedAppUrlConfig = makePublicValueConfig(
113 "T3CODE_HOSTED_APP_URL",
114 DEFAULT_HOSTED_APP_URL,
115).pipe(Config.mapEffect(validateHostedAppUrl));
116
117function validateHostedAppUrl(value: string) {
118 try {
119 const url = new URL(value);
120 const isLoopbackHttp =
121 url.protocol === "http:" &&
122 (url.hostname === "localhost" || url.hostname === "127.0.0.1" || url.hostname === "[::1]");
123 if (
124 (url.protocol !== "https:" && !isLoopbackHttp) ||
125 url.pathname !== "/" ||
126 url.search !== "" ||
127 url.hash !== ""
128 ) {
129 throw new Error("invalid hosted app origin");
130 }
131 return Effect.succeed(url.origin);
132 } catch {
133 return Effect.fail(
134 new Config.ConfigError(
135 new Schema.SchemaError(
136 new SchemaIssue.InvalidValue({
137 message: "Hosted app URL must be an absolute HTTPS origin (or HTTP loopback origin).",
138 }),
139 ),
140 ),
141 );
142 }
143}
144
145function makePublicValueConfig(name: string, fallback: string) {
146 const runtimeConfig = Config.NonEmptyString(name);
147 return (fallback ? runtimeConfig.pipe(Config.withDefault(fallback)) : runtimeConfig).pipe(
148 Config.map((value) => value.trim()),
149 );
150}
151
152/**
153 * The CLI never calls Clerk's /oauth/authorize itself: the browser leg goes
154 * through the hosted /connect page, which builds the authorize URL after a
155 * Clerk session exists (see CliTokenManager.login). The token endpoint and,
156 * for headless hosts, the device authorization endpoint are contacted
157 * directly.
158 */
159export interface CloudCliOAuthConfig {
160 readonly tokenEndpoint: string;
161 readonly deviceAuthorizationEndpoint: string;
162 readonly clientId: string;
163 readonly loopbackPort: number;
164 readonly redirectUri: string;
165 readonly scopes: typeof CLOUD_CLI_OAUTH_SCOPES;
166}
167
168export function makeCloudCliOAuthConfig({
169 clerkPublishableKeyFallback = buildTimeClerkPublishableKey,
170 clerkCliOAuthClientIdFallback = buildTimeClerkCliOAuthClientId,
171}: {
172 readonly clerkPublishableKeyFallback?: string;
173 readonly clerkCliOAuthClientIdFallback?: string;
174} = {}) {
175 return Config.all({
176 clerkPublishableKey: makePublicValueConfig(
177 "T3CODE_CLERK_PUBLISHABLE_KEY",
178 clerkPublishableKeyFallback,
179 ),
180 clientId: makePublicValueConfig(
181 "T3CODE_CLERK_CLI_OAUTH_CLIENT_ID",
182 clerkCliOAuthClientIdFallback,
183 ),
184 }).pipe(
185 Config.mapEffect(({ clerkPublishableKey, clientId }) =>
186 Effect.try({
187 try: () => clerkFrontendApiUrlFromPublishableKey(clerkPublishableKey),
188 catch: (cause) =>
189 new Config.ConfigError(
190 new ConfigProvider.SourceError({
191 message: "Failed to derive Clerk Frontend API URL from the publishable key.",
192 cause,
193 }),
194 ),
195 }).pipe(
196 Effect.map(
197 (clerkFrontendApiUrl) =>
198 ({
199 tokenEndpoint: `${clerkFrontendApiUrl}/oauth/token`,
200 deviceAuthorizationEndpoint: `${clerkFrontendApiUrl}/oauth/device_authorization`,
201 clientId,
202 loopbackPort: CLOUD_CLI_OAUTH_LOOPBACK_PORT,
203 redirectUri: connectLoopbackRedirectUri(CLOUD_CLI_OAUTH_LOOPBACK_PORT),
204 scopes: CLOUD_CLI_OAUTH_SCOPES,
205 }) satisfies CloudCliOAuthConfig,
206 ),
207 ),
208 ),
209 );
210}
211
212export const cloudCliOAuthConfig = makeCloudCliOAuthConfig();
213
214export const hasCloudPublicConfig = Boolean(
215 (normalizeSecureRelayUrl(process.env.T3CODE_RELAY_URL ?? "") ?? buildTimeRelayUrl) &&
216 (process.env.T3CODE_CLERK_PUBLISHABLE_KEY?.trim() || buildTimeClerkPublishableKey) &&
217 (process.env.T3CODE_CLERK_CLI_OAUTH_CLIENT_ID?.trim() || buildTimeClerkCliOAuthClientId),
218);