feat(cloud): manage cloudflared installation and relay defaults
Co-authored-by: codex <[email protected]>
This commit is contained in:
1 parent
2b5213d920
commit
eadcf71a49
38 files changed
+1557
-74
No files matched your search
@@ -0,0 +1,5 @@
|
||||
# Optional root-level overrides for the checked-in public client configuration.
|
||||
# Server-side secrets must never be committed here.
|
||||
#
|
||||
# T3CODE_CLERK_PUBLISHABLE_KEY=pk_test_...
|
||||
# T3_RELAY_URL=https://relay.example.com
|
||||
@@ -26,6 +26,10 @@ permissions:
|
||||
contents: read
|
||||
id-token: none
|
||||
|
||||
env:
|
||||
T3CODE_CLERK_PUBLISHABLE_KEY: ${{ vars.T3CODE_CLERK_PUBLISHABLE_KEY }}
|
||||
T3_RELAY_URL: ${{ vars.T3_RELAY_URL }}
|
||||
|
||||
jobs:
|
||||
check_changes:
|
||||
name: Check for changes since last nightly
|
||||
@@ -648,6 +652,8 @@ jobs:
|
||||
--token "$VERCEL_TOKEN" \
|
||||
"${vercel_scope_args[@]}" \
|
||||
--build-env "APP_VERSION=${{ needs.preflight.outputs.version }}" \
|
||||
--build-env "T3CODE_CLERK_PUBLISHABLE_KEY=${T3CODE_CLERK_PUBLISHABLE_KEY:-}" \
|
||||
--build-env "T3_RELAY_URL=${T3_RELAY_URL:-}" \
|
||||
--build-env "VITE_HOSTED_APP_URL=$router_url" \
|
||||
--build-env "VITE_HOSTED_APP_CHANNEL=$channel_name"
|
||||
)"
|
||||
|
||||
@@ -62,6 +62,11 @@ mise install
|
||||
vp install
|
||||
```
|
||||
|
||||
T3 Cloud public client configuration has checked-in development defaults, so a fresh clone works
|
||||
without creating app-local `.env` files. To point web, desktop, and mobile at another Clerk/relay
|
||||
deployment, copy [`.env.example`](./.env.example) to `.env` at the repository root and set the
|
||||
canonical overrides there.
|
||||
|
||||
Read [CONTRIBUTING.md](./CONTRIBUTING.md) before opening an issue or PR.
|
||||
|
||||
Need support? Join the [Discord](https://discord.gg/jn4EGJjrvv).
|
||||
@@ -9,6 +9,7 @@ import {
|
||||
setCloudAuthToken,
|
||||
} from "./methods/cloudAuth.ts";
|
||||
import { getClientSettings, setClientSettings } from "./methods/clientSettings.ts";
|
||||
import { getCloudflaredStatus, installCloudflared } from "./methods/cloudflared.ts";
|
||||
import {
|
||||
getSavedEnvironmentRegistry,
|
||||
getSavedEnvironmentSecret,
|
||||
@@ -87,6 +88,8 @@ export const installDesktopIpcHandlers = Effect.gen(function* () {
|
||||
yield* ipc.handle(setCloudAuthToken);
|
||||
yield* ipc.handle(clearCloudAuthToken);
|
||||
yield* ipc.handle(fetchCloudAuth);
|
||||
yield* ipc.handle(getCloudflaredStatus);
|
||||
yield* ipc.handle(installCloudflared);
|
||||
|
||||
yield* ipc.handle(getUpdateState);
|
||||
yield* ipc.handle(setUpdateChannel);
|
||||
|
||||
@@ -8,6 +8,8 @@ export const GET_CLOUD_AUTH_TOKEN_CHANNEL = "desktop:get-cloud-auth-token";
|
||||
export const SET_CLOUD_AUTH_TOKEN_CHANNEL = "desktop:set-cloud-auth-token";
|
||||
export const CLEAR_CLOUD_AUTH_TOKEN_CHANNEL = "desktop:clear-cloud-auth-token";
|
||||
export const FETCH_CLOUD_AUTH_CHANNEL = "desktop:fetch-cloud-auth";
|
||||
export const GET_CLOUDFLARED_STATUS_CHANNEL = "desktop:get-cloudflared-status";
|
||||
export const INSTALL_CLOUDFLARED_CHANNEL = "desktop:install-cloudflared";
|
||||
export const CLOUD_AUTH_CALLBACK_CHANNEL = "desktop:cloud-auth-callback";
|
||||
export const MENU_ACTION_CHANNEL = "desktop:menu-action";
|
||||
export const UPDATE_STATE_CHANNEL = "desktop:update-state";
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/unstable/http";
|
||||
|
||||
import { fetchCloudAuth } from "./cloudAuth.ts";
|
||||
|
||||
function makeHttpClientLayer(
|
||||
handler: (
|
||||
request: HttpClientRequest.HttpClientRequest,
|
||||
) => Effect.Effect<HttpClientResponse.HttpClientResponse, never>,
|
||||
) {
|
||||
return Layer.succeed(
|
||||
HttpClient.HttpClient,
|
||||
HttpClient.make((request) => handler(request)),
|
||||
);
|
||||
}
|
||||
|
||||
describe("Desktop cloud auth IPC", () => {
|
||||
it.effect("preserves Clerk's URL-encoded OAuth form content type", () => {
|
||||
const body = "strategy=oauth_google&redirect_url=t3code%3A%2F%2Fauth%2Fcallback";
|
||||
let forwardedRequest: HttpClientRequest.HttpClientRequest | null = null;
|
||||
const layer = makeHttpClientLayer((request) =>
|
||||
Effect.sync(() => {
|
||||
forwardedRequest = request;
|
||||
return HttpClientResponse.fromWeb(
|
||||
request,
|
||||
Response.json({ response: { object: "sign_in_attempt" } }),
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
return Effect.gen(function* () {
|
||||
yield* fetchCloudAuth.handler({
|
||||
url: "https://example.clerk.accounts.dev/v1/client/sign_ins",
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/x-www-form-urlencoded;charset=UTF-8",
|
||||
"x-mobile": "1",
|
||||
},
|
||||
body,
|
||||
});
|
||||
|
||||
assert(forwardedRequest !== null);
|
||||
assert.equal(
|
||||
forwardedRequest.headers["content-type"],
|
||||
"application/x-www-form-urlencoded;charset=UTF-8",
|
||||
);
|
||||
assert.equal(forwardedRequest.body._tag, "Uint8Array");
|
||||
if (forwardedRequest.body._tag === "Uint8Array") {
|
||||
assert.equal(new TextDecoder().decode(forwardedRequest.body.body), body);
|
||||
}
|
||||
}).pipe(Effect.provide(layer));
|
||||
});
|
||||
});
|
||||
@@ -6,7 +6,7 @@ import * as Data from "effect/Data";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Schema from "effect/Schema";
|
||||
import { HttpClient, HttpClientRequest } from "effect/unstable/http";
|
||||
import { Headers, HttpClient, HttpClientRequest } from "effect/unstable/http";
|
||||
|
||||
import * as DesktopCloudAuth from "../../app/DesktopCloudAuth.ts";
|
||||
import * as DesktopCloudAuthTokenStore from "../../app/DesktopCloudAuthTokenStore.ts";
|
||||
@@ -91,11 +91,20 @@ export const fetchCloudAuth = makeIpcMethod({
|
||||
}),
|
||||
});
|
||||
|
||||
const request = HttpClientRequest.make((input.method ?? "GET") as "GET" | "POST")(url, {
|
||||
headers: input.headers,
|
||||
}).pipe(
|
||||
input.body === undefined ? (request) => request : HttpClientRequest.bodyText(input.body),
|
||||
const requestWithoutBody = HttpClientRequest.make((input.method ?? "GET") as "GET" | "POST")(
|
||||
url,
|
||||
{
|
||||
headers: input.headers,
|
||||
},
|
||||
);
|
||||
const request =
|
||||
input.body === undefined
|
||||
? requestWithoutBody
|
||||
: HttpClientRequest.bodyText(
|
||||
requestWithoutBody,
|
||||
input.body,
|
||||
Option.getOrUndefined(Headers.get(requestWithoutBody.headers, "content-type")),
|
||||
);
|
||||
|
||||
const response = yield* HttpClient.execute(request).pipe(
|
||||
Effect.mapError(
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
import { describe, expect, it } from "@effect/vitest";
|
||||
import * as Cloudflared from "@t3tools/shared/cloudflared";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
|
||||
import { getCloudflaredStatus, installCloudflared } from "./cloudflared.ts";
|
||||
|
||||
const available = {
|
||||
status: "available",
|
||||
executablePath: "/Users/test/.t3/tools/cloudflared/cloudflared",
|
||||
source: "managed",
|
||||
version: Cloudflared.CLOUDFLARED_VERSION,
|
||||
} as const;
|
||||
|
||||
describe("Desktop cloudflared IPC", () => {
|
||||
it.effect("reads status and delegates installation to the shared manager", () =>
|
||||
Effect.gen(function* () {
|
||||
const installed: Array<boolean> = [];
|
||||
const layer = Layer.succeed(
|
||||
Cloudflared.CloudflaredExecutable,
|
||||
Cloudflared.CloudflaredExecutable.of({
|
||||
resolve: Effect.succeed({
|
||||
status: "missing",
|
||||
version: Cloudflared.CLOUDFLARED_VERSION,
|
||||
}),
|
||||
install: Effect.sync(() => {
|
||||
installed.push(true);
|
||||
return available;
|
||||
}),
|
||||
}),
|
||||
);
|
||||
|
||||
expect(yield* getCloudflaredStatus.handler(undefined).pipe(Effect.provide(layer))).toEqual({
|
||||
status: "missing",
|
||||
version: Cloudflared.CLOUDFLARED_VERSION,
|
||||
});
|
||||
expect(yield* installCloudflared.handler(undefined).pipe(Effect.provide(layer))).toEqual(
|
||||
available,
|
||||
);
|
||||
expect(installed).toEqual([true]);
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,27 @@
|
||||
import { DesktopCloudflaredStatusSchema } from "@t3tools/contracts";
|
||||
import * as Cloudflared from "@t3tools/shared/cloudflared";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
import * as IpcChannels from "../channels.ts";
|
||||
import { makeIpcMethod } from "../DesktopIpc.ts";
|
||||
|
||||
export const getCloudflaredStatus = makeIpcMethod({
|
||||
channel: IpcChannels.GET_CLOUDFLARED_STATUS_CHANNEL,
|
||||
payload: Schema.Undefined,
|
||||
result: DesktopCloudflaredStatusSchema,
|
||||
handler: Effect.fn("desktop.ipc.cloudflared.getStatus")(function* () {
|
||||
const cloudflared = yield* Cloudflared.CloudflaredExecutable;
|
||||
return yield* cloudflared.resolve;
|
||||
}),
|
||||
});
|
||||
|
||||
export const installCloudflared = makeIpcMethod({
|
||||
channel: IpcChannels.INSTALL_CLOUDFLARED_CHANNEL,
|
||||
payload: Schema.Undefined,
|
||||
result: DesktopCloudflaredStatusSchema,
|
||||
handler: Effect.fn("desktop.ipc.cloudflared.install")(function* () {
|
||||
const cloudflared = yield* Cloudflared.CloudflaredExecutable;
|
||||
return yield* cloudflared.install;
|
||||
}),
|
||||
});
|
||||
@@ -9,6 +9,7 @@ import * as Option from "effect/Option";
|
||||
import * as Electron from "electron";
|
||||
|
||||
import * as NetService from "@t3tools/shared/Net";
|
||||
import * as Cloudflared from "@t3tools/shared/cloudflared";
|
||||
import { resolveRemoteT3CliPackageSpec } from "@t3tools/ssh/command";
|
||||
import type { RemoteT3RunnerOptions } from "@t3tools/ssh/tunnel";
|
||||
import serverPackageJson from "../../server/package.json" with { type: "json" };
|
||||
@@ -94,6 +95,17 @@ const desktopSshEnvironmentLayer = Layer.unwrap(
|
||||
}),
|
||||
);
|
||||
|
||||
const desktopCloudflaredLayer = Layer.unwrap(
|
||||
Effect.gen(function* () {
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
return Cloudflared.layer({
|
||||
baseDir: environment.baseDir,
|
||||
platform: environment.platform,
|
||||
arch: environment.processArch,
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
const electronLayer = Layer.mergeAll(
|
||||
ElectronApp.layer,
|
||||
ElectronDialog.layer,
|
||||
@@ -141,7 +153,11 @@ const desktopApplicationLayer = Layer.mergeAll(
|
||||
DesktopCloudAuth.layer,
|
||||
DesktopShellEnvironment.layer,
|
||||
desktopSshLayer,
|
||||
).pipe(Layer.provideMerge(DesktopUpdates.layer), Layer.provideMerge(desktopBackendLayer));
|
||||
).pipe(
|
||||
Layer.provideMerge(DesktopUpdates.layer),
|
||||
Layer.provideMerge(desktopCloudflaredLayer),
|
||||
Layer.provideMerge(desktopBackendLayer),
|
||||
);
|
||||
|
||||
const desktopRuntimeLayer = ElectronProtocol.layerSchemePrivileges.pipe(
|
||||
Layer.flatMap(() =>
|
||||
|
||||
@@ -102,6 +102,8 @@ contextBridge.exposeInMainWorld("desktopBridge", {
|
||||
ipcRenderer.invoke(IpcChannels.SET_CLOUD_AUTH_TOKEN_CHANNEL, token),
|
||||
clearCloudAuthToken: () => ipcRenderer.invoke(IpcChannels.CLEAR_CLOUD_AUTH_TOKEN_CHANNEL),
|
||||
fetchCloudAuth: (input) => ipcRenderer.invoke(IpcChannels.FETCH_CLOUD_AUTH_CHANNEL, input),
|
||||
getCloudflaredStatus: () => ipcRenderer.invoke(IpcChannels.GET_CLOUDFLARED_STATUS_CHANNEL),
|
||||
installCloudflared: () => ipcRenderer.invoke(IpcChannels.INSTALL_CLOUDFLARED_CHANNEL),
|
||||
onCloudAuthCallback: (listener) => {
|
||||
const wrappedListener = (_event: Electron.IpcRendererEvent, rawUrl: unknown) => {
|
||||
if (typeof rawUrl !== "string") return;
|
||||
|
||||
@@ -16,6 +16,10 @@ This app has three variants:
|
||||
|
||||
Run commands from `apps/mobile`.
|
||||
|
||||
Public T3 Cloud development defaults are shared with web and desktop. Optional overrides belong in
|
||||
the repository-root `.env` or `.env.local`, not an `apps/mobile/.env` file. See
|
||||
[`../../.env.example`](../../.env.example).
|
||||
|
||||
## Development
|
||||
|
||||
Start Metro for the dev client:
|
||||
@@ -63,6 +67,9 @@ 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 `T3_RELAY_URL`
|
||||
as EAS environment variables. Expo config maps the canonical values into the mobile build.
|
||||
|
||||
Create a PR preview dev-client build manually:
|
||||
|
||||
```bash
|
||||
|
||||
@@ -1,8 +1,13 @@
|
||||
import type { ExpoConfig } from "expo/config";
|
||||
|
||||
import { loadRepoEnv } from "../../scripts/lib/public-config";
|
||||
|
||||
type AppVariant = "development" | "preview" | "production";
|
||||
|
||||
const APP_VARIANT = resolveAppVariant(process.env.APP_VARIANT);
|
||||
const repoEnv = loadRepoEnv();
|
||||
Object.assign(process.env, repoEnv);
|
||||
|
||||
const APP_VARIANT = resolveAppVariant(repoEnv.APP_VARIANT);
|
||||
|
||||
const VARIANT_CONFIG: Record<
|
||||
AppVariant,
|
||||
@@ -150,10 +155,10 @@ const config: ExpoConfig = {
|
||||
extra: {
|
||||
appVariant: APP_VARIANT,
|
||||
relay: {
|
||||
url: process.env.T3_RELAY_URL ?? null,
|
||||
url: repoEnv.T3_RELAY_URL ?? null,
|
||||
},
|
||||
clerk: {
|
||||
publishableKey: process.env.EXPO_PUBLIC_CLERK_PUBLISHABLE_KEY ?? null,
|
||||
publishableKey: repoEnv.EXPO_PUBLIC_CLERK_PUBLISHABLE_KEY ?? null,
|
||||
},
|
||||
eas: {
|
||||
projectId: "d763fcb8-d37c-41ea-a773-b54a0ab4a454",
|
||||
|
||||
@@ -57,7 +57,7 @@ export default function SettingsWaitlistRouteScreen() {
|
||||
textAlign: "center",
|
||||
}}
|
||||
>
|
||||
Add EXPO_PUBLIC_CLERK_PUBLISHABLE_KEY to this build to enable waitlist enrollment.
|
||||
Add T3CODE_CLERK_PUBLISHABLE_KEY to this build to enable waitlist enrollment.
|
||||
</Text>
|
||||
</View>
|
||||
)}
|
||||
|
||||
@@ -1,14 +1,36 @@
|
||||
import { describe, expect, it } from "@effect/vitest";
|
||||
import { vi } from "vitest";
|
||||
import * as Deferred from "effect/Deferred";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Fiber from "effect/Fiber";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as PlatformError from "effect/PlatformError";
|
||||
import * as Sink from "effect/Sink";
|
||||
import * as Stream from "effect/Stream";
|
||||
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||
import * as Cloudflared from "@t3tools/shared/cloudflared";
|
||||
|
||||
import { makeCloudManagedEndpointRuntime } from "./ManagedEndpointRuntime.ts";
|
||||
|
||||
const cloudflaredAvailableLayer = Layer.succeed(
|
||||
Cloudflared.CloudflaredExecutable,
|
||||
Cloudflared.CloudflaredExecutable.of({
|
||||
resolve: Effect.succeed({
|
||||
status: "available",
|
||||
executablePath: "cloudflared",
|
||||
source: "path",
|
||||
version: Cloudflared.CLOUDFLARED_VERSION,
|
||||
}),
|
||||
install: Effect.die("unused"),
|
||||
}),
|
||||
);
|
||||
|
||||
const runtimeDependencies = (spawner: ReturnType<typeof ChildProcessSpawner.make>) =>
|
||||
Layer.mergeAll(
|
||||
Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner),
|
||||
cloudflaredAvailableLayer,
|
||||
);
|
||||
|
||||
function makeHandle(input: {
|
||||
readonly pid: number;
|
||||
readonly onKill: () => void;
|
||||
@@ -58,7 +80,7 @@ describe("CloudManagedEndpointRuntime", () => {
|
||||
}),
|
||||
);
|
||||
const runtime = yield* makeCloudManagedEndpointRuntime.pipe(
|
||||
Effect.provide(Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner)),
|
||||
Effect.provide(runtimeDependencies(spawner)),
|
||||
);
|
||||
|
||||
yield* runtime.applyConfig({
|
||||
@@ -88,6 +110,7 @@ describe("CloudManagedEndpointRuntime", () => {
|
||||
]);
|
||||
expect(spawned.map((command) => command.options.stdout)).toEqual(["ignore", "ignore"]);
|
||||
expect(spawned.map((command) => command.options.stderr)).toEqual(["ignore", "ignore"]);
|
||||
expect(spawned.map((command) => command.options.detached)).toEqual([false, false]);
|
||||
expect(killed).toEqual([100, 101]);
|
||||
expect(stopped).toEqual({ status: "disabled" });
|
||||
}),
|
||||
@@ -109,7 +132,7 @@ describe("CloudManagedEndpointRuntime", () => {
|
||||
}),
|
||||
);
|
||||
const runtime = yield* makeCloudManagedEndpointRuntime.pipe(
|
||||
Effect.provide(Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner)),
|
||||
Effect.provide(runtimeDependencies(spawner)),
|
||||
);
|
||||
|
||||
const started = yield* runtime.applyConfig({
|
||||
@@ -148,7 +171,7 @@ describe("CloudManagedEndpointRuntime", () => {
|
||||
}),
|
||||
);
|
||||
const runtime = yield* makeCloudManagedEndpointRuntime.pipe(
|
||||
Effect.provide(Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner)),
|
||||
Effect.provide(runtimeDependencies(spawner)),
|
||||
);
|
||||
const config = {
|
||||
providerKind: "cloudflare_tunnel" as const,
|
||||
@@ -195,7 +218,7 @@ describe("CloudManagedEndpointRuntime", () => {
|
||||
}),
|
||||
);
|
||||
const runtime = yield* makeCloudManagedEndpointRuntime.pipe(
|
||||
Effect.provide(Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner)),
|
||||
Effect.provide(runtimeDependencies(spawner)),
|
||||
);
|
||||
|
||||
const started = yield* runtime.applyConfig({
|
||||
@@ -208,7 +231,59 @@ describe("CloudManagedEndpointRuntime", () => {
|
||||
|
||||
expect(started).toMatchObject({ status: "running", pid: 400 });
|
||||
expect(spawned).toEqual([400, 401]);
|
||||
expect(killed).toEqual([]);
|
||||
expect(killed).toEqual([400]);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("serializes concurrent connector config changes", () =>
|
||||
Effect.gen(function* () {
|
||||
const spawned: Array<number> = [];
|
||||
const killed: Array<number> = [];
|
||||
const firstSpawnEntered = yield* Deferred.make<void>();
|
||||
const releaseFirstSpawn = yield* Deferred.make<void>();
|
||||
const spawner = ChildProcessSpawner.make(() =>
|
||||
Effect.gen(function* () {
|
||||
const pid = 500 + spawned.length;
|
||||
spawned.push(pid);
|
||||
if (pid === 500) {
|
||||
yield* Deferred.succeed(firstSpawnEntered, undefined);
|
||||
yield* Deferred.await(releaseFirstSpawn);
|
||||
}
|
||||
const handle = makeHandle({
|
||||
pid,
|
||||
onKill: () => {
|
||||
killed.push(pid);
|
||||
},
|
||||
});
|
||||
yield* Effect.addFinalizer(() => handle.kill().pipe(Effect.ignore));
|
||||
return handle;
|
||||
}),
|
||||
);
|
||||
const runtime = yield* makeCloudManagedEndpointRuntime.pipe(
|
||||
Effect.provide(runtimeDependencies(spawner)),
|
||||
);
|
||||
|
||||
const first = yield* runtime
|
||||
.applyConfig({
|
||||
providerKind: "cloudflare_tunnel",
|
||||
connectorToken: "token-1",
|
||||
})
|
||||
.pipe(Effect.forkChild);
|
||||
yield* Deferred.await(firstSpawnEntered);
|
||||
const second = yield* runtime
|
||||
.applyConfig({
|
||||
providerKind: "cloudflare_tunnel",
|
||||
connectorToken: "token-2",
|
||||
})
|
||||
.pipe(Effect.forkChild);
|
||||
yield* Deferred.succeed(releaseFirstSpawn, undefined);
|
||||
|
||||
yield* Fiber.join(first);
|
||||
const status = yield* Fiber.join(second);
|
||||
|
||||
expect(status).toMatchObject({ status: "running", pid: 501 });
|
||||
expect(spawned).toEqual([500, 501]);
|
||||
expect(killed).toEqual([500]);
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -225,7 +300,7 @@ describe("CloudManagedEndpointRuntime", () => {
|
||||
),
|
||||
);
|
||||
const runtime = yield* makeCloudManagedEndpointRuntime.pipe(
|
||||
Effect.provide(Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner)),
|
||||
Effect.provide(runtimeDependencies(spawner)),
|
||||
);
|
||||
|
||||
const status = yield* runtime.applyConfig({
|
||||
@@ -241,4 +316,40 @@ describe("CloudManagedEndpointRuntime", () => {
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("reports a missing cloudflared executable without spawning", () =>
|
||||
Effect.gen(function* () {
|
||||
const spawn = vi.fn();
|
||||
const spawner = ChildProcessSpawner.make(spawn);
|
||||
const runtime = yield* makeCloudManagedEndpointRuntime.pipe(
|
||||
Effect.provide(
|
||||
Layer.mergeAll(
|
||||
Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner),
|
||||
Layer.succeed(
|
||||
Cloudflared.CloudflaredExecutable,
|
||||
Cloudflared.CloudflaredExecutable.of({
|
||||
resolve: Effect.succeed({
|
||||
status: "missing",
|
||||
version: Cloudflared.CLOUDFLARED_VERSION,
|
||||
}),
|
||||
install: Effect.die("unused"),
|
||||
}),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const status = yield* runtime.applyConfig({
|
||||
providerKind: "cloudflare_tunnel",
|
||||
connectorToken: "token",
|
||||
});
|
||||
|
||||
expect(status).toEqual({
|
||||
status: "failed",
|
||||
providerKind: "cloudflare_tunnel",
|
||||
reason: "cloudflared is not installed.",
|
||||
});
|
||||
expect(spawn).not.toHaveBeenCalled();
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -1,10 +1,13 @@
|
||||
import type { RelayManagedEndpointRuntimeConfig } from "@t3tools/contracts/relay";
|
||||
import * as Cloudflared from "@t3tools/shared/cloudflared";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Exit from "effect/Exit";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as Result from "effect/Result";
|
||||
import * as Semaphore from "effect/Semaphore";
|
||||
import * as Scope from "effect/Scope";
|
||||
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
@@ -88,8 +91,11 @@ const stopConnector = (connector: ActiveConnector | null) =>
|
||||
|
||||
export const makeCloudManagedEndpointRuntime = Effect.gen(function* () {
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const cloudflared = yield* Cloudflared.CloudflaredExecutable;
|
||||
const activeRef = yield* Ref.make<ActiveConnector | null>(null);
|
||||
let applyConfig: CloudManagedEndpointRuntimeShape["applyConfig"];
|
||||
const desiredConfigRef = yield* Ref.make<RelayManagedEndpointRuntimeConfig | null>(null);
|
||||
const reconcileSemaphore = yield* Semaphore.make(1);
|
||||
let reconcileConfig: CloudManagedEndpointRuntimeShape["applyConfig"];
|
||||
|
||||
const stopActive = Effect.gen(function* () {
|
||||
const active = yield* Ref.getAndSet(activeRef, null);
|
||||
@@ -98,26 +104,46 @@ export const makeCloudManagedEndpointRuntime = Effect.gen(function* () {
|
||||
|
||||
const superviseConnector = (connector: ActiveConnector) =>
|
||||
Effect.gen(function* () {
|
||||
const exitCode = yield* connector.child.exitCode;
|
||||
const active = yield* Ref.get(activeRef);
|
||||
if (active?.child.pid !== connector.child.pid || active.configKey !== connector.configKey) {
|
||||
return;
|
||||
}
|
||||
yield* Ref.set(activeRef, null);
|
||||
yield* Effect.logWarning("Cloudflare managed endpoint connector exited; restarting", {
|
||||
pid: Number(connector.child.pid),
|
||||
exitCode: Number(exitCode),
|
||||
tunnelId: connector.config.tunnelId,
|
||||
tunnelName: connector.config.tunnelName,
|
||||
});
|
||||
yield* applyConfig(connector.config);
|
||||
const result = yield* Effect.result(connector.child.exitCode);
|
||||
yield* reconcileSemaphore.withPermits(1)(
|
||||
Effect.gen(function* () {
|
||||
const active = yield* Ref.get(activeRef);
|
||||
if (
|
||||
active?.child.pid !== connector.child.pid ||
|
||||
active.configKey !== connector.configKey
|
||||
) {
|
||||
return;
|
||||
}
|
||||
yield* Ref.set(activeRef, null);
|
||||
yield* stopConnector(connector);
|
||||
|
||||
const desiredConfig = yield* Ref.get(desiredConfigRef);
|
||||
if (
|
||||
!desiredConfig ||
|
||||
desiredConfig.providerKind !== "cloudflare_tunnel" ||
|
||||
runtimeConfigKey(desiredConfig) !== connector.configKey
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
yield* Effect.logWarning("Cloudflare managed endpoint connector exited; restarting", {
|
||||
pid: Number(connector.child.pid),
|
||||
...(Result.isSuccess(result)
|
||||
? { exitCode: Number(result.success) }
|
||||
: { cause: result.failure }),
|
||||
tunnelId: connector.config.tunnelId,
|
||||
tunnelName: connector.config.tunnelName,
|
||||
});
|
||||
yield* reconcileConfig(desiredConfig);
|
||||
}),
|
||||
);
|
||||
}).pipe(
|
||||
Effect.catch((cause) =>
|
||||
Effect.catchCause((cause) =>
|
||||
Effect.logWarning("Cloudflare managed endpoint connector supervisor failed", { cause }),
|
||||
),
|
||||
);
|
||||
|
||||
applyConfig = Effect.fn("CloudManagedEndpointRuntime.applyConfig")(function* (config) {
|
||||
reconcileConfig = Effect.fn("CloudManagedEndpointRuntime.reconcileConfig")(function* (config) {
|
||||
if (!config || config.providerKind !== "cloudflare_tunnel") {
|
||||
yield* stopActive;
|
||||
return config
|
||||
@@ -144,14 +170,33 @@ export const makeCloudManagedEndpointRuntime = Effect.gen(function* () {
|
||||
|
||||
yield* stopActive;
|
||||
|
||||
const executable = yield* cloudflared.resolve;
|
||||
if (executable.status !== "available") {
|
||||
return {
|
||||
status: "failed",
|
||||
providerKind: "cloudflare_tunnel",
|
||||
reason:
|
||||
executable.status === "unsupported"
|
||||
? `Managed cloudflared is unsupported on ${executable.platform}-${executable.arch}.`
|
||||
: "cloudflared is not installed.",
|
||||
...(config.tunnelId ? { tunnelId: config.tunnelId } : {}),
|
||||
...(config.tunnelName ? { tunnelName: config.tunnelName } : {}),
|
||||
} satisfies CloudManagedEndpointRuntimeStatus;
|
||||
}
|
||||
|
||||
const connectorScope = yield* Scope.make("sequential");
|
||||
const child = yield* spawner
|
||||
.spawn(
|
||||
ChildProcess.make("cloudflared", ["tunnel", "run", "--token", config.connectorToken], {
|
||||
shell: process.platform === "win32",
|
||||
stderr: "ignore",
|
||||
stdout: "ignore",
|
||||
}),
|
||||
ChildProcess.make(
|
||||
executable.executablePath,
|
||||
["tunnel", "run", "--token", config.connectorToken],
|
||||
{
|
||||
detached: false,
|
||||
shell: process.platform === "win32",
|
||||
stderr: "ignore",
|
||||
stdout: "ignore",
|
||||
},
|
||||
),
|
||||
)
|
||||
.pipe(
|
||||
Effect.provideService(Scope.Scope, connectorScope),
|
||||
@@ -210,6 +255,13 @@ export const makeCloudManagedEndpointRuntime = Effect.gen(function* () {
|
||||
} satisfies CloudManagedEndpointRuntimeStatus;
|
||||
});
|
||||
|
||||
const applyConfig = Effect.fn("CloudManagedEndpointRuntime.applyConfig")(
|
||||
(config: RelayManagedEndpointRuntimeConfig | null) =>
|
||||
reconcileSemaphore.withPermits(1)(
|
||||
Ref.set(desiredConfigRef, config).pipe(Effect.andThen(reconcileConfig(config))),
|
||||
),
|
||||
);
|
||||
|
||||
return CloudManagedEndpointRuntime.of({
|
||||
applyConfig,
|
||||
});
|
||||
|
||||
@@ -81,6 +81,7 @@ import {
|
||||
} from "./serverRuntimeState.ts";
|
||||
import { orchestrationHttpApiLayer } from "./orchestration/http.ts";
|
||||
import * as NetService from "@t3tools/shared/Net";
|
||||
import * as Cloudflared from "@t3tools/shared/cloudflared";
|
||||
import { disableTailscaleServe, ensureTailscaleServe } from "@t3tools/tailscale";
|
||||
|
||||
const PtyAdapterLive = Layer.unwrap(
|
||||
@@ -95,6 +96,13 @@ const PtyAdapterLive = Layer.unwrap(
|
||||
}),
|
||||
);
|
||||
|
||||
const CloudflaredExecutableLive = Layer.unwrap(
|
||||
Effect.gen(function* () {
|
||||
const config = yield* ServerConfig;
|
||||
return Cloudflared.layer({ baseDir: config.baseDir });
|
||||
}),
|
||||
);
|
||||
|
||||
const HttpServerLive = Layer.unwrap(
|
||||
Effect.gen(function* () {
|
||||
const config = yield* ServerConfig;
|
||||
@@ -277,7 +285,10 @@ const RuntimeCoreDependenciesLive = ReactorLayerLive.pipe(
|
||||
Layer.provideMerge(AuthLayerLive),
|
||||
Layer.provideMerge(ServerSecretStore.layer),
|
||||
Layer.provideMerge(
|
||||
CloudManagedEndpointRuntime.layer.pipe(Layer.provide(ServerSecretStore.layer)),
|
||||
CloudManagedEndpointRuntime.layer.pipe(
|
||||
Layer.provide(ServerSecretStore.layer),
|
||||
Layer.provide(CloudflaredExecutableLive),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { EnvironmentId } from "@t3tools/contracts";
|
||||
import { RelayWebClientId } from "@t3tools/contracts/relay";
|
||||
import { beforeEach, vi } from "vitest";
|
||||
import { afterEach, beforeEach, vi } from "vitest";
|
||||
import type { DesktopBridge } from "@t3tools/contracts";
|
||||
import { describe, expect, it } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
@@ -15,6 +16,7 @@ import {
|
||||
import type { SavedEnvironmentRecord } from "../environments/runtime";
|
||||
import {
|
||||
connectManagedCloudEnvironment,
|
||||
ensureDesktopCloudflaredAvailable,
|
||||
linkEnvironmentToCloud,
|
||||
linkPrimaryEnvironmentToCloud,
|
||||
listManagedCloudEnvironments,
|
||||
@@ -96,6 +98,13 @@ function requestBodyText(body: BodyInit | null | undefined): string {
|
||||
}
|
||||
|
||||
describe("web cloud link environment client", () => {
|
||||
afterEach(() => {
|
||||
if ("window" in globalThis) {
|
||||
Reflect.deleteProperty(window, "desktopBridge");
|
||||
}
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
createProofMock.mockClear();
|
||||
@@ -115,6 +124,48 @@ describe("web cloud link environment client", () => {
|
||||
expect(normalizeRelayBaseUrl(" ")).toBeNull();
|
||||
});
|
||||
|
||||
it("installs cloudflared after desktop confirmation", async () => {
|
||||
vi.stubGlobal("window", {});
|
||||
const confirm = vi.fn().mockResolvedValue(true);
|
||||
const installCloudflared = vi.fn().mockResolvedValue({
|
||||
status: "available",
|
||||
executablePath: "/Users/test/.t3/tools/cloudflared/cloudflared",
|
||||
source: "managed",
|
||||
version: "2026.5.2",
|
||||
});
|
||||
window.desktopBridge = {
|
||||
confirm,
|
||||
getCloudflaredStatus: vi.fn().mockResolvedValue({
|
||||
status: "missing",
|
||||
version: "2026.5.2",
|
||||
}),
|
||||
installCloudflared,
|
||||
} as unknown as DesktopBridge;
|
||||
|
||||
await Effect.runPromise(ensureDesktopCloudflaredAvailable());
|
||||
|
||||
expect(confirm).toHaveBeenCalledOnce();
|
||||
expect(installCloudflared).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it("does not install cloudflared when desktop confirmation is declined", async () => {
|
||||
vi.stubGlobal("window", {});
|
||||
const installCloudflared = vi.fn();
|
||||
window.desktopBridge = {
|
||||
confirm: vi.fn().mockResolvedValue(false),
|
||||
getCloudflaredStatus: vi.fn().mockResolvedValue({
|
||||
status: "missing",
|
||||
version: "2026.5.2",
|
||||
}),
|
||||
installCloudflared,
|
||||
} as unknown as DesktopBridge;
|
||||
|
||||
await expect(Effect.runPromise(ensureDesktopCloudflaredAvailable())).rejects.toMatchObject({
|
||||
message: "Cloudflare Tunnel installation was cancelled.",
|
||||
});
|
||||
expect(installCloudflared).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it.effect("lists relay-managed environments for hosted and served web clients", () =>
|
||||
Effect.gen(function* () {
|
||||
const fetchMock = vi.fn().mockResolvedValueOnce(
|
||||
|
||||
@@ -55,6 +55,59 @@ export class CloudEnvironmentLinkError extends Data.TaggedError("CloudEnvironmen
|
||||
readonly cause?: unknown;
|
||||
}> {}
|
||||
|
||||
const desktopCloudflaredBridgeError = (cause: unknown) =>
|
||||
new CloudEnvironmentLinkError({
|
||||
message: "Could not prepare Cloudflare Tunnel.",
|
||||
cause,
|
||||
});
|
||||
|
||||
export function ensureDesktopCloudflaredAvailable(): Effect.Effect<
|
||||
void,
|
||||
CloudEnvironmentLinkError
|
||||
> {
|
||||
const bridge = typeof window === "undefined" ? undefined : window.desktopBridge;
|
||||
if (!bridge) return Effect.void;
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const status = yield* Effect.tryPromise({
|
||||
try: () => bridge.getCloudflaredStatus(),
|
||||
catch: desktopCloudflaredBridgeError,
|
||||
});
|
||||
if (status.status === "available") return;
|
||||
if (status.status === "unsupported") {
|
||||
return yield* new CloudEnvironmentLinkError({
|
||||
message: `T3 Code cannot install cloudflared automatically on ${status.platform}-${status.arch}.`,
|
||||
});
|
||||
}
|
||||
|
||||
const confirmed = yield* Effect.tryPromise({
|
||||
try: () =>
|
||||
bridge.confirm(
|
||||
"T3 Code needs Cloudflare Tunnel to make this environment available through T3 Cloud. Download and install cloudflared now?",
|
||||
),
|
||||
catch: desktopCloudflaredBridgeError,
|
||||
});
|
||||
if (!confirmed) {
|
||||
return yield* new CloudEnvironmentLinkError({
|
||||
message: "Cloudflare Tunnel installation was cancelled.",
|
||||
});
|
||||
}
|
||||
|
||||
const installed = yield* Effect.tryPromise({
|
||||
try: () => bridge.installCloudflared(),
|
||||
catch: desktopCloudflaredBridgeError,
|
||||
});
|
||||
if (installed.status !== "available") {
|
||||
return yield* new CloudEnvironmentLinkError({
|
||||
message:
|
||||
installed.status === "unsupported"
|
||||
? `T3 Code cannot install cloudflared automatically on ${installed.platform}-${installed.arch}.`
|
||||
: "cloudflared is still unavailable after installation.",
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
const isRelayProtectedError = Schema.is(RelayProtectedError);
|
||||
const isEnvironmentCloudApiError = Schema.is(
|
||||
Schema.Union([
|
||||
@@ -231,7 +284,7 @@ export function listManagedCloudEnvironments(input: {
|
||||
const configuredRelayUrl = relayUrl();
|
||||
if (!configuredRelayUrl) {
|
||||
return yield* new CloudEnvironmentLinkError({
|
||||
message: "VITE_T3_RELAY_URL is not configured.",
|
||||
message: "T3_RELAY_URL is not configured.",
|
||||
});
|
||||
}
|
||||
const relayClient = yield* ManagedRelayClient;
|
||||
@@ -261,7 +314,7 @@ export function listCloudDevices(input: {
|
||||
return Effect.gen(function* () {
|
||||
if (!relayUrl()) {
|
||||
return yield* new CloudEnvironmentLinkError({
|
||||
message: "VITE_T3_RELAY_URL is not configured.",
|
||||
message: "T3_RELAY_URL is not configured.",
|
||||
});
|
||||
}
|
||||
const relayClient = yield* ManagedRelayClient;
|
||||
@@ -290,7 +343,7 @@ export function connectManagedCloudEnvironment(input: {
|
||||
const configuredRelayUrl = relayUrl();
|
||||
if (!configuredRelayUrl) {
|
||||
return yield* new CloudEnvironmentLinkError({
|
||||
message: "VITE_T3_RELAY_URL is not configured.",
|
||||
message: "T3_RELAY_URL is not configured.",
|
||||
});
|
||||
}
|
||||
const persistedRelayUrl = normalizeRelayBaseUrl(input.relayUrl);
|
||||
@@ -465,7 +518,7 @@ export function linkEnvironmentToCloud(input: {
|
||||
const configuredRelayUrl = relayUrl();
|
||||
if (!configuredRelayUrl) {
|
||||
return yield* new CloudEnvironmentLinkError({
|
||||
message: "VITE_T3_RELAY_URL is not configured.",
|
||||
message: "T3_RELAY_URL is not configured.",
|
||||
});
|
||||
}
|
||||
const relayClient = yield* ManagedRelayClient;
|
||||
@@ -560,7 +613,7 @@ export function linkPrimaryEnvironmentToCloud(input: {
|
||||
const configuredRelayUrl = relayUrl();
|
||||
if (!configuredRelayUrl) {
|
||||
return yield* new CloudEnvironmentLinkError({
|
||||
message: "VITE_T3_RELAY_URL is not configured.",
|
||||
message: "T3_RELAY_URL is not configured.",
|
||||
});
|
||||
}
|
||||
const relayClient = yield* ManagedRelayClient;
|
||||
@@ -570,6 +623,7 @@ export function linkPrimaryEnvironmentToCloud(input: {
|
||||
message: "Local environment is not ready yet.",
|
||||
});
|
||||
}
|
||||
yield* ensureDesktopCloudflaredAvailable();
|
||||
|
||||
const challenge = yield* relayClient
|
||||
.createEnvironmentLinkChallenge({
|
||||
|
||||
@@ -64,7 +64,7 @@ export function CloudSettingsPanel() {
|
||||
<SettingsSection title="T3 Cloud" icon={<CloudIcon className="size-3.5" />}>
|
||||
<SettingsRow
|
||||
title="Cloud account"
|
||||
description="Set VITE_CLERK_PUBLISHABLE_KEY to enable optional cloud features."
|
||||
description="Set T3CODE_CLERK_PUBLISHABLE_KEY to enable optional cloud features."
|
||||
/>
|
||||
</SettingsSection>
|
||||
</SettingsPageContainer>
|
||||
|
||||
@@ -470,6 +470,18 @@ const createDesktopBridgeStub = (overrides?: {
|
||||
headers: {},
|
||||
body: "",
|
||||
}),
|
||||
getCloudflaredStatus: vi.fn().mockResolvedValue({
|
||||
status: "available",
|
||||
executablePath: "/usr/local/bin/cloudflared",
|
||||
source: "path",
|
||||
version: "2026.5.2",
|
||||
}),
|
||||
installCloudflared: vi.fn().mockResolvedValue({
|
||||
status: "available",
|
||||
executablePath: "/usr/local/bin/cloudflared",
|
||||
source: "path",
|
||||
version: "2026.5.2",
|
||||
}),
|
||||
onCloudAuthCallback: () => () => {},
|
||||
onMenuAction: () => () => {},
|
||||
getUpdateState: vi.fn().mockResolvedValue(idleUpdateState),
|
||||
|
||||
@@ -245,6 +245,18 @@ function makeDesktopBridge(overrides: Partial<DesktopBridge> = {}): DesktopBridg
|
||||
headers: {},
|
||||
body: "",
|
||||
}),
|
||||
getCloudflaredStatus: async () => ({
|
||||
status: "available",
|
||||
executablePath: "/usr/local/bin/cloudflared",
|
||||
source: "path",
|
||||
version: "2026.5.2",
|
||||
}),
|
||||
installCloudflared: async () => ({
|
||||
status: "available",
|
||||
executablePath: "/usr/local/bin/cloudflared",
|
||||
source: "path",
|
||||
version: "2026.5.2",
|
||||
}),
|
||||
onCloudAuthCallback: () => () => undefined,
|
||||
onMenuAction: () => () => undefined,
|
||||
getUpdateState: async () => {
|
||||
|
||||
@@ -26,5 +26,5 @@
|
||||
}
|
||||
]
|
||||
},
|
||||
"include": ["src", "vite.config.ts", "vercel.ts", "test"]
|
||||
"include": ["src", "vite.config.ts", "vercel.ts", "test", "../../scripts/lib/public-config.ts"]
|
||||
}
|
||||
@@ -8,9 +8,16 @@ import "vite-plus/test/config";
|
||||
import { defineConfig } from "vite-plus";
|
||||
import pkg from "./package.json" with { type: "json" };
|
||||
|
||||
import { loadRepoEnv } from "../../scripts/lib/public-config";
|
||||
|
||||
const repoEnv = loadRepoEnv();
|
||||
Object.assign(process.env, repoEnv);
|
||||
|
||||
const port = Number(process.env.PORT ?? 5733);
|
||||
const host = process.env.HOST?.trim() || "localhost";
|
||||
const configuredWsUrl = process.env.VITE_WS_URL?.trim();
|
||||
const configuredRelayUrl = repoEnv.VITE_T3_RELAY_URL?.trim() || "";
|
||||
const configuredClerkPublishableKey = repoEnv.VITE_CLERK_PUBLISHABLE_KEY?.trim() || "";
|
||||
const configuredHostedAppChannel = process.env.VITE_HOSTED_APP_CHANNEL?.trim() || "";
|
||||
const configuredAppVersion = process.env.APP_VERSION?.trim() || pkg.version;
|
||||
const configuredHostedAppUrl = (() => {
|
||||
@@ -123,6 +130,8 @@ export default defineConfig(() => {
|
||||
define: {
|
||||
// In dev mode, tell the web app where the WebSocket server lives
|
||||
"import.meta.env.VITE_WS_URL": JSON.stringify(configuredWsUrl ?? ""),
|
||||
"import.meta.env.VITE_T3_RELAY_URL": JSON.stringify(configuredRelayUrl),
|
||||
"import.meta.env.VITE_CLERK_PUBLISHABLE_KEY": JSON.stringify(configuredClerkPublishableKey),
|
||||
"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),
|
||||
|
||||
+36
-9
@@ -6,15 +6,41 @@ audience.
|
||||
|
||||
## Application Keys
|
||||
|
||||
Use keys from the same Clerk instance in each location:
|
||||
Web, desktop, and mobile use checked-in public development defaults from
|
||||
`packages/shared/src/relayAuth.ts`, so a fresh clone can use T3 Cloud without creating local
|
||||
environment files. These values are safe to embed in client builds: the Clerk publishable key and
|
||||
relay URL are public identifiers, not secrets.
|
||||
|
||||
| Consumer | Configuration | Value |
|
||||
| ------------------------ | --------------------------------------- | ----------------------------------------------------- |
|
||||
| Web and desktop renderer | `apps/web/.env` | `VITE_CLERK_PUBLISHABLE_KEY=<publishable key>` |
|
||||
| Mobile build | `apps/mobile/.env` or build environment | `EXPO_PUBLIC_CLERK_PUBLISHABLE_KEY=<publishable key>` |
|
||||
| Relay deployment | Alchemy secret | `CLERK_SECRET_KEY=<secret key>` |
|
||||
To point all clients at another Clerk/relay deployment, add a repository-root `.env` or
|
||||
`.env.local` file:
|
||||
|
||||
Never put `CLERK_SECRET_KEY` in a client application environment.
|
||||
```dotenv
|
||||
T3CODE_CLERK_PUBLISHABLE_KEY=<publishable key>
|
||||
T3_RELAY_URL=https://relay.example.com
|
||||
```
|
||||
|
||||
The shared client loader projects these canonical values into the framework-specific
|
||||
`VITE_CLERK_PUBLISHABLE_KEY`, `VITE_T3_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.
|
||||
|
||||
Configuration precedence is:
|
||||
|
||||
1. Process or CI environment variables.
|
||||
2. Repository-root `.env.local`.
|
||||
3. Repository-root `.env`.
|
||||
4. Checked-in public development defaults.
|
||||
|
||||
Release builds read `T3CODE_CLERK_PUBLISHABLE_KEY` and `T3_RELAY_URL` from GitHub Actions repository
|
||||
variables. EAS preview and production builds should define the same client-facing values in their
|
||||
EAS environment.
|
||||
|
||||
For a hosted relay deployment, copy `infra/relay/.env.example` to `infra/relay/.env`. The relay
|
||||
deployment reads `T3_RELAY_DOMAIN` and `T3_RELAY_ZONE_NAME` through Effect `Config`, with the
|
||||
checked-in shared values as defaults. `bun --cwd infra/relay run deploy` invokes Alchemy from the
|
||||
relay directory, so Alchemy loads `infra/relay/.env`. The relay still requires `CLERK_SECRET_KEY` as
|
||||
an Alchemy secret. Never put `CLERK_SECRET_KEY` in a client application environment or commit it to
|
||||
the repository.
|
||||
|
||||
## JWT Template
|
||||
|
||||
@@ -25,8 +51,9 @@ In **Clerk Dashboard > JWT templates**, create a template with:
|
||||
| Name | `t3-relay` |
|
||||
| Claims | `{ "aud": "https://t3code-relay.ineededadomain.com" }` |
|
||||
|
||||
The `aud` value must be the deployed relay public URL, with no trailing slash, and must match
|
||||
`VITE_T3_RELAY_URL` and `T3_RELAY_URL`. If the relay domain changes, update all three values.
|
||||
The `aud` value must be the deployed relay public URL, with no trailing slash. It must match the
|
||||
client-facing `T3_RELAY_URL` and the HTTPS URL derived from the deployment's `T3_RELAY_DOMAIN`. If
|
||||
the relay domain changes, update both values and the JWT template.
|
||||
|
||||
## Desktop OAuth Redirect Allowlist
|
||||
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
# Relay deployment overrides. The public relay URL is derived as
|
||||
# https://<T3_RELAY_DOMAIN>.
|
||||
T3_RELAY_DOMAIN=relay.example.com
|
||||
T3_RELAY_ZONE_NAME=example.com
|
||||
|
||||
# Relay runtime secrets and APNs configuration.
|
||||
CLERK_SECRET_KEY=sk_test_...
|
||||
APNS_ENVIRONMENT=sandbox
|
||||
APNS_TEAM_ID=...
|
||||
APNS_KEY_ID=...
|
||||
APNS_BUNDLE_ID=...
|
||||
APNS_PRIVATE_KEY=...
|
||||
@@ -80,12 +80,13 @@ dependencies represented at their boundary rather than mocking internal behavior
|
||||
The relay deploys through Alchemy:
|
||||
|
||||
```sh
|
||||
cd infra/relay
|
||||
bun run deploy
|
||||
bun --cwd infra/relay run deploy
|
||||
```
|
||||
|
||||
The stack provisions the Cloudflare Worker and queues, managed endpoint resources, database
|
||||
connectivity, and relay tracing resources. Runtime secrets include Clerk and APNs credentials.
|
||||
connectivity, and relay tracing resources. Copy [`infra/relay/.env.example`](./.env.example) to
|
||||
`infra/relay/.env` and fill in the deployment-specific values before deploying. Alchemy loads that
|
||||
file from the relay directory. Runtime secrets include Clerk and APNs credentials.
|
||||
|
||||
See:
|
||||
|
||||
|
||||
@@ -25,7 +25,7 @@ export default Alchemy.Stack(
|
||||
Effect.gen(function* () {
|
||||
const db = yield* PlanetscaleDatabase;
|
||||
const hyperdrive = yield* RelayHyperdrive;
|
||||
const zone = yield* ManagedEndpointZone;
|
||||
const zone = yield* ManagedEndpointZone.pipe(Effect.orDie);
|
||||
const api = yield* Api;
|
||||
|
||||
return {
|
||||
|
||||
+14
-10
@@ -29,7 +29,7 @@ import {
|
||||
tokenApi,
|
||||
withoutCapturedParentSpan,
|
||||
} from "./http/Api.ts";
|
||||
import { ManagedEndpointZone, RELAY_PUBLIC_DOMAIN, RELAY_PUBLIC_ORIGIN } from "./zone.ts";
|
||||
import { ManagedEndpointZone, RelayDeploymentConfig } from "./zone.ts";
|
||||
import { makeRelayTraceLayer, RelayObservability } from "./observability.ts";
|
||||
import * as DeliveryAttempts from "./agentActivity/DeliveryAttempts.ts";
|
||||
import * as AgentActivityRows from "./agentActivity/AgentActivityRows.ts";
|
||||
@@ -87,18 +87,22 @@ const ApnsDeliveryJobSigningSecret = Alchemy.makeRandom("ApnsDeliveryJobSigningS
|
||||
|
||||
export default class Api extends Cloudflare.Worker<Api>()(
|
||||
"Api",
|
||||
{
|
||||
main: import.meta.filename,
|
||||
compatibility: {
|
||||
date: "2026-05-22",
|
||||
flags: ["nodejs_compat"],
|
||||
},
|
||||
domain: RELAY_PUBLIC_DOMAIN,
|
||||
},
|
||||
RelayDeploymentConfig.pipe(
|
||||
Config.map(({ relayPublicDomain }) => ({
|
||||
main: import.meta.filename,
|
||||
compatibility: {
|
||||
date: "2026-05-22",
|
||||
flags: ["nodejs_compat"],
|
||||
},
|
||||
domain: relayPublicDomain,
|
||||
})),
|
||||
Effect.orDie,
|
||||
),
|
||||
Effect.gen(function* () {
|
||||
//
|
||||
// 1. Provision Infrastructure for the Worker to use
|
||||
//
|
||||
const { relayPublicOrigin } = yield* RelayDeploymentConfig;
|
||||
const apnsDeliveryQueue = yield* RelayApnsDeliveryQueue;
|
||||
const apnsDeliveryDeadLetterQueue = yield* RelayApnsDeliveryDeadLetterQueue;
|
||||
const cloudMintKeyPair = yield* CloudMintKeyPair;
|
||||
@@ -142,7 +146,7 @@ export default class Api extends Cloudflare.Worker<Api>()(
|
||||
|
||||
const loadSettings = Effect.gen(function* () {
|
||||
return RelayConfiguration.RelayConfiguration.of({
|
||||
relayIssuer: RELAY_PUBLIC_ORIGIN,
|
||||
relayIssuer: relayPublicOrigin,
|
||||
apns: {
|
||||
environment,
|
||||
teamId: apnsTeamId,
|
||||
|
||||
+22
-5
@@ -1,9 +1,26 @@
|
||||
import { adopt } from "alchemy/AdoptPolicy";
|
||||
import * as Cloudflare from "alchemy/Cloudflare";
|
||||
import * as Config from "effect/Config";
|
||||
import * as Effect from "effect/Effect";
|
||||
|
||||
export const RELAY_PUBLIC_DOMAIN = "t3code-relay.ineededadomain.com";
|
||||
export const RELAY_PUBLIC_ORIGIN = `https://${RELAY_PUBLIC_DOMAIN}`;
|
||||
import { DEFAULT_T3_RELAY_DOMAIN, DEFAULT_T3_RELAY_ZONE_NAME } from "@t3tools/shared/relayAuth";
|
||||
|
||||
export const ManagedEndpointZone = Cloudflare.Zone("ManagedEndpointZone", {
|
||||
name: "ineededadomain.com",
|
||||
}).pipe(adopt(true));
|
||||
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 ManagedEndpointZone = RelayDeploymentConfig.pipe(
|
||||
Config.map(({ managedEndpointZoneName }) => managedEndpointZoneName),
|
||||
Effect.flatMap((name) => Cloudflare.Zone("ManagedEndpointZone", { name }).pipe(adopt(true))),
|
||||
);
|
||||
@@ -394,6 +394,26 @@ export const DesktopCloudAuthFetchResultSchema = Schema.Struct({
|
||||
});
|
||||
export type DesktopCloudAuthFetchResult = typeof DesktopCloudAuthFetchResultSchema.Type;
|
||||
|
||||
export const DesktopCloudflaredStatusSchema = Schema.Union([
|
||||
Schema.Struct({
|
||||
status: Schema.Literal("available"),
|
||||
executablePath: Schema.String,
|
||||
source: Schema.Literals(["override", "managed", "path"]),
|
||||
version: Schema.String,
|
||||
}),
|
||||
Schema.Struct({
|
||||
status: Schema.Literal("missing"),
|
||||
version: Schema.String,
|
||||
}),
|
||||
Schema.Struct({
|
||||
status: Schema.Literal("unsupported"),
|
||||
platform: Schema.String,
|
||||
arch: Schema.String,
|
||||
version: Schema.String,
|
||||
}),
|
||||
]);
|
||||
export type DesktopCloudflaredStatus = typeof DesktopCloudflaredStatusSchema.Type;
|
||||
|
||||
export interface DesktopBridge {
|
||||
getAppBranding: () => DesktopAppBranding | null;
|
||||
getLocalEnvironmentBootstrap: () => DesktopEnvironmentBootstrap | null;
|
||||
@@ -444,6 +464,8 @@ export interface DesktopBridge {
|
||||
setCloudAuthToken: (token: string) => Promise<boolean>;
|
||||
clearCloudAuthToken: () => Promise<void>;
|
||||
fetchCloudAuth: (input: DesktopCloudAuthFetchInput) => Promise<DesktopCloudAuthFetchResult>;
|
||||
getCloudflaredStatus: () => Promise<DesktopCloudflaredStatus>;
|
||||
installCloudflared: () => Promise<DesktopCloudflaredStatus>;
|
||||
onCloudAuthCallback: (listener: (rawUrl: string) => void) => () => void;
|
||||
onMenuAction: (listener: (action: string) => void) => () => void;
|
||||
getUpdateState: () => Promise<DesktopUpdateState>;
|
||||
|
||||
@@ -138,6 +138,10 @@
|
||||
"./terminalLabels": {
|
||||
"types": "./src/terminalLabels.ts",
|
||||
"import": "./src/terminalLabels.ts"
|
||||
},
|
||||
"./cloudflared": {
|
||||
"types": "./src/cloudflared.ts",
|
||||
"import": "./src/cloudflared.ts"
|
||||
}
|
||||
},
|
||||
"scripts": {
|
||||
|
||||
@@ -0,0 +1,257 @@
|
||||
import { sha256 } from "@noble/hashes/sha2";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { describe, expect, it } from "@effect/vitest";
|
||||
import * as ConfigProvider from "effect/ConfigProvider";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Encoding from "effect/Encoding";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Sink from "effect/Sink";
|
||||
import * as Stream from "effect/Stream";
|
||||
import { HttpClient, HttpClientResponse } from "effect/unstable/http";
|
||||
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import {
|
||||
CloudflaredInstallError,
|
||||
CLOUDFLARED_VERSION,
|
||||
makeCloudflaredExecutable,
|
||||
resolveManagedCloudflaredPath,
|
||||
} from "./cloudflared.ts";
|
||||
|
||||
const emptyConfigProvider = () => ConfigProvider.fromEnv({ env: {} });
|
||||
|
||||
function makeHandle(exitCode = 0) {
|
||||
return ChildProcessSpawner.makeHandle({
|
||||
pid: ChildProcessSpawner.ProcessId(100),
|
||||
exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(exitCode)),
|
||||
isRunning: Effect.succeed(false),
|
||||
kill: () => Effect.void,
|
||||
unref: Effect.succeed(Effect.void),
|
||||
stdin: Sink.drain,
|
||||
stdout: Stream.empty,
|
||||
stderr: Stream.empty,
|
||||
all: Stream.empty,
|
||||
getInputFd: () => Sink.drain,
|
||||
getOutputFd: () => Stream.empty,
|
||||
});
|
||||
}
|
||||
|
||||
const makeHttpClientLayer = (bytes: Uint8Array) =>
|
||||
Layer.succeed(
|
||||
HttpClient.HttpClient,
|
||||
HttpClient.make((request) =>
|
||||
Effect.succeed(
|
||||
HttpClientResponse.fromWeb(request, new Response(bytes.buffer as ArrayBuffer)),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const makeSpawnerLayer = (commands: Array<string>) =>
|
||||
Layer.succeed(
|
||||
ChildProcessSpawner.ChildProcessSpawner,
|
||||
ChildProcessSpawner.make((command) =>
|
||||
Effect.sync(() => {
|
||||
commands.push(ChildProcess.isStandardCommand(command) ? command.command : "piped-command");
|
||||
return makeHandle();
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
describe("CloudflaredExecutable", () => {
|
||||
it.effect("resolves explicit overrides before managed and PATH executables", () =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-cloudflared-test-",
|
||||
});
|
||||
const overridePath = `${baseDir}/override-cloudflared`;
|
||||
yield* fileSystem.writeFileString(overridePath, "override");
|
||||
yield* fileSystem.chmod(overridePath, 0o755);
|
||||
const manager = yield* makeCloudflaredExecutable({
|
||||
baseDir,
|
||||
platform: "linux",
|
||||
arch: "x64",
|
||||
configProvider: () =>
|
||||
ConfigProvider.fromEnv({
|
||||
env: {
|
||||
PATH: "",
|
||||
T3CODE_CLOUDFLARED_PATH: overridePath,
|
||||
},
|
||||
}),
|
||||
});
|
||||
|
||||
expect(yield* manager.resolve).toEqual({
|
||||
status: "available",
|
||||
executablePath: overridePath,
|
||||
source: "override",
|
||||
version: CLOUDFLARED_VERSION,
|
||||
});
|
||||
}).pipe(
|
||||
Effect.scoped,
|
||||
Effect.provide(
|
||||
Layer.mergeAll(
|
||||
NodeServices.layer,
|
||||
makeHttpClientLayer(new Uint8Array()),
|
||||
makeSpawnerLayer([]),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("downloads, verifies, validates, and atomically installs the managed executable", () =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-cloudflared-test-",
|
||||
});
|
||||
const bytes = new TextEncoder().encode("test-cloudflared-binary");
|
||||
const manager = yield* makeCloudflaredExecutable({
|
||||
baseDir,
|
||||
platform: "linux",
|
||||
arch: "x64",
|
||||
releaseAsset: {
|
||||
url: "https://example.test/cloudflared",
|
||||
sha256: Encoding.encodeHex(sha256(bytes)),
|
||||
archive: "binary",
|
||||
},
|
||||
configProvider: emptyConfigProvider,
|
||||
});
|
||||
|
||||
const installed = yield* manager.install;
|
||||
const managedPath = resolveManagedCloudflaredPath({
|
||||
baseDir,
|
||||
platform: "linux",
|
||||
arch: "x64",
|
||||
});
|
||||
expect(installed).toEqual({
|
||||
status: "available",
|
||||
executablePath: managedPath,
|
||||
source: "managed",
|
||||
version: CLOUDFLARED_VERSION,
|
||||
});
|
||||
expect(new TextDecoder().decode(yield* fileSystem.readFile(managedPath))).toBe(
|
||||
"test-cloudflared-binary",
|
||||
);
|
||||
expect(yield* manager.resolve).toEqual(installed);
|
||||
}).pipe(
|
||||
Effect.scoped,
|
||||
Effect.provide(
|
||||
Layer.mergeAll(
|
||||
NodeServices.layer,
|
||||
makeHttpClientLayer(new TextEncoder().encode("test-cloudflared-binary")),
|
||||
makeSpawnerLayer([]),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("rejects downloads whose checksum does not match the pinned manifest", () =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-cloudflared-test-",
|
||||
});
|
||||
const manager = yield* makeCloudflaredExecutable({
|
||||
baseDir,
|
||||
platform: "linux",
|
||||
arch: "x64",
|
||||
releaseAsset: {
|
||||
url: "https://example.test/cloudflared",
|
||||
sha256: Encoding.encodeHex(sha256(new TextEncoder().encode("expected"))),
|
||||
archive: "binary",
|
||||
},
|
||||
configProvider: emptyConfigProvider,
|
||||
});
|
||||
|
||||
const error = yield* manager.install.pipe(Effect.flip);
|
||||
expect(error).toBeInstanceOf(CloudflaredInstallError);
|
||||
expect(error.reason).toBe("invalid_checksum");
|
||||
}).pipe(
|
||||
Effect.scoped,
|
||||
Effect.provide(
|
||||
Layer.mergeAll(
|
||||
NodeServices.layer,
|
||||
makeHttpClientLayer(new TextEncoder().encode("tampered")),
|
||||
makeSpawnerLayer([]),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("serializes concurrent installs within one runtime", () => {
|
||||
const commands: Array<string> = [];
|
||||
const bytes = new TextEncoder().encode("test-cloudflared-binary");
|
||||
return Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-cloudflared-test-",
|
||||
});
|
||||
const manager = yield* makeCloudflaredExecutable({
|
||||
baseDir,
|
||||
platform: "linux",
|
||||
arch: "x64",
|
||||
releaseAsset: {
|
||||
url: "https://example.test/cloudflared",
|
||||
sha256: Encoding.encodeHex(sha256(bytes)),
|
||||
archive: "binary",
|
||||
},
|
||||
configProvider: emptyConfigProvider,
|
||||
});
|
||||
|
||||
const [first, second] = yield* Effect.all([manager.install, manager.install], {
|
||||
concurrency: "unbounded",
|
||||
});
|
||||
expect(second).toEqual(first);
|
||||
expect(commands).toHaveLength(1);
|
||||
}).pipe(
|
||||
Effect.scoped,
|
||||
Effect.provide(
|
||||
Layer.mergeAll(NodeServices.layer, makeHttpClientLayer(bytes), makeSpawnerLayer(commands)),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("observes PATH changes after the manager has been constructed", () =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-cloudflared-test-",
|
||||
});
|
||||
const binDir = `${baseDir}/bin`;
|
||||
const executablePath = `${binDir}/cloudflared`;
|
||||
let path = "";
|
||||
const manager = yield* makeCloudflaredExecutable({
|
||||
baseDir,
|
||||
platform: "linux",
|
||||
arch: "x64",
|
||||
configProvider: () => ConfigProvider.fromEnv({ env: { PATH: path } }),
|
||||
});
|
||||
|
||||
expect(yield* manager.resolve).toEqual({
|
||||
status: "missing",
|
||||
version: CLOUDFLARED_VERSION,
|
||||
});
|
||||
|
||||
yield* fileSystem.makeDirectory(binDir);
|
||||
yield* fileSystem.writeFileString(executablePath, "cloudflared");
|
||||
yield* fileSystem.chmod(executablePath, 0o755);
|
||||
path = binDir;
|
||||
|
||||
expect(yield* manager.resolve).toEqual({
|
||||
status: "available",
|
||||
executablePath,
|
||||
source: "path",
|
||||
version: CLOUDFLARED_VERSION,
|
||||
});
|
||||
}).pipe(
|
||||
Effect.scoped,
|
||||
Effect.provide(
|
||||
Layer.mergeAll(
|
||||
NodeServices.layer,
|
||||
makeHttpClientLayer(new Uint8Array()),
|
||||
makeSpawnerLayer([]),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,477 @@
|
||||
import * as Clock from "effect/Clock";
|
||||
import * as Config from "effect/Config";
|
||||
import * as ConfigProvider from "effect/ConfigProvider";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Crypto from "effect/Crypto";
|
||||
import * as Data from "effect/Data";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Encoding from "effect/Encoding";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Path from "effect/Path";
|
||||
import * as PlatformError from "effect/PlatformError";
|
||||
import * as Semaphore from "effect/Semaphore";
|
||||
import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/unstable/http";
|
||||
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
export const CLOUDFLARED_VERSION = "2026.5.2";
|
||||
export const CLOUDFLARED_PATH_ENV_NAME = "T3CODE_CLOUDFLARED_PATH";
|
||||
|
||||
export type CloudflaredExecutableSource = "override" | "managed" | "path";
|
||||
|
||||
export type CloudflaredExecutableStatus =
|
||||
| {
|
||||
readonly status: "available";
|
||||
readonly executablePath: string;
|
||||
readonly source: CloudflaredExecutableSource;
|
||||
readonly version: string;
|
||||
}
|
||||
| {
|
||||
readonly status: "missing";
|
||||
readonly version: string;
|
||||
}
|
||||
| {
|
||||
readonly status: "unsupported";
|
||||
readonly platform: NodeJS.Platform;
|
||||
readonly arch: string;
|
||||
readonly version: string;
|
||||
};
|
||||
|
||||
export type AvailableCloudflaredExecutable = Extract<
|
||||
CloudflaredExecutableStatus,
|
||||
{ readonly status: "available" }
|
||||
>;
|
||||
|
||||
export class CloudflaredInstallError extends Data.TaggedError("CloudflaredInstallError")<{
|
||||
readonly reason:
|
||||
| "download_failed"
|
||||
| "invalid_checksum"
|
||||
| "install_locked"
|
||||
| "override_missing"
|
||||
| "unsupported_platform"
|
||||
| "validation_failed"
|
||||
| "write_failed";
|
||||
readonly message: string;
|
||||
readonly cause?: unknown;
|
||||
}> {}
|
||||
|
||||
class CloudflaredCommandError extends Data.TaggedError("CloudflaredCommandError")<{
|
||||
readonly command: string;
|
||||
readonly exitCode: number;
|
||||
}> {}
|
||||
|
||||
export interface CloudflaredReleaseAsset {
|
||||
readonly url: string;
|
||||
readonly sha256: string;
|
||||
readonly archive: "binary" | "tgz";
|
||||
}
|
||||
|
||||
const CLOUDFLARED_RELEASE_ASSETS: Readonly<
|
||||
Partial<Record<`${NodeJS.Platform}-${string}`, CloudflaredReleaseAsset>>
|
||||
> = {
|
||||
"darwin-arm64": {
|
||||
url: "https://github.com/cloudflare/cloudflared/releases/download/2026.5.2/cloudflared-darwin-arm64.tgz",
|
||||
sha256: "ba94054c9fd4297645093d59d51442e5e546d07bb0516120e694a13d5b216d38",
|
||||
archive: "tgz",
|
||||
},
|
||||
"darwin-x64": {
|
||||
url: "https://github.com/cloudflare/cloudflared/releases/download/2026.5.2/cloudflared-darwin-amd64.tgz",
|
||||
sha256: "7240f709506bc2c1eb9da4d89cf2555499c60280ecb854b7d80e8f17d4b7903d",
|
||||
archive: "tgz",
|
||||
},
|
||||
"linux-arm64": {
|
||||
url: "https://github.com/cloudflare/cloudflared/releases/download/2026.5.2/cloudflared-linux-arm64",
|
||||
sha256: "5a4e8ce2701105271412059f44b6a0bf1ae4542b4d98ff3180c0c019443a5815",
|
||||
archive: "binary",
|
||||
},
|
||||
"linux-x64": {
|
||||
url: "https://github.com/cloudflare/cloudflared/releases/download/2026.5.2/cloudflared-linux-amd64",
|
||||
sha256: "5286698547f03df745adb2355f04c12dde52ef425491e81f433642d695521886",
|
||||
archive: "binary",
|
||||
},
|
||||
"win32-x64": {
|
||||
url: "https://github.com/cloudflare/cloudflared/releases/download/2026.5.2/cloudflared-windows-amd64.exe",
|
||||
sha256: "20b9638f685333d623798e733effbad2487093f15ba592f6c7752360ff3b7ab7",
|
||||
archive: "binary",
|
||||
},
|
||||
};
|
||||
|
||||
const INSTALL_LOCK_RETRY_COUNT = 100;
|
||||
const INSTALL_LOCK_RETRY_DELAY = "100 millis";
|
||||
const INSTALL_LOCK_STALE_MS = 5 * 60 * 1_000;
|
||||
|
||||
const trimmedString = (name: string) =>
|
||||
Config.string(name).pipe(
|
||||
Config.option,
|
||||
Config.map(
|
||||
Option.flatMap((value) => {
|
||||
const trimmed = value.trim();
|
||||
return trimmed.length > 0 ? Option.some(trimmed) : Option.none();
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const CloudflaredConfig = Config.all({
|
||||
executableOverride: trimmedString(CLOUDFLARED_PATH_ENV_NAME),
|
||||
path: trimmedString("PATH"),
|
||||
});
|
||||
|
||||
export interface CloudflaredExecutableOptions {
|
||||
readonly baseDir: string;
|
||||
readonly platform?: NodeJS.Platform;
|
||||
readonly arch?: string;
|
||||
readonly releaseAsset?: CloudflaredReleaseAsset;
|
||||
readonly configProvider?: () => ConfigProvider.ConfigProvider;
|
||||
}
|
||||
|
||||
export interface CloudflaredExecutableShape {
|
||||
readonly resolve: Effect.Effect<CloudflaredExecutableStatus>;
|
||||
readonly install: Effect.Effect<AvailableCloudflaredExecutable, CloudflaredInstallError>;
|
||||
}
|
||||
|
||||
export class CloudflaredExecutable extends Context.Service<
|
||||
CloudflaredExecutable,
|
||||
CloudflaredExecutableShape
|
||||
>()("@t3tools/shared/cloudflared/CloudflaredExecutable") {}
|
||||
|
||||
function executableFileName(platform: NodeJS.Platform): string {
|
||||
return platform === "win32" ? "cloudflared.exe" : "cloudflared";
|
||||
}
|
||||
|
||||
export function resolveManagedCloudflaredPath(input: {
|
||||
readonly baseDir: string;
|
||||
readonly platform: NodeJS.Platform;
|
||||
readonly arch: string;
|
||||
}): string {
|
||||
const separator = input.platform === "win32" ? "\\" : "/";
|
||||
return [
|
||||
input.baseDir.replace(/[\\/]+$/u, ""),
|
||||
"tools",
|
||||
"cloudflared",
|
||||
CLOUDFLARED_VERSION,
|
||||
`${input.platform}-${input.arch}`,
|
||||
executableFileName(input.platform),
|
||||
].join(separator);
|
||||
}
|
||||
|
||||
function resolveReleaseAsset(
|
||||
platform: NodeJS.Platform,
|
||||
arch: string,
|
||||
): CloudflaredReleaseAsset | null {
|
||||
return CLOUDFLARED_RELEASE_ASSETS[`${platform}-${arch}`] ?? null;
|
||||
}
|
||||
|
||||
function isAlreadyExists(error: PlatformError.PlatformError): boolean {
|
||||
return error.reason._tag === "AlreadyExists";
|
||||
}
|
||||
|
||||
const wrapInstallFailure =
|
||||
(
|
||||
reason: CloudflaredInstallError["reason"],
|
||||
message: string,
|
||||
): (<E, R>(
|
||||
effect: Effect.Effect<void, E, R>,
|
||||
) => Effect.Effect<void, CloudflaredInstallError, R>) =>
|
||||
(effect) =>
|
||||
effect.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new CloudflaredInstallError({
|
||||
reason,
|
||||
message,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
export const makeCloudflaredExecutable = Effect.fn("cloudflared.make")(function* (
|
||||
options: CloudflaredExecutableOptions,
|
||||
): Effect.fn.Return<
|
||||
CloudflaredExecutableShape,
|
||||
never,
|
||||
| ChildProcessSpawner.ChildProcessSpawner
|
||||
| Crypto.Crypto
|
||||
| FileSystem.FileSystem
|
||||
| HttpClient.HttpClient
|
||||
| Path.Path
|
||||
> {
|
||||
const crypto = yield* Crypto.Crypto;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const httpClient = yield* HttpClient.HttpClient;
|
||||
const path = yield* Path.Path;
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const installSemaphore = yield* Semaphore.make(1);
|
||||
const platform = options.platform ?? process.platform;
|
||||
const arch = options.arch ?? process.arch;
|
||||
const releaseAsset = options.releaseAsset ?? resolveReleaseAsset(platform, arch);
|
||||
const loadCloudflaredConfig = Effect.suspend(() =>
|
||||
CloudflaredConfig.pipe(
|
||||
Effect.provideService(
|
||||
ConfigProvider.ConfigProvider,
|
||||
options.configProvider?.() ?? ConfigProvider.fromEnv(),
|
||||
),
|
||||
),
|
||||
).pipe(Effect.orDie);
|
||||
const managedPath = path.join(
|
||||
options.baseDir,
|
||||
"tools",
|
||||
"cloudflared",
|
||||
CLOUDFLARED_VERSION,
|
||||
`${platform}-${arch}`,
|
||||
executableFileName(platform),
|
||||
);
|
||||
|
||||
const isExecutableFile = Effect.fn("cloudflared.isExecutableFile")(function* (
|
||||
executablePath: string,
|
||||
) {
|
||||
const info = yield* fileSystem.stat(executablePath).pipe(Effect.option);
|
||||
if (Option.isNone(info) || info.value.type !== "File") return false;
|
||||
return platform === "win32" || (info.value.mode & 0o111) !== 0;
|
||||
});
|
||||
|
||||
const resolvePathExecutable = Effect.gen(function* () {
|
||||
const config = yield* loadCloudflaredConfig;
|
||||
const pathValue = Option.getOrUndefined(config.path);
|
||||
if (!pathValue) return null;
|
||||
const delimiter = platform === "win32" ? ";" : ":";
|
||||
for (const directory of pathValue.split(delimiter)) {
|
||||
const trimmed = directory.trim().replace(/^"|"$/gu, "");
|
||||
if (trimmed.length === 0) continue;
|
||||
const candidate = path.join(trimmed, executableFileName(platform));
|
||||
if (yield* isExecutableFile(candidate)) return candidate;
|
||||
}
|
||||
return null;
|
||||
});
|
||||
|
||||
const resolve: CloudflaredExecutableShape["resolve"] = Effect.gen(function* () {
|
||||
const config = yield* loadCloudflaredConfig;
|
||||
if (Option.isSome(config.executableOverride)) {
|
||||
return (yield* isExecutableFile(config.executableOverride.value))
|
||||
? {
|
||||
status: "available",
|
||||
executablePath: config.executableOverride.value,
|
||||
source: "override",
|
||||
version: CLOUDFLARED_VERSION,
|
||||
}
|
||||
: { status: "missing", version: CLOUDFLARED_VERSION };
|
||||
}
|
||||
if (yield* isExecutableFile(managedPath)) {
|
||||
return {
|
||||
status: "available",
|
||||
executablePath: managedPath,
|
||||
source: "managed",
|
||||
version: CLOUDFLARED_VERSION,
|
||||
};
|
||||
}
|
||||
const pathExecutable = yield* resolvePathExecutable;
|
||||
if (pathExecutable) {
|
||||
return {
|
||||
status: "available",
|
||||
executablePath: pathExecutable,
|
||||
source: "path",
|
||||
version: CLOUDFLARED_VERSION,
|
||||
};
|
||||
}
|
||||
return releaseAsset
|
||||
? { status: "missing", version: CLOUDFLARED_VERSION }
|
||||
: {
|
||||
status: "unsupported",
|
||||
platform,
|
||||
arch,
|
||||
version: CLOUDFLARED_VERSION,
|
||||
};
|
||||
});
|
||||
|
||||
const runCommand = Effect.fn("cloudflared.runCommand")(function* (
|
||||
command: string,
|
||||
args: ReadonlyArray<string>,
|
||||
) {
|
||||
const child = yield* spawner.spawn(
|
||||
ChildProcess.make(command, args, {
|
||||
shell: platform === "win32",
|
||||
stdout: "ignore",
|
||||
stderr: "ignore",
|
||||
}),
|
||||
);
|
||||
const exitCode = Number(yield* child.exitCode);
|
||||
if (exitCode !== 0) {
|
||||
return yield* new CloudflaredCommandError({ command, exitCode });
|
||||
}
|
||||
});
|
||||
|
||||
const downloadAsset = Effect.fn("cloudflared.downloadAsset")(function* (
|
||||
asset: CloudflaredReleaseAsset,
|
||||
) {
|
||||
const response = yield* httpClient.execute(HttpClientRequest.get(asset.url)).pipe(
|
||||
Effect.flatMap(HttpClientResponse.filterStatusOk),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new CloudflaredInstallError({
|
||||
reason: "download_failed",
|
||||
message: "Could not download cloudflared.",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
const bytes = new Uint8Array(
|
||||
yield* response.arrayBuffer.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new CloudflaredInstallError({
|
||||
reason: "download_failed",
|
||||
message: "Could not read the downloaded cloudflared binary.",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
const checksum = yield* crypto.digest("SHA-256", bytes).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new CloudflaredInstallError({
|
||||
reason: "validation_failed",
|
||||
message: "Could not verify the downloaded cloudflared checksum.",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
if (Encoding.encodeHex(checksum) !== asset.sha256) {
|
||||
return yield* new CloudflaredInstallError({
|
||||
reason: "invalid_checksum",
|
||||
message: "Downloaded cloudflared checksum did not match the pinned release.",
|
||||
});
|
||||
}
|
||||
return bytes;
|
||||
});
|
||||
|
||||
const acquireInstallLock = Effect.fn("cloudflared.acquireInstallLock")(function* (
|
||||
lockPath: string,
|
||||
) {
|
||||
for (let attempt = 0; attempt < INSTALL_LOCK_RETRY_COUNT; attempt += 1) {
|
||||
const acquired = yield* fileSystem.writeFileString(lockPath, "", { flag: "wx" }).pipe(
|
||||
Effect.as(true),
|
||||
Effect.catch((error) =>
|
||||
isAlreadyExists(error) ? Effect.succeed(false) : Effect.fail(error),
|
||||
),
|
||||
);
|
||||
if (acquired) return;
|
||||
|
||||
const now = yield* Clock.currentTimeMillis;
|
||||
const lockInfo = yield* fileSystem.stat(lockPath).pipe(Effect.option);
|
||||
const mtime = Option.flatMap(lockInfo, (info) => info.mtime);
|
||||
if (Option.isSome(mtime) && now - mtime.value.getTime() > INSTALL_LOCK_STALE_MS) {
|
||||
yield* fileSystem.remove(lockPath, { force: true });
|
||||
continue;
|
||||
}
|
||||
yield* Effect.sleep(INSTALL_LOCK_RETRY_DELAY);
|
||||
}
|
||||
return yield* new CloudflaredInstallError({
|
||||
reason: "install_locked",
|
||||
message: "Another cloudflared installation is still in progress.",
|
||||
});
|
||||
});
|
||||
|
||||
const installUnlocked: CloudflaredExecutableShape["install"] = Effect.gen(function* () {
|
||||
const existing = yield* resolve;
|
||||
if (existing.status === "available") return existing;
|
||||
const config = yield* loadCloudflaredConfig;
|
||||
if (Option.isSome(config.executableOverride)) {
|
||||
return yield* new CloudflaredInstallError({
|
||||
reason: "override_missing",
|
||||
message: `${CLOUDFLARED_PATH_ENV_NAME} does not point to an executable file.`,
|
||||
});
|
||||
}
|
||||
if (!releaseAsset) {
|
||||
return yield* new CloudflaredInstallError({
|
||||
reason: "unsupported_platform",
|
||||
message: `T3 Code does not provide a managed cloudflared binary for ${platform}-${arch}.`,
|
||||
});
|
||||
}
|
||||
|
||||
const managedDirectory = path.dirname(managedPath);
|
||||
const lockPath = `${managedPath}.lock`;
|
||||
yield* fileSystem
|
||||
.makeDirectory(managedDirectory, { recursive: true })
|
||||
.pipe(wrapInstallFailure("write_failed", "Could not create the cloudflared tool directory."));
|
||||
yield* acquireInstallLock(lockPath).pipe(
|
||||
Effect.catchTag("PlatformError", (cause) =>
|
||||
Effect.fail(
|
||||
new CloudflaredInstallError({
|
||||
reason: "write_failed",
|
||||
message: "Could not acquire the cloudflared installation lock.",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
return yield* Effect.gen(function* () {
|
||||
const afterLock = yield* resolve;
|
||||
if (afterLock.status === "available") return afterLock;
|
||||
|
||||
const tempDirectory = yield* fileSystem.makeTempDirectoryScoped({
|
||||
directory: managedDirectory,
|
||||
prefix: ".install-",
|
||||
});
|
||||
const archivePath = path.join(
|
||||
tempDirectory,
|
||||
releaseAsset.archive === "tgz" ? "cloudflared.tgz" : executableFileName(platform),
|
||||
);
|
||||
yield* fileSystem
|
||||
.writeFile(archivePath, yield* downloadAsset(releaseAsset))
|
||||
.pipe(wrapInstallFailure("write_failed", "Could not write the cloudflared download."));
|
||||
|
||||
const executablePath = path.join(tempDirectory, executableFileName(platform));
|
||||
if (releaseAsset.archive === "tgz") {
|
||||
yield* runCommand("tar", ["-xzf", archivePath, "-C", tempDirectory]).pipe(
|
||||
wrapInstallFailure("write_failed", "Could not extract cloudflared."),
|
||||
);
|
||||
}
|
||||
if (platform !== "win32") {
|
||||
yield* fileSystem
|
||||
.chmod(executablePath, 0o755)
|
||||
.pipe(wrapInstallFailure("write_failed", "Could not make cloudflared executable."));
|
||||
}
|
||||
yield* runCommand(executablePath, ["--version"]).pipe(
|
||||
wrapInstallFailure("validation_failed", "The downloaded cloudflared binary did not run."),
|
||||
);
|
||||
|
||||
const stagedPath = `${managedPath}.${yield* crypto.randomUUIDv4}.tmp`;
|
||||
yield* fileSystem
|
||||
.rename(executablePath, stagedPath)
|
||||
.pipe(wrapInstallFailure("write_failed", "Could not stage cloudflared."));
|
||||
yield* fileSystem
|
||||
.rename(stagedPath, managedPath)
|
||||
.pipe(
|
||||
wrapInstallFailure("write_failed", "Could not activate cloudflared."),
|
||||
Effect.ensuring(fileSystem.remove(stagedPath, { force: true }).pipe(Effect.ignore)),
|
||||
);
|
||||
return {
|
||||
status: "available",
|
||||
executablePath: managedPath,
|
||||
source: "managed",
|
||||
version: CLOUDFLARED_VERSION,
|
||||
} satisfies AvailableCloudflaredExecutable;
|
||||
}).pipe(
|
||||
Effect.scoped,
|
||||
Effect.ensuring(fileSystem.remove(lockPath, { force: true }).pipe(Effect.ignore)),
|
||||
Effect.catch((cause) =>
|
||||
cause instanceof CloudflaredInstallError
|
||||
? Effect.fail(cause)
|
||||
: Effect.fail(
|
||||
new CloudflaredInstallError({
|
||||
reason: "write_failed",
|
||||
message: "Could not install cloudflared.",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
});
|
||||
const install = installSemaphore.withPermit(installUnlocked);
|
||||
|
||||
return CloudflaredExecutable.of({ resolve, install });
|
||||
});
|
||||
|
||||
export const layer = (options: CloudflaredExecutableOptions) =>
|
||||
Layer.effect(CloudflaredExecutable, makeCloudflaredExecutable(options));
|
||||
@@ -1,3 +1,12 @@
|
||||
export const DEFAULT_T3_RELAY_DOMAIN = "t3code-relay.ineededadomain.com";
|
||||
|
||||
export const DEFAULT_T3_RELAY_URL = `https://${DEFAULT_T3_RELAY_DOMAIN}`;
|
||||
|
||||
export const DEFAULT_T3_RELAY_ZONE_NAME = "ineededadomain.com";
|
||||
|
||||
export const DEFAULT_T3_CLERK_PUBLISHABLE_KEY =
|
||||
"pk_test_YXdhaXRlZC1tb25rZmlzaC01OC5jbGVyay5hY2NvdW50cy5kZXYk";
|
||||
|
||||
export const RELAY_CLERK_JWT_TEMPLATE = "t3-relay";
|
||||
|
||||
export const RELAY_CLERK_TOKEN_OPTIONS = {
|
||||
|
||||
@@ -17,6 +17,10 @@ import * as Schema from "effect/Schema";
|
||||
import { Argument, Command, Flag } from "effect/unstable/cli";
|
||||
import { ChildProcess } from "effect/unstable/process";
|
||||
|
||||
import { loadRepoEnv } from "./lib/public-config.ts";
|
||||
|
||||
Object.assign(process.env, loadRepoEnv());
|
||||
|
||||
const BASE_SERVER_PORT = 13773;
|
||||
const BASE_WEB_PORT = 5733;
|
||||
const MAX_HASH_OFFSET = 3000;
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
// @effect-diagnostics nodeBuiltinImport:off - Tests exercise root env file precedence directly.
|
||||
import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
|
||||
import { DEFAULT_PUBLIC_CONFIG, loadRepoEnv, resolvePublicConfig } from "./public-config.ts";
|
||||
|
||||
const temporaryDirectories: string[] = [];
|
||||
|
||||
afterEach(() => {
|
||||
for (const directory of temporaryDirectories.splice(0)) {
|
||||
rmSync(directory, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
describe("loadRepoEnv", () => {
|
||||
it("projects checked-in public defaults into Vite and Expo aliases", () => {
|
||||
const env = loadRepoEnv({ baseEnv: {}, repoRoot: makeTemporaryDirectory() });
|
||||
|
||||
expect(env.T3CODE_CLERK_PUBLISHABLE_KEY).toBe(DEFAULT_PUBLIC_CONFIG.clerkPublishableKey);
|
||||
expect(env.VITE_CLERK_PUBLISHABLE_KEY).toBe(DEFAULT_PUBLIC_CONFIG.clerkPublishableKey);
|
||||
expect(env.EXPO_PUBLIC_CLERK_PUBLISHABLE_KEY).toBe(DEFAULT_PUBLIC_CONFIG.clerkPublishableKey);
|
||||
expect(env.T3_RELAY_URL).toBe(DEFAULT_PUBLIC_CONFIG.relayUrl);
|
||||
expect(env.VITE_T3_RELAY_URL).toBe(DEFAULT_PUBLIC_CONFIG.relayUrl);
|
||||
});
|
||||
|
||||
it("applies process, root local, root, and checked-in precedence in that order", () => {
|
||||
const repoRoot = makeTemporaryDirectory();
|
||||
writeFileSync(
|
||||
join(repoRoot, ".env"),
|
||||
"T3CODE_CLERK_PUBLISHABLE_KEY=pk_root\nT3_RELAY_URL=https://root.example.test\n",
|
||||
);
|
||||
writeFileSync(
|
||||
join(repoRoot, ".env.local"),
|
||||
"T3CODE_CLERK_PUBLISHABLE_KEY=pk_local\nT3_RELAY_URL=https://local.example.test\n",
|
||||
);
|
||||
|
||||
expect(loadRepoEnv({ baseEnv: {}, repoRoot }).T3_RELAY_URL).toBe("https://local.example.test");
|
||||
expect(
|
||||
loadRepoEnv({
|
||||
baseEnv: {
|
||||
T3CODE_CLERK_PUBLISHABLE_KEY: "pk_ci",
|
||||
T3_RELAY_URL: "https://ci.example.test",
|
||||
},
|
||||
repoRoot,
|
||||
}),
|
||||
).toMatchObject({
|
||||
T3CODE_CLERK_PUBLISHABLE_KEY: "pk_ci",
|
||||
VITE_CLERK_PUBLISHABLE_KEY: "pk_ci",
|
||||
EXPO_PUBLIC_CLERK_PUBLISHABLE_KEY: "pk_ci",
|
||||
T3_RELAY_URL: "https://ci.example.test",
|
||||
VITE_T3_RELAY_URL: "https://ci.example.test",
|
||||
});
|
||||
});
|
||||
|
||||
it("accepts legacy framework aliases as root overrides", () => {
|
||||
expect(
|
||||
resolvePublicConfig({
|
||||
VITE_CLERK_PUBLISHABLE_KEY: "pk_legacy",
|
||||
VITE_T3_RELAY_URL: "https://legacy.example.test",
|
||||
}),
|
||||
).toEqual({
|
||||
clerkPublishableKey: "pk_legacy",
|
||||
relayUrl: "https://legacy.example.test",
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
function makeTemporaryDirectory() {
|
||||
const directory = mkdtempSync(join(tmpdir(), "t3code-public-config-"));
|
||||
temporaryDirectories.push(directory);
|
||||
return directory;
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
// @effect-diagnostics nodeBuiltinImport:off - Build bootstrap reads optional root env files before an Effect runtime exists.
|
||||
import * as NodeFS from "node:fs";
|
||||
import * as NodePath from "node:path";
|
||||
import * as NodeURL from "node:url";
|
||||
import * as NodeUtil from "node:util";
|
||||
|
||||
import { DEFAULT_T3_CLERK_PUBLISHABLE_KEY, DEFAULT_T3_RELAY_URL } from "@t3tools/shared/relayAuth";
|
||||
|
||||
export interface T3CodePublicConfig {
|
||||
readonly clerkPublishableKey: string;
|
||||
readonly relayUrl: string;
|
||||
}
|
||||
|
||||
type Environment = Readonly<Record<string, string | undefined>>;
|
||||
|
||||
const REPO_ROOT = NodePath.dirname(
|
||||
NodePath.dirname(NodePath.dirname(NodeURL.fileURLToPath(import.meta.url))),
|
||||
);
|
||||
|
||||
// These values are intentionally public. Client builds embed them so a fresh clone can use
|
||||
// T3 Cloud without local setup. Use root .env files or CI environment variables to override them.
|
||||
export const DEFAULT_PUBLIC_CONFIG: T3CodePublicConfig = {
|
||||
clerkPublishableKey: DEFAULT_T3_CLERK_PUBLISHABLE_KEY,
|
||||
relayUrl: DEFAULT_T3_RELAY_URL,
|
||||
};
|
||||
|
||||
export function loadRepoEnv({
|
||||
baseEnv = process.env,
|
||||
repoRoot = REPO_ROOT,
|
||||
}: {
|
||||
readonly baseEnv?: Environment;
|
||||
readonly repoRoot?: string;
|
||||
} = {}): Record<string, string | undefined> {
|
||||
const rootEnv = readEnvFile(NodePath.join(repoRoot, ".env"));
|
||||
const localEnv = readEnvFile(NodePath.join(repoRoot, ".env.local"));
|
||||
const config = resolvePublicConfig(baseEnv, localEnv, rootEnv);
|
||||
|
||||
return {
|
||||
...rootEnv,
|
||||
...localEnv,
|
||||
...baseEnv,
|
||||
T3CODE_CLERK_PUBLISHABLE_KEY: config.clerkPublishableKey,
|
||||
T3_RELAY_URL: config.relayUrl,
|
||||
VITE_CLERK_PUBLISHABLE_KEY: config.clerkPublishableKey,
|
||||
VITE_T3_RELAY_URL: config.relayUrl,
|
||||
EXPO_PUBLIC_CLERK_PUBLISHABLE_KEY: config.clerkPublishableKey,
|
||||
};
|
||||
}
|
||||
|
||||
export function resolvePublicConfig(...sources: readonly Environment[]): T3CodePublicConfig {
|
||||
return {
|
||||
clerkPublishableKey:
|
||||
firstNonEmpty(
|
||||
sources,
|
||||
"T3CODE_CLERK_PUBLISHABLE_KEY",
|
||||
"VITE_CLERK_PUBLISHABLE_KEY",
|
||||
"EXPO_PUBLIC_CLERK_PUBLISHABLE_KEY",
|
||||
) ?? DEFAULT_PUBLIC_CONFIG.clerkPublishableKey,
|
||||
relayUrl:
|
||||
firstNonEmpty(sources, "T3_RELAY_URL", "VITE_T3_RELAY_URL") ?? DEFAULT_PUBLIC_CONFIG.relayUrl,
|
||||
};
|
||||
}
|
||||
|
||||
function firstNonEmpty(sources: readonly Environment[], ...names: readonly string[]) {
|
||||
for (const source of sources) {
|
||||
for (const name of names) {
|
||||
const value = source[name]?.trim();
|
||||
if (value) {
|
||||
return value;
|
||||
}
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function readEnvFile(path: string): Record<string, string | undefined> {
|
||||
return NodeFS.existsSync(path) ? NodeUtil.parseEnv(NodeFS.readFileSync(path, "utf8")) : {};
|
||||
}
|
||||
Reference in new issue
Block a user