feat(cloud): make relay public config opt-in

Co-authored-by: codex <[email protected]>
This commit is contained in:
Julius Marmingeandcodex committed 2026-06-03 23:48:05 -07:00
1 parent c2d004a20e
commit 4600dd719f
26 files changed
+411 -309

No files matched your search

+8 -3
View File
@@ -1,5 +1,10 @@
# Optional root-level overrides for the checked-in public client configuration.
# Server-side secrets must never be committed here.
#
# Optional: T3 Cloud source builds
# Leave these unset to disable optional T3 Cloud features in local source builds.
# Release builds inject their public values at build time. Do not add server-side
# secrets to this file.
# Get this from the Clerk Dashboard under API keys.
# T3CODE_CLERK_PUBLISHABLE_KEY=pk_test_...
# Get this from your relay deployment. `infra/relay` deploys update it automatically.
# T3_RELAY_URL=https://relay.example.com
+3 -4
View File
@@ -62,10 +62,9 @@ mise install
vp install
```
T3 Cloud public client configuration has checked-in development defaults, so a fresh clone works
without creating app-local `.env` files. To point web, desktop, and mobile at another Clerk/relay
deployment, copy [`.env.example`](./.env.example) to `.env` at the repository root and set the
canonical overrides there.
T3 Cloud is optional and disabled in a fresh clone. To enable it for web, desktop, and mobile source
builds, copy [`.env.example`](./.env.example) to `.env` at the repository root and set the canonical
public configuration there.
Read [CONTRIBUTING.md](./CONTRIBUTING.md) before opening an issue or PR.
+2 -2
View File
@@ -16,8 +16,8 @@ This app has three variants:
Run commands from `apps/mobile`.
Public T3 Cloud development defaults are shared with web and desktop. Optional overrides belong in
the repository-root `.env` or `.env.local`, not an `apps/mobile/.env` file. See
T3 Cloud is optional and disabled in a fresh clone. Public configuration belongs in the
repository-root `.env` or `.env.local`, not an `apps/mobile/.env` file. See
[`../../.env.example`](../../.env.example).
## Development
+103 -106
View File
@@ -11,6 +11,7 @@ import { useSafeAreaInsets } from "react-native-safe-area-context";
import { AppText as Text } from "../../components/AppText";
import { connectCloudEnvironment } from "../../features/cloud/linkEnvironment";
import { hasCloudPublicConfig } from "../../features/cloud/publicConfig";
import {
useManagedRelayEnvironments,
useManagedRelayEnvironmentStatus,
@@ -26,22 +27,15 @@ import {
} from "../../state/use-remote-environment-registry";
export default function SettingsEnvironmentsRouteScreen() {
const { getToken, isSignedIn } = useAuth({ treatPendingAsSignedOut: false });
const {
connectedEnvironments,
onReconnectEnvironment,
onRemoveEnvironmentPress,
onUpdateEnvironment,
} = useRemoteConnections();
const { savedConnectionsById } = useRemoteEnvironmentState();
const insets = useSafeAreaInsets();
const hasEnvironments = connectedEnvironments.length > 0;
const [expandedId, setExpandedId] = useState<EnvironmentId | null>(null);
const cloudEnvironmentsState = useManagedRelayEnvironments();
const [connectingCloudEnvironmentId, setConnectingCloudEnvironmentId] = useState<string | null>(
null,
);
const accentColor = useThemeColor("--color-icon-muted");
const iconColor = useThemeColor("--color-icon");
@@ -49,40 +43,6 @@ export default function SettingsEnvironmentsRouteScreen() {
setExpandedId((prev) => (prev === environmentId ? null : environmentId));
}, []);
const availableCloudEnvironments = useMemo(
() =>
(cloudEnvironmentsState.data ?? []).filter(
(environment) => savedConnectionsById[environment.environmentId] === undefined,
),
[cloudEnvironmentsState.data, savedConnectionsById],
);
const handleConnectCloudEnvironment = useCallback(
async (environment: RelayClientEnvironmentRecord) => {
setConnectingCloudEnvironmentId(environment.environmentId);
try {
const token = await getToken(RELAY_CLERK_TOKEN_OPTIONS);
if (!token) {
throw new Error("Sign in to T3 Cloud before connecting.");
}
await mobileRuntime.runPromise(
connectCloudEnvironment({
clerkToken: token,
environment,
}).pipe(Effect.flatMap(connectSavedEnvironment)),
);
} catch (error) {
Alert.alert(
"Connect failed",
error instanceof Error ? error.message : "Could not connect to this environment.",
);
} finally {
setConnectingCloudEnvironmentId(null);
}
},
[getToken],
);
return (
<View collapsable={false} className="flex-1 bg-sheet">
<Stack.Screen
@@ -156,76 +116,113 @@ export default function SettingsEnvironmentsRouteScreen() {
</View>
)}
{isSignedIn ? (
<View collapsable={false} className="mt-5 gap-3">
<View className="flex-row items-center justify-between px-1">
<Text className="text-[13px] font-t3-bold uppercase text-foreground-muted">
T3 Cloud
</Text>
<Pressable
accessibilityRole="button"
disabled={cloudEnvironmentsState.isPending}
onPress={cloudEnvironmentsState.refresh}
className="h-9 w-9 items-center justify-center rounded-full bg-subtle active:opacity-70 disabled:opacity-50"
>
{cloudEnvironmentsState.isPending ? (
<ActivityIndicator color={iconColor} size="small" />
) : (
<SymbolView
name="arrow.clockwise"
size={14}
tintColor={iconColor}
type="monochrome"
/>
)}
</Pressable>
</View>
{availableCloudEnvironments.length > 0 ? (
<View collapsable={false} className="overflow-hidden rounded-[24px] bg-card">
{availableCloudEnvironments.map((environment, index) => (
<CloudEnvironmentRow
key={environment.environmentId}
environment={environment}
borderTop={index !== 0}
isConnecting={connectingCloudEnvironmentId === environment.environmentId}
onConnect={() => handleConnectCloudEnvironment(environment)}
/>
))}
</View>
) : cloudEnvironmentsState.data === null ? (
<View
collapsable={false}
className="items-center gap-3 rounded-[24px] bg-card px-6 py-6"
>
<ActivityIndicator color={iconColor} />
<Text className="text-center text-[14px] leading-[20px] text-foreground-muted">
Loading linked cloud environments.
</Text>
</View>
) : cloudEnvironmentsState.error ? (
<View collapsable={false} className="gap-3 rounded-[24px] bg-card px-5 py-5">
<Text className="text-[15px] font-t3-bold text-foreground">
Could not load T3 Cloud environments
</Text>
<Text className="text-[13px] leading-[18px] text-foreground-muted">
{cloudEnvironmentsState.error}
</Text>
</View>
) : (
<View collapsable={false} className="rounded-[24px] bg-card px-5 py-5">
<Text className="text-[14px] leading-[20px] text-foreground-muted">
No additional linked cloud environments.
</Text>
</View>
)}
</View>
) : null}
{hasCloudPublicConfig() ? <ConfiguredCloudEnvironmentRows /> : null}
</ScrollView>
</View>
);
}
function ConfiguredCloudEnvironmentRows() {
const { getToken, isSignedIn } = useAuth({ treatPendingAsSignedOut: false });
const { savedConnectionsById } = useRemoteEnvironmentState();
const cloudEnvironmentsState = useManagedRelayEnvironments();
const [connectingCloudEnvironmentId, setConnectingCloudEnvironmentId] = useState<string | null>(
null,
);
const iconColor = useThemeColor("--color-icon");
const availableCloudEnvironments = useMemo(
() =>
(cloudEnvironmentsState.data ?? []).filter(
(environment) => savedConnectionsById[environment.environmentId] === undefined,
),
[cloudEnvironmentsState.data, savedConnectionsById],
);
const handleConnectCloudEnvironment = useCallback(
async (environment: RelayClientEnvironmentRecord) => {
setConnectingCloudEnvironmentId(environment.environmentId);
try {
const token = await getToken(RELAY_CLERK_TOKEN_OPTIONS);
if (!token) {
throw new Error("Sign in to T3 Cloud before connecting.");
}
await mobileRuntime.runPromise(
connectCloudEnvironment({
clerkToken: token,
environment,
}).pipe(Effect.flatMap(connectSavedEnvironment)),
);
} catch (error) {
Alert.alert(
"Connect failed",
error instanceof Error ? error.message : "Could not connect to this environment.",
);
} finally {
setConnectingCloudEnvironmentId(null);
}
},
[getToken],
);
if (!isSignedIn) return null;
return (
<View collapsable={false} className="mt-5 gap-3">
<View className="flex-row items-center justify-between px-1">
<Text className="text-[13px] font-t3-bold uppercase text-foreground-muted">T3 Cloud</Text>
<Pressable
accessibilityRole="button"
disabled={cloudEnvironmentsState.isPending}
onPress={cloudEnvironmentsState.refresh}
className="h-9 w-9 items-center justify-center rounded-full bg-subtle active:opacity-70 disabled:opacity-50"
>
{cloudEnvironmentsState.isPending ? (
<ActivityIndicator color={iconColor} size="small" />
) : (
<SymbolView name="arrow.clockwise" size={14} tintColor={iconColor} type="monochrome" />
)}
</Pressable>
</View>
{availableCloudEnvironments.length > 0 ? (
<View collapsable={false} className="overflow-hidden rounded-[24px] bg-card">
{availableCloudEnvironments.map((environment, index) => (
<CloudEnvironmentRow
key={environment.environmentId}
environment={environment}
borderTop={index !== 0}
isConnecting={connectingCloudEnvironmentId === environment.environmentId}
onConnect={() => handleConnectCloudEnvironment(environment)}
/>
))}
</View>
) : cloudEnvironmentsState.data === null ? (
<View collapsable={false} className="items-center gap-3 rounded-[24px] bg-card p-6">
<ActivityIndicator color={iconColor} />
<Text className="text-center text-[14px] leading-[20px] text-foreground-muted">
Loading linked cloud environments.
</Text>
</View>
) : cloudEnvironmentsState.error ? (
<View collapsable={false} className="gap-3 rounded-[24px] bg-card p-5">
<Text className="text-[15px] font-t3-bold text-foreground">
Could not load T3 Cloud environments
</Text>
<Text className="text-[13px] leading-[18px] text-foreground-muted">
{cloudEnvironmentsState.error}
</Text>
</View>
) : (
<View collapsable={false} className="rounded-[24px] bg-card p-5">
<Text className="text-[14px] leading-[20px] text-foreground-muted">
No additional linked cloud environments.
</Text>
</View>
)}
</View>
);
}
function CloudEnvironmentRow(props: {
readonly environment: RelayClientEnvironmentRecord;
readonly borderTop: boolean;
+62 -16
View File
@@ -14,6 +14,7 @@ import { setLiveActivityUpdatesEnabled } from "../../features/agent-awareness/li
import { requestAgentNotificationPermission } from "../../features/agent-awareness/notificationPermissions";
import { refreshAgentAwarenessRegistration } from "../../features/agent-awareness/remoteRegistration";
import { refreshManagedRelayEnvironments } from "../../features/cloud/managedRelayState";
import { hasCloudPublicConfig } from "../../features/cloud/publicConfig";
import { mobileRuntime } from "../../lib/runtime";
import { loadPreferences } from "../../lib/storage";
import { useThemeColor } from "../../lib/useThemeColor";
@@ -23,6 +24,44 @@ type NotificationStatus = "checking" | "enabled" | "disabled" | "unsupported";
type LiveActivityStatus = "checking" | "enabled" | "disabled" | "signed-out" | "linking";
export default function SettingsRouteScreen() {
return hasCloudPublicConfig() ? <ConfiguredSettingsRouteScreen /> : <LocalSettingsRouteScreen />;
}
function LocalSettingsRouteScreen() {
const insets = useSafeAreaInsets();
const { savedConnectionsById } = useRemoteEnvironmentState();
const environmentCount = Object.keys(savedConnectionsById).length;
return (
<View collapsable={false} className="flex-1 bg-sheet">
<Stack.Screen options={{ title: "Settings" }} />
<ScrollView
contentInsetAdjustmentBehavior="automatic"
showsVerticalScrollIndicator={false}
style={{ flex: 1 }}
contentContainerStyle={{
gap: 24,
paddingBottom: Math.max(insets.bottom, 18) + 18,
paddingHorizontal: 20,
paddingTop: 16,
}}
>
<SettingsSection title="Configuration">
<SettingsRow
icon="desktopcomputer"
label="Environments"
value={`${environmentCount}`}
href="/settings/environments"
/>
</SettingsSection>
<AppSettingsSection />
</ScrollView>
</View>
);
}
function ConfiguredSettingsRouteScreen() {
const insets = useSafeAreaInsets();
const { push } = useRouter();
const { getToken, isLoaded, isSignedIn } = useAuth({ treatPendingAsSignedOut: false });
@@ -32,7 +71,6 @@ export default function SettingsRouteScreen() {
const [notificationStatus, setNotificationStatus] = useState<NotificationStatus>("checking");
const [liveActivityStatus, setLiveActivityStatus] = useState<LiveActivityStatus>("checking");
const icon = useThemeColor("--color-icon");
const connections = useMemo(() => Object.values(savedConnectionsById), [savedConnectionsById]);
const environmentCount = connections.length;
const accountLabel = useMemo(() => {
@@ -289,19 +327,7 @@ export default function SettingsRouteScreen() {
/>
</SettingsSection>
<SettingsSection title="App">
<View className="flex-row items-center gap-4 px-4 py-4">
<SymbolView
name="info.circle"
size={22}
tintColor={icon}
type="monochrome"
weight="regular"
/>
<Text className="flex-1 text-[17px] text-foreground">Version</Text>
<Text className="text-[17px] text-foreground-muted">Alpha</Text>
</View>
</SettingsSection>
<AppSettingsSection />
</ScrollView>
</View>
);
@@ -323,6 +349,26 @@ function SettingsSection(props: { readonly title: string; readonly children: Rea
);
}
function AppSettingsSection() {
const icon = useThemeColor("--color-icon");
return (
<SettingsSection title="App">
<View className="flex-row items-center gap-4 p-4">
<SymbolView
name="info.circle"
size={22}
tintColor={icon}
type="monochrome"
weight="regular"
/>
<Text className="flex-1 text-[17px] text-foreground">Version</Text>
<Text className="text-[17px] text-foreground-muted">Alpha</Text>
</View>
</SettingsSection>
);
}
function SettingsRow(props: {
readonly disabled?: boolean;
readonly icon: SymbolName;
@@ -335,7 +381,7 @@ function SettingsRow(props: {
const chevron = useThemeColor("--color-chevron");
const content = (
<View
className="flex-row items-center gap-4 px-4 py-4"
className="flex-row items-center gap-4 p-4"
style={{ opacity: props.disabled ? 0.45 : 1 }}
>
<SymbolView name={props.icon} size={22} tintColor={icon} type="monochrome" weight="regular" />
@@ -386,7 +432,7 @@ function SettingsSwitchRow(props: {
return (
<View
className="flex-row items-center gap-4 px-4 py-4"
className="flex-row items-center gap-4 p-4"
style={{ opacity: props.disabled ? 0.45 : 1 }}
>
<SymbolView name={props.icon} size={22} tintColor={icon} type="monochrome" weight="regular" />
+12 -41
View File
@@ -1,22 +1,20 @@
import Constants from "expo-constants";
import { Stack } from "expo-router";
import { ScrollView, Text, View } from "react-native";
import { Redirect, Stack } from "expo-router";
import { ScrollView } from "react-native";
import { CloudWaitlistEnrollment } from "../../features/cloud/CloudWaitlistEnrollment";
import { hasCloudPublicConfig } from "../../features/cloud/publicConfig";
import { useNativeClerkAuthModal } from "../../features/cloud/useNativeClerkAuthModal";
import { useThemeColor } from "../../lib/useThemeColor";
function hasClerkConfig(): boolean {
const clerkConfig = Constants.expoConfig?.extra?.clerk as
| { readonly publishableKey?: string | null }
| undefined;
return Boolean(clerkConfig?.publishableKey);
}
export default function SettingsWaitlistRouteScreen() {
return hasCloudPublicConfig() ? (
<ConfiguredSettingsWaitlistRouteScreen />
) : (
<Redirect href="/settings" />
);
}
function ConfiguredSettingsWaitlistRouteScreen() {
const { presentAuth } = useNativeClerkAuthModal();
const foreground = String(useThemeColor("--color-foreground"));
const secondaryForeground = String(useThemeColor("--color-foreground-secondary"));
return (
<>
@@ -33,34 +31,7 @@ export default function SettingsWaitlistRouteScreen() {
keyboardShouldPersistTaps="handled"
showsVerticalScrollIndicator={false}
>
{hasClerkConfig() ? (
<CloudWaitlistEnrollment onSignIn={() => void presentAuth()} />
) : (
<View className="gap-3 px-4">
<Text
style={{
color: foreground,
fontFamily: "DMSans_700Bold",
fontSize: 22,
textAlign: "center",
}}
>
T3 Cloud is not configured
</Text>
<Text
selectable
style={{
color: secondaryForeground,
fontFamily: "DMSans_400Regular",
fontSize: 16,
lineHeight: 22,
textAlign: "center",
}}
>
Add T3CODE_CLERK_PUBLISHABLE_KEY to this build to enable waitlist enrollment.
</Text>
</View>
)}
<CloudWaitlistEnrollment onSignIn={() => void presentAuth()} />
</ScrollView>
</>
);
@@ -18,6 +18,7 @@ import {
loadPreferences,
} from "../../lib/storage";
import type { AgentActivityProps } from "../../widgets/AgentActivity";
import { resolveCloudPublicConfig } from "../cloud/publicConfig";
import { makeRelayDeviceRegistrationRequest } from "./registrationPayload";
const environmentConnections = new Map<EnvironmentId, SavedRemoteConnection>();
@@ -38,10 +39,7 @@ export function normalizeAgentAwarenessRelayBaseUrl(
}
function readRelayConfig(): { readonly url: string } | null {
const relayConfig = Constants.expoConfig?.extra?.relay as
| { readonly url?: string | null }
| undefined;
const relayUrl = normalizeAgentAwarenessRelayBaseUrl(relayConfig?.url);
const relayUrl = resolveCloudPublicConfig().relayUrl;
if (!relayUrl) {
logRegistrationDebug("relay registration skipped; relay config missing");
return null;
@@ -1,7 +1,6 @@
import { ClerkProvider, useAuth } from "@clerk/expo";
import { tokenCache } from "@clerk/expo/token-cache";
import { createManagedRelaySession, setManagedRelaySession } from "@t3tools/client-runtime";
import Constants from "expo-constants";
import { type ReactNode, useEffect, useRef } from "react";
import { RELAY_CLERK_TOKEN_OPTIONS } from "@t3tools/shared/relayAuth";
@@ -12,13 +11,7 @@ import {
unregisterAgentAwarenessDeviceForCurrentUser,
} from "../agent-awareness/remoteRegistration";
import { refreshActiveLiveActivityRemoteRegistration } from "../agent-awareness/liveActivityController";
function readClerkPublishableKey(): string | null {
const clerkConfig = Constants.expoConfig?.extra?.clerk as
| { readonly publishableKey?: string | null }
| undefined;
return clerkConfig?.publishableKey ?? null;
}
import { resolveCloudPublicConfig } from "./publicConfig";
function CloudAuthBridge(props: { readonly children: ReactNode }) {
const { getToken, isLoaded, isSignedIn, userId } = useAuth({ treatPendingAsSignedOut: false });
@@ -80,16 +73,16 @@ function CloudAuthBridge(props: { readonly children: ReactNode }) {
}
export function CloudAuthProvider(props: { readonly children: ReactNode }) {
const publishableKey = readClerkPublishableKey();
const { clerkPublishableKey: publishableKey, relayUrl } = resolveCloudPublicConfig();
useEffect(() => {
if (!publishableKey) {
if (!publishableKey || !relayUrl) {
setAgentAwarenessRelayTokenProvider(null);
setManagedRelaySession(appAtomRegistry, null);
}
}, [publishableKey]);
}, [publishableKey, relayUrl]);
if (!publishableKey) {
if (!publishableKey || !relayUrl) {
return props.children;
}
@@ -1,4 +1,3 @@
import Constants from "expo-constants";
import * as Data from "effect/Data";
import * as Effect from "effect/Effect";
import * as Schema from "effect/Schema";
@@ -35,6 +34,7 @@ import {
import { mobileAuthClientMetadata } from "../../lib/authClientMetadata";
import type { SavedRemoteConnection } from "../../lib/connection";
import { loadOrCreateAgentAwarenessDeviceId, loadPreferences } from "../../lib/storage";
import { resolveCloudPublicConfig } from "./publicConfig";
const RELAY_STATUS_AND_CONNECT_SCOPES = [
RelayEnvironmentStatusScope,
@@ -50,10 +50,7 @@ export function normalizeRelayBaseUrl(value: string | null | undefined): string
}
function readRelayUrl(): string | null {
const relayConfig = Constants.expoConfig?.extra?.relay as
| { readonly url?: string | null }
| undefined;
return normalizeRelayBaseUrl(relayConfig?.url);
return resolveCloudPublicConfig().relayUrl;
}
export class CloudEnvironmentLinkError extends Data.TaggedError("CloudEnvironmentLinkError")<{
@@ -0,0 +1,32 @@
import { describe, expect, it, vi } from "vitest";
import { resolveCloudPublicConfig } from "./publicConfig";
vi.mock("expo-constants", () => ({
default: {
expoConfig: {
extra: {},
},
},
}));
describe("resolveCloudPublicConfig", () => {
it("returns no cloud configuration for an unconfigured build", () => {
expect(resolveCloudPublicConfig({})).toEqual({
clerkPublishableKey: null,
relayUrl: null,
});
});
it("normalizes statically injected cloud configuration", () => {
expect(
resolveCloudPublicConfig({
clerk: { publishableKey: " pk_test_example " },
relay: { url: " https://relay.example.test/// " },
}),
).toEqual({
clerkPublishableKey: "pk_test_example",
relayUrl: "https://relay.example.test",
});
});
});
@@ -0,0 +1,27 @@
import Constants from "expo-constants";
type ExpoExtra = Readonly<Record<string, unknown>> | undefined;
export interface CloudPublicConfig {
readonly clerkPublishableKey: string | null;
readonly relayUrl: string | null;
}
function trimNonEmpty(value: unknown): string | null {
return typeof value === "string" && value.trim() ? value.trim() : null;
}
export function resolveCloudPublicConfig(extra: ExpoExtra = Constants.expoConfig?.extra) {
const clerk = extra?.clerk as { readonly publishableKey?: unknown } | undefined;
const relay = extra?.relay as { readonly url?: unknown } | undefined;
return {
clerkPublishableKey: trimNonEmpty(clerk?.publishableKey),
relayUrl: trimNonEmpty(relay?.url)?.replace(/\/+$/u, "") ?? null,
} satisfies CloudPublicConfig;
}
export function hasCloudPublicConfig(): boolean {
const config = resolveCloudPublicConfig();
return Boolean(config.clerkPublishableKey && config.relayUrl);
}
+2 -4
View File
@@ -1,4 +1,3 @@
import Constants from "expo-constants";
import * as Layer from "effect/Layer";
import * as ManagedRuntime from "effect/ManagedRuntime";
@@ -6,11 +5,10 @@ import { remoteHttpClientLayer } from "@t3tools/client-runtime";
import { mobileCryptoLayer } from "../features/cloud/dpop";
import { mobileManagedRelayClientLayer } from "../features/cloud/managedRelayLayer";
import { resolveCloudPublicConfig } from "../features/cloud/publicConfig";
function configuredRelayUrl(): string {
const relay = Constants.expoConfig?.extra?.relay as { readonly url?: string | null } | undefined;
const value = relay?.url?.trim();
return value ? value.replace(/\/+$/g, "") : "http://relay.invalid";
return resolveCloudPublicConfig().relayUrl ?? "http://relay.invalid";
}
const mobileHttpClientLayer = remoteHttpClientLayer(fetch);
+2 -1
View File
@@ -37,6 +37,7 @@ import {
resolvePrimaryEnvironmentHttpUrl,
} from "../environments/primary";
import { withPrimaryEnvironmentRequestInit } from "../environments/primary/requestInit";
import { resolveCloudPublicConfig } from "./publicConfig";
export function normalizeRelayBaseUrl(value: string | null | undefined): string | null {
const trimmed = value?.trim();
@@ -47,7 +48,7 @@ export function normalizeRelayBaseUrl(value: string | null | undefined): string
}
function relayUrl(): string | null {
return normalizeRelayBaseUrl(import.meta.env.VITE_T3_RELAY_URL as string | undefined);
return resolveCloudPublicConfig().relayUrl;
}
export class CloudEnvironmentLinkError extends Data.TaggedError("CloudEnvironmentLinkError")<{
+21
View File
@@ -0,0 +1,21 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import { hasCloudPublicConfig } from "./publicConfig.ts";
afterEach(() => {
vi.unstubAllEnvs();
});
describe("hasCloudPublicConfig", () => {
it("requires both public cloud values", () => {
vi.stubEnv("VITE_CLERK_PUBLISHABLE_KEY", "");
vi.stubEnv("VITE_T3_RELAY_URL", "");
expect(hasCloudPublicConfig()).toBe(false);
vi.stubEnv("VITE_CLERK_PUBLISHABLE_KEY", "pk_test_example");
expect(hasCloudPublicConfig()).toBe(false);
vi.stubEnv("VITE_T3_RELAY_URL", "https://relay.example.test");
expect(hasCloudPublicConfig()).toBe(true);
});
});
+24
View File
@@ -0,0 +1,24 @@
export interface CloudPublicConfig {
readonly clerkPublishableKey: string | null;
readonly relayUrl: string | null;
}
function trimNonEmpty(value: string | undefined): string | null {
return value?.trim() || null;
}
export function resolveCloudPublicConfig(): CloudPublicConfig {
return {
clerkPublishableKey: trimNonEmpty(
import.meta.env.VITE_CLERK_PUBLISHABLE_KEY as string | undefined,
),
relayUrl:
trimNonEmpty(import.meta.env.VITE_T3_RELAY_URL as string | undefined)?.replace(/\/+$/u, "") ??
null,
};
}
export function hasCloudPublicConfig(): boolean {
const config = resolveCloudPublicConfig();
return Boolean(config.clerkPublishableKey && config.relayUrl);
}
@@ -4,6 +4,7 @@ import { CloudIcon, RefreshCwIcon, SmartphoneIcon } from "lucide-react";
import { useEffect, useState } from "react";
import { updatePrimaryCloudPreferences } from "../../cloud/linkEnvironment";
import { hasCloudPublicConfig } from "../../cloud/publicConfig";
import { useManagedRelayDevices } from "../../cloud/managedRelayState";
import { usePrimaryCloudLinkState } from "../../cloud/primaryCloudLinkState";
import { isElectron } from "../../env";
@@ -49,27 +50,12 @@ function EmptyNotificationDevices() {
);
}
function hasClerkConfig(): boolean {
return Boolean(import.meta.env.VITE_CLERK_PUBLISHABLE_KEY);
}
function cloudErrorMessage(error: unknown, fallback: string): string {
return error instanceof Error ? error.message : fallback;
}
export function CloudSettingsPanel() {
if (!hasClerkConfig()) {
return (
<SettingsPageContainer>
<SettingsSection title="T3 Cloud" icon={<CloudIcon className="size-3.5" />}>
<SettingsRow
title="Cloud account"
description="Set T3CODE_CLERK_PUBLISHABLE_KEY to enable optional cloud features."
/>
</SettingsSection>
</SettingsPageContainer>
);
}
if (!hasCloudPublicConfig()) return null;
return <ConfiguredCloudSettingsPanel />;
}
@@ -128,13 +128,10 @@ import {
} from "~/cloud/managedRelayState";
import { usePrimaryCloudLinkState } from "~/cloud/primaryCloudLinkState";
import { webRuntime } from "~/lib/runtime";
import { hasCloudPublicConfig } from "~/cloud/publicConfig";
const DEFAULT_TAILSCALE_SERVE_PORT = 443;
function hasCloudConfig(): boolean {
return Boolean(import.meta.env.VITE_CLERK_PUBLISHABLE_KEY);
}
const accessTimestampFormatter = new Intl.DateTimeFormat(undefined, {
dateStyle: "medium",
timeStyle: "short",
@@ -1704,24 +1701,10 @@ function ConfiguredCloudLinkRow({ canManageRelay }: { readonly canManageRelay: b
}
function CloudLinkRow({ canManageRelay }: { readonly canManageRelay: boolean }) {
return hasCloudConfig() ? (
<ConfiguredCloudLinkRow canManageRelay={canManageRelay} />
) : (
<SettingsRow
title="T3 Cloud"
description="Make this environment available to your other devices through T3 Cloud."
control={
<CloudLinkSwitch
checked={false}
disabled
disabledReason="T3 Cloud is not configured in this build."
/>
}
/>
);
return hasCloudPublicConfig() ? <ConfiguredCloudLinkRow canManageRelay={canManageRelay} /> : null;
}
function EmptyRemoteEnvironments() {
function EmptyRemoteEnvironments({ cloudEnabled = true }: { readonly cloudEnabled?: boolean }) {
return (
<Empty className="min-h-52">
<EmptyMedia variant="icon">
@@ -1730,8 +1713,9 @@ function EmptyRemoteEnvironments() {
<EmptyHeader>
<EmptyTitle>No saved remote environments</EmptyTitle>
<EmptyDescription>
Click &ldquo;Add environment&rdquo; to pair another environment, or connect one from T3
Cloud.
{cloudEnabled
? "Click “Add environment” to pair another environment, or connect one from T3 Cloud."
: "Click “Add environment” to pair another environment."}
</EmptyDescription>
</EmptyHeader>
</Empty>
@@ -1840,13 +1824,13 @@ function CloudRemoteEnvironmentRows({
readonly primaryEnvironmentId: EnvironmentId | null;
readonly savedEnvironmentIds: ReadonlyArray<EnvironmentId>;
}) {
return hasCloudConfig() ? (
return hasCloudPublicConfig() ? (
<ConfiguredCloudRemoteEnvironmentRows
primaryEnvironmentId={primaryEnvironmentId}
savedEnvironmentIds={savedEnvironmentIds}
/>
) : savedEnvironmentIds.length === 0 ? (
<EmptyRemoteEnvironments />
<EmptyRemoteEnvironments cloudEnabled={false} />
) : null;
}
@@ -22,6 +22,7 @@ import {
useSidebar,
} from "../ui/sidebar";
import { Badge } from "../ui/badge";
import { hasCloudPublicConfig } from "../../cloud/publicConfig";
export type SettingsSectionPath =
| "/settings/general"
@@ -76,7 +77,9 @@ export function SettingsSidebarNav({ pathname }: { pathname: string }) {
<SidebarContent className="overflow-x-hidden">
<SidebarGroup className="px-2 py-3">
<SidebarMenu>
{SETTINGS_NAV_ITEMS.map((item) => {
{SETTINGS_NAV_ITEMS.filter(
(item) => item.to !== "/settings/cloud" || hasCloudPublicConfig(),
).map((item) => {
const Icon = item.icon;
const isActive = pathname === item.to;
return (
+2 -2
View File
@@ -12,10 +12,10 @@ import { primaryEnvironmentRequestInit } from "../environments/primary/requestIn
import { browserCryptoLayer } from "../cloud/dpop";
import { webManagedRelayClientLayer } from "../cloud/managedRelayLayer";
import { resolveCloudPublicConfig } from "../cloud/publicConfig";
function configuredRelayUrl(): string {
const value = (import.meta.env.VITE_T3_RELAY_URL as string | undefined)?.trim();
return value ? value.replace(/\/+$/g, "") : "http://relay.invalid";
return resolveCloudPublicConfig().relayUrl ?? "http://relay.invalid";
}
const webHttpClientLayer = remoteHttpClientLayer(globalThis.fetch);
+2 -1
View File
@@ -10,6 +10,7 @@ import "./index.css";
import { isElectron } from "./env";
import { DesktopClerkProvider } from "./cloud/desktopClerk";
import { ManagedRelayAuthProvider } from "./cloud/managedAuth";
import { hasCloudPublicConfig } from "./cloud/publicConfig";
import { getRouter } from "./router";
import { APP_DISPLAY_NAME } from "./branding";
import { syncDocumentWindowControlsOverlayClass } from "./lib/windowControlsOverlay";
@@ -32,7 +33,7 @@ const app = <RouterProvider router={router} />;
ReactDOM.createRoot(document.getElementById("root") as HTMLElement).render(
<React.StrictMode>
{clerkPublishableKey ? (
{clerkPublishableKey && hasCloudPublicConfig() ? (
isElectron ? (
<DesktopClerkProvider publishableKey={clerkPublishableKey}>
<ManagedRelayAuthProvider>{app}</ManagedRelayAuthProvider>
+11 -4
View File
@@ -7,6 +7,7 @@ import { Empty, EmptyDescription, EmptyHeader, EmptyTitle } from "../components/
import { SidebarInset, SidebarTrigger } from "../components/ui/sidebar";
import { useSavedEnvironmentRegistryStore } from "../environments/runtime";
import { APP_DISPLAY_NAME } from "~/branding";
import { hasCloudPublicConfig } from "~/cloud/publicConfig";
function ChatIndexRouteView() {
const { authGateState } = Route.useRouteContext();
@@ -26,6 +27,8 @@ export const Route = createFileRoute("/_chat/")({
});
function HostedStaticOnboardingState() {
const cloudEnabled = hasCloudPublicConfig();
return (
<SidebarInset className="h-dvh min-h-0 overflow-hidden overscroll-y-none bg-background text-foreground">
<div className="flex min-h-0 min-w-0 flex-1 flex-col overflow-x-hidden bg-background">
@@ -48,13 +51,17 @@ function HostedStaticOnboardingState() {
Connect an environment to get started
</EmptyTitle>
<EmptyDescription className="mt-2 text-sm leading-relaxed text-muted-foreground/78">
Sign in to T3 Cloud to connect a linked environment through its managed tunnel, or
add a reachable backend manually.
{cloudEnabled
? "Sign in to T3 Cloud to connect a linked environment through its managed tunnel, or add a reachable backend manually."
: "Add a reachable backend manually to start working from this browser."}
</EmptyDescription>
<div className="mt-6 flex justify-center">
<Button render={<a href="/settings/cloud" />} size="sm">
<Button
render={<a href={cloudEnabled ? "/settings/cloud" : "/settings/connections"} />}
size="sm"
>
<PlusIcon className="size-4" />
Open T3 Cloud
{cloudEnabled ? "Open T3 Cloud" : "Add environment"}
</Button>
</div>
</EmptyHeader>
+7 -1
View File
@@ -1,7 +1,13 @@
import { createFileRoute } from "@tanstack/react-router";
import { createFileRoute, redirect } from "@tanstack/react-router";
import { CloudSettingsPanel } from "../components/settings/CloudSettings";
import { hasCloudPublicConfig } from "../cloud/publicConfig";
export const Route = createFileRoute("/settings/cloud")({
beforeLoad: () => {
if (!hasCloudPublicConfig()) {
throw redirect({ to: "/settings/general", replace: true });
}
},
component: CloudSettingsPanel,
});
+24 -20
View File
@@ -6,13 +6,8 @@ audience.
## Application Keys
Web, desktop, and mobile use checked-in public development defaults from
`packages/shared/src/relayAuth.ts`, so a fresh clone can use T3 Cloud without creating local
environment files. These values are safe to embed in client builds: the Clerk publishable key and
relay URL are public identifiers, not secrets.
To point all clients at another Clerk/relay deployment, add a repository-root `.env` or
`.env.local` file:
T3 Cloud is disabled in a fresh clone. To enable it for source builds, add a repository-root `.env`
or `.env.local` file:
```dotenv
T3CODE_CLERK_PUBLISHABLE_KEY=<publishable key>
@@ -29,27 +24,36 @@ Configuration precedence is:
1. Process or CI environment variables.
2. Repository-root `.env.local`.
3. Repository-root `.env`.
4. Checked-in public development defaults.
Release builds read `T3CODE_CLERK_PUBLISHABLE_KEY` and `T3_RELAY_URL` from GitHub Actions repository
variables. EAS preview and production builds should define the same client-facing values in their
EAS environment.
The Clerk publishable key and relay URL are public identifiers, not secrets. Web, desktop, and
mobile builds statically inject them during their build step. A built artifact does not need an
environment file at runtime. CI release builds should set `T3CODE_CLERK_PUBLISHABLE_KEY` and
`T3_RELAY_URL` before building. EAS preview and production builds should define the same
client-facing values in their EAS environment.
When either public value is absent, cloud UI is omitted.
For a hosted relay deployment, copy `infra/relay/.env.example` to `infra/relay/.env`. The relay
deployment reads `T3_RELAY_DOMAIN` and `T3_RELAY_ZONE_NAME` through Effect `Config`, with the
checked-in shared values as defaults. `bun --cwd infra/relay run deploy` invokes Alchemy from the
relay directory, so Alchemy loads `infra/relay/.env`. The relay still requires `CLERK_SECRET_KEY` as
an Alchemy secret. Never put `CLERK_SECRET_KEY` in a client application environment or commit it to
the repository.
deployment reads `T3_RELAY_DOMAIN`, `T3_RELAY_ZONE_NAME`, and
`T3CODE_CLERK_PUBLISHABLE_KEY` through Effect `Config`. There are no checked-in deployment defaults.
`bun --cwd infra/relay run deploy` invokes Alchemy from the relay directory, so Alchemy loads
`infra/relay/.env`. After a successful deployment, the wrapper updates the repository-root `.env`
with the HTTPS relay URL derived from `T3_RELAY_DOMAIN`. The relay still requires
`CLERK_SECRET_KEY` as an Alchemy secret. Never put `CLERK_SECRET_KEY` in a client application
environment or commit it to the repository.
The `prod` Alchemy stage owns the retained PlanetScale database. Non-production stages reference
that database and provision isolated PlanetScale branches, so deploy `prod` before creating a
preview or developer stage.
## JWT Template
In **Clerk Dashboard > JWT templates**, create a template with:
| Setting | Value |
| ------- | ------------------------------------------------------ |
| Name | `t3-relay` |
| Claims | `{ "aud": "https://t3code-relay.ineededadomain.com" }` |
| Setting | Value |
| ------- | ---------------------------------------- |
| Name | `t3-relay` |
| Claims | `{ "aud": "https://relay.example.com" }` |
The `aud` value must be the deployed relay public URL, with no trailing slash. It must match the
client-facing `T3_RELAY_URL` and the HTTPS URL derived from the deployment's `T3_RELAY_DOMAIN`. If
-9
View File
@@ -1,12 +1,3 @@
export const DEFAULT_T3_RELAY_DOMAIN = "t3code-relay.ineededadomain.com";
export const DEFAULT_T3_RELAY_URL = `https://${DEFAULT_T3_RELAY_DOMAIN}`;
export const DEFAULT_T3_RELAY_ZONE_NAME = "ineededadomain.com";
export const DEFAULT_T3_CLERK_PUBLISHABLE_KEY =
"pk_test_YXdhaXRlZC1tb25rZmlzaC01OC5jbGVyay5hY2NvdW50cy5kZXYk";
export const RELAY_CLERK_JWT_TEMPLATE = "t3-relay";
export const RELAY_CLERK_TOKEN_OPTIONS = {
+22 -8
View File
@@ -4,7 +4,7 @@ import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterEach, describe, expect, it } from "vitest";
import { DEFAULT_PUBLIC_CONFIG, loadRepoEnv, resolvePublicConfig } from "./public-config.ts";
import { loadRepoEnv, resolvePublicConfig } from "./public-config.ts";
const temporaryDirectories: string[] = [];
@@ -15,17 +15,17 @@ afterEach(() => {
});
describe("loadRepoEnv", () => {
it("projects checked-in public defaults into Vite and Expo aliases", () => {
it("does not project cloud configuration for an unconfigured clone", () => {
const env = loadRepoEnv({ baseEnv: {}, repoRoot: makeTemporaryDirectory() });
expect(env.T3CODE_CLERK_PUBLISHABLE_KEY).toBe(DEFAULT_PUBLIC_CONFIG.clerkPublishableKey);
expect(env.VITE_CLERK_PUBLISHABLE_KEY).toBe(DEFAULT_PUBLIC_CONFIG.clerkPublishableKey);
expect(env.EXPO_PUBLIC_CLERK_PUBLISHABLE_KEY).toBe(DEFAULT_PUBLIC_CONFIG.clerkPublishableKey);
expect(env.T3_RELAY_URL).toBe(DEFAULT_PUBLIC_CONFIG.relayUrl);
expect(env.VITE_T3_RELAY_URL).toBe(DEFAULT_PUBLIC_CONFIG.relayUrl);
expect(env.T3CODE_CLERK_PUBLISHABLE_KEY).toBeUndefined();
expect(env.VITE_CLERK_PUBLISHABLE_KEY).toBeUndefined();
expect(env.EXPO_PUBLIC_CLERK_PUBLISHABLE_KEY).toBeUndefined();
expect(env.T3_RELAY_URL).toBeUndefined();
expect(env.VITE_T3_RELAY_URL).toBeUndefined();
});
it("applies process, root local, root, and checked-in precedence in that order", () => {
it("applies process, root local, and root precedence in that order", () => {
const repoRoot = makeTemporaryDirectory();
writeFileSync(
join(repoRoot, ".env"),
@@ -65,6 +65,20 @@ describe("loadRepoEnv", () => {
relayUrl: "https://legacy.example.test",
});
});
it("projects only the configured aliases", () => {
expect(
loadRepoEnv({
baseEnv: {
T3_RELAY_URL: "https://relay.example.test",
},
repoRoot: makeTemporaryDirectory(),
}),
).toEqual({
T3_RELAY_URL: "https://relay.example.test",
VITE_T3_RELAY_URL: "https://relay.example.test",
});
});
});
function makeTemporaryDirectory() {
+22 -25
View File
@@ -4,11 +4,9 @@ import * as NodePath from "node:path";
import * as NodeURL from "node:url";
import * as NodeUtil from "node:util";
import { DEFAULT_T3_CLERK_PUBLISHABLE_KEY, DEFAULT_T3_RELAY_URL } from "@t3tools/shared/relayAuth";
export interface T3CodePublicConfig {
readonly clerkPublishableKey: string;
readonly relayUrl: string;
readonly clerkPublishableKey: string | undefined;
readonly relayUrl: string | undefined;
}
type Environment = Readonly<Record<string, string | undefined>>;
@@ -17,13 +15,6 @@ const REPO_ROOT = NodePath.dirname(
NodePath.dirname(NodePath.dirname(NodeURL.fileURLToPath(import.meta.url))),
);
// These values are intentionally public. Client builds embed them so a fresh clone can use
// T3 Cloud without local setup. Use root .env files or CI environment variables to override them.
export const DEFAULT_PUBLIC_CONFIG: T3CodePublicConfig = {
clerkPublishableKey: DEFAULT_T3_CLERK_PUBLISHABLE_KEY,
relayUrl: DEFAULT_T3_RELAY_URL,
};
export function loadRepoEnv({
baseEnv = process.env,
repoRoot = REPO_ROOT,
@@ -39,25 +30,31 @@ export function loadRepoEnv({
...rootEnv,
...localEnv,
...baseEnv,
T3CODE_CLERK_PUBLISHABLE_KEY: config.clerkPublishableKey,
T3_RELAY_URL: config.relayUrl,
VITE_CLERK_PUBLISHABLE_KEY: config.clerkPublishableKey,
VITE_T3_RELAY_URL: config.relayUrl,
EXPO_PUBLIC_CLERK_PUBLISHABLE_KEY: config.clerkPublishableKey,
...(config.clerkPublishableKey
? {
T3CODE_CLERK_PUBLISHABLE_KEY: config.clerkPublishableKey,
VITE_CLERK_PUBLISHABLE_KEY: config.clerkPublishableKey,
EXPO_PUBLIC_CLERK_PUBLISHABLE_KEY: config.clerkPublishableKey,
}
: {}),
...(config.relayUrl
? {
T3_RELAY_URL: config.relayUrl,
VITE_T3_RELAY_URL: config.relayUrl,
}
: {}),
};
}
export function resolvePublicConfig(...sources: readonly Environment[]): T3CodePublicConfig {
return {
clerkPublishableKey:
firstNonEmpty(
sources,
"T3CODE_CLERK_PUBLISHABLE_KEY",
"VITE_CLERK_PUBLISHABLE_KEY",
"EXPO_PUBLIC_CLERK_PUBLISHABLE_KEY",
) ?? DEFAULT_PUBLIC_CONFIG.clerkPublishableKey,
relayUrl:
firstNonEmpty(sources, "T3_RELAY_URL", "VITE_T3_RELAY_URL") ?? DEFAULT_PUBLIC_CONFIG.relayUrl,
clerkPublishableKey: firstNonEmpty(
sources,
"T3CODE_CLERK_PUBLISHABLE_KEY",
"VITE_CLERK_PUBLISHABLE_KEY",
"EXPO_PUBLIC_CLERK_PUBLISHABLE_KEY",
),
relayUrl: firstNonEmpty(sources, "T3_RELAY_URL", "VITE_T3_RELAY_URL"),
};
}