diff --git a/.env.example b/.env.example index 4db2b2d4fa..0a8ce8bfc1 100644 --- a/.env.example +++ b/.env.example @@ -3,8 +3,9 @@ # 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. +# Get these from the Clerk Dashboard under API keys and JWT templates. # T3CODE_CLERK_PUBLISHABLE_KEY=pk_test_... +# T3CODE_CLERK_JWT_TEMPLATE=t3-relay # Get this from your relay deployment. `infra/relay` deploys update it automatically. # T3CODE_RELAY_URL=https://relay.example.com diff --git a/.github/workflows/deploy-relay.yml b/.github/workflows/deploy-relay.yml index eec2c100f7..18a76142c9 100644 --- a/.github/workflows/deploy-relay.yml +++ b/.github/workflows/deploy-relay.yml @@ -32,6 +32,7 @@ jobs: RELAY_DOMAIN: ${{ vars.RELAY_DOMAIN }} RELAY_ZONE_NAME: ${{ vars.RELAY_ZONE_NAME }} CLERK_PUBLISHABLE_KEY: ${{ vars.CLERK_PUBLISHABLE_KEY }} + CLERK_JWT_AUDIENCE: ${{ vars.CLERK_JWT_AUDIENCE }} CLERK_SECRET_KEY: ${{ secrets.CLERK_SECRET_KEY }} APNS_ENVIRONMENT: ${{ vars.APNS_ENVIRONMENT }} APNS_TEAM_ID: ${{ vars.APNS_TEAM_ID }} diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 2f3171518d..150a26948b 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -176,10 +176,12 @@ jobs: name: production outputs: clerk_publishable_key: ${{ steps.public_config.outputs.clerk_publishable_key }} + clerk_jwt_template: ${{ steps.public_config.outputs.clerk_jwt_template }} relay_url: ${{ steps.public_config.outputs.relay_url }} env: RELAY_DOMAIN: ${{ vars.RELAY_DOMAIN }} CLERK_PUBLISHABLE_KEY: ${{ vars.CLERK_PUBLISHABLE_KEY }} + CLERK_JWT_TEMPLATE: ${{ vars.CLERK_JWT_TEMPLATE }} steps: - id: public_config name: Resolve production relay public config @@ -190,6 +192,7 @@ jobs: required=( RELAY_DOMAIN CLERK_PUBLISHABLE_KEY + CLERK_JWT_TEMPLATE ) missing=() for name in "${required[@]}"; do @@ -203,6 +206,7 @@ jobs: fi echo "clerk_publishable_key=$CLERK_PUBLISHABLE_KEY" >> "$GITHUB_OUTPUT" + echo "clerk_jwt_template=$CLERK_JWT_TEMPLATE" >> "$GITHUB_OUTPUT" echo "relay_url=https://$RELAY_DOMAIN" >> "$GITHUB_OUTPUT" build: @@ -213,6 +217,7 @@ jobs: timeout-minutes: 30 env: T3CODE_CLERK_PUBLISHABLE_KEY: ${{ needs.relay_public_config.outputs.clerk_publishable_key }} + T3CODE_CLERK_JWT_TEMPLATE: ${{ needs.relay_public_config.outputs.clerk_jwt_template }} T3CODE_RELAY_URL: ${{ needs.relay_public_config.outputs.relay_url }} strategy: fail-fast: false @@ -473,6 +478,7 @@ jobs: id-token: write env: T3CODE_CLERK_PUBLISHABLE_KEY: ${{ needs.relay_public_config.outputs.clerk_publishable_key }} + T3CODE_CLERK_JWT_TEMPLATE: ${{ needs.relay_public_config.outputs.clerk_jwt_template }} T3CODE_RELAY_URL: ${{ needs.relay_public_config.outputs.relay_url }} steps: - name: Checkout @@ -628,6 +634,7 @@ jobs: timeout-minutes: 10 env: T3CODE_CLERK_PUBLISHABLE_KEY: ${{ needs.relay_public_config.outputs.clerk_publishable_key }} + T3CODE_CLERK_JWT_TEMPLATE: ${{ needs.relay_public_config.outputs.clerk_jwt_template }} T3CODE_RELAY_URL: ${{ needs.relay_public_config.outputs.relay_url }} VERCEL_TOKEN: ${{ secrets.VERCEL_TOKEN }} VERCEL_ORG_ID: ${{ secrets.VERCEL_ORG_ID }} @@ -696,6 +703,7 @@ jobs: "${vercel_scope_args[@]}" \ --build-env "APP_VERSION=${{ needs.preflight.outputs.version }}" \ --build-env "T3CODE_CLERK_PUBLISHABLE_KEY=${T3CODE_CLERK_PUBLISHABLE_KEY:-}" \ + --build-env "T3CODE_CLERK_JWT_TEMPLATE=${T3CODE_CLERK_JWT_TEMPLATE:-}" \ --build-env "T3CODE_RELAY_URL=${T3CODE_RELAY_URL:-}" \ --build-env "VITE_HOSTED_APP_URL=$router_url" \ --build-env "VITE_HOSTED_APP_CHANNEL=$channel_name" diff --git a/apps/mobile/README.md b/apps/mobile/README.md index 37318c49b4..f5be27c6c3 100644 --- a/apps/mobile/README.md +++ b/apps/mobile/README.md @@ -67,7 +67,8 @@ The native lint task runs SwiftLint for Swift plus ktlint and detekt for Kotlin. CI uses Expo fingerprinting with the `preview:dev` profile to reuse an existing compatible build when possible, or start a new internal EAS build when native runtime inputs change. Production and default local builds continue to use the `appVersion` runtime policy. -For preview or production EAS environments, set `T3CODE_CLERK_PUBLISHABLE_KEY` and `T3CODE_RELAY_URL` +For preview or production EAS environments, set `T3CODE_CLERK_PUBLISHABLE_KEY`, +`T3CODE_CLERK_JWT_TEMPLATE`, and `T3CODE_RELAY_URL` as EAS environment variables. Expo config maps the canonical values into the mobile build. Create a PR preview dev-client build manually: diff --git a/apps/mobile/app.config.ts b/apps/mobile/app.config.ts index 7266ff0401..c208bcd26a 100644 --- a/apps/mobile/app.config.ts +++ b/apps/mobile/app.config.ts @@ -159,6 +159,7 @@ const config: ExpoConfig = { }, clerk: { publishableKey: repoEnv.EXPO_PUBLIC_CLERK_PUBLISHABLE_KEY ?? null, + jwtTemplate: repoEnv.EXPO_PUBLIC_CLERK_JWT_TEMPLATE ?? null, }, eas: { projectId: "d763fcb8-d37c-41ea-a773-b54a0ab4a454", diff --git a/apps/mobile/src/app/settings/environments.tsx b/apps/mobile/src/app/settings/environments.tsx index 220f10ba59..0a8e896972 100644 --- a/apps/mobile/src/app/settings/environments.tsx +++ b/apps/mobile/src/app/settings/environments.tsx @@ -3,7 +3,6 @@ import { Link, Stack } from "expo-router"; import { SymbolView } from "expo-symbols"; import type { EnvironmentId } from "@t3tools/contracts"; import type { RelayClientEnvironmentRecord } from "@t3tools/contracts/relay"; -import { RELAY_CLERK_TOKEN_OPTIONS } from "@t3tools/shared/relayAuth"; import * as Effect from "effect/Effect"; import { useCallback, useMemo, useState } from "react"; import { ActivityIndicator, Alert, Pressable, ScrollView, View } from "react-native"; @@ -11,7 +10,10 @@ 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 { + hasCloudPublicConfig, + resolveRelayClerkTokenOptions, +} from "../../features/cloud/publicConfig"; import { useManagedRelayEnvironments, useManagedRelayEnvironmentStatus, @@ -142,7 +144,7 @@ function ConfiguredCloudEnvironmentRows() { async (environment: RelayClientEnvironmentRecord) => { setConnectingCloudEnvironmentId(environment.environmentId); try { - const token = await getToken(RELAY_CLERK_TOKEN_OPTIONS); + const token = await getToken(resolveRelayClerkTokenOptions()); if (!token) { throw new Error("Sign in to T3 Cloud before connecting."); } diff --git a/apps/mobile/src/app/settings/index.tsx b/apps/mobile/src/app/settings/index.tsx index d3f472e590..b25de62686 100644 --- a/apps/mobile/src/app/settings/index.tsx +++ b/apps/mobile/src/app/settings/index.tsx @@ -1,6 +1,5 @@ import { useAuth, useUser, useUserProfileModal } from "@clerk/expo"; import * as Notifications from "expo-notifications"; -import { RELAY_CLERK_TOKEN_OPTIONS } from "@t3tools/shared/relayAuth"; import { Link, Stack, useRouter } from "expo-router"; import { SymbolView } from "expo-symbols"; import * as Effect from "effect/Effect"; @@ -14,7 +13,10 @@ 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 { + hasCloudPublicConfig, + resolveRelayClerkTokenOptions, +} from "../../features/cloud/publicConfig"; import { mobileRuntime } from "../../lib/runtime"; import { loadPreferences } from "../../lib/storage"; import { useThemeColor } from "../../lib/useThemeColor"; @@ -176,7 +178,7 @@ function ConfiguredSettingsRouteScreen() { setLiveActivityStatus("linking"); try { - const token = await getToken(RELAY_CLERK_TOKEN_OPTIONS); + const token = await getToken(resolveRelayClerkTokenOptions()); if (!token) { promptSignIn(); setLiveActivityStatus("signed-out"); @@ -232,7 +234,7 @@ function ConfiguredSettingsRouteScreen() { setLiveActivityStatus("disabled"); void (async () => { try { - const token = isSignedIn ? await getToken(RELAY_CLERK_TOKEN_OPTIONS) : null; + const token = isSignedIn ? await getToken(resolveRelayClerkTokenOptions()) : null; await mobileRuntime.runPromise( setLiveActivityUpdatesEnabled({ enabled: false, diff --git a/apps/mobile/src/features/cloud/CloudAuthProvider.tsx b/apps/mobile/src/features/cloud/CloudAuthProvider.tsx index b0a2c4b0ca..470bd130e9 100644 --- a/apps/mobile/src/features/cloud/CloudAuthProvider.tsx +++ b/apps/mobile/src/features/cloud/CloudAuthProvider.tsx @@ -2,7 +2,6 @@ import { ClerkProvider, useAuth } from "@clerk/expo"; import { tokenCache } from "@clerk/expo/token-cache"; import { createManagedRelaySession, setManagedRelaySession } from "@t3tools/client-runtime"; import { type ReactNode, useEffect, useRef } from "react"; -import { RELAY_CLERK_TOKEN_OPTIONS } from "@t3tools/shared/relayAuth"; import { mobileRuntime } from "../../lib/runtime"; import { appAtomRegistry } from "../../state/atom-registry"; @@ -11,7 +10,7 @@ import { unregisterAgentAwarenessDeviceForCurrentUser, } from "../agent-awareness/remoteRegistration"; import { refreshActiveLiveActivityRemoteRegistration } from "../agent-awareness/liveActivityController"; -import { resolveCloudPublicConfig } from "./publicConfig"; +import { resolveCloudPublicConfig, resolveRelayClerkTokenOptions } from "./publicConfig"; function CloudAuthBridge(props: { readonly children: ReactNode }) { const { getToken, isLoaded, isSignedIn, userId } = useAuth({ treatPendingAsSignedOut: false }); @@ -43,7 +42,7 @@ function CloudAuthBridge(props: { readonly children: ReactNode }) { .runPromise(unregisterAgentAwarenessDeviceForCurrentUser(previous.provider)) .catch(() => undefined); } - const tokenProvider = () => getToken(RELAY_CLERK_TOKEN_OPTIONS); + const tokenProvider = () => getToken(resolveRelayClerkTokenOptions()); previousTokenProviderRef.current = { userId, provider: tokenProvider }; setAgentAwarenessRelayTokenProvider(tokenProvider, userId); setManagedRelaySession( diff --git a/apps/mobile/src/features/cloud/publicConfig.test.ts b/apps/mobile/src/features/cloud/publicConfig.test.ts index 11b3ee2a66..26c1561bf0 100644 --- a/apps/mobile/src/features/cloud/publicConfig.test.ts +++ b/apps/mobile/src/features/cloud/publicConfig.test.ts @@ -14,6 +14,7 @@ describe("resolveCloudPublicConfig", () => { it("returns no cloud configuration for an unconfigured build", () => { expect(resolveCloudPublicConfig({})).toEqual({ clerkPublishableKey: null, + clerkJwtTemplate: null, relayUrl: null, }); }); @@ -21,11 +22,12 @@ describe("resolveCloudPublicConfig", () => { it("normalizes statically injected cloud configuration", () => { expect( resolveCloudPublicConfig({ - clerk: { publishableKey: " pk_test_example " }, + clerk: { publishableKey: " pk_test_example ", jwtTemplate: " t3-relay " }, relay: { url: " https://relay.example.test/// " }, }), ).toEqual({ clerkPublishableKey: "pk_test_example", + clerkJwtTemplate: "t3-relay", relayUrl: "https://relay.example.test", }); }); diff --git a/apps/mobile/src/features/cloud/publicConfig.ts b/apps/mobile/src/features/cloud/publicConfig.ts index 1a18bdec7f..d775f06101 100644 --- a/apps/mobile/src/features/cloud/publicConfig.ts +++ b/apps/mobile/src/features/cloud/publicConfig.ts @@ -1,9 +1,11 @@ import Constants from "expo-constants"; +import { relayClerkTokenOptions } from "@t3tools/shared/relayAuth"; type ExpoExtra = Readonly> | undefined; export interface CloudPublicConfig { readonly clerkPublishableKey: string | null; + readonly clerkJwtTemplate: string | null; readonly relayUrl: string | null; } @@ -12,16 +14,27 @@ function trimNonEmpty(value: unknown): string | null { } export function resolveCloudPublicConfig(extra: ExpoExtra = Constants.expoConfig?.extra) { - const clerk = extra?.clerk as { readonly publishableKey?: unknown } | undefined; + const clerk = extra?.clerk as + | { readonly publishableKey?: unknown; readonly jwtTemplate?: unknown } + | undefined; const relay = extra?.relay as { readonly url?: unknown } | undefined; return { clerkPublishableKey: trimNonEmpty(clerk?.publishableKey), + clerkJwtTemplate: trimNonEmpty(clerk?.jwtTemplate), relayUrl: trimNonEmpty(relay?.url)?.replace(/\/+$/u, "") ?? null, } satisfies CloudPublicConfig; } export function hasCloudPublicConfig(): boolean { const config = resolveCloudPublicConfig(); - return Boolean(config.clerkPublishableKey && config.relayUrl); + return Boolean(config.clerkPublishableKey && config.clerkJwtTemplate && config.relayUrl); +} + +export function resolveRelayClerkTokenOptions() { + const { clerkJwtTemplate } = resolveCloudPublicConfig(); + if (!clerkJwtTemplate) { + throw new Error("T3CODE_CLERK_JWT_TEMPLATE is not configured."); + } + return relayClerkTokenOptions(clerkJwtTemplate); } diff --git a/apps/web/src/cloud/managedAuth.tsx b/apps/web/src/cloud/managedAuth.tsx index df4e06a97c..b00c445f08 100644 --- a/apps/web/src/cloud/managedAuth.tsx +++ b/apps/web/src/cloud/managedAuth.tsx @@ -1,9 +1,9 @@ import { useAuth } from "@clerk/react"; import { createManagedRelaySession, setManagedRelaySession } from "@t3tools/client-runtime"; -import { RELAY_CLERK_TOKEN_OPTIONS } from "@t3tools/shared/relayAuth"; import { useEffect, type ReactNode } from "react"; import { appAtomRegistry } from "../rpc/atomRegistry"; +import { resolveRelayClerkTokenOptions } from "./publicConfig"; let relayTokenProvider: (() => Promise) | null = null; @@ -15,13 +15,13 @@ export function ManagedRelayAuthProvider({ children }: { readonly children: Reac const { getToken, isSignedIn, userId } = useAuth(); useEffect(() => { - relayTokenProvider = isSignedIn ? () => getToken(RELAY_CLERK_TOKEN_OPTIONS) : null; + relayTokenProvider = isSignedIn ? () => getToken(resolveRelayClerkTokenOptions()) : null; setManagedRelaySession( appAtomRegistry, isSignedIn && userId ? createManagedRelaySession({ accountId: userId, - readClerkToken: () => getToken(RELAY_CLERK_TOKEN_OPTIONS), + readClerkToken: () => getToken(resolveRelayClerkTokenOptions()), }) : null, ); diff --git a/apps/web/src/cloud/publicConfig.test.ts b/apps/web/src/cloud/publicConfig.test.ts index c40026ee06..32a902c47e 100644 --- a/apps/web/src/cloud/publicConfig.test.ts +++ b/apps/web/src/cloud/publicConfig.test.ts @@ -9,12 +9,16 @@ afterEach(() => { describe("hasCloudPublicConfig", () => { it("requires both public cloud values", () => { vi.stubEnv("VITE_CLERK_PUBLISHABLE_KEY", ""); + vi.stubEnv("VITE_CLERK_JWT_TEMPLATE", ""); vi.stubEnv("VITE_T3CODE_RELAY_URL", ""); expect(hasCloudPublicConfig()).toBe(false); vi.stubEnv("VITE_CLERK_PUBLISHABLE_KEY", "pk_test_example"); expect(hasCloudPublicConfig()).toBe(false); + vi.stubEnv("VITE_CLERK_JWT_TEMPLATE", "t3-relay"); + expect(hasCloudPublicConfig()).toBe(false); + vi.stubEnv("VITE_T3CODE_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 index 1df9696209..fe3d5b5e63 100644 --- a/apps/web/src/cloud/publicConfig.ts +++ b/apps/web/src/cloud/publicConfig.ts @@ -1,5 +1,8 @@ +import { relayClerkTokenOptions } from "@t3tools/shared/relayAuth"; + export interface CloudPublicConfig { readonly clerkPublishableKey: string | null; + readonly clerkJwtTemplate: string | null; readonly relayUrl: string | null; } @@ -12,6 +15,7 @@ export function resolveCloudPublicConfig(): CloudPublicConfig { clerkPublishableKey: trimNonEmpty( import.meta.env.VITE_CLERK_PUBLISHABLE_KEY as string | undefined, ), + clerkJwtTemplate: trimNonEmpty(import.meta.env.VITE_CLERK_JWT_TEMPLATE as string | undefined), relayUrl: trimNonEmpty(import.meta.env.VITE_T3CODE_RELAY_URL as string | undefined)?.replace( /\/+$/u, @@ -22,5 +26,13 @@ export function resolveCloudPublicConfig(): CloudPublicConfig { export function hasCloudPublicConfig(): boolean { const config = resolveCloudPublicConfig(); - return Boolean(config.clerkPublishableKey && config.relayUrl); + return Boolean(config.clerkPublishableKey && config.clerkJwtTemplate && config.relayUrl); +} + +export function resolveRelayClerkTokenOptions() { + const { clerkJwtTemplate } = resolveCloudPublicConfig(); + if (!clerkJwtTemplate) { + throw new Error("T3CODE_CLERK_JWT_TEMPLATE is not configured."); + } + return relayClerkTokenOptions(clerkJwtTemplate); } diff --git a/apps/web/src/components/settings/ConnectionsSettings.tsx b/apps/web/src/components/settings/ConnectionsSettings.tsx index 3666fc2f2d..9dab7b61fa 100644 --- a/apps/web/src/components/settings/ConnectionsSettings.tsx +++ b/apps/web/src/components/settings/ConnectionsSettings.tsx @@ -30,7 +30,6 @@ import { type EnvironmentId, } from "@t3tools/contracts"; import { WsRpcClient } from "@t3tools/client-runtime"; -import { RELAY_CLERK_TOKEN_OPTIONS } from "@t3tools/shared/relayAuth"; import type { RelayClientEnvironmentRecord } from "@t3tools/contracts/relay"; import * as DateTime from "effect/DateTime"; @@ -38,6 +37,7 @@ import { useCopyToClipboard } from "../../hooks/useCopyToClipboard"; import { cn } from "../../lib/utils"; import { formatElapsedDurationLabel, formatExpiresInLabel } from "../../timestampFormat"; import { resolveDesktopPairingUrl, resolveHostedPairingUrl } from "./pairingUrls"; +import { resolveRelayClerkTokenOptions } from "../../cloud/publicConfig"; import { SettingsPageContainer, SettingsRow, @@ -1640,7 +1640,7 @@ function ConfiguredCloudLinkRow({ canManageRelay }: { readonly canManageRelay: b setIsUpdating(true); setOperationError(null); try { - const clerkToken = await getToken(RELAY_CLERK_TOKEN_OPTIONS); + const clerkToken = await getToken(resolveRelayClerkTokenOptions()); if (enabled) { if (!clerkToken) { throw new Error("Sign in from T3 Cloud settings before linking this environment."); @@ -1753,7 +1753,7 @@ function ConfiguredCloudRemoteEnvironmentRows({ const connectEnvironment = async (environment: RelayClientEnvironmentRecord) => { setConnectingEnvironmentId(environment.environmentId); try { - const clerkToken = await getToken(RELAY_CLERK_TOKEN_OPTIONS); + const clerkToken = await getToken(resolveRelayClerkTokenOptions()); if (!clerkToken) { throw new Error("Sign in from T3 Cloud settings before connecting this environment."); } diff --git a/apps/web/src/vite-env.d.ts b/apps/web/src/vite-env.d.ts index c00ade5912..0c06dbb9dd 100644 --- a/apps/web/src/vite-env.d.ts +++ b/apps/web/src/vite-env.d.ts @@ -8,6 +8,7 @@ interface ImportMetaEnv { readonly VITE_HOSTED_APP_URL: string; readonly VITE_HOSTED_APP_CHANNEL: string; readonly VITE_CLERK_PUBLISHABLE_KEY: string; + readonly VITE_CLERK_JWT_TEMPLATE: string; readonly APP_VERSION: string; } diff --git a/apps/web/vite.config.ts b/apps/web/vite.config.ts index 381dac5889..cc15820edf 100644 --- a/apps/web/vite.config.ts +++ b/apps/web/vite.config.ts @@ -18,6 +18,7 @@ const host = process.env.HOST?.trim() || "localhost"; const configuredWsUrl = process.env.VITE_WS_URL?.trim(); const configuredRelayUrl = repoEnv.VITE_T3CODE_RELAY_URL?.trim() || ""; const configuredClerkPublishableKey = repoEnv.VITE_CLERK_PUBLISHABLE_KEY?.trim() || ""; +const configuredClerkJwtTemplate = repoEnv.VITE_CLERK_JWT_TEMPLATE?.trim() || ""; const configuredHostedAppChannel = process.env.VITE_HOSTED_APP_CHANNEL?.trim() || ""; const configuredAppVersion = process.env.APP_VERSION?.trim() || pkg.version; const configuredHostedAppUrl = (() => { @@ -132,6 +133,7 @@ export default defineConfig(() => { "import.meta.env.VITE_WS_URL": JSON.stringify(configuredWsUrl ?? ""), "import.meta.env.VITE_T3CODE_RELAY_URL": JSON.stringify(configuredRelayUrl), "import.meta.env.VITE_CLERK_PUBLISHABLE_KEY": JSON.stringify(configuredClerkPublishableKey), + "import.meta.env.VITE_CLERK_JWT_TEMPLATE": JSON.stringify(configuredClerkJwtTemplate), "import.meta.env.VITE_HOSTED_APP_URL": JSON.stringify(configuredHostedAppUrl ?? ""), "import.meta.env.VITE_HOSTED_APP_CHANNEL": JSON.stringify(configuredHostedAppChannel), "import.meta.env.APP_VERSION": JSON.stringify(configuredAppVersion), diff --git a/docs/release.md b/docs/release.md index 4a4674f51e..082fa08e03 100644 --- a/docs/release.md +++ b/docs/release.md @@ -10,7 +10,7 @@ This document covers the unified release workflow for stable and nightly desktop - scheduled nightly check every three hours - manual `workflow_dispatch` for either channel - Runs quality gates first: lint, typecheck, test. -- Reads the shared production T3 Cloud relay URL and Clerk publishable key before packaging clients. +- Reads the shared production T3 Cloud relay URL and Clerk client configuration before packaging clients. - Builds four artifacts in parallel for both channels: - macOS `arm64` DMG - macOS `x64` DMG @@ -38,7 +38,7 @@ release channels. `.github/workflows/deploy-relay.yml` deploys Alchemy stage `prod` on every push to `main`. It also supports manual dispatch for retries. The release workflow reads the relay URL and Clerk -publishable key from the existing `production` GitHub Actions environment before building +client configuration from the existing `production` GitHub Actions environment before building desktop, CLI, or hosted web artifacts. Required repository variables shared by relay deployments: @@ -59,6 +59,8 @@ Required `production` environment variables: - `RELAY_DOMAIN` - `RELAY_ZONE_NAME` - `CLERK_PUBLISHABLE_KEY` +- `CLERK_JWT_AUDIENCE` +- `CLERK_JWT_TEMPLATE` - `CLERK_CLI_OAUTH_CLIENT_ID` - `APNS_ENVIRONMENT` - `APNS_TEAM_ID` diff --git a/docs/t3-cloud-clerk.md b/docs/t3-cloud-clerk.md index 518fcbf613..10a05a7ee3 100644 --- a/docs/t3-cloud-clerk.md +++ b/docs/t3-cloud-clerk.md @@ -1,8 +1,8 @@ # T3 Cloud Clerk Setup T3 Cloud uses one Clerk application for web, desktop, and mobile authentication. The relay accepts -Clerk JWTs only when they are generated from the `t3-relay` template with the relay URL as the -audience. +Clerk JWTs only when they are generated from the `t3-relay` template with the shared +`t3-code-relay` audience. ## Application Keys @@ -11,13 +11,13 @@ or `.env.local` file: ```dotenv T3CODE_CLERK_PUBLISHABLE_KEY= +T3CODE_CLERK_JWT_TEMPLATE= T3CODE_RELAY_URL=https://relay.example.com ``` -The shared client loader projects these canonical values into the framework-specific -`VITE_CLERK_PUBLISHABLE_KEY`, `VITE_T3CODE_RELAY_URL`, and -`EXPO_PUBLIC_CLERK_PUBLISHABLE_KEY` aliases. Existing aliases remain accepted as overrides for -compatibility, but new client configuration should use the canonical names. +The shared client loader projects these canonical values into framework-specific `VITE_*` and +`EXPO_PUBLIC_*` aliases. Existing aliases remain accepted as overrides for compatibility, but new +client configuration should use the canonical names. Configuration precedence is: @@ -25,17 +25,18 @@ Configuration precedence is: 2. Repository-root `.env.local`. 3. Repository-root `.env`. -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 -`T3CODE_RELAY_URL` before building. EAS preview and production builds should define the same -client-facing values in their EAS environment. +The Clerk publishable key, JWT template name, 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`, `T3CODE_CLERK_JWT_TEMPLATE`, and `T3CODE_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. +When any client-facing 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 `RELAY_DOMAIN`, `RELAY_ZONE_NAME`, and `CLERK_PUBLISHABLE_KEY` through Effect -`Config`. There are no checked-in deployment defaults. +deployment reads `RELAY_DOMAIN`, `RELAY_ZONE_NAME`, `CLERK_PUBLISHABLE_KEY`, and +`CLERK_JWT_AUDIENCE` 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 `RELAY_DOMAIN`. The relay still requires @@ -50,14 +51,16 @@ preview or developer stage. In **Clerk Dashboard > JWT templates**, create a template with: -| Setting | Value | -| ------- | ---------------------------------------- | -| Name | `t3-relay` | -| Claims | `{ "aud": "https://relay.example.com" }` | +| Setting | Value | +| ------- | ---------------------------- | +| Name | `t3-relay` | +| Claims | `{ "aud": "t3-code-relay" }` | -The `aud` value must be the deployed relay public URL, with no trailing slash. It must match the -client-facing `T3CODE_RELAY_URL` and the HTTPS URL derived from the deployment's `RELAY_DOMAIN`. If -the relay domain changes, update both values and the JWT template. +Set `T3CODE_CLERK_JWT_TEMPLATE=t3-relay` in the repository-root `.env`, and set +`CLERK_JWT_AUDIENCE=t3-code-relay` in `infra/relay/.env`. Define `CLERK_JWT_TEMPLATE` and +`CLERK_JWT_AUDIENCE` in the production relay deployment environment as well. The stable `aud` value +is shared by production and non-production relay stages. The client-facing `T3CODE_RELAY_URL` still +selects the concrete relay deployment, but changing that URL does not require a JWT template change. ## Desktop OAuth Redirect Allowlist diff --git a/infra/relay/.env.example b/infra/relay/.env.example index 66a73eaf9f..c63cf71985 100644 --- a/infra/relay/.env.example +++ b/infra/relay/.env.example @@ -8,9 +8,11 @@ RELAY_ZONE_NAME=example.com # RELAY_DOMAIN=relay.example.com # Required: Clerk -# Get both values from the Clerk Dashboard under API keys. +# Get the keys from the Clerk Dashboard under API keys. Set the JWT audience to +# the `aud` claim configured on the `t3-relay` JWT template. CLERK_PUBLISHABLE_KEY=pk_test_... CLERK_SECRET_KEY=sk_test_... +CLERK_JWT_AUDIENCE=t3-code-relay # Required: Apple Push Notification service # Get these values from your Apple Developer account. Use `sandbox` for diff --git a/infra/relay/README.md b/infra/relay/README.md index 21414063f6..26d57a275a 100644 --- a/infra/relay/README.md +++ b/infra/relay/README.md @@ -133,6 +133,8 @@ The `production` GitHub environment must define these Actions variables: - `RELAY_ZONE_NAME` - `RELAY_DOMAIN` if overriding the derived production relay domain - `CLERK_PUBLISHABLE_KEY` +- `CLERK_JWT_AUDIENCE` +- `CLERK_JWT_TEMPLATE` - `APNS_ENVIRONMENT` - `APNS_TEAM_ID` - `APNS_KEY_ID` diff --git a/infra/relay/src/Config.ts b/infra/relay/src/Config.ts index 95a020cf4e..23f3ba061b 100644 --- a/infra/relay/src/Config.ts +++ b/infra/relay/src/Config.ts @@ -18,6 +18,7 @@ export interface RelayConfigurationShape { readonly apns: ApnsCredentials; readonly clerkSecretKey: Redacted.Redacted; readonly clerkPublishableKey: string; + readonly clerkJwtAudience: string; readonly apnsDeliveryJobSigningSecret: Redacted.Redacted; readonly cloudMintPrivateKey: Redacted.Redacted; readonly cloudMintPublicKey: string; diff --git a/infra/relay/src/agentActivity/ApnsDeliveries.test.ts b/infra/relay/src/agentActivity/ApnsDeliveries.test.ts index 9e2d418aa1..0dfee1fb0c 100644 --- a/infra/relay/src/agentActivity/ApnsDeliveries.test.ts +++ b/infra/relay/src/agentActivity/ApnsDeliveries.test.ts @@ -39,6 +39,7 @@ const config = RelayConfiguration.RelayConfiguration.of({ apnsDeliveryJobSigningSecret: Redacted.make("job-signing-secret"), clerkSecretKey: Redacted.make("clerk-secret"), clerkPublishableKey: "pk_test_test", + clerkJwtAudience: "t3-code-relay", cloudMintPrivateKey: Redacted.make("cloud-private-key"), cloudMintPublicKey: "cloud-public-key", managedEndpointBaseDomain: undefined, diff --git a/infra/relay/src/agentActivity/MobileRegistrations.test.ts b/infra/relay/src/agentActivity/MobileRegistrations.test.ts index 8227667273..74cf905523 100644 --- a/infra/relay/src/agentActivity/MobileRegistrations.test.ts +++ b/infra/relay/src/agentActivity/MobileRegistrations.test.ts @@ -129,6 +129,7 @@ const config = RelayConfiguration.RelayConfiguration.of({ }, clerkSecretKey: Redacted.make("clerk-secret"), clerkPublishableKey: "pk_test_test", + clerkJwtAudience: "t3-code-relay", apnsDeliveryJobSigningSecret: Redacted.make("apns-job-secret"), cloudMintPrivateKey: Redacted.make("cloud-private-key"), cloudMintPublicKey: "cloud-public-key", diff --git a/infra/relay/src/auth/RelayTokens.test.ts b/infra/relay/src/auth/RelayTokens.test.ts index afdb69ce76..171981834c 100644 --- a/infra/relay/src/auth/RelayTokens.test.ts +++ b/infra/relay/src/auth/RelayTokens.test.ts @@ -26,6 +26,7 @@ const config = RelayConfiguration.RelayConfiguration.of({ apnsDeliveryJobSigningSecret: Redacted.make("job-secret"), clerkSecretKey: Redacted.make("clerk-secret"), clerkPublishableKey: "pk_test_test", + clerkJwtAudience: "t3-code-relay", cloudMintPrivateKey: Redacted.make(keyPair.privateKey), cloudMintPublicKey: keyPair.publicKey, managedEndpointBaseDomain: undefined, diff --git a/infra/relay/src/environments/EnvironmentConnector.test.ts b/infra/relay/src/environments/EnvironmentConnector.test.ts index 7587b744b8..553491d881 100644 --- a/infra/relay/src/environments/EnvironmentConnector.test.ts +++ b/infra/relay/src/environments/EnvironmentConnector.test.ts @@ -66,6 +66,7 @@ const settings = RelayConfiguration.RelayConfiguration.of({ apnsDeliveryJobSigningSecret: Redacted.make("job-secret"), clerkSecretKey: Redacted.make("clerk-secret"), clerkPublishableKey: "pk_test_test", + clerkJwtAudience: "t3-code-relay", cloudMintPrivateKey: Redacted.make(cloudKeyPair.privateKey), cloudMintPublicKey: cloudKeyPair.publicKey, managedEndpointBaseDomain: undefined, diff --git a/infra/relay/src/environments/EnvironmentLinker.test.ts b/infra/relay/src/environments/EnvironmentLinker.test.ts index 7a8843cb05..cbf2b89fdd 100644 --- a/infra/relay/src/environments/EnvironmentLinker.test.ts +++ b/infra/relay/src/environments/EnvironmentLinker.test.ts @@ -39,6 +39,7 @@ const config = RelayConfiguration.RelayConfiguration.of({ apnsDeliveryJobSigningSecret: Redacted.make("job-secret"), clerkSecretKey: Redacted.make("clerk-secret"), clerkPublishableKey: "pk_test_test", + clerkJwtAudience: "t3-code-relay", cloudMintPrivateKey: Redacted.make(relayKeyPair.privateKey), cloudMintPublicKey: relayKeyPair.publicKey, managedEndpointBaseDomain: undefined, diff --git a/infra/relay/src/environments/EnvironmentPublishSignatures.test.ts b/infra/relay/src/environments/EnvironmentPublishSignatures.test.ts index c6f5a84034..a74ce670cf 100644 --- a/infra/relay/src/environments/EnvironmentPublishSignatures.test.ts +++ b/infra/relay/src/environments/EnvironmentPublishSignatures.test.ts @@ -34,6 +34,7 @@ const config = RelayConfiguration.RelayConfiguration.of({ apnsDeliveryJobSigningSecret: Redacted.make("job-secret"), clerkSecretKey: Redacted.make("clerk-secret"), clerkPublishableKey: "pk_test_test", + clerkJwtAudience: "t3-code-relay", cloudMintPrivateKey: Redacted.make(keyPair.privateKey), cloudMintPublicKey: keyPair.publicKey, managedEndpointBaseDomain: undefined, diff --git a/infra/relay/src/environments/ManagedEndpointProvider.test.ts b/infra/relay/src/environments/ManagedEndpointProvider.test.ts index 1b8bcde672..8466c9b919 100644 --- a/infra/relay/src/environments/ManagedEndpointProvider.test.ts +++ b/infra/relay/src/environments/ManagedEndpointProvider.test.ts @@ -21,6 +21,7 @@ const config = RelayConfiguration.RelayConfiguration.of({ apnsDeliveryJobSigningSecret: Redacted.make("job-secret"), clerkSecretKey: Redacted.make("clerk-secret"), clerkPublishableKey: "pk_test_test", + clerkJwtAudience: "t3-code-relay", cloudMintPrivateKey: Redacted.make("cloud-private-key"), cloudMintPublicKey: "cloud-public-key", managedEndpointBaseDomain: "t3code.test", diff --git a/infra/relay/src/http/Api.test.ts b/infra/relay/src/http/Api.test.ts index f0a49bd34b..2822d30b1e 100644 --- a/infra/relay/src/http/Api.test.ts +++ b/infra/relay/src/http/Api.test.ts @@ -40,6 +40,7 @@ const relaySettings: RelayConfiguration.RelayConfigurationShape = { }, clerkSecretKey: Redacted.make("clerk-secret-key"), clerkPublishableKey: "pk_test_test", + clerkJwtAudience: "t3-code-relay", apnsDeliveryJobSigningSecret: Redacted.make("apns-delivery-secret"), cloudMintPrivateKey: Redacted.make("cloud-mint-private-key"), cloudMintPublicKey: "cloud-mint-public-key", @@ -52,13 +53,17 @@ describe("relay client authentication", () => { Effect.gen(function* () { vi.mocked(verifyToken).mockResolvedValue({ sub: "user_session", - aud: relaySettings.relayIssuer, + aud: relaySettings.clerkJwtAudience, } as never); expect(yield* verifyRelayClientBearerToken(relaySettings, "session-token")).toEqual({ sub: "user_session", mode: "clerk_session_bearer", }); + expect(verifyToken).toHaveBeenCalledWith("session-token", { + secretKey: "clerk-secret-key", + audience: relaySettings.clerkJwtAudience, + }); expect(createClerkClient).not.toHaveBeenCalled(); }).pipe( Effect.ensuring( diff --git a/infra/relay/src/http/Api.ts b/infra/relay/src/http/Api.ts index 4b79a858ff..fada5a307c 100644 --- a/infra/relay/src/http/Api.ts +++ b/infra/relay/src/http/Api.ts @@ -578,7 +578,7 @@ export const tokenApi = HttpApiBuilder.group( const verified = yield* verifyClerkBearerToken(config, args.payload.subject_token).pipe( Effect.catch(() => relayAuthInvalidError("invalid_bearer")), ); - if (!verified.sub || !hasExpectedClerkAudience(verified.aud, config.relayIssuer)) { + if (!verified.sub || !hasExpectedClerkAudience(verified.aud, config.clerkJwtAudience)) { return yield* relayAuthInvalidError("invalid_bearer"); } const proofKeyThumbprint = yield* requireDpopProof().pipe( @@ -960,8 +960,7 @@ function clerkVerificationFailureReason(cause: unknown): string { return "unknown"; } -function hasExpectedClerkAudience(audience: unknown, relayIssuer: string): boolean { - const expectedAudience = normalizeRelayIssuer(relayIssuer); +function hasExpectedClerkAudience(audience: unknown, expectedAudience: string): boolean { return typeof audience === "string" ? audience === expectedAudience : Array.isArray(audience) && @@ -973,7 +972,7 @@ function verifyClerkBearerToken(config: RelayConfiguration.RelayConfigurationSha try: () => verifyToken(token, { secretKey: Redacted.value(config.clerkSecretKey), - audience: normalizeRelayIssuer(config.relayIssuer), + audience: config.clerkJwtAudience, }), catch: (cause) => new ClerkTokenVerificationFailed({ cause }), }).pipe( @@ -1015,7 +1014,7 @@ export function verifyRelayClientBearerToken( ) { return verifyClerkBearerToken(config, token).pipe( Effect.flatMap((verified) => - verified.sub && hasExpectedClerkAudience(verified.aud, config.relayIssuer) + verified.sub && hasExpectedClerkAudience(verified.aud, config.clerkJwtAudience) ? Effect.succeed({ sub: verified.sub, mode: "clerk_session_bearer" as const }) : Effect.fail(new ClerkTokenVerificationFailed({ cause: "missing_relay_audience" })), ), diff --git a/infra/relay/src/worker.ts b/infra/relay/src/worker.ts index 712e822e68..9e2ac934c3 100644 --- a/infra/relay/src/worker.ts +++ b/infra/relay/src/worker.ts @@ -130,6 +130,7 @@ export default class Api extends Cloudflare.Worker()( const clerkSecretKey = yield* Config.redacted("CLERK_SECRET_KEY"); const clerkPublishableKey = yield* Config.string("CLERK_PUBLISHABLE_KEY"); + const clerkJwtAudience = yield* Config.string("CLERK_JWT_AUDIENCE"); const cloudMintPrivateKey = yield* cloudMintKeyPair.privateKey; const cloudMintPublicKey = yield* cloudMintKeyPair.publicKey; @@ -158,6 +159,7 @@ export default class Api extends Cloudflare.Worker()( apnsDeliveryJobSigningSecret: yield* apnsDeliveryJobSigningSecret, clerkSecretKey, clerkPublishableKey, + clerkJwtAudience, cloudMintPrivateKey: yield* cloudMintPrivateKey, cloudMintPublicKey: yield* cloudMintPublicKey, managedEndpointBaseDomain: yield* managedEndpointZoneName, diff --git a/packages/shared/src/relayAuth.ts b/packages/shared/src/relayAuth.ts index 0f8c139d41..eb65da9398 100644 --- a/packages/shared/src/relayAuth.ts +++ b/packages/shared/src/relayAuth.ts @@ -1,6 +1,6 @@ -export const RELAY_CLERK_JWT_TEMPLATE = "t3-relay"; - -export const RELAY_CLERK_TOKEN_OPTIONS = { - template: RELAY_CLERK_JWT_TEMPLATE, - skipCache: true, -} as const; +export function relayClerkTokenOptions(template: string) { + return { + template, + skipCache: true, + } as const; +} diff --git a/scripts/lib/public-config.test.ts b/scripts/lib/public-config.test.ts index f5af24a500..40cd29b3c1 100644 --- a/scripts/lib/public-config.test.ts +++ b/scripts/lib/public-config.test.ts @@ -21,6 +21,9 @@ describe("loadRepoEnv", () => { expect(env.T3CODE_CLERK_PUBLISHABLE_KEY).toBeUndefined(); expect(env.VITE_CLERK_PUBLISHABLE_KEY).toBeUndefined(); expect(env.EXPO_PUBLIC_CLERK_PUBLISHABLE_KEY).toBeUndefined(); + expect(env.T3CODE_CLERK_JWT_TEMPLATE).toBeUndefined(); + expect(env.VITE_CLERK_JWT_TEMPLATE).toBeUndefined(); + expect(env.EXPO_PUBLIC_CLERK_JWT_TEMPLATE).toBeUndefined(); expect(env.T3CODE_RELAY_URL).toBeUndefined(); expect(env.VITE_T3CODE_RELAY_URL).toBeUndefined(); }); @@ -29,11 +32,11 @@ describe("loadRepoEnv", () => { const repoRoot = makeTemporaryDirectory(); writeFileSync( join(repoRoot, ".env"), - "T3CODE_CLERK_PUBLISHABLE_KEY=pk_root\nT3CODE_RELAY_URL=https://root.example.test\n", + "T3CODE_CLERK_PUBLISHABLE_KEY=pk_root\nT3CODE_CLERK_JWT_TEMPLATE=template_root\nT3CODE_RELAY_URL=https://root.example.test\n", ); writeFileSync( join(repoRoot, ".env.local"), - "T3CODE_CLERK_PUBLISHABLE_KEY=pk_local\nT3CODE_RELAY_URL=https://local.example.test\n", + "T3CODE_CLERK_PUBLISHABLE_KEY=pk_local\nT3CODE_CLERK_JWT_TEMPLATE=template_local\nT3CODE_RELAY_URL=https://local.example.test\n", ); expect(loadRepoEnv({ baseEnv: {}, repoRoot }).T3CODE_RELAY_URL).toBe( @@ -43,6 +46,7 @@ describe("loadRepoEnv", () => { loadRepoEnv({ baseEnv: { T3CODE_CLERK_PUBLISHABLE_KEY: "pk_ci", + T3CODE_CLERK_JWT_TEMPLATE: "template_ci", T3CODE_RELAY_URL: "https://ci.example.test", }, repoRoot, @@ -51,6 +55,9 @@ describe("loadRepoEnv", () => { T3CODE_CLERK_PUBLISHABLE_KEY: "pk_ci", VITE_CLERK_PUBLISHABLE_KEY: "pk_ci", EXPO_PUBLIC_CLERK_PUBLISHABLE_KEY: "pk_ci", + T3CODE_CLERK_JWT_TEMPLATE: "template_ci", + VITE_CLERK_JWT_TEMPLATE: "template_ci", + EXPO_PUBLIC_CLERK_JWT_TEMPLATE: "template_ci", T3CODE_RELAY_URL: "https://ci.example.test", VITE_T3CODE_RELAY_URL: "https://ci.example.test", }); @@ -60,10 +67,12 @@ describe("loadRepoEnv", () => { expect( resolvePublicConfig({ VITE_CLERK_PUBLISHABLE_KEY: "pk_legacy", + VITE_CLERK_JWT_TEMPLATE: "template_legacy", VITE_T3CODE_RELAY_URL: "https://legacy.example.test", }), ).toEqual({ clerkPublishableKey: "pk_legacy", + clerkJwtTemplate: "template_legacy", relayUrl: "https://legacy.example.test", }); }); diff --git a/scripts/lib/public-config.ts b/scripts/lib/public-config.ts index ea3819bf84..8176a9cae2 100644 --- a/scripts/lib/public-config.ts +++ b/scripts/lib/public-config.ts @@ -6,6 +6,7 @@ import * as NodeUtil from "node:util"; export interface T3CodePublicConfig { readonly clerkPublishableKey: string | undefined; + readonly clerkJwtTemplate: string | undefined; readonly relayUrl: string | undefined; } @@ -37,6 +38,13 @@ export function loadRepoEnv({ EXPO_PUBLIC_CLERK_PUBLISHABLE_KEY: config.clerkPublishableKey, } : {}), + ...(config.clerkJwtTemplate + ? { + T3CODE_CLERK_JWT_TEMPLATE: config.clerkJwtTemplate, + VITE_CLERK_JWT_TEMPLATE: config.clerkJwtTemplate, + EXPO_PUBLIC_CLERK_JWT_TEMPLATE: config.clerkJwtTemplate, + } + : {}), ...(config.relayUrl ? { T3CODE_RELAY_URL: config.relayUrl, @@ -54,6 +62,12 @@ export function resolvePublicConfig(...sources: readonly Environment[]): T3CodeP "VITE_CLERK_PUBLISHABLE_KEY", "EXPO_PUBLIC_CLERK_PUBLISHABLE_KEY", ), + clerkJwtTemplate: firstNonEmpty( + sources, + "T3CODE_CLERK_JWT_TEMPLATE", + "VITE_CLERK_JWT_TEMPLATE", + "EXPO_PUBLIC_CLERK_JWT_TEMPLATE", + ), relayUrl: firstNonEmpty(sources, "T3CODE_RELAY_URL", "VITE_T3CODE_RELAY_URL"), }; }