From 56d1cbebdbbd55e82d20938a1eb1b685559787ca Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Tue, 2 Jun 2026 15:37:20 -0700 Subject: [PATCH] feat(cloud): isolate relay resources by stage Co-authored-by: codex --- infra/relay/.env.example | 8 +- infra/relay/README.md | 16 +- infra/relay/alchemy.run.ts | 1 + infra/relay/package.json | 2 +- infra/relay/scripts/deploy.test.ts | 93 +++++++++++ infra/relay/scripts/deploy.ts | 156 ++++++++++++++++++ infra/relay/src/Config.ts | 2 + .../src/agentActivity/ApnsDeliveries.test.ts | 2 + .../agentActivity/MobileRegistrations.test.ts | 2 + infra/relay/src/auth/RelayTokens.test.ts | 2 + infra/relay/src/db.ts | 36 +++- infra/relay/src/dbConfig.test.ts | 11 ++ infra/relay/src/dbConfig.ts | 5 + infra/relay/src/deploymentConfig.test.ts | 52 ++++++ infra/relay/src/deploymentConfig.ts | 59 +++++++ .../environments/EnvironmentConnector.test.ts | 2 + .../environments/EnvironmentLinker.test.ts | 2 + .../EnvironmentPublishSignatures.test.ts | 2 + .../ManagedEndpointProvider.test.ts | 110 ++++++------ .../environments/ManagedEndpointProvider.ts | 44 ++--- infra/relay/src/http/Api.test.ts | 79 +++++++++ infra/relay/src/http/Api.ts | 56 ++++++- infra/relay/src/worker.ts | 7 +- infra/relay/src/zone.ts | 37 +++-- 24 files changed, 658 insertions(+), 128 deletions(-) create mode 100644 infra/relay/scripts/deploy.test.ts create mode 100644 infra/relay/scripts/deploy.ts create mode 100644 infra/relay/src/dbConfig.test.ts create mode 100644 infra/relay/src/dbConfig.ts create mode 100644 infra/relay/src/deploymentConfig.test.ts create mode 100644 infra/relay/src/deploymentConfig.ts diff --git a/infra/relay/.env.example b/infra/relay/.env.example index 591ceefa5b..a227a15706 100644 --- a/infra/relay/.env.example +++ b/infra/relay/.env.example @@ -1,7 +1,9 @@ -# Relay deployment overrides. The public relay URL is derived as -# https://. -T3_RELAY_DOMAIN=relay.example.com +# Relay deployment configuration. Production derives relay.; personal +# stages derive relay-., matching Alchemy resource naming. T3_RELAY_ZONE_NAME=example.com +# Optional explicit public relay domain override. +# T3_RELAY_DOMAIN=relay.example.com +T3CODE_CLERK_PUBLISHABLE_KEY=pk_test_... # Relay runtime secrets and APNs configuration. CLERK_SECRET_KEY=sk_test_... diff --git a/infra/relay/README.md b/infra/relay/README.md index 8d3525ed03..abeec1bc86 100644 --- a/infra/relay/README.md +++ b/infra/relay/README.md @@ -95,12 +95,17 @@ developer stages: ```sh bun --cwd infra/relay run deploy -- --stage prod -bun --cwd infra/relay run deploy -- --stage "$USER" --env-file .env.local +bun --cwd infra/relay run deploy -- --env-file .env.local ``` -After a successful deploy, the wrapper updates the repository-root `.env` file with the relay URL -derived from `T3_RELAY_DOMAIN`. That makes subsequent source builds point at the relay that was just -deployed without copying the URL manually. +Alchemy defaults personal deployments to the `dev_$USER` stage. Relay custom domains apply the same +DNS-safe sanitization as Alchemy physical resource names, so `prod` uses +`relay.` and `dev_julius` uses `relay-dev-julius.`. +`T3_RELAY_DOMAIN` remains available as an explicit override. + +After a successful deploy, the wrapper updates the repository-root `.env` file with the derived relay +URL. That makes subsequent source builds point at the relay that was just deployed without copying +the URL manually. ### Deployment CI @@ -125,10 +130,9 @@ The repository must define these Actions secrets shared by relay deployments: The `production` GitHub environment must define these Actions variables: -- `T3_RELAY_DOMAIN` - `T3_RELAY_ZONE_NAME` +- `T3_RELAY_DOMAIN` if overriding the derived production relay domain - `T3CODE_CLERK_PUBLISHABLE_KEY` -- `CLERK_CLI_OAUTH_CLIENT_ID` - `APNS_ENVIRONMENT` - `APNS_TEAM_ID` - `APNS_KEY_ID` diff --git a/infra/relay/alchemy.run.ts b/infra/relay/alchemy.run.ts index 4e9bd17495..472d6b95a5 100644 --- a/infra/relay/alchemy.run.ts +++ b/infra/relay/alchemy.run.ts @@ -30,6 +30,7 @@ export default Alchemy.Stack( return { databaseName: db.database.name, + databaseBranchName: db.branch?.name ?? "main", hyperdriveName: hyperdrive.name, workerName: api.workerName, url: api.url, diff --git a/infra/relay/package.json b/infra/relay/package.json index 996b5980e5..f31f1b76b9 100644 --- a/infra/relay/package.json +++ b/infra/relay/package.json @@ -3,7 +3,7 @@ "private": true, "type": "module", "scripts": { - "deploy": "alchemy deploy", + "deploy": "node scripts/deploy.ts", "destroy": "alchemy destroy", "test": "vitest run", "typecheck": "tsgo --noEmit" diff --git a/infra/relay/scripts/deploy.test.ts b/infra/relay/scripts/deploy.test.ts new file mode 100644 index 0000000000..e16be4fa41 --- /dev/null +++ b/infra/relay/scripts/deploy.test.ts @@ -0,0 +1,93 @@ +import * as Config from "effect/Config"; +import * as ConfigProvider from "effect/ConfigProvider"; +import * as Effect from "effect/Effect"; +import * as Option from "effect/Option"; +import { describe, expect, it } from "vitest"; + +import { + makeDeployConfigProvider, + readEnvFileArgument, + readStageArgument, + reconcileRootEnvRelayUrl, + resolveRelayDeployDomain, +} from "./deploy.ts"; + +describe("readEnvFileArgument", () => { + it("supports separated and inline Alchemy env file flags", () => { + expect(readEnvFileArgument(["--stage", "preview", "--env-file", ".env.preview"])).toBe( + ".env.preview", + ); + expect(readEnvFileArgument(["--env-file=.env.preview"])).toBe(".env.preview"); + }); +}); + +describe("readStageArgument", () => { + it("supports separated and inline Alchemy stage flags", () => { + expect(readStageArgument(["--stage", "dev_julius"])).toBe("dev_julius"); + expect(readStageArgument(["--stage=dev_julius"])).toBe("dev_julius"); + }); +}); + +describe("resolveRelayDeployDomain", () => { + it("derives personal stage domains from the imported Cloudflare zone", () => { + expect( + resolveRelayDeployDomain({ + relayDomainOverride: Option.none(), + stage: "dev_julius", + zoneName: "example.test", + }), + ).toBe("relay-dev-julius.example.test"); + }); + + it("preserves explicit domain overrides", () => { + expect( + resolveRelayDeployDomain({ + relayDomainOverride: Option.some("relay.override.test"), + stage: "dev_julius", + zoneName: "example.test", + }), + ).toBe("relay.override.test"); + }); +}); + +describe("makeDeployConfigProvider", () => { + it("prefers injected environment values while retaining dotenv fallbacks", async () => { + const provider = makeDeployConfigProvider( + ConfigProvider.fromEnv({ env: { T3_RELAY_DOMAIN: "ci.example.test" } }), + ConfigProvider.fromEnv({ + env: { + T3_RELAY_DOMAIN: "dotenv.example.test", + T3_RELAY_ZONE_NAME: "example.test", + }, + }), + ); + const config = Config.all({ + relayDomain: Config.string("T3_RELAY_DOMAIN"), + relayZoneName: Config.string("T3_RELAY_ZONE_NAME"), + }).pipe(Effect.provide(ConfigProvider.layer(provider))); + + await expect(Effect.runPromise(config)).resolves.toEqual({ + relayDomain: "ci.example.test", + relayZoneName: "example.test", + }); + }); +}); + +describe("reconcileRootEnvRelayUrl", () => { + it("adds the relay URL to an empty root env file", () => { + expect(reconcileRootEnvRelayUrl("", "https://relay.example.test")).toBe( + "T3_RELAY_URL=https://relay.example.test\n", + ); + }); + + it("preserves unrelated root env entries while replacing a previous relay URL", () => { + expect( + reconcileRootEnvRelayUrl( + "T3CODE_CLERK_PUBLISHABLE_KEY=pk_test_example\nT3_RELAY_URL=https://old.example.test\n", + "https://relay.example.test", + ), + ).toBe( + "T3CODE_CLERK_PUBLISHABLE_KEY=pk_test_example\nT3_RELAY_URL=https://relay.example.test\n", + ); + }); +}); diff --git a/infra/relay/scripts/deploy.ts b/infra/relay/scripts/deploy.ts new file mode 100644 index 0000000000..4441f08b86 --- /dev/null +++ b/infra/relay/scripts/deploy.ts @@ -0,0 +1,156 @@ +#!/usr/bin/env node + +import * as NodeRuntime from "@effect/platform-node/NodeRuntime"; +import * as NodeServices from "@effect/platform-node/NodeServices"; +import * as Config from "effect/Config"; +import * as ConfigProvider from "effect/ConfigProvider"; +import * as Console from "effect/Console"; +import * as Data from "effect/Data"; +import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; +import * as Option from "effect/Option"; +import * as Path from "effect/Path"; +import { ChildProcess } from "effect/unstable/process"; + +import { relayPublicDomainForStage } from "../src/deploymentConfig.ts"; + +export class RelayDeployError extends Data.TaggedError("RelayDeployError")<{ + readonly message: string; +}> {} + +export function readEnvFileArgument(args: ReadonlyArray): string | undefined { + for (let index = 0; index < args.length; index += 1) { + const argument = args[index]; + if (argument === "--env-file") { + return args[index + 1]; + } + if (argument?.startsWith("--env-file=")) { + return argument.slice("--env-file=".length); + } + } + return undefined; +} + +export function readStageArgument(args: ReadonlyArray): string | undefined { + for (let index = 0; index < args.length; index += 1) { + const argument = args[index]; + if (argument === "--stage") { + return args[index + 1]; + } + if (argument?.startsWith("--stage=")) { + return argument.slice("--stage=".length); + } + } + return undefined; +} + +export function resolveRelayDeployDomain(input: { + readonly relayDomainOverride: Option.Option; + readonly stage: string; + readonly zoneName: string; +}): string { + return Option.getOrElse(input.relayDomainOverride, () => + relayPublicDomainForStage(input.stage, input.zoneName), + ); +} + +export function reconcileRootEnvRelayUrl(contents: string, relayUrl: string): string { + const entry = `T3_RELAY_URL=${relayUrl}`; + if (/^T3_RELAY_URL=.*$/mu.test(contents)) { + return contents.replace(/^T3_RELAY_URL=.*$/mu, entry); + } + if (!contents) { + return `${entry}\n`; + } + return `${contents}${contents.endsWith("\n") ? "" : "\n"}${entry}\n`; +} + +export function makeDeployConfigProvider( + environmentProvider: ConfigProvider.ConfigProvider, + dotenvProvider?: ConfigProvider.ConfigProvider, +) { + return dotenvProvider + ? ConfigProvider.orElse(environmentProvider, dotenvProvider) + : environmentProvider; +} + +const relayRoot = Effect.service(Path.Path).pipe( + Effect.flatMap((path) => path.fromFileUrl(new URL("..", import.meta.url))), +); +const repoRoot = Effect.service(Path.Path).pipe( + Effect.flatMap((path) => path.fromFileUrl(new URL("../../..", import.meta.url))), +); + +const loadDeployConfigProvider = Effect.fn("relay.deploy.loadConfigProvider")(function* ( + args: ReadonlyArray, +) { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const root = yield* relayRoot; + const selectedEnvFile = readEnvFileArgument(args); + const envFile = selectedEnvFile ? path.resolve(root, selectedEnvFile) : path.join(root, ".env"); + if (!(yield* fs.exists(envFile))) { + return makeDeployConfigProvider(ConfigProvider.fromEnv()); + } + return makeDeployConfigProvider( + ConfigProvider.fromEnv(), + yield* ConfigProvider.fromDotEnv({ path: envFile }), + ); +}); + +const runAlchemyDeploy = Effect.fn("relay.deploy.runAlchemy")(function* ( + args: ReadonlyArray, +) { + const root = yield* relayRoot; + const child = yield* ChildProcess.make("alchemy", ["deploy", ...args], { + cwd: root, + detached: false, + stderr: "inherit", + stdin: "inherit", + stdout: "inherit", + }); + const exitCode = yield* child.exitCode; + if (exitCode !== 0) { + return yield* new RelayDeployError({ + message: `alchemy deploy exited with code ${exitCode}`, + }); + } +}); + +const reconcileRootEnv = Effect.fn("relay.deploy.reconcileRootEnv")(function* ( + args: ReadonlyArray, +) { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const root = yield* repoRoot; + const provider = yield* loadDeployConfigProvider(args); + const config = yield* Config.all({ + relayDomainOverride: Config.nonEmptyString("T3_RELAY_DOMAIN").pipe(Config.option), + stage: Config.nonEmptyString("stage").pipe( + Config.option, + Config.map( + Option.getOrElse(() => `dev_${process.env.USER ?? process.env.USERNAME ?? "unknown"}`), + ), + ), + zoneName: Config.nonEmptyString("T3_RELAY_ZONE_NAME"), + }).pipe(Effect.provide(ConfigProvider.layer(provider))); + const relayDomain = resolveRelayDeployDomain({ + ...config, + stage: readStageArgument(args) ?? config.stage, + }); + const relayUrl = `https://${relayDomain}`; + const rootEnvPath = path.join(root, ".env"); + const contents = (yield* fs.exists(rootEnvPath)) ? yield* fs.readFileString(rootEnvPath) : ""; + + yield* fs.writeFileString(rootEnvPath, reconcileRootEnvRelayUrl(contents, relayUrl)); + yield* Console.log(`Updated ${rootEnvPath} with T3_RELAY_URL=${relayUrl}`); +}); + +export const deploy = Effect.fn("relay.deploy")(function* (args: ReadonlyArray) { + yield* runAlchemyDeploy(args); + yield* reconcileRootEnv(args); +}); + +if (import.meta.main) { + deploy(process.argv.slice(2)).pipe(Effect.provide(NodeServices.layer), NodeRuntime.runMain); +} diff --git a/infra/relay/src/Config.ts b/infra/relay/src/Config.ts index 685a2f0bd3..95a020cf4e 100644 --- a/infra/relay/src/Config.ts +++ b/infra/relay/src/Config.ts @@ -17,10 +17,12 @@ export interface RelayConfigurationShape { readonly relayIssuer: string; readonly apns: ApnsCredentials; readonly clerkSecretKey: Redacted.Redacted; + readonly clerkPublishableKey: string; readonly apnsDeliveryJobSigningSecret: Redacted.Redacted; readonly cloudMintPrivateKey: Redacted.Redacted; readonly cloudMintPublicKey: string; readonly managedEndpointBaseDomain: string | undefined; + readonly managedEndpointNamespace: string | undefined; } export class RelayConfiguration extends Context.Service< diff --git a/infra/relay/src/agentActivity/ApnsDeliveries.test.ts b/infra/relay/src/agentActivity/ApnsDeliveries.test.ts index 54ccee62e6..9e2d418aa1 100644 --- a/infra/relay/src/agentActivity/ApnsDeliveries.test.ts +++ b/infra/relay/src/agentActivity/ApnsDeliveries.test.ts @@ -38,9 +38,11 @@ const config = RelayConfiguration.RelayConfiguration.of({ }, apnsDeliveryJobSigningSecret: Redacted.make("job-signing-secret"), clerkSecretKey: Redacted.make("clerk-secret"), + clerkPublishableKey: "pk_test_test", cloudMintPrivateKey: Redacted.make("cloud-private-key"), cloudMintPublicKey: "cloud-public-key", managedEndpointBaseDomain: undefined, + managedEndpointNamespace: undefined, }); const apnsSigningKeyPair = NodeCrypto.generateKeyPairSync("ec", { diff --git a/infra/relay/src/agentActivity/MobileRegistrations.test.ts b/infra/relay/src/agentActivity/MobileRegistrations.test.ts index d548b925ef..8227667273 100644 --- a/infra/relay/src/agentActivity/MobileRegistrations.test.ts +++ b/infra/relay/src/agentActivity/MobileRegistrations.test.ts @@ -128,10 +128,12 @@ const config = RelayConfiguration.RelayConfiguration.of({ privateKey: Redacted.make("apns-private-key"), }, clerkSecretKey: Redacted.make("clerk-secret"), + clerkPublishableKey: "pk_test_test", apnsDeliveryJobSigningSecret: Redacted.make("apns-job-secret"), cloudMintPrivateKey: Redacted.make("cloud-private-key"), cloudMintPublicKey: "cloud-public-key", managedEndpointBaseDomain: undefined, + managedEndpointNamespace: undefined, }); function makeRegistrationReplayLayer(input: { diff --git a/infra/relay/src/auth/RelayTokens.test.ts b/infra/relay/src/auth/RelayTokens.test.ts index 4c48dc157c..afdb69ce76 100644 --- a/infra/relay/src/auth/RelayTokens.test.ts +++ b/infra/relay/src/auth/RelayTokens.test.ts @@ -25,9 +25,11 @@ const config = RelayConfiguration.RelayConfiguration.of({ }, apnsDeliveryJobSigningSecret: Redacted.make("job-secret"), clerkSecretKey: Redacted.make("clerk-secret"), + clerkPublishableKey: "pk_test_test", cloudMintPrivateKey: Redacted.make(keyPair.privateKey), cloudMintPublicKey: keyPair.publicKey, managedEndpointBaseDomain: undefined, + managedEndpointNamespace: undefined, }); const layer = RelayTokens.layer.pipe( diff --git a/infra/relay/src/db.ts b/infra/relay/src/db.ts index e4094240d9..8d938bb3fe 100644 --- a/infra/relay/src/db.ts +++ b/infra/relay/src/db.ts @@ -2,10 +2,14 @@ import type { PgClient } from "@effect/sql-pg/PgClient"; import * as Cloudflare from "alchemy/Cloudflare"; import * as Drizzle from "alchemy/Drizzle"; import * as Planetscale from "alchemy/Planetscale"; +import * as Alchemy from "alchemy"; +import * as RemovalPolicy from "alchemy/RemovalPolicy"; import type { EffectPgDatabase } from "drizzle-orm/effect-postgres"; import * as Context from "effect/Context"; import * as Effect from "effect/Effect"; +import { relayDatabaseMode } from "./dbConfig.ts"; + export interface RelayDatabase extends EffectPgDatabase { readonly $client: PgClient; } @@ -13,26 +17,42 @@ export interface RelayDatabase extends EffectPgDatabase { export class RelayDb extends Context.Service()("t3code-relay/db/RelayDb") {} export const PlanetscaleDatabase = Effect.gen(function* () { + const { stage } = yield* Alchemy.Stack; const schema = yield* Drizzle.Schema("RelaySchema", { schema: "./src/persistence/schema.ts", out: "./migrations/postgres", dialect: "postgres", }); - const database = yield* Planetscale.PostgresDatabase("RelayPostgresDatabase", { - region: { slug: "us-west" }, - clusterSize: "PS_5", - migrationsDir: schema.out, - migrationsTable: "relay_migrations", - replicas: 0, // BUMP BEFORE GOING TO PROD - }); + const mode = relayDatabaseMode(stage); + const database = + mode === "shared-database" + ? yield* Planetscale.PostgresDatabase("RelayPostgresDatabase", { + region: { slug: "us-west" }, + clusterSize: "PS_5", + migrationsDir: schema.out, + migrationsTable: "relay_migrations", + replicas: 0, // BUMP BEFORE GOING TO PROD + }).pipe(RemovalPolicy.retain()) + : yield* Planetscale.PostgresDatabase.ref("RelayPostgresDatabase", { + stage: "prod", + }); + const branch = + mode === "stage-branch" + ? yield* Planetscale.PostgresBranch("RelayPostgresBranch", { + database, + migrationsDir: schema.out, + migrationsTable: "relay_migrations", + }) + : undefined; const runtimeRole = yield* Planetscale.PostgresRole("RelayPostgresRuntimeRole", { database, + ...(branch ? { branch } : {}), inheritedRoles: ["pg_read_all_data", "pg_write_all_data"], }); - return { database, runtimeRole }; + return { branch, database, runtimeRole }; }); export const RelayHyperdrive = Effect.gen(function* () { diff --git a/infra/relay/src/dbConfig.test.ts b/infra/relay/src/dbConfig.test.ts new file mode 100644 index 0000000000..31a1c06531 --- /dev/null +++ b/infra/relay/src/dbConfig.test.ts @@ -0,0 +1,11 @@ +import { describe, expect, it } from "vitest"; + +import { relayDatabaseMode } from "./dbConfig.ts"; + +describe("relayDatabaseMode", () => { + it("uses the shared database only for production", () => { + expect(relayDatabaseMode("prod")).toBe("shared-database"); + expect(relayDatabaseMode("dev_julius")).toBe("stage-branch"); + expect(relayDatabaseMode("preview")).toBe("stage-branch"); + }); +}); diff --git a/infra/relay/src/dbConfig.ts b/infra/relay/src/dbConfig.ts new file mode 100644 index 0000000000..9f6416aedc --- /dev/null +++ b/infra/relay/src/dbConfig.ts @@ -0,0 +1,5 @@ +export type RelayDatabaseMode = "shared-database" | "stage-branch"; + +export function relayDatabaseMode(stage: string): RelayDatabaseMode { + return stage === "prod" ? "shared-database" : "stage-branch"; +} diff --git a/infra/relay/src/deploymentConfig.test.ts b/infra/relay/src/deploymentConfig.test.ts new file mode 100644 index 0000000000..29223472b4 --- /dev/null +++ b/infra/relay/src/deploymentConfig.test.ts @@ -0,0 +1,52 @@ +import { describe, expect, it } from "vitest"; + +import { + managedEndpointDigestInput, + managedEndpointHostname, + managedEndpointTunnelName, + relayPublicDomainForStage, + relayStageSlug, +} from "./deploymentConfig.ts"; + +describe("relayStageSlug", () => { + it("matches Alchemy physical-name sanitization for default developer stages", () => { + expect(relayStageSlug("dev_julius")).toBe("dev-julius"); + }); +}); + +describe("relayPublicDomainForStage", () => { + it("uses the canonical relay hostname for production", () => { + expect(relayPublicDomainForStage("prod", ".example.com.")).toBe("relay.example.com"); + }); + + it("isolates personal stages below the imported zone", () => { + expect(relayPublicDomainForStage("dev_julius", "example.com")).toBe( + "relay-dev-julius.example.com", + ); + }); +}); + +describe("managed endpoint names", () => { + it("uses the stage slug and a stable stage-scoped digest suffix", () => { + const hash = "ABCDEF0123456789ABCDEF0123456789"; + + expect(managedEndpointDigestInput("dev_julius", "env_123")).toBe("dev_julius:env_123"); + expect(managedEndpointHostname("dev_julius", ".example.com.", hash)).toBe( + "tunnels-dev-julius-abcdef0123456789.example.com", + ); + expect(managedEndpointTunnelName("dev_julius", hash)).toBe( + "t3coderelay-managedendpoint-dev-julius-abcdef0123456789", + ); + }); + + it("keeps the DNS label within the provider limit for long stage names", () => { + const hostname = managedEndpointHostname( + "dev_" + "x".repeat(100), + "example.com", + "a".repeat(64), + ); + + expect(hostname.split(".")[0]?.length).toBeLessThanOrEqual(63); + expect(hostname).toMatch(/-a{16}\.example\.com$/); + }); +}); diff --git a/infra/relay/src/deploymentConfig.ts b/infra/relay/src/deploymentConfig.ts new file mode 100644 index 0000000000..c298087bdb --- /dev/null +++ b/infra/relay/src/deploymentConfig.ts @@ -0,0 +1,59 @@ +const DNS_LABEL_MAX_LENGTH = 63; +const MANAGED_ENDPOINT_HASH_LENGTH = 16; +const MANAGED_ENDPOINT_HOST_PREFIX = "tunnels"; +const MANAGED_ENDPOINT_TUNNEL_PREFIX = "t3coderelay-managedendpoint"; + +function normalizeZoneName(zoneName: string): string { + return zoneName + .trim() + .toLowerCase() + .replace(/^\.+|\.+$/g, ""); +} + +function stableSuffix(hash: string): string { + return hash.toLowerCase().slice(0, MANAGED_ENDPOINT_HASH_LENGTH); +} + +function appendDnsSafeSuffix(prefix: string, suffix: string): string { + const truncatedPrefix = prefix + .slice(0, DNS_LABEL_MAX_LENGTH - suffix.length - 1) + .replace(/-+$/g, ""); + return `${truncatedPrefix}-${suffix}`; +} + +/** + * Alchemy's physical-name helper sanitizes resource names after adding the + * stage. Keep custom domains and runtime-created resources aligned with it. + */ +export function relayStageSlug(stage: string): string { + return stage + .toLowerCase() + .replaceAll(/[^a-z0-9-]/g, "-") + .replaceAll(/-+/g, "-") + .replace(/^-+|-+$/g, ""); +} + +export function relayPublicDomainForStage(stage: string, zoneName: string): string { + const stageSlug = relayStageSlug(stage); + const relayLabel = stage === "prod" ? "relay" : `relay-${stageSlug}`; + if (relayLabel.length > DNS_LABEL_MAX_LENGTH) { + throw new Error(`Relay stage is too long for a custom domain: ${stage}`); + } + return `${relayLabel}.${normalizeZoneName(zoneName)}`; +} + +export function managedEndpointDigestInput(stage: string, environmentId: string): string { + return `${stage}:${environmentId}`; +} + +export function managedEndpointHostname(stage: string, baseDomain: string, hash: string): string { + const label = appendDnsSafeSuffix( + `${MANAGED_ENDPOINT_HOST_PREFIX}-${relayStageSlug(stage)}`, + stableSuffix(hash), + ); + return `${label}.${normalizeZoneName(baseDomain)}`; +} + +export function managedEndpointTunnelName(stage: string, hash: string): string { + return `${MANAGED_ENDPOINT_TUNNEL_PREFIX}-${relayStageSlug(stage)}-${stableSuffix(hash)}`; +} diff --git a/infra/relay/src/environments/EnvironmentConnector.test.ts b/infra/relay/src/environments/EnvironmentConnector.test.ts index 3232949db0..7587b744b8 100644 --- a/infra/relay/src/environments/EnvironmentConnector.test.ts +++ b/infra/relay/src/environments/EnvironmentConnector.test.ts @@ -65,9 +65,11 @@ const settings = RelayConfiguration.RelayConfiguration.of({ }, apnsDeliveryJobSigningSecret: Redacted.make("job-secret"), clerkSecretKey: Redacted.make("clerk-secret"), + clerkPublishableKey: "pk_test_test", cloudMintPrivateKey: Redacted.make(cloudKeyPair.privateKey), cloudMintPublicKey: cloudKeyPair.publicKey, managedEndpointBaseDomain: undefined, + managedEndpointNamespace: undefined, }); function signTestJwt(payload: object, typ: string, privateKey: string): string { diff --git a/infra/relay/src/environments/EnvironmentLinker.test.ts b/infra/relay/src/environments/EnvironmentLinker.test.ts index 7edf9a9107..7a8843cb05 100644 --- a/infra/relay/src/environments/EnvironmentLinker.test.ts +++ b/infra/relay/src/environments/EnvironmentLinker.test.ts @@ -38,9 +38,11 @@ const config = RelayConfiguration.RelayConfiguration.of({ }, apnsDeliveryJobSigningSecret: Redacted.make("job-secret"), clerkSecretKey: Redacted.make("clerk-secret"), + clerkPublishableKey: "pk_test_test", cloudMintPrivateKey: Redacted.make(relayKeyPair.privateKey), cloudMintPublicKey: relayKeyPair.publicKey, managedEndpointBaseDomain: undefined, + managedEndpointNamespace: undefined, }); function signTestJwt(payload: object, typ: string, privateKey: string): string { diff --git a/infra/relay/src/environments/EnvironmentPublishSignatures.test.ts b/infra/relay/src/environments/EnvironmentPublishSignatures.test.ts index fc056eff8f..c6f5a84034 100644 --- a/infra/relay/src/environments/EnvironmentPublishSignatures.test.ts +++ b/infra/relay/src/environments/EnvironmentPublishSignatures.test.ts @@ -33,9 +33,11 @@ const config = RelayConfiguration.RelayConfiguration.of({ }, apnsDeliveryJobSigningSecret: Redacted.make("job-secret"), clerkSecretKey: Redacted.make("clerk-secret"), + clerkPublishableKey: "pk_test_test", cloudMintPrivateKey: Redacted.make(keyPair.privateKey), cloudMintPublicKey: keyPair.publicKey, managedEndpointBaseDomain: undefined, + managedEndpointNamespace: undefined, }); const state: RelayAgentActivityState = { environmentId: "env" as RelayAgentActivityState["environmentId"], diff --git a/infra/relay/src/environments/ManagedEndpointProvider.test.ts b/infra/relay/src/environments/ManagedEndpointProvider.test.ts index 0c2cb8869a..1b8bcde672 100644 --- a/infra/relay/src/environments/ManagedEndpointProvider.test.ts +++ b/infra/relay/src/environments/ManagedEndpointProvider.test.ts @@ -20,9 +20,11 @@ const config = RelayConfiguration.RelayConfiguration.of({ }, apnsDeliveryJobSigningSecret: Redacted.make("job-secret"), clerkSecretKey: Redacted.make("clerk-secret"), + clerkPublishableKey: "pk_test_test", cloudMintPrivateKey: Redacted.make("cloud-private-key"), cloudMintPublicKey: "cloud-public-key", managedEndpointBaseDomain: "t3code.test", + managedEndpointNamespace: "dev_julius", }); interface TunnelCall { @@ -90,13 +92,19 @@ function providerLayer(tunnelClient = makeTunnelClient(), dnsClient = makeDnsCli } function expectedManagedHostname(environmentId: string): string { - const hash = NodeCrypto.createHash("sha256").update(environmentId).digest("hex").slice(0, 16); - return `tunnels-env-abc-${hash}.t3code.test`; + const hash = NodeCrypto.createHash("sha256") + .update(`dev_julius:${environmentId}`) + .digest("hex") + .slice(0, 16); + return `tunnels-dev-julius-${hash}.t3code.test`; } function expectedManagedTunnelName(environmentId: string): string { - const hash = NodeCrypto.createHash("sha256").update(environmentId).digest("hex").slice(0, 16); - return `t3-code-env-abc-${hash}`; + const hash = NodeCrypto.createHash("sha256") + .update(`dev_julius:${environmentId}`) + .digest("hex") + .slice(0, 16); + return `t3coderelay-managedendpoint-dev-julius-${hash}`; } describe("ManagedEndpointProvider", () => { @@ -162,58 +170,52 @@ describe("ManagedEndpointProvider", () => { }).pipe(Effect.provide(providerLayer(makeTunnelClient(tunnelCalls), makeDnsClient(dnsCalls)))); }); - it.effect( - "normalizes unusual environment ids before using them in Cloudflare tunnel names", - () => { - const tunnelCalls: TunnelCall[] = []; + it.effect("uses stage-scoped stable names without leaking unusual environment ids", () => { + const tunnelCalls: TunnelCall[] = []; - return Effect.gen(function* () { - const environmentId = "ENV With Spaces/../Symbols!" + "x".repeat(80); - const provider = yield* ManagedEndpointProvider.ManagedEndpointProvider; - yield* provider.provision({ - environmentId, - origin: { localHttpHost: "127.0.0.1", localHttpPort: 3773 }, - }); + return Effect.gen(function* () { + const environmentId = "ENV With Spaces/../Symbols!" + "x".repeat(80); + const provider = yield* ManagedEndpointProvider.ManagedEndpointProvider; + yield* provider.provision({ + environmentId, + origin: { localHttpHost: "127.0.0.1", localHttpPort: 3773 }, + }); - const requestedName = ( - tunnelCalls.find((call) => call.operation === "list")?.input as - | { readonly name?: string } - | undefined - )?.name; - expect(requestedName).toMatch(/^t3-code-env-with-spaces-symbols-x+-[a-f0-9]{16}$/); - expect(requestedName?.length).toBeLessThanOrEqual(89); - const configBody = ( - tunnelCalls.find((call) => call.operation === "putConfiguration")?.input as - | { readonly tunnelConfig?: unknown } - | undefined - )?.tunnelConfig; - expect(configBody).toMatchObject({ - ingress: [ - { - hostname: expect.stringMatching( - /^tunnels-env-with-spaces-symbols-x+-[a-f0-9]{16}\.t3code\.test$/, - ), - }, - { service: "http_status:404" }, - ], - }); - const hostname = ( - configBody as - | { - readonly ingress?: readonly [{ readonly hostname?: unknown }, unknown]; - } - | undefined - )?.ingress?.[0]?.hostname; - expect( - typeof hostname === "string" ? hostname.split(".")[0]?.length : 0, - ).toBeLessThanOrEqual(63); - expect(tunnelCalls.find((call) => call.operation === "create")?.input).toMatchObject({ - name: requestedName, - configSrc: "cloudflare", - }); - }).pipe(Effect.provide(providerLayer(makeTunnelClient(tunnelCalls)))); - }, - ); + const requestedName = ( + tunnelCalls.find((call) => call.operation === "list")?.input as + | { readonly name?: string } + | undefined + )?.name; + expect(requestedName).toMatch(/^t3coderelay-managedendpoint-dev-julius-[a-f0-9]{16}$/); + const configBody = ( + tunnelCalls.find((call) => call.operation === "putConfiguration")?.input as + | { readonly tunnelConfig?: unknown } + | undefined + )?.tunnelConfig; + expect(configBody).toMatchObject({ + ingress: [ + { + hostname: expect.stringMatching(/^tunnels-dev-julius-[a-f0-9]{16}\.t3code\.test$/), + }, + { service: "http_status:404" }, + ], + }); + const hostname = ( + configBody as + | { + readonly ingress?: readonly [{ readonly hostname?: unknown }, unknown]; + } + | undefined + )?.ingress?.[0]?.hostname; + expect(typeof hostname === "string" ? hostname.split(".")[0]?.length : 0).toBeLessThanOrEqual( + 63, + ); + expect(tunnelCalls.find((call) => call.operation === "create")?.input).toMatchObject({ + name: requestedName, + configSrc: "cloudflare", + }); + }).pipe(Effect.provide(providerLayer(makeTunnelClient(tunnelCalls)))); + }); it.effect("formats IPv6 loopback origins as valid Cloudflare ingress service URLs", () => { const tunnelCalls: TunnelCall[] = []; diff --git a/infra/relay/src/environments/ManagedEndpointProvider.ts b/infra/relay/src/environments/ManagedEndpointProvider.ts index c2a98b8f3b..78ce919dc9 100644 --- a/infra/relay/src/environments/ManagedEndpointProvider.ts +++ b/infra/relay/src/environments/ManagedEndpointProvider.ts @@ -17,6 +17,11 @@ import type { } from "@t3tools/contracts/relay"; import * as RelayConfiguration from "../Config.ts"; +import { + managedEndpointDigestInput, + managedEndpointHostname, + managedEndpointTunnelName, +} from "../deploymentConfig.ts"; export class ManagedEndpointProvisioningNotConfigured extends Data.TaggedError( "ManagedEndpointProvisioningNotConfigured", @@ -132,41 +137,15 @@ export class ManagedEndpointDnsClient extends Context.Service< const requireCloudflareSettings = Effect.fnUntraced(function* ( settings: RelayConfiguration.RelayConfigurationShape, ) { - if (!settings.managedEndpointBaseDomain) { + if (!settings.managedEndpointBaseDomain || !settings.managedEndpointNamespace) { return yield* new ManagedEndpointProvisioningNotConfigured(); } return { baseDomain: settings.managedEndpointBaseDomain, + namespace: settings.managedEndpointNamespace, }; }); -const MANAGED_ENDPOINT_HOST_PREFIX = "tunnels"; -const DNS_LABEL_MAX_LENGTH = 63; -const MANAGED_ENDPOINT_HASH_LENGTH = 16; -const MANAGED_ENDPOINT_SAFE_ID_LENGTH = - DNS_LABEL_MAX_LENGTH - MANAGED_ENDPOINT_HOST_PREFIX.length - 2 - MANAGED_ENDPOINT_HASH_LENGTH; - -function managedHostname(environmentId: string, baseDomain: string, hash: string): string { - const safeId = environmentId - .toLowerCase() - .replaceAll(/[^a-z0-9-]/g, "-") - .replaceAll(/-+/g, "-") - .replaceAll(/^-+|-+$/g, "") - .slice(0, MANAGED_ENDPOINT_SAFE_ID_LENGTH); - const prefix = safeId.length > 0 ? safeId : "env"; - return `${MANAGED_ENDPOINT_HOST_PREFIX}-${prefix}-${hash.slice(0, MANAGED_ENDPOINT_HASH_LENGTH)}.${baseDomain.replace(/^\.+|\.+$/g, "")}`; -} - -function managedTunnelName(environmentId: string, hash: string): string { - const safeId = environmentId - .toLowerCase() - .replaceAll(/[^a-z0-9-]/g, "-") - .replaceAll(/-+/g, "-") - .replaceAll(/^-+|-+$/g, "") - .slice(0, 64); - return `t3-code-${safeId.length > 0 ? safeId : "env"}-${hash.slice(0, 16)}`; -} - function formatOriginService(origin: RelayManagedEndpointOrigin): string { const host = origin.localHttpHost.includes(":") ? `[${origin.localHttpHost.replace(/^\[(.*)\]$/u, "$1")}]` @@ -212,13 +191,16 @@ const make = Effect.gen(function* () { } const cf = yield* requireCloudflareSettings(config); const environmentHash = yield* crypto - .digest("SHA-256", new TextEncoder().encode(input.environmentId)) + .digest( + "SHA-256", + new TextEncoder().encode(managedEndpointDigestInput(cf.namespace, input.environmentId)), + ) .pipe( Effect.map(Encoding.encodeHex), Effect.mapError((cause) => new ManagedEndpointProvisioningFailed({ cause })), ); - const hostname = managedHostname(input.environmentId, cf.baseDomain, environmentHash); - const tunnelName = managedTunnelName(input.environmentId, environmentHash); + const hostname = managedEndpointHostname(cf.namespace, cf.baseDomain, environmentHash); + const tunnelName = managedEndpointTunnelName(cf.namespace, environmentHash); const tunnel = yield* tunnels.list({ name: tunnelName, isDeleted: false }).pipe( Effect.map((tunnels) => tunnels.result), diff --git a/infra/relay/src/http/Api.test.ts b/infra/relay/src/http/Api.test.ts index 9eccb8d16b..f0a49bd34b 100644 --- a/infra/relay/src/http/Api.test.ts +++ b/infra/relay/src/http/Api.test.ts @@ -1,4 +1,6 @@ +import { createClerkClient, verifyToken } from "@clerk/backend"; import { describe, expect, it } from "@effect/vitest"; +import { vi } from "vitest"; import * as Context from "effect/Context"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; @@ -16,10 +18,87 @@ import { relayEnvironmentAuthLayer, relayNotFoundRoute, traceRelayHttpRequestWith, + verifyRelayClientBearerToken, withoutCapturedParentSpan, } from "./Api.ts"; +import * as RelayConfiguration from "../Config.ts"; import * as EnvironmentCredentials from "../environments/EnvironmentCredentials.ts"; +vi.mock("@clerk/backend", () => ({ + createClerkClient: vi.fn(), + verifyToken: vi.fn(), +})); + +const relaySettings: RelayConfiguration.RelayConfigurationShape = { + relayIssuer: "https://relay.example.test", + apns: { + teamId: "apns-team", + keyId: "apns-key", + privateKey: Redacted.make("apns-private-key"), + bundleId: "com.example.t3", + environment: "sandbox", + }, + clerkSecretKey: Redacted.make("clerk-secret-key"), + clerkPublishableKey: "pk_test_test", + apnsDeliveryJobSigningSecret: Redacted.make("apns-delivery-secret"), + cloudMintPrivateKey: Redacted.make("cloud-mint-private-key"), + cloudMintPublicKey: "cloud-mint-public-key", + managedEndpointBaseDomain: undefined, + managedEndpointNamespace: undefined, +}; + +describe("relay client authentication", () => { + it.effect("preserves the existing Clerk session JWT path", () => + Effect.gen(function* () { + vi.mocked(verifyToken).mockResolvedValue({ + sub: "user_session", + aud: relaySettings.relayIssuer, + } as never); + + expect(yield* verifyRelayClientBearerToken(relaySettings, "session-token")).toEqual({ + sub: "user_session", + mode: "clerk_session_bearer", + }); + expect(createClerkClient).not.toHaveBeenCalled(); + }).pipe( + Effect.ensuring( + Effect.sync(() => { + vi.mocked(verifyToken).mockReset(); + vi.mocked(createClerkClient).mockReset(); + }), + ), + ), + ); + + it.effect("falls back to Clerk OAuth token verification for the headless CLI", () => + Effect.gen(function* () { + vi.mocked(verifyToken).mockRejectedValue(new Error("not a session JWT")); + vi.mocked(createClerkClient).mockReturnValue({ + authenticateRequest: vi.fn().mockResolvedValue({ + isAuthenticated: true, + toAuth: () => ({ userId: "user_oauth" }), + }), + } as never); + + expect(yield* verifyRelayClientBearerToken(relaySettings, "oauth-token")).toEqual({ + sub: "user_oauth", + mode: "clerk_oauth_bearer", + }); + expect(createClerkClient).toHaveBeenCalledWith({ + secretKey: "clerk-secret-key", + publishableKey: "pk_test_test", + }); + }).pipe( + Effect.ensuring( + Effect.sync(() => { + vi.mocked(verifyToken).mockReset(); + vi.mocked(createClerkClient).mockReset(); + }), + ), + ), + ); +}); + describe("relay environment authentication", () => { it.effect("preserves credential lookup persistence failures as internal errors", () => { const failure = new EnvironmentCredentials.EnvironmentCredentialAuthenticatePersistenceError({ diff --git a/infra/relay/src/http/Api.ts b/infra/relay/src/http/Api.ts index 451c198169..4b79a858ff 100644 --- a/infra/relay/src/http/Api.ts +++ b/infra/relay/src/http/Api.ts @@ -1,4 +1,4 @@ -import { verifyToken } from "@clerk/backend"; +import { createClerkClient, verifyToken } from "@clerk/backend"; import { sql as drizzleSql } from "drizzle-orm"; import * as Data from "effect/Data"; import * as Crypto from "effect/Crypto"; @@ -188,7 +188,7 @@ export const relayClientAuthLayer = Layer.effect( return { bearer: Effect.fn("relay.auth.client.bearer")(function* (httpEffect, { credential }) { const token = readHttpAuthorizationCredential(credential); - const verified = yield* verifyClerkBearerToken(config, token).pipe( + const verified = yield* verifyRelayClientBearerToken(config, token).pipe( Effect.tapError((error) => Effect.annotateCurrentSpan( "relay.auth.clerk_verification_failure", @@ -197,16 +197,14 @@ export const relayClientAuthLayer = Layer.effect( ), Effect.catch(() => relayAuthInvalidError("invalid_bearer")), ); - if (!verified.sub || !hasExpectedClerkAudience(verified.aud, config.relayIssuer)) { + if (!verified.sub) { yield* Effect.annotateCurrentSpan({ - "relay.auth.clerk_verification_failure": !verified.sub - ? "missing_subject" - : "missing_relay_audience", + "relay.auth.clerk_verification_failure": "missing_subject", }); return yield* relayAuthInvalidError("invalid_bearer"); } yield* Effect.annotateCurrentSpan({ - "relay.auth.mode": "clerk_bearer", + "relay.auth.mode": verified.mode, "relay.auth.subject": verified.sub, }); @@ -985,6 +983,50 @@ function verifyClerkBearerToken(config: RelayConfiguration.RelayConfigurationSha ); } +function verifyClerkOAuthBearerToken( + config: RelayConfiguration.RelayConfigurationShape, + token: string, +) { + return Effect.tryPromise({ + try: async () => { + const client = createClerkClient({ + secretKey: Redacted.value(config.clerkSecretKey), + publishableKey: config.clerkPublishableKey, + }); + const state = await client.authenticateRequest( + new Request(config.relayIssuer, { + headers: { authorization: `Bearer ${token}` }, + }), + { acceptsToken: "oauth_token" }, + ); + const auth = state.toAuth(); + if (!state.isAuthenticated || !auth.userId) { + throw new Error("Clerk OAuth token is not authenticated."); + } + return { sub: auth.userId }; + }, + catch: (cause) => new ClerkTokenVerificationFailed({ cause }), + }); +} + +export function verifyRelayClientBearerToken( + config: RelayConfiguration.RelayConfigurationShape, + token: string, +) { + return verifyClerkBearerToken(config, token).pipe( + Effect.flatMap((verified) => + verified.sub && hasExpectedClerkAudience(verified.aud, config.relayIssuer) + ? Effect.succeed({ sub: verified.sub, mode: "clerk_session_bearer" as const }) + : Effect.fail(new ClerkTokenVerificationFailed({ cause: "missing_relay_audience" })), + ), + Effect.catch(() => + verifyClerkOAuthBearerToken(config, token).pipe( + Effect.map((verified) => ({ ...verified, mode: "clerk_oauth_bearer" as const })), + ), + ), + ); +} + const requireDpopPrincipalScope = Effect.fn("relay.api.require_dpop_principal_scope")(function* ( scope: RelayDpopAccessTokenScope, ) { diff --git a/infra/relay/src/worker.ts b/infra/relay/src/worker.ts index c44bff79d8..f5f07964a6 100644 --- a/infra/relay/src/worker.ts +++ b/infra/relay/src/worker.ts @@ -88,7 +88,7 @@ const ApnsDeliveryJobSigningSecret = Alchemy.makeRandom("ApnsDeliveryJobSigningS export default class Api extends Cloudflare.Worker()( "Api", RelayDeploymentConfig.pipe( - Config.map(({ relayPublicDomain }) => ({ + Effect.map(({ relayPublicDomain }) => ({ main: import.meta.filename, compatibility: { date: "2026-05-22", @@ -102,7 +102,7 @@ export default class Api extends Cloudflare.Worker()( // // 1. Provision Infrastructure for the Worker to use // - const { relayPublicOrigin } = yield* RelayDeploymentConfig; + const { relayPublicOrigin, stage } = yield* RelayDeploymentConfig; const apnsDeliveryQueue = yield* RelayApnsDeliveryQueue; const apnsDeliveryDeadLetterQueue = yield* RelayApnsDeliveryDeadLetterQueue; const cloudMintKeyPair = yield* CloudMintKeyPair; @@ -129,6 +129,7 @@ export default class Api extends Cloudflare.Worker()( const axiomTracesEndpoint = yield* observability.traces.otelTracesEndpoint; const clerkSecretKey = yield* Config.redacted("CLERK_SECRET_KEY"); + const clerkPublishableKey = yield* Config.string("T3CODE_CLERK_PUBLISHABLE_KEY"); const cloudMintPrivateKey = yield* cloudMintKeyPair.privateKey; const cloudMintPublicKey = yield* cloudMintKeyPair.publicKey; @@ -156,9 +157,11 @@ export default class Api extends Cloudflare.Worker()( }, apnsDeliveryJobSigningSecret: yield* apnsDeliveryJobSigningSecret, clerkSecretKey, + clerkPublishableKey, cloudMintPrivateKey: yield* cloudMintPrivateKey, cloudMintPublicKey: yield* cloudMintPublicKey, managedEndpointBaseDomain: yield* managedEndpointZoneName, + managedEndpointNamespace: stage, }); }); diff --git a/infra/relay/src/zone.ts b/infra/relay/src/zone.ts index 12022bb04d..bd48cea535 100644 --- a/infra/relay/src/zone.ts +++ b/infra/relay/src/zone.ts @@ -1,26 +1,31 @@ +import * as Alchemy from "alchemy"; import { adopt } from "alchemy/AdoptPolicy"; import * as Cloudflare from "alchemy/Cloudflare"; import * as Config from "effect/Config"; import * as Effect from "effect/Effect"; +import * as Option from "effect/Option"; -import { DEFAULT_T3_RELAY_DOMAIN, DEFAULT_T3_RELAY_ZONE_NAME } from "@t3tools/shared/relayAuth"; +import { relayPublicDomainForStage } from "./deploymentConfig.ts"; -export const RelayDeploymentConfig = Config.all({ - relayPublicDomain: Config.string("T3_RELAY_DOMAIN").pipe( - Config.withDefault(DEFAULT_T3_RELAY_DOMAIN), - ), - managedEndpointZoneName: Config.string("T3_RELAY_ZONE_NAME").pipe( - Config.withDefault(DEFAULT_T3_RELAY_ZONE_NAME), - ), -}).pipe( - Config.map((config) => ({ - relayPublicDomain: config.relayPublicDomain, - relayPublicOrigin: `https://${config.relayPublicDomain}`, - managedEndpointZoneName: config.managedEndpointZoneName, - })), -); +export const RelayDeploymentConfig = Effect.gen(function* () { + const stage = yield* Alchemy.Stage; + const managedEndpointZoneName = yield* Config.nonEmptyString("T3_RELAY_ZONE_NAME"); + const relayPublicDomainOverride = yield* Config.nonEmptyString("T3_RELAY_DOMAIN").pipe( + Config.option, + ); + const relayPublicDomain = Option.getOrElse(relayPublicDomainOverride, () => + relayPublicDomainForStage(stage, managedEndpointZoneName), + ); + + return { + stage, + relayPublicDomain, + relayPublicOrigin: `https://${relayPublicDomain}`, + managedEndpointZoneName, + }; +}); export const ManagedEndpointZone = RelayDeploymentConfig.pipe( - Config.map(({ managedEndpointZoneName }) => managedEndpointZoneName), + Effect.map(({ managedEndpointZoneName }) => managedEndpointZoneName), Effect.flatMap((name) => Cloudflare.Zone("ManagedEndpointZone", { name }).pipe(adopt(true))), );