feat(cloud): isolate relay resources by stage

Co-authored-by: codex <[email protected]>
This commit is contained in:
Julius Marmingeandcodex committed 2026-06-03 23:48:05 -07:00
1 parent 6c89f75d4e
commit 56d1cbebdb
24 files changed
+658 -128

No files matched your search

+5 -3
View File
@@ -1,7 +1,9 @@
# Relay deployment overrides. The public relay URL is derived as
# https://<T3_RELAY_DOMAIN>.
T3_RELAY_DOMAIN=relay.example.com
# Relay deployment configuration. Production derives relay.<zone>; personal
# stages derive relay-<stage-slug>.<zone>, 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_...
+10 -6
View File
@@ -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.<T3_RELAY_ZONE_NAME>` and `dev_julius` uses `relay-dev-julius.<T3_RELAY_ZONE_NAME>`.
`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`
+1
View File
@@ -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,
+1 -1
View File
@@ -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"
+93
View File
@@ -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",
);
});
});
+156
View File
@@ -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>): 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>): 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<string>;
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<string>,
) {
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<string>,
) {
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<string>,
) {
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<string>) {
yield* runAlchemyDeploy(args);
yield* reconcileRootEnv(args);
});
if (import.meta.main) {
deploy(process.argv.slice(2)).pipe(Effect.provide(NodeServices.layer), NodeRuntime.runMain);
}
+2
View File
@@ -17,10 +17,12 @@ export interface RelayConfigurationShape {
readonly relayIssuer: string;
readonly apns: ApnsCredentials;
readonly clerkSecretKey: Redacted.Redacted<string>;
readonly clerkPublishableKey: string;
readonly apnsDeliveryJobSigningSecret: Redacted.Redacted<string>;
readonly cloudMintPrivateKey: Redacted.Redacted<string>;
readonly cloudMintPublicKey: string;
readonly managedEndpointBaseDomain: string | undefined;
readonly managedEndpointNamespace: string | undefined;
}
export class RelayConfiguration extends Context.Service<
@@ -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", {
@@ -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: {
+2
View File
@@ -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(
+28 -8
View File
@@ -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<RelayDb, RelayDatabase>()("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* () {
+11
View File
@@ -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");
});
});
+5
View File
@@ -0,0 +1,5 @@
export type RelayDatabaseMode = "shared-database" | "stage-branch";
export function relayDatabaseMode(stage: string): RelayDatabaseMode {
return stage === "prod" ? "shared-database" : "stage-branch";
}
+52
View File
@@ -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$/);
});
});
+59
View File
@@ -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)}`;
}
@@ -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 {
@@ -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 {
@@ -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"],
@@ -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[] = [];
@@ -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),
+79
View File
@@ -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({
+49 -7
View File
@@ -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,
) {
+5 -2
View File
@@ -88,7 +88,7 @@ const ApnsDeliveryJobSigningSecret = Alchemy.makeRandom("ApnsDeliveryJobSigningS
export default class Api extends Cloudflare.Worker<Api>()(
"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<Api>()(
//
// 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<Api>()(
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<Api>()(
},
apnsDeliveryJobSigningSecret: yield* apnsDeliveryJobSigningSecret,
clerkSecretKey,
clerkPublishableKey,
cloudMintPrivateKey: yield* cloudMintPrivateKey,
cloudMintPublicKey: yield* cloudMintPublicKey,
managedEndpointBaseDomain: yield* managedEndpointZoneName,
managedEndpointNamespace: stage,
});
});
+21 -16
View File
@@ -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))),
);