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 { isRelayTracingEnabled } from "@t3tools/shared/otelEnvironment";
8import { normalizeSecureRelayUrl } from "@t3tools/shared/relayUrl";
9import * as Config from "effect/Config";
10import * as ConfigProvider from "effect/ConfigProvider";
11import * as Effect from "effect/Effect";
12import * as Schema from "effect/Schema";
13import * as SchemaIssue from "effect/SchemaIssue";
14
15declare const __T3CODE_BUILD_RELAY_URL__: string | undefined;
16declare const __T3CODE_BUILD_CLERK_PUBLISHABLE_KEY__: string | undefined;
17declare const __T3CODE_BUILD_CLERK_CLI_OAUTH_CLIENT_ID__: string | undefined;
18declare const __T3CODE_BUILD_RELAY_CLIENT_OTLP_TRACES_URL__: string | undefined;
19declare const __T3CODE_BUILD_RELAY_CLIENT_OTLP_TRACES_DATASET__: string | undefined;
20declare const __T3CODE_BUILD_RELAY_CLIENT_OTLP_TRACES_TOKEN__: string | undefined;
21
22const CLOUD_CLI_OAUTH_LOOPBACK_PORT = 34338;
23const CLOUD_CLI_OAUTH_SCOPES = CONNECT_OAUTH_SCOPES;
24
25function validateRelayUrl(value: string) {
26 const relayUrl = normalizeSecureRelayUrl(value);
27 return relayUrl === null
28 ? Effect.fail(
29 new Config.ConfigError(
30 new Schema.SchemaError(
31 new SchemaIssue.InvalidValue({
32 message: "Relay URL must be a secure absolute HTTPS origin.",
33 }),
34 ),
35 ),
36 )
37 : Effect.succeed(relayUrl);
38}
39
40function readBuildTimeValue(value: string | undefined): string {
41 return typeof value === "undefined" ? "" : value.trim();
42}
43
44function normalizeSecureUrl(value: string): string | null {
45 try {
46 const url = new URL(value);
47 return url.protocol === "https:" ? url.toString() : null;
48 } catch {
49 return null;
50 }
51}
52
53const buildTimeRelayUrl =
54 typeof __T3CODE_BUILD_RELAY_URL__ === "undefined"
55 ? ""
56 : (normalizeSecureRelayUrl(__T3CODE_BUILD_RELAY_URL__) ?? "");
57const buildTimeClerkPublishableKey = readBuildTimeValue(
58 typeof __T3CODE_BUILD_CLERK_PUBLISHABLE_KEY__ === "undefined"
59 ? undefined
60 : __T3CODE_BUILD_CLERK_PUBLISHABLE_KEY__,
61);
62const buildTimeClerkCliOAuthClientId = readBuildTimeValue(
63 typeof __T3CODE_BUILD_CLERK_CLI_OAUTH_CLIENT_ID__ === "undefined"
64 ? undefined
65 : __T3CODE_BUILD_CLERK_CLI_OAUTH_CLIENT_ID__,
66);
67const buildTimeRelayClientTracing = {
68 tracesUrl: readBuildTimeValue(
69 typeof __T3CODE_BUILD_RELAY_CLIENT_OTLP_TRACES_URL__ === "undefined"
70 ? undefined
71 : __T3CODE_BUILD_RELAY_CLIENT_OTLP_TRACES_URL__,
72 ),
73 tracesDataset: readBuildTimeValue(
74 typeof __T3CODE_BUILD_RELAY_CLIENT_OTLP_TRACES_DATASET__ === "undefined"
75 ? undefined
76 : __T3CODE_BUILD_RELAY_CLIENT_OTLP_TRACES_DATASET__,
77 ),
78 tracesToken: readBuildTimeValue(
79 typeof __T3CODE_BUILD_RELAY_CLIENT_OTLP_TRACES_TOKEN__ === "undefined"
80 ? undefined
81 : __T3CODE_BUILD_RELAY_CLIENT_OTLP_TRACES_TOKEN__,
82 ),
83} as const;
84
85export function resolveRelayClientTracingConfig(
86 env: Readonly<Record<string, string | undefined>> = process.env,
87 fallback = buildTimeRelayClientTracing,
88) {
89 if (!isRelayTracingEnabled(env)) {
90 return null;
91 }
92
93 const tracesUrl = env.T3CODE_RELAY_CLIENT_OTLP_TRACES_URL?.trim() || fallback.tracesUrl;
94 const tracesDataset =
95 env.T3CODE_RELAY_CLIENT_OTLP_TRACES_DATASET?.trim() || fallback.tracesDataset;
96 const tracesToken = env.T3CODE_RELAY_CLIENT_OTLP_TRACES_TOKEN?.trim() || fallback.tracesToken;
97 const normalizedTracesUrl = normalizeSecureUrl(tracesUrl);
98 return normalizedTracesUrl && tracesDataset && tracesToken
99 ? { tracesUrl: normalizedTracesUrl, tracesDataset, tracesToken }
100 : null;
101}
102
103export function makeRelayUrlConfig(fallback = buildTimeRelayUrl) {
104 const runtimeConfig = Config.NonEmptyString("T3CODE_RELAY_URL");
105 return (fallback ? runtimeConfig.pipe(Config.withDefault(fallback)) : runtimeConfig).pipe(
106 Config.mapEffect(validateRelayUrl),
107 );
108}
109
110export const relayUrlConfig = makeRelayUrlConfig();
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
152export interface CloudCliOAuthConfig {
153 readonly tokenEndpoint: string;
154 readonly deviceAuthorizationEndpoint: string;
155 readonly clientId: string;
156 readonly loopbackPort: number;
157 readonly redirectUri: string;
158 readonly scopes: typeof CLOUD_CLI_OAUTH_SCOPES;
159}
160
161export function makeCloudCliOAuthConfig({
162 clerkPublishableKeyFallback = buildTimeClerkPublishableKey,
163 clerkCliOAuthClientIdFallback = buildTimeClerkCliOAuthClientId,
164}: {
165 readonly clerkPublishableKeyFallback?: string;
166 readonly clerkCliOAuthClientIdFallback?: string;
167} = {}) {
168 return Config.all({
169 clerkPublishableKey: makePublicValueConfig(
170 "T3CODE_CLERK_PUBLISHABLE_KEY",
171 clerkPublishableKeyFallback,
172 ),
173 clientId: makePublicValueConfig(
174 "T3CODE_CLERK_CLI_OAUTH_CLIENT_ID",
175 clerkCliOAuthClientIdFallback,
176 ),
177 }).pipe(
178 Config.mapEffect(({ clerkPublishableKey, clientId }) =>
179 Effect.try({
180 try: () => clerkFrontendApiUrlFromPublishableKey(clerkPublishableKey),
181 catch: (cause) =>
182 new Config.ConfigError(
183 new ConfigProvider.SourceError({
184 message: "Failed to derive Clerk Frontend API URL from the publishable key.",
185 cause,
186 }),
187 ),
188 }).pipe(
189 Effect.map(
190 (clerkFrontendApiUrl) =>
191 ({
192 tokenEndpoint: `${clerkFrontendApiUrl}/oauth/token`,
193 deviceAuthorizationEndpoint: `${clerkFrontendApiUrl}/oauth/device_authorization`,
194 clientId,
195 loopbackPort: CLOUD_CLI_OAUTH_LOOPBACK_PORT,
196 redirectUri: connectLoopbackRedirectUri(CLOUD_CLI_OAUTH_LOOPBACK_PORT),
197 scopes: CLOUD_CLI_OAUTH_SCOPES,
198 }) satisfies CloudCliOAuthConfig,
199 ),
200 ),
201 ),
202 );
203}
204
205export const cloudCliOAuthConfig = makeCloudCliOAuthConfig();
206
207export const hasCloudPublicConfig = Boolean(
208 (normalizeSecureRelayUrl(process.env.T3CODE_RELAY_URL ?? "") ?? buildTimeRelayUrl) &&
209 (process.env.T3CODE_CLERK_PUBLISHABLE_KEY?.trim() || buildTimeClerkPublishableKey) &&
210 (process.env.T3CODE_CLERK_CLI_OAUTH_CLIENT_ID?.trim() || buildTimeClerkCliOAuthClientId),
211);