diff --git a/.env.example b/.env.example index 7ab513c242..83dd4c39bb 100644 --- a/.env.example +++ b/.env.example @@ -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 diff --git a/README.md b/README.md index 7279d63e2a..5856f7e1b2 100644 --- a/README.md +++ b/README.md @@ -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. diff --git a/apps/mobile/README.md b/apps/mobile/README.md index 8054828bc6..fefd9491a3 100644 --- a/apps/mobile/README.md +++ b/apps/mobile/README.md @@ -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 diff --git a/apps/mobile/src/app/settings/environments.tsx b/apps/mobile/src/app/settings/environments.tsx index d5a503bc62..220f10ba59 100644 --- a/apps/mobile/src/app/settings/environments.tsx +++ b/apps/mobile/src/app/settings/environments.tsx @@ -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(null); - const cloudEnvironmentsState = useManagedRelayEnvironments(); - const [connectingCloudEnvironmentId, setConnectingCloudEnvironmentId] = useState( - 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 ( )} - {isSignedIn ? ( - - - - T3 Cloud - - - {cloudEnvironmentsState.isPending ? ( - - ) : ( - - )} - - - - {availableCloudEnvironments.length > 0 ? ( - - {availableCloudEnvironments.map((environment, index) => ( - handleConnectCloudEnvironment(environment)} - /> - ))} - - ) : cloudEnvironmentsState.data === null ? ( - - - - Loading linked cloud environments. - - - ) : cloudEnvironmentsState.error ? ( - - - Could not load T3 Cloud environments - - - {cloudEnvironmentsState.error} - - - ) : ( - - - No additional linked cloud environments. - - - )} - - ) : null} + {hasCloudPublicConfig() ? : null} ); } +function ConfiguredCloudEnvironmentRows() { + const { getToken, isSignedIn } = useAuth({ treatPendingAsSignedOut: false }); + const { savedConnectionsById } = useRemoteEnvironmentState(); + const cloudEnvironmentsState = useManagedRelayEnvironments(); + const [connectingCloudEnvironmentId, setConnectingCloudEnvironmentId] = useState( + 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 ( + + + T3 Cloud + + {cloudEnvironmentsState.isPending ? ( + + ) : ( + + )} + + + + {availableCloudEnvironments.length > 0 ? ( + + {availableCloudEnvironments.map((environment, index) => ( + handleConnectCloudEnvironment(environment)} + /> + ))} + + ) : cloudEnvironmentsState.data === null ? ( + + + + Loading linked cloud environments. + + + ) : cloudEnvironmentsState.error ? ( + + + Could not load T3 Cloud environments + + + {cloudEnvironmentsState.error} + + + ) : ( + + + No additional linked cloud environments. + + + )} + + ); +} + function CloudEnvironmentRow(props: { readonly environment: RelayClientEnvironmentRecord; readonly borderTop: boolean; diff --git a/apps/mobile/src/app/settings/index.tsx b/apps/mobile/src/app/settings/index.tsx index 85d09a1851..d3f472e590 100644 --- a/apps/mobile/src/app/settings/index.tsx +++ b/apps/mobile/src/app/settings/index.tsx @@ -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() ? : ; +} + +function LocalSettingsRouteScreen() { + const insets = useSafeAreaInsets(); + const { savedConnectionsById } = useRemoteEnvironmentState(); + const environmentCount = Object.keys(savedConnectionsById).length; + + return ( + + + + + + + + + + + ); +} + +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("checking"); const [liveActivityStatus, setLiveActivityStatus] = useState("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() { /> - - - - Version - Alpha - - + ); @@ -323,6 +349,26 @@ function SettingsSection(props: { readonly title: string; readonly children: Rea ); } +function AppSettingsSection() { + const icon = useThemeColor("--color-icon"); + + return ( + + + + Version + Alpha + + + ); +} + function SettingsRow(props: { readonly disabled?: boolean; readonly icon: SymbolName; @@ -335,7 +381,7 @@ function SettingsRow(props: { const chevron = useThemeColor("--color-chevron"); const content = ( @@ -386,7 +432,7 @@ function SettingsSwitchRow(props: { return ( diff --git a/apps/mobile/src/app/settings/waitlist.tsx b/apps/mobile/src/app/settings/waitlist.tsx index faab343470..891a7f4ce2 100644 --- a/apps/mobile/src/app/settings/waitlist.tsx +++ b/apps/mobile/src/app/settings/waitlist.tsx @@ -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() ? ( + + ) : ( + + ); +} + +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() ? ( - void presentAuth()} /> - ) : ( - - - T3 Cloud is not configured - - - Add T3CODE_CLERK_PUBLISHABLE_KEY to this build to enable waitlist enrollment. - - - )} + void presentAuth()} /> ); diff --git a/apps/mobile/src/features/agent-awareness/remoteRegistration.ts b/apps/mobile/src/features/agent-awareness/remoteRegistration.ts index 0ca8330da9..558cc9ec7a 100644 --- a/apps/mobile/src/features/agent-awareness/remoteRegistration.ts +++ b/apps/mobile/src/features/agent-awareness/remoteRegistration.ts @@ -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(); @@ -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; diff --git a/apps/mobile/src/features/cloud/CloudAuthProvider.tsx b/apps/mobile/src/features/cloud/CloudAuthProvider.tsx index aada03d5c9..b0a2c4b0ca 100644 --- a/apps/mobile/src/features/cloud/CloudAuthProvider.tsx +++ b/apps/mobile/src/features/cloud/CloudAuthProvider.tsx @@ -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; } diff --git a/apps/mobile/src/features/cloud/linkEnvironment.ts b/apps/mobile/src/features/cloud/linkEnvironment.ts index cd364637a1..61ebad2623 100644 --- a/apps/mobile/src/features/cloud/linkEnvironment.ts +++ b/apps/mobile/src/features/cloud/linkEnvironment.ts @@ -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")<{ diff --git a/apps/mobile/src/features/cloud/publicConfig.test.ts b/apps/mobile/src/features/cloud/publicConfig.test.ts new file mode 100644 index 0000000000..11b3ee2a66 --- /dev/null +++ b/apps/mobile/src/features/cloud/publicConfig.test.ts @@ -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", + }); + }); +}); diff --git a/apps/mobile/src/features/cloud/publicConfig.ts b/apps/mobile/src/features/cloud/publicConfig.ts new file mode 100644 index 0000000000..1a18bdec7f --- /dev/null +++ b/apps/mobile/src/features/cloud/publicConfig.ts @@ -0,0 +1,27 @@ +import Constants from "expo-constants"; + +type ExpoExtra = Readonly> | 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); +} diff --git a/apps/mobile/src/lib/runtime.ts b/apps/mobile/src/lib/runtime.ts index 22b8b4fa55..80083869d7 100644 --- a/apps/mobile/src/lib/runtime.ts +++ b/apps/mobile/src/lib/runtime.ts @@ -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); diff --git a/apps/web/src/cloud/linkEnvironment.ts b/apps/web/src/cloud/linkEnvironment.ts index 746ec7cfa8..ec133b6589 100644 --- a/apps/web/src/cloud/linkEnvironment.ts +++ b/apps/web/src/cloud/linkEnvironment.ts @@ -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")<{ diff --git a/apps/web/src/cloud/publicConfig.test.ts b/apps/web/src/cloud/publicConfig.test.ts new file mode 100644 index 0000000000..7ccf90b6a7 --- /dev/null +++ b/apps/web/src/cloud/publicConfig.test.ts @@ -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); + }); +}); diff --git a/apps/web/src/cloud/publicConfig.ts b/apps/web/src/cloud/publicConfig.ts new file mode 100644 index 0000000000..bac4deb1ba --- /dev/null +++ b/apps/web/src/cloud/publicConfig.ts @@ -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); +} diff --git a/apps/web/src/components/settings/CloudSettings.tsx b/apps/web/src/components/settings/CloudSettings.tsx index b9a9c44df6..c2a1541b12 100644 --- a/apps/web/src/components/settings/CloudSettings.tsx +++ b/apps/web/src/components/settings/CloudSettings.tsx @@ -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 ( - - }> - - - - ); - } + if (!hasCloudPublicConfig()) return null; return ; } diff --git a/apps/web/src/components/settings/ConnectionsSettings.tsx b/apps/web/src/components/settings/ConnectionsSettings.tsx index 92b1132928..3666fc2f2d 100644 --- a/apps/web/src/components/settings/ConnectionsSettings.tsx +++ b/apps/web/src/components/settings/ConnectionsSettings.tsx @@ -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() ? ( - - ) : ( - - } - /> - ); + return hasCloudPublicConfig() ? : null; } -function EmptyRemoteEnvironments() { +function EmptyRemoteEnvironments({ cloudEnabled = true }: { readonly cloudEnabled?: boolean }) { return ( @@ -1730,8 +1713,9 @@ function EmptyRemoteEnvironments() { No saved remote environments - Click “Add environment” 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."} @@ -1840,13 +1824,13 @@ function CloudRemoteEnvironmentRows({ readonly primaryEnvironmentId: EnvironmentId | null; readonly savedEnvironmentIds: ReadonlyArray; }) { - return hasCloudConfig() ? ( + return hasCloudPublicConfig() ? ( ) : savedEnvironmentIds.length === 0 ? ( - + ) : null; } diff --git a/apps/web/src/components/settings/SettingsSidebarNav.tsx b/apps/web/src/components/settings/SettingsSidebarNav.tsx index 0904ad3b7b..c0238a4651 100644 --- a/apps/web/src/components/settings/SettingsSidebarNav.tsx +++ b/apps/web/src/components/settings/SettingsSidebarNav.tsx @@ -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 }) { - {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 ( diff --git a/apps/web/src/lib/runtime.ts b/apps/web/src/lib/runtime.ts index 34f6d8264a..60510f7ee8 100644 --- a/apps/web/src/lib/runtime.ts +++ b/apps/web/src/lib/runtime.ts @@ -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); diff --git a/apps/web/src/main.tsx b/apps/web/src/main.tsx index a665bc4d43..f791f998d7 100644 --- a/apps/web/src/main.tsx +++ b/apps/web/src/main.tsx @@ -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 = ; ReactDOM.createRoot(document.getElementById("root") as HTMLElement).render( - {clerkPublishableKey ? ( + {clerkPublishableKey && hasCloudPublicConfig() ? ( isElectron ? ( {app} diff --git a/apps/web/src/routes/_chat.index.tsx b/apps/web/src/routes/_chat.index.tsx index 32587c0f18..50ca6c4b32 100644 --- a/apps/web/src/routes/_chat.index.tsx +++ b/apps/web/src/routes/_chat.index.tsx @@ -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 (
@@ -48,13 +51,17 @@ function HostedStaticOnboardingState() { Connect an environment to get started - 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."}
-
diff --git a/apps/web/src/routes/settings.cloud.tsx b/apps/web/src/routes/settings.cloud.tsx index e91eb70e81..a2854e9719 100644 --- a/apps/web/src/routes/settings.cloud.tsx +++ b/apps/web/src/routes/settings.cloud.tsx @@ -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, }); diff --git a/docs/t3-cloud-clerk.md b/docs/t3-cloud-clerk.md index 450be3db59..13fa007406 100644 --- a/docs/t3-cloud-clerk.md +++ b/docs/t3-cloud-clerk.md @@ -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= @@ -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 diff --git a/packages/shared/src/relayAuth.ts b/packages/shared/src/relayAuth.ts index b2c36968ad..0f8c139d41 100644 --- a/packages/shared/src/relayAuth.ts +++ b/packages/shared/src/relayAuth.ts @@ -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 = { diff --git a/scripts/lib/public-config.test.ts b/scripts/lib/public-config.test.ts index 24666c276d..fea7a7ad3b 100644 --- a/scripts/lib/public-config.test.ts +++ b/scripts/lib/public-config.test.ts @@ -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() { diff --git a/scripts/lib/public-config.ts b/scripts/lib/public-config.ts index ac6f3790a1..9eb3522128 100644 --- a/scripts/lib/public-config.ts +++ b/scripts/lib/public-config.ts @@ -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>; @@ -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"), }; }