feat(cloud): add headless cloud CLI control plane (#2905)

Co-authored-by: codex <[email protected]>
This commit is contained in:
Julius Marmingeandcodex committed 2026-06-04 14:03:35 -07:00
1 parent 3024b5804e
commit e25cf80506
32 files changed
+2860 -1502

No files matched your search

+2 -1
View File
@@ -3,9 +3,10 @@
# Release builds inject their public values at build time. Do not add server-side
# secrets to this file.
# Get these from the Clerk Dashboard under API keys and JWT templates.
# Get these from the Clerk Dashboard under API keys, JWT templates, and OAuth applications.
# T3CODE_CLERK_PUBLISHABLE_KEY=pk_test_...
# T3CODE_CLERK_JWT_TEMPLATE=t3-relay
# T3CODE_CLERK_CLI_OAUTH_CLIENT_ID=oauthapp_...
# Get this from your relay deployment. `infra/relay` deploys update it automatically.
# T3CODE_RELAY_URL=https://relay.example.com
+6
View File
@@ -177,11 +177,13 @@ jobs:
outputs:
clerk_publishable_key: ${{ steps.public_config.outputs.clerk_publishable_key }}
clerk_jwt_template: ${{ steps.public_config.outputs.clerk_jwt_template }}
clerk_cli_oauth_client_id: ${{ steps.public_config.outputs.clerk_cli_oauth_client_id }}
relay_url: ${{ steps.public_config.outputs.relay_url }}
env:
RELAY_DOMAIN: ${{ vars.RELAY_DOMAIN }}
CLERK_PUBLISHABLE_KEY: ${{ vars.CLERK_PUBLISHABLE_KEY }}
CLERK_JWT_TEMPLATE: ${{ vars.CLERK_JWT_TEMPLATE }}
CLERK_CLI_OAUTH_CLIENT_ID: ${{ vars.CLERK_CLI_OAUTH_CLIENT_ID }}
steps:
- id: public_config
name: Resolve production relay public config
@@ -193,6 +195,7 @@ jobs:
RELAY_DOMAIN
CLERK_PUBLISHABLE_KEY
CLERK_JWT_TEMPLATE
CLERK_CLI_OAUTH_CLIENT_ID
)
missing=()
for name in "${required[@]}"; do
@@ -207,6 +210,7 @@ jobs:
echo "clerk_publishable_key=$CLERK_PUBLISHABLE_KEY" >> "$GITHUB_OUTPUT"
echo "clerk_jwt_template=$CLERK_JWT_TEMPLATE" >> "$GITHUB_OUTPUT"
echo "clerk_cli_oauth_client_id=$CLERK_CLI_OAUTH_CLIENT_ID" >> "$GITHUB_OUTPUT"
echo "relay_url=https://$RELAY_DOMAIN" >> "$GITHUB_OUTPUT"
build:
@@ -218,6 +222,7 @@ jobs:
env:
T3CODE_CLERK_PUBLISHABLE_KEY: ${{ needs.relay_public_config.outputs.clerk_publishable_key }}
T3CODE_CLERK_JWT_TEMPLATE: ${{ needs.relay_public_config.outputs.clerk_jwt_template }}
T3CODE_CLERK_CLI_OAUTH_CLIENT_ID: ${{ needs.relay_public_config.outputs.clerk_cli_oauth_client_id }}
T3CODE_RELAY_URL: ${{ needs.relay_public_config.outputs.relay_url }}
strategy:
fail-fast: false
@@ -479,6 +484,7 @@ jobs:
env:
T3CODE_CLERK_PUBLISHABLE_KEY: ${{ needs.relay_public_config.outputs.clerk_publishable_key }}
T3CODE_CLERK_JWT_TEMPLATE: ${{ needs.relay_public_config.outputs.clerk_jwt_template }}
T3CODE_CLERK_CLI_OAUTH_CLIENT_ID: ${{ needs.relay_public_config.outputs.clerk_cli_oauth_client_id }}
T3CODE_RELAY_URL: ${{ needs.relay_public_config.outputs.relay_url }}
steps:
- name: Checkout
+51 -1
View File
@@ -2,8 +2,14 @@ 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 { afterEach } from "vitest";
import { fetchCloudAuth } from "./cloudAuth.ts";
import { fetchCloudAuth, validateClerkFrontendApiUrl } from "./cloudAuth.ts";
const originalClerkPublishableKey = process.env.T3CODE_CLERK_PUBLISHABLE_KEY;
const clerkPublishableKey = (hostname: string): string =>
`pk_test_${Buffer.from(`${hostname}$`).toString("base64")}`;
function makeHttpClientLayer(
handler: (
@@ -17,6 +23,14 @@ function makeHttpClientLayer(
}
describe("Desktop cloud auth IPC", () => {
afterEach(() => {
if (originalClerkPublishableKey === undefined) {
delete process.env.T3CODE_CLERK_PUBLISHABLE_KEY;
} else {
process.env.T3CODE_CLERK_PUBLISHABLE_KEY = originalClerkPublishableKey;
}
});
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;
@@ -52,4 +66,40 @@ describe("Desktop cloud auth IPC", () => {
}
}).pipe(Effect.provide(layer));
});
it.effect(
"allows the custom Clerk Frontend API host encoded by the configured publishable key",
() => {
process.env.T3CODE_CLERK_PUBLISHABLE_KEY = clerkPublishableKey("clerk.t3.codes");
let forwardedRequest: HttpClientRequest.HttpClientRequest | null = null;
const layer = makeHttpClientLayer((request) =>
Effect.sync(() => {
forwardedRequest = request;
return HttpClientResponse.fromWeb(
request,
Response.json({ response: { object: "client" } }),
);
}),
);
return Effect.gen(function* () {
yield* fetchCloudAuth.handler({
url: "https://clerk.t3.codes/v1/client",
method: "GET",
headers: {},
});
assert(forwardedRequest !== null);
assert.equal(forwardedRequest.url.toString(), "https://clerk.t3.codes/v1/client");
}).pipe(Effect.provide(layer));
},
);
it("rejects arbitrary HTTPS hosts that are not configured Clerk Frontend API hosts", () => {
process.env.T3CODE_CLERK_PUBLISHABLE_KEY = clerkPublishableKey("clerk.t3.codes");
assert.throws(
() => validateClerkFrontendApiUrl("https://attacker.example/v1/client"),
/restricted to Clerk Frontend API HTTPS hosts/u,
);
});
});
+20 -3
View File
@@ -2,6 +2,10 @@ import {
DesktopCloudAuthFetchInputSchema,
DesktopCloudAuthFetchResultSchema,
} from "@t3tools/contracts";
import {
clerkFrontendApiHostnameFromPublishableKey,
isAllowedClerkFrontendApiHostname,
} from "@t3tools/shared/relayAuth";
import * as Data from "effect/Data";
import * as Effect from "effect/Effect";
import * as Option from "effect/Option";
@@ -13,6 +17,8 @@ import * as DesktopCloudAuthTokenStore from "../../app/DesktopCloudAuthTokenStor
import * as IpcChannels from "../channels.ts";
import { makeIpcMethod } from "../DesktopIpc.ts";
declare const __T3CODE_BUILD_CLERK_PUBLISHABLE_KEY__: string | undefined;
export class DesktopCloudAuthFetchError extends Data.TaggedError("DesktopCloudAuthFetchError")<{
readonly reason: string;
readonly cause?: unknown;
@@ -22,10 +28,21 @@ export class DesktopCloudAuthFetchError extends Data.TaggedError("DesktopCloudAu
}
}
const allowedClerkFrontendApiHosts = (hostname: string): boolean =>
hostname.endsWith(".clerk.accounts.dev") || hostname.endsWith(".clerk.accounts.com");
function configuredClerkFrontendApiHostname(): string | null {
const publishableKey =
process.env.T3CODE_CLERK_PUBLISHABLE_KEY?.trim() ||
(typeof __T3CODE_BUILD_CLERK_PUBLISHABLE_KEY__ === "undefined"
? ""
: __T3CODE_BUILD_CLERK_PUBLISHABLE_KEY__.trim());
if (!publishableKey) return null;
function validateClerkFrontendApiUrl(rawUrl: string): URL {
return clerkFrontendApiHostnameFromPublishableKey(publishableKey);
}
const allowedClerkFrontendApiHosts = (hostname: string): boolean =>
isAllowedClerkFrontendApiHostname(hostname, configuredClerkFrontendApiHostname());
export function validateClerkFrontendApiUrl(rawUrl: string): URL {
const url = new URL(rawUrl);
if (url.protocol !== "https:" || !allowedClerkFrontendApiHosts(url.hostname)) {
throw new DesktopCloudAuthFetchError({
+73 -7
View File
@@ -32,10 +32,13 @@ const environmentInput = {
} satisfies DesktopEnvironment.MakeDesktopEnvironmentInput;
function makeFakeBrowserWindow() {
const webContentsListeners = new Map<string, (...args: readonly unknown[]) => void>();
const webContents = {
copyImageAt: vi.fn(),
isLoadingMainFrame: vi.fn(() => false),
on: vi.fn(),
on: vi.fn((eventName: string, listener: (...args: readonly unknown[]) => void) => {
webContentsListeners.set(eventName, listener);
}),
once: vi.fn(),
openDevTools: vi.fn(),
replaceMisspelling: vi.fn(),
@@ -63,6 +66,7 @@ function makeFakeBrowserWindow() {
window: window as unknown as Electron.BrowserWindow,
loadURL: window.loadURL,
openDevTools: webContents.openDevTools,
webContentsListeners,
};
}
@@ -96,11 +100,6 @@ const electronMenuLayer = Layer.succeed(ElectronMenu.ElectronMenu, {
showContextMenu: () => Effect.succeed(Option.none()),
} satisfies ElectronMenu.ElectronMenuShape);
const electronShellLayer = Layer.succeed(ElectronShell.ElectronShell, {
openExternal: () => Effect.succeed(true),
copyText: () => Effect.void,
} satisfies ElectronShell.ElectronShellShape);
const electronThemeLayer = Layer.succeed(ElectronTheme.ElectronTheme, {
shouldUseDarkColors: Effect.succeed(false),
setSource: () => Effect.void,
@@ -123,6 +122,7 @@ function makeTestLayer(input: {
readonly window: Electron.BrowserWindow;
readonly createCount: Ref.Ref<number>;
readonly mainWindow: Ref.Ref<Option.Option<Electron.BrowserWindow>>;
readonly openedExternalUrls?: unknown[];
}) {
const electronWindowLayer = Layer.succeed(ElectronWindow.ElectronWindow, {
create: () => Ref.update(input.createCount, (count) => count + 1).pipe(Effect.as(input.window)),
@@ -145,7 +145,14 @@ function makeTestLayer(input: {
desktopServerExposureLayer,
DesktopState.layer,
electronMenuLayer,
electronShellLayer,
Layer.succeed(ElectronShell.ElectronShell, {
openExternal: (url) =>
Effect.sync(() => {
input.openedExternalUrls?.push(url);
return true;
}),
copyText: () => Effect.void,
} satisfies ElectronShell.ElectronShellShape),
electronThemeLayer,
electronWindowLayer,
),
@@ -154,6 +161,27 @@ function makeTestLayer(input: {
}
describe("DesktopWindow", () => {
it("recognizes only same-origin renderer navigations", () => {
assert.isTrue(
DesktopWindow.isSameOriginRendererNavigation({
applicationUrl: "http://127.0.0.1:3773/",
navigationUrl: "http://127.0.0.1:3773/settings/cloud",
}),
);
assert.isFalse(
DesktopWindow.isSameOriginRendererNavigation({
applicationUrl: "http://127.0.0.1:3773/",
navigationUrl: "https://accounts.microsoft.com/oauth",
}),
);
assert.isFalse(
DesktopWindow.isSameOriginRendererNavigation({
applicationUrl: "http://127.0.0.1:3773/",
navigationUrl: "not a url",
}),
);
});
it.effect("does not open a development window until the backend is ready", () =>
Effect.gen(function* () {
const fakeWindow = makeFakeBrowserWindow();
@@ -177,4 +205,42 @@ describe("DesktopWindow", () => {
}).pipe(Effect.provide(layer));
}),
);
it.effect("opens safe off-origin renderer navigations in the system browser", () =>
Effect.gen(function* () {
const fakeWindow = makeFakeBrowserWindow();
const createCount = yield* Ref.make(0);
const mainWindow = yield* Ref.make<Option.Option<Electron.BrowserWindow>>(Option.none());
const openedExternalUrls: unknown[] = [];
const layer = makeTestLayer({
window: fakeWindow.window,
createCount,
mainWindow,
openedExternalUrls,
});
yield* Effect.gen(function* () {
const desktopWindow = yield* DesktopWindow.DesktopWindow;
yield* desktopWindow.handleBackendReady;
const willNavigate = fakeWindow.webContentsListeners.get("will-navigate");
if (!willNavigate) {
return yield* Effect.die("will-navigate listener was not registered");
}
let prevented = false;
willNavigate(
{
preventDefault: () => {
prevented = true;
},
},
"https://accounts.microsoft.com/oauth",
);
yield* Effect.promise(() => Promise.resolve());
assert.isTrue(prevented);
assert.deepEqual(openedExternalUrls, ["https://accounts.microsoft.com/oauth"]);
}).pipe(Effect.provide(layer));
}),
);
});
+31 -3
View File
@@ -92,6 +92,17 @@ function getInitialWindowBackgroundColor(shouldUseDarkColors: boolean): string {
return shouldUseDarkColors ? "#0a0a0a" : "#ffffff";
}
export function isSameOriginRendererNavigation(input: {
readonly applicationUrl: string;
readonly navigationUrl: string;
}): boolean {
try {
return new URL(input.applicationUrl).origin === new URL(input.navigationUrl).origin;
} catch {
return false;
}
}
function getWindowTitleBarOptions(shouldUseDarkColors: boolean): WindowTitleBarOptions {
if (process.platform === "darwin") {
return {
@@ -159,6 +170,9 @@ const make = Effect.gen(function* () {
const createWindow = Effect.fn("desktop.window.createWindow")(function* (
backendHttpUrl: URL,
): Effect.fn.Return<Electron.BrowserWindow, DesktopWindowError> {
const applicationUrl = environment.isDevelopment
? yield* resolveDesktopDevServerUrl(environment)
: backendHttpUrl.href;
const iconPaths = yield* assets.iconPaths;
const iconOption = getIconOption(iconPaths);
const shouldUseDarkColors = yield* electronTheme.shouldUseDarkColors;
@@ -235,6 +249,21 @@ const make = Effect.gen(function* () {
}
return { action: "deny" };
});
window.webContents.on("will-navigate", (event, url) => {
if (
isSameOriginRendererNavigation({
applicationUrl,
navigationUrl: url,
})
) {
return;
}
event.preventDefault();
if (Option.isSome(ElectronShell.parseSafeExternalUrl(url))) {
void runPromise(electronShell.openExternal(url));
}
});
window.on("page-title-updated", (event) => {
event.preventDefault();
@@ -276,11 +305,10 @@ const make = Effect.gen(function* () {
});
if (environment.isDevelopment) {
const devServerUrl = yield* resolveDesktopDevServerUrl(environment);
void window.loadURL(devServerUrl);
void window.loadURL(applicationUrl);
window.webContents.openDevTools({ mode: "detach" });
} else {
void window.loadURL(backendHttpUrl.href);
void window.loadURL(applicationUrl);
}
window.on("closed", () => {
+1 -1
View File
@@ -5,5 +5,5 @@
"types": ["node", "electron"],
"lib": ["ESNext", "DOM", "esnext.disposable"]
},
"include": ["src", "vite.config.ts"]
"include": ["src", "vite.config.ts", "../../scripts/lib"]
}
+10
View File
@@ -1,6 +1,14 @@
import { defineConfig } from "vite-plus";
import { loadRepoEnv } from "../../scripts/lib/public-config.ts";
const repoEnv = loadRepoEnv();
const shouldLaunchElectronAfterPack = process.env.T3CODE_DESKTOP_DEV === "1";
const publicConfigDefine = {
__T3CODE_BUILD_CLERK_PUBLISHABLE_KEY__: JSON.stringify(
repoEnv.T3CODE_CLERK_PUBLISHABLE_KEY?.trim() ?? "",
),
};
export default defineConfig({
run: {
@@ -32,6 +40,7 @@ export default defineConfig({
outDir: "dist-electron",
sourcemap: true,
outExtensions: () => ({ js: ".cjs" }),
define: publicConfigDefine,
entry: ["src/main.ts"],
clean: true,
deps: {
@@ -44,6 +53,7 @@ export default defineConfig({
outDir: "dist-electron",
sourcemap: true,
outExtensions: () => ({ js: ".cjs" }),
define: publicConfigDefine,
entry: ["src/preload.ts"],
},
],
+1 -1
View File
@@ -1,6 +1,6 @@
import type { ExpoConfig } from "expo/config";
import { loadRepoEnv } from "../../scripts/lib/public-config";
import { loadRepoEnv } from "../../scripts/lib/public-config.ts";
type AppVariant = "development" | "preview" | "production";
+122 -3
View File
@@ -1,6 +1,6 @@
// @effect-diagnostics nodeBuiltinImport:off - CLI integration exercises Node HTTP and filesystem boundaries.
import * as NodeHttp from "node:http";
import { mkdtempSync } from "node:fs";
import { existsSync, mkdirSync, mkdtempSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
@@ -19,7 +19,7 @@ import * as CliError from "effect/unstable/cli/CliError";
import * as TestConsole from "effect/testing/TestConsole";
import { Command } from "effect/unstable/cli";
import { cli } from "./bin.ts";
import { cli, makeCli } from "./bin.ts";
import { deriveServerPaths, ServerConfig, type ServerConfigShape } from "./config.ts";
import { ProjectionSnapshotQuery } from "./orchestration/Services/ProjectionSnapshotQuery.ts";
import { OrchestrationLayerLive } from "./orchestration/runtimeLayer.ts";
@@ -38,7 +38,11 @@ import { environmentAuthenticatedAuthLayer } from "./auth/http.ts";
const CliRuntimeLayer = Layer.mergeAll(NodeServices.layer, NetService.layer);
class ProjectCliHttpApi extends HttpApi.make("environment").add(EnvironmentOrchestrationHttpApi) {}
const runCli = (args: ReadonlyArray<string>) => Command.runWith(cli, { version: "0.0.0" })(args);
const cloudCli = makeCli({ cloudEnabled: true });
const noCloudCli = makeCli({ cloudEnabled: false });
const runCli = (args: ReadonlyArray<string>, command = cli) =>
Command.runWith(command, { version: "0.0.0" })(args);
const runCloudCli = (args: ReadonlyArray<string>) => runCli(args, cloudCli);
const runCliWithRuntime = (args: ReadonlyArray<string>) =>
runCli(args).pipe(Effect.provide(CliRuntimeLayer));
@@ -175,6 +179,121 @@ it.layer(NodeServices.layer)("bin cli parsing", (it) => {
}),
);
it.effect("rejects cloud commands when public cloud configuration is missing", () =>
Effect.gen(function* () {
const error = yield* runCli(["cloud", "status"], noCloudCli).pipe(Effect.flip);
if (!CliError.isCliError(error)) {
assert.fail(`Expected CliError, got ${String(error)}`);
}
if (error._tag !== "ShowHelp") {
assert.fail(`Expected ShowHelp, got ${error._tag}`);
}
assert.deepEqual(error.commandPath, ["t3", "cloud"]);
assert.include(error.errors[0]?.message ?? "", "missing T3 Cloud public configuration");
const output = (yield* TestConsole.errorLines).join("\n");
assert.include(output, "ERROR");
assert.include(output, "missing T3 Cloud public configuration");
}).pipe(Effect.provide(Layer.mergeAll(CliRuntimeLayer, TestConsole.layer))),
);
it.effect("reports fresh headless cloud state without requiring local configuration", () =>
Effect.gen(function* () {
const baseDir = mkdtempSync(join(tmpdir(), "t3-cli-cloud-status-test-"));
const { output } = yield* captureStdout(
runCloudCli(["cloud", "status", "--base-dir", baseDir, "--json"]),
);
// @effect-diagnostics-next-line preferSchemaOverJson:off - CLI JSON output is decoded as a presentation DTO.
const status = JSON.parse(output) as {
readonly desired: boolean;
readonly authenticated: boolean;
readonly linked: boolean;
readonly cloudUserId: string | null;
readonly relayUrl: string | null;
};
assert.equal(status.desired, false);
assert.equal(status.authenticated, false);
assert.equal(status.linked, false);
assert.equal(status.cloudUserId, null);
assert.equal(status.relayUrl, null);
}),
);
it.effect("reports actionable human-readable headless cloud state", () =>
Effect.gen(function* () {
const baseDir = mkdtempSync(join(tmpdir(), "t3-cli-cloud-status-human-test-"));
const { output } = yield* captureStdout(
runCloudCli(["cloud", "status", "--base-dir", baseDir]),
);
assert.include(output, "T3 Cloud\n Exposure: disabled");
assert.include(output, " Authorization: missing");
assert.include(output, " Environment link: not provisioned");
assert.include(output, "Next: Run `t3 cloud link` to authorize and enable cloud exposure.");
}),
);
it.effect("logs in to headless cloud without enabling exposure", () =>
Effect.gen(function* () {
const baseDir = mkdtempSync(join(tmpdir(), "t3-cli-cloud-login-test-"));
const { secretsDir } = yield* deriveServerPaths(baseDir, undefined);
mkdirSync(secretsDir, { recursive: true });
writeFileSync(
join(secretsDir, "cloud-cli-oauth-token.bin"),
// @effect-diagnostics-next-line preferSchemaOverJson:off - Test fixture matches the persisted CLI token representation.
JSON.stringify({
accessToken: "access-token",
refreshToken: "refresh-token",
expiresAtEpochMs: Number.MAX_SAFE_INTEGER,
}),
);
const login = yield* captureStdout(runCloudCli(["cloud", "login", "--base-dir", baseDir]));
const status = yield* captureStdout(
runCloudCli(["cloud", "status", "--base-dir", baseDir, "--json"]),
);
// @effect-diagnostics-next-line preferSchemaOverJson:off - CLI JSON output is decoded as a presentation DTO.
const decoded = JSON.parse(status.output) as {
readonly desired: boolean;
readonly authenticated: boolean;
};
assert.equal(login.output, "Signed in to T3 Cloud.");
assert.isFalse(decoded.desired);
assert.isTrue(decoded.authenticated);
}),
);
it.effect("disables headless cloud exposure without a running server", () =>
Effect.gen(function* () {
const baseDir = mkdtempSync(join(tmpdir(), "t3-cli-cloud-unlink-test-"));
const { output } = yield* captureStdout(
runCloudCli(["cloud", "unlink", "--base-dir", baseDir]),
);
assert.equal(output, "T3 Cloud exposure is disabled locally.");
}),
);
it.effect("logs out of headless cloud and removes the stored CLI authorization", () =>
Effect.gen(function* () {
const baseDir = mkdtempSync(join(tmpdir(), "t3-cli-cloud-logout-test-"));
const { secretsDir } = yield* deriveServerPaths(baseDir, undefined);
const tokenPath = join(secretsDir, "cloud-cli-oauth-token.bin");
mkdirSync(secretsDir, { recursive: true });
writeFileSync(tokenPath, "invalid persisted token");
const { output } = yield* captureStdout(
runCloudCli(["cloud", "logout", "--base-dir", baseDir]),
);
assert.equal(output, "Signed out of T3 Cloud locally.");
assert.isFalse(existsSync(tokenPath));
}),
);
it.effect("executes auth pairing subcommands and redacts secrets from list output", () =>
Effect.gen(function* () {
const baseDir = mkdtempSync(join(tmpdir(), "t3-cli-auth-pairing-test-"));
+38 -4
View File
@@ -3,22 +3,56 @@ import * as NodeServices from "@effect/platform-node/NodeServices";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import { Command } from "effect/unstable/cli";
import * as CliError from "effect/unstable/cli/CliError";
import * as NetService from "@t3tools/shared/Net";
import packageJson from "../package.json" with { type: "json" };
import { authCommand } from "./cli/auth.ts";
import { cloudCommand } from "./cli/cloud.ts";
import { hasCloudPublicConfig } from "./cloud/publicConfig.ts";
import { sharedServerCommandFlags } from "./cli/config.ts";
import { projectCommand } from "./cli/project.ts";
import { runServerCommand, serveCommand, startCommand } from "./cli/server.ts";
const CliRuntimeLayer = Layer.mergeAll(NodeServices.layer, NetService.layer);
export const cli = Command.make("t3", { ...sharedServerCommandFlags }).pipe(
Command.withDescription("Run the T3 Code server."),
Command.withHandler((flags) => runServerCommand(flags)),
Command.withSubcommands([startCommand, serveCommand, authCommand, projectCommand]),
const cloudPublicConfigMissingMessage =
"T3 Cloud commands are unavailable: this build is missing T3 Cloud public configuration.";
class CloudPublicConfigMissingError extends CliError.UserError {
override get message() {
return cloudPublicConfigMissingMessage;
}
}
const cloudUnavailableCommand = Command.make("cloud").pipe(
Command.withDescription("T3 Cloud is unavailable in builds without public cloud configuration."),
Command.withHidden,
Command.withHandler(() =>
Effect.fail(
new CliError.ShowHelp({
commandPath: ["t3", "cloud"],
errors: [new CloudPublicConfigMissingError({ cause: cloudPublicConfigMissingMessage })],
}),
),
),
);
export const makeCli = ({ cloudEnabled = hasCloudPublicConfig } = {}) =>
Command.make("t3", { ...sharedServerCommandFlags }).pipe(
Command.withDescription("Run the T3 Code server."),
Command.withHandler((flags) => runServerCommand(flags)),
Command.withSubcommands([
startCommand,
serveCommand,
authCommand,
projectCommand,
cloudEnabled ? cloudCommand : cloudUnavailableCommand,
]),
);
export const cli = makeCli();
if (import.meta.main) {
Command.run(cli, { version: packageJson.version }).pipe(
Effect.scoped,
+102
View File
@@ -0,0 +1,102 @@
import * as RelayClient from "@t3tools/shared/relayClient";
import { assert, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as Option from "effect/Option";
import { acquireRelayClientForLink } from "./cloud.ts";
const managedExecutable = {
status: "available",
executablePath: "/tmp/cloudflared",
source: "managed",
version: RelayClient.CLOUDFLARED_VERSION,
} as const;
it.effect("does not install the relay client when the user declines the managed download", () =>
Effect.gen(function* () {
let installCalls = 0;
const result = yield* acquireRelayClientForLink(
{
resolve: Effect.succeed({
status: "missing",
version: RelayClient.CLOUDFLARED_VERSION,
}),
install: Effect.sync(() => {
installCalls += 1;
return managedExecutable;
}),
installWithProgress: () =>
Effect.sync(() => {
installCalls += 1;
return managedExecutable;
}),
},
() => Effect.succeed(false),
() => Effect.void,
);
assert.isTrue(Option.isNone(result));
assert.equal(installCalls, 0);
}),
);
it.effect("installs the relay client after the user accepts the managed download", () =>
Effect.gen(function* () {
let installCalls = 0;
const progress: Array<string> = [];
const result = yield* acquireRelayClientForLink(
{
resolve: Effect.succeed({
status: "missing",
version: RelayClient.CLOUDFLARED_VERSION,
}),
install: Effect.sync(() => {
installCalls += 1;
return managedExecutable;
}),
installWithProgress: (report) =>
report({ type: "progress", stage: "downloading" }).pipe(
Effect.andThen(
Effect.sync(() => {
installCalls += 1;
return managedExecutable;
}),
),
),
},
() => Effect.succeed(true),
(event) =>
Effect.sync(() => {
if (event.type === "progress") {
progress.push(event.stage);
}
}),
);
assert.deepEqual(Option.getOrThrow(result), managedExecutable);
assert.equal(installCalls, 1);
assert.deepEqual(progress, ["downloading"]);
}),
);
it.effect("reuses an available relay client executable without prompting", () =>
Effect.gen(function* () {
let promptCalls = 0;
const result = yield* acquireRelayClientForLink(
{
resolve: Effect.succeed(managedExecutable),
install: Effect.die("unexpected install"),
installWithProgress: () => Effect.die("unexpected install"),
},
() =>
Effect.sync(() => {
promptCalls += 1;
return false;
}),
() => Effect.void,
);
assert.deepEqual(Option.getOrThrow(result), managedExecutable);
assert.equal(promptCalls, 0);
}),
);
+425
View File
@@ -0,0 +1,425 @@
import {
AuthRelayWriteScope,
EnvironmentHttpApi,
type RelayClientInstallProgressEvent,
type RelayClientInstallProgressStage,
} from "@t3tools/contracts";
import { RelayOkResponse } from "@t3tools/contracts/relay";
import * as RelayClient from "@t3tools/shared/relayClient";
import * as Console from "effect/Console";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as References from "effect/References";
import { Command, Flag, GlobalFlag, Prompt } from "effect/unstable/cli";
import {
FetchHttpClient,
HttpClient,
HttpClientRequest,
HttpClientResponse,
} from "effect/unstable/http";
import * as HttpApiClient from "effect/unstable/httpapi/HttpApiClient";
import * as EnvironmentAuth from "../auth/EnvironmentAuth.ts";
import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
import * as CliState from "../cloud/CliState.ts";
import * as CliTokenManager from "../cloud/CliTokenManager.ts";
import { CLOUD_LINKED_USER_ID, RELAY_URL_SECRET } from "../cloud/config.ts";
import { relayUrlConfig } from "../cloud/publicConfig.ts";
import { ServerConfig } from "../config.ts";
import { ServerEnvironmentLive } from "../environment/Layers/ServerEnvironment.ts";
import { ServerEnvironment } from "../environment/Services/ServerEnvironment.ts";
import { readPersistedServerRuntimeState } from "../serverRuntimeState.ts";
import { projectLocationFlags, resolveCliAuthConfig } from "./config.ts";
const jsonFlag = Flag.boolean("json").pipe(
Flag.withDescription("Emit JSON instead of human-readable output."),
Flag.withDefault(false),
);
function bytesToString(value: Uint8Array): string {
return new TextDecoder().decode(value);
}
interface CloudCliStatus {
readonly desired: boolean;
readonly authenticated: boolean;
readonly linked: boolean;
readonly cloudUserId: string | null;
readonly relayUrl: string | null;
readonly relayClient: RelayClient.RelayClientStatus;
}
function formatRelayClientStatus(executable: RelayClient.RelayClientStatus): ReadonlyArray<string> {
switch (executable.status) {
case "available": {
const source =
executable.source === "path"
? "PATH"
: executable.source === "managed"
? "managed install"
: "configured override";
return [
` Relay client: available via ${source}`,
` Path: ${executable.executablePath}`,
` Version: ${executable.version}`,
];
}
case "missing":
return [" Relay client: not installed"];
case "unsupported":
return [
` Relay client: unsupported on ${executable.platform}-${executable.arch}`,
` Managed version: ${executable.version}`,
];
}
}
function formatCloudStatus(status: CloudCliStatus, options?: { readonly json?: boolean }): string {
if (options?.json) {
return JSON.stringify(status, null, 2);
}
const provisioned = status.linked
? "provisioned"
: status.desired && status.authenticated
? "pending server startup"
: "not provisioned";
const nextStep = !status.authenticated
? "Run `t3 cloud link` to authorize and enable cloud exposure."
: !status.desired
? "Run `t3 cloud link` to enable cloud exposure."
: !status.linked
? "Start T3 to provision the environment link and launch its managed tunnel."
: undefined;
return [
"T3 Cloud",
` Exposure: ${status.desired ? "enabled" : "disabled"}`,
` Authorization: ${status.authenticated ? "stored credential" : "missing"}`,
` Environment link: ${provisioned}`,
` Relay: ${status.relayUrl ?? "not provisioned"}`,
...formatRelayClientStatus(status.relayClient),
...(nextStep ? ["", `Next: ${nextStep}`] : []),
].join("\n");
}
const CLOUD_CLI_LIVE_SERVER_TIMEOUT = Duration.seconds(5);
const confirmRelayClientInstall = (version: string) =>
Prompt.run(
Prompt.confirm({
message: `The T3 relay client is required for T3 Cloud exposure. Download and install version ${version}?`,
initial: false,
}),
);
function relayClientInstallProgressMessage(stage: RelayClientInstallProgressStage): string {
switch (stage) {
case "checking":
return "Checking existing installation";
case "waiting_for_lock":
return "Waiting for installation lock";
case "downloading":
return "Downloading";
case "verifying":
return "Verifying download";
case "installing":
return "Installing";
case "validating":
return "Validating executable";
case "activating":
return "Activating installation";
}
}
const reportRelayClientInstallProgress = (event: RelayClientInstallProgressEvent) =>
event.type === "progress"
? Console.log(`Relay client: ${relayClientInstallProgressMessage(event.stage)}...`)
: Effect.void;
export const acquireRelayClientForLink = Effect.fn("cloud.cli.acquire_relay_client_for_link")(
function* <ConfirmError, ConfirmContext>(
relayClient: RelayClient.RelayClientShape,
confirmInstall: (version: string) => Effect.Effect<boolean, ConfirmError, ConfirmContext>,
reportProgress: (event: RelayClientInstallProgressEvent) => Effect.Effect<void>,
) {
const executable = yield* relayClient.resolve;
if (executable.status === "available") {
return Option.some(executable);
}
if (executable.status === "unsupported") {
return Option.some(yield* relayClient.installWithProgress(reportProgress));
}
if (!(yield* confirmInstall(executable.version))) {
return Option.none();
}
return Option.some(yield* relayClient.installWithProgress(reportProgress));
},
);
const withCloudCliSessionToken = <A, E, R>(
environmentAuth: EnvironmentAuth.EnvironmentAuthShape,
run: (token: string) => Effect.Effect<A, E, R>,
) =>
Effect.acquireUseRelease(
environmentAuth.issueSession({
scopes: [AuthRelayWriteScope],
subject: "cloud-cli",
label: "t3 cloud cli",
}),
(issued) => run(issued.token),
(issued) => environmentAuth.revokeSession(issued.sessionId).pipe(Effect.ignore({ log: true })),
);
type LiveCloudActionResult =
| { readonly status: "not-running" }
| { readonly status: "succeeded" }
| { readonly status: "failed"; readonly cause: unknown };
const runLiveCloudUnlink = Effect.fn("cloud.cli.run_live_unlink")(function* () {
const config = yield* ServerConfig;
const runtimeState = yield* readPersistedServerRuntimeState(config.serverRuntimeStatePath);
if (Option.isNone(runtimeState)) {
return { status: "not-running" } satisfies LiveCloudActionResult;
}
const environmentAuth = yield* EnvironmentAuth.EnvironmentAuth;
const result = yield* Effect.exit(
withCloudCliSessionToken(environmentAuth, (token) =>
HttpApiClient.make(EnvironmentHttpApi, {
baseUrl: runtimeState.value.origin,
}).pipe(
Effect.flatMap((client) =>
client.cloud.unlink({ headers: { authorization: `Bearer ${token}` } }),
),
Effect.timeout(CLOUD_CLI_LIVE_SERVER_TIMEOUT),
),
),
);
return Exit.isSuccess(result)
? ({ status: "succeeded" } satisfies LiveCloudActionResult)
: ({ status: "failed", cause: result.cause } satisfies LiveCloudActionResult);
});
type RelayUnlinkResult =
| { readonly status: "not-authenticated" }
| { readonly status: "revoked" }
| { readonly status: "not-linked" };
const unlinkRelayEnvironment = Effect.fn("cloud.cli.unlink_relay_environment")(function* () {
const tokens = yield* CliTokenManager.CloudCliTokenManager;
const token = yield* tokens.getExisting;
if (Option.isNone(token)) {
return { status: "not-authenticated" } satisfies RelayUnlinkResult;
}
const environment = yield* ServerEnvironment;
const environmentId = yield* environment.getEnvironmentId;
const relayUrl = yield* relayUrlConfig;
const httpClient = yield* HttpClient.HttpClient;
const response = yield* HttpClientRequest.delete(
`${relayUrl}/v1/client/environment-links/${encodeURIComponent(environmentId)}`,
).pipe(
HttpClientRequest.bearerToken(token.value.accessToken),
httpClient.execute,
Effect.flatMap(HttpClientResponse.filterStatusOk),
Effect.flatMap(HttpClientResponse.schemaBodyJson(RelayOkResponse)),
);
return response.ok
? ({ status: "revoked" } satisfies RelayUnlinkResult)
: ({ status: "not-linked" } satisfies RelayUnlinkResult);
});
const disconnectCloud = Effect.fn("cloud.cli.disconnect")(function* (options: {
readonly clearAuthorization: boolean;
}) {
yield* CliState.setCliDesiredCloudLink(false);
const liveResult = yield* runLiveCloudUnlink();
const relayResult = yield* Effect.exit(unlinkRelayEnvironment());
yield* CliState.clearPersistedCloudLink;
if (options.clearAuthorization) {
const tokens = yield* CliTokenManager.CloudCliTokenManager;
yield* tokens.clear;
}
if (liveResult.status === "failed") {
yield* Console.warn(
`T3 Cloud exposure is disabled, but the running server could not stop its tunnel: ${String(liveResult.cause)}\nRestart that server to stop the connector.`,
);
} else {
yield* Console.log("T3 Cloud exposure is disabled locally.");
}
if (Exit.isFailure(relayResult)) {
yield* Console.warn(
options.clearAuthorization
? `Could not revoke the relay-side environment record before signing out: ${String(relayResult.cause)}\nThe stored CLI authorization was still removed locally.`
: `Could not revoke the relay-side environment record yet: ${String(relayResult.cause)}\nRun \`t3 cloud unlink\` again when the relay is reachable.`,
);
} else if (relayResult.value.status === "revoked") {
yield* Console.log("Revoked the relay-side environment record.");
}
if (options.clearAuthorization) {
yield* Console.log("Signed out of T3 Cloud locally.");
}
});
const runCloudCommand = <A, E>(
flags: { readonly baseDir: Option.Option<string> },
run: Effect.Effect<
A,
E,
| ServerSecretStore.ServerSecretStore
| CliTokenManager.CloudCliTokenManager
| RelayClient.RelayClient
| EnvironmentAuth.EnvironmentAuth
| FileSystem.FileSystem
| HttpClient.HttpClient
| Prompt.Environment
| ServerConfig
| ServerEnvironment
>,
options?: {
readonly quietLogs?: boolean;
},
) =>
Effect.gen(function* () {
const logLevel = yield* GlobalFlag.LogLevel;
const config = yield* resolveCliAuthConfig(flags, logLevel);
const minimumLogLevel = options?.quietLogs ? "Error" : config.logLevel;
const runtimeLayer = Layer.mergeAll(
ServerSecretStore.layer,
CliTokenManager.layer.pipe(Layer.provide(ServerSecretStore.layer)),
RelayClient.layerCloudflared({ baseDir: config.baseDir }),
EnvironmentAuth.runtimeLayer,
ServerEnvironmentLive,
).pipe(
Layer.provideMerge(FetchHttpClient.layer),
Layer.provideMerge(Layer.succeed(ServerConfig, config)),
Layer.provide(Layer.succeed(References.MinimumLogLevel, minimumLogLevel)),
);
return yield* run.pipe(Effect.provide(runtimeLayer));
});
const cloudLoginCommand = Command.make("login", {
...projectLocationFlags,
}).pipe(
Command.withDescription("Authorize the T3 Cloud CLI without enabling cloud exposure."),
Command.withHandler((flags) =>
runCloudCommand(
flags,
Effect.gen(function* () {
const tokens = yield* CliTokenManager.CloudCliTokenManager;
yield* tokens.get;
yield* Console.log("Signed in to T3 Cloud.");
}),
),
),
);
const cloudLinkCommand = Command.make("link", {
...projectLocationFlags,
}).pipe(
Command.withDescription("Authorize this environment for T3 Cloud and expose it on next start."),
Command.withHandler((flags) =>
runCloudCommand(
flags,
Effect.gen(function* () {
const relayClient = yield* RelayClient.RelayClient;
const installed = yield* acquireRelayClientForLink(
relayClient,
confirmRelayClientInstall,
reportRelayClientInstallProgress,
);
if (Option.isNone(installed)) {
yield* Console.log("T3 Cloud link cancelled. The relay client was not installed.");
return;
}
yield* Console.log(
`Using relay client ${installed.value.version} from ${installed.value.executablePath}.`,
);
const tokens = yield* CliTokenManager.CloudCliTokenManager;
yield* tokens.get;
yield* CliState.setCliDesiredCloudLink(true);
yield* Console.log(
"This T3 environment will be available over T3 Cloud the next time T3 starts.",
);
}),
),
),
);
const cloudStatusCommand = Command.make("status", {
...projectLocationFlags,
json: jsonFlag,
}).pipe(
Command.withDescription("Show persisted T3 Cloud and relay client state."),
Command.withHandler((flags) =>
runCloudCommand(
flags,
Effect.gen(function* () {
const secrets = yield* ServerSecretStore.ServerSecretStore;
const relayClient = yield* RelayClient.RelayClient;
const tokens = yield* CliTokenManager.CloudCliTokenManager;
const [desired, authenticated, cloudUserId, relayUrl, executable] = yield* Effect.all(
[
CliState.readCliDesiredCloudLink,
tokens.hasCredential,
secrets.get(CLOUD_LINKED_USER_ID),
secrets.get(RELAY_URL_SECRET),
relayClient.resolve,
],
{ concurrency: "unbounded" },
);
const status: CloudCliStatus = {
desired,
authenticated,
linked: cloudUserId !== null,
cloudUserId: cloudUserId ? bytesToString(cloudUserId) : null,
relayUrl: relayUrl ? bytesToString(relayUrl) : null,
relayClient: executable,
};
yield* Console.log(formatCloudStatus(status, { json: flags.json }));
}),
{
quietLogs: flags.json,
},
),
),
);
const cloudUnlinkCommand = Command.make("unlink", {
...projectLocationFlags,
}).pipe(
Command.withDescription("Disable T3 Cloud exposure while retaining the stored authorization."),
Command.withHandler((flags) =>
runCloudCommand(flags, disconnectCloud({ clearAuthorization: false })),
),
);
const cloudLogoutCommand = Command.make("logout", {
...projectLocationFlags,
}).pipe(
Command.withDescription("Disable T3 Cloud exposure and clear the stored CLI authorization."),
Command.withHandler((flags) =>
runCloudCommand(flags, disconnectCloud({ clearAuthorization: true })),
),
);
export const cloudCommand = Command.make("cloud").pipe(
Command.withDescription("Manage headless T3 Cloud exposure."),
Command.withSubcommands([
cloudLoginCommand,
cloudLinkCommand,
cloudStatusCommand,
cloudUnlinkCommand,
cloudLogoutCommand,
]),
);
+58
View File
@@ -0,0 +1,58 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { expect, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
import { ServerConfig } from "../config.ts";
import * as CliState from "./CliState.ts";
import {
CLOUD_ENDPOINT_RUNTIME_CONFIG,
CLOUD_LINKED_USER_ID,
CLOUD_MINT_PUBLIC_KEY,
PUBLISH_AGENT_ACTIVITY_SECRET,
RELAY_ENVIRONMENT_CREDENTIAL_SECRET,
RELAY_ISSUER_SECRET,
RELAY_URL_SECRET,
} from "./config.ts";
const persistedCloudLinkSecrets = [
CLOUD_LINKED_USER_ID,
RELAY_URL_SECRET,
RELAY_ISSUER_SECRET,
RELAY_ENVIRONMENT_CREDENTIAL_SECRET,
CLOUD_MINT_PUBLIC_KEY,
CLOUD_ENDPOINT_RUNTIME_CONFIG,
PUBLISH_AGENT_ACTIVITY_SECRET,
] as const;
const makeTestLayer = () =>
ServerSecretStore.layer.pipe(
Layer.provide(
ServerConfig.layerTest(process.cwd(), {
prefix: "t3-cloud-cli-state-test-",
}),
),
);
it.layer(NodeServices.layer)("CliState", (it) => {
it.effect("persists desired exposure and clears provisioned relay state", () =>
Effect.gen(function* () {
const secrets = yield* ServerSecretStore.ServerSecretStore;
expect(yield* CliState.readCliDesiredCloudLink).toBe(false);
yield* CliState.setCliDesiredCloudLink(true);
expect(yield* CliState.readCliDesiredCloudLink).toBe(true);
for (const name of persistedCloudLinkSecrets) {
yield* secrets.set(name, new TextEncoder().encode(name));
}
yield* CliState.clearPersistedCloudLink;
expect(yield* CliState.readCliDesiredCloudLink).toBe(false);
for (const name of persistedCloudLinkSecrets) {
expect(yield* secrets.get(name)).toBe(null);
}
}).pipe(Effect.provide(makeTestLayer())),
);
});
+49
View File
@@ -0,0 +1,49 @@
import * as Effect from "effect/Effect";
import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
import {
CLOUD_ENDPOINT_RUNTIME_CONFIG,
CLOUD_LINKED_USER_ID,
CLOUD_MINT_PUBLIC_KEY,
PUBLISH_AGENT_ACTIVITY_SECRET,
RELAY_ENVIRONMENT_CREDENTIAL_SECRET,
RELAY_ISSUER_SECRET,
RELAY_URL_SECRET,
} from "./config.ts";
export const CLOUD_CLI_DESIRED_LINK_SECRET = "cloud-cli-desired-link";
const TRUE_BYTES = new TextEncoder().encode("true");
export const readCliDesiredCloudLink = Effect.gen(function* () {
const secrets = yield* ServerSecretStore.ServerSecretStore;
return (yield* secrets.get(CLOUD_CLI_DESIRED_LINK_SECRET)) !== null;
});
export const setCliDesiredCloudLink = Effect.fn("cloud.cli_state.set_desired")(function* (
desired: boolean,
) {
const secrets = yield* ServerSecretStore.ServerSecretStore;
if (desired) {
yield* secrets.set(CLOUD_CLI_DESIRED_LINK_SECRET, TRUE_BYTES);
} else {
yield* secrets.remove(CLOUD_CLI_DESIRED_LINK_SECRET);
}
});
export const clearPersistedCloudLink = Effect.gen(function* () {
const secrets = yield* ServerSecretStore.ServerSecretStore;
yield* Effect.all(
[
secrets.remove(CLOUD_CLI_DESIRED_LINK_SECRET),
secrets.remove(CLOUD_LINKED_USER_ID),
secrets.remove(RELAY_URL_SECRET),
secrets.remove(RELAY_ISSUER_SECRET),
secrets.remove(RELAY_ENVIRONMENT_CREDENTIAL_SECRET),
secrets.remove(CLOUD_MINT_PUBLIC_KEY),
secrets.remove(CLOUD_ENDPOINT_RUNTIME_CONFIG),
secrets.remove(PUBLISH_AGENT_ACTIVITY_SECRET),
],
{ concurrency: "unbounded" },
);
});
+236
View File
@@ -0,0 +1,236 @@
// @effect-diagnostics nodeBuiltinImport:off - The CLI loopback OAuth callback is a Node HTTP boundary.
import { createServer } from "node:http";
import * as NodeHttpServer from "@effect/platform-node/NodeHttpServer";
import * as Clock from "effect/Clock";
import * as Console from "effect/Console";
import * as Context from "effect/Context";
import * as Crypto from "effect/Crypto";
import * as Data from "effect/Data";
import * as Deferred from "effect/Deferred";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Encoding from "effect/Encoding";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
import * as Semaphore from "effect/Semaphore";
import * as HttpRouter from "effect/unstable/http/HttpRouter";
import * as HttpServerRequest from "effect/unstable/http/HttpServerRequest";
import * as HttpServerResponse from "effect/unstable/http/HttpServerResponse";
import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/unstable/http";
import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
import { cloudCliOAuthConfig, type CloudCliOAuthConfig } from "./publicConfig.ts";
const CLOUD_CLI_OAUTH_TOKEN_SECRET = "cloud-cli-oauth-token";
const CLOUD_CLI_OAUTH_CALLBACK_TIMEOUT = Duration.minutes(10);
const CLOUD_CLI_OAUTH_REFRESH_EARLY_MS = Duration.toMillis(Duration.minutes(5));
const PersistedToken = Schema.Struct({
accessToken: Schema.String,
refreshToken: Schema.String,
expiresAtEpochMs: Schema.Number,
});
type PersistedToken = typeof PersistedToken.Type;
const PersistedTokenJson = Schema.fromJsonString(PersistedToken);
const decodePersistedToken = Schema.decodeUnknownEffect(PersistedTokenJson);
const encodePersistedToken = Schema.encodeEffect(PersistedTokenJson);
const OAuthTokenResponse = Schema.Struct({
access_token: Schema.String,
refresh_token: Schema.optional(Schema.String),
expires_in: Schema.Number,
token_type: Schema.String,
});
export class CloudCliTokenManagerError extends Data.TaggedError("CloudCliTokenManagerError")<{
readonly message: string;
readonly cause?: unknown;
}> {}
export interface CloudCliTokenManagerShape {
readonly get: Effect.Effect<PersistedToken, CloudCliTokenManagerError>;
readonly getExisting: Effect.Effect<Option.Option<PersistedToken>, CloudCliTokenManagerError>;
readonly hasCredential: Effect.Effect<boolean, CloudCliTokenManagerError>;
readonly clear: Effect.Effect<void, CloudCliTokenManagerError>;
}
export class CloudCliTokenManager extends Context.Service<
CloudCliTokenManager,
CloudCliTokenManagerShape
>()("t3/cloud/CliTokenManager/CloudCliTokenManager") {}
const wrapError =
(message: string) =>
<A, E, R>(effect: Effect.Effect<A, E, R>): Effect.Effect<A, CloudCliTokenManagerError, R> =>
effect.pipe(
Effect.mapError(
(cause) =>
new CloudCliTokenManagerError({
message,
cause,
}),
),
);
function stringToBytes(value: string): Uint8Array {
return new TextEncoder().encode(value);
}
function bytesToString(value: Uint8Array): string {
return new TextDecoder().decode(value);
}
const make = Effect.gen(function* () {
const crypto = yield* Crypto.Crypto;
const httpClient = (yield* HttpClient.HttpClient).pipe(HttpClient.filterStatusOk);
const secrets = yield* ServerSecretStore.ServerSecretStore;
const semaphore = yield* Semaphore.make(1);
const persist = Effect.fn("cloud.cli_token.persist")(function* (token: PersistedToken) {
const encoded = yield* encodePersistedToken(token);
yield* secrets.set(CLOUD_CLI_OAUTH_TOKEN_SECRET, stringToBytes(encoded));
return token;
});
const clear = secrets
.remove(CLOUD_CLI_OAUTH_TOKEN_SECRET)
.pipe(wrapError("Could not remove the stored T3 Cloud CLI credential."));
const read = Effect.fn("cloud.cli_token.read")(function* () {
const encoded = yield* secrets.get(CLOUD_CLI_OAUTH_TOKEN_SECRET);
if (!encoded) return Option.none<PersistedToken>();
return Option.some(yield* decodePersistedToken(bytesToString(encoded)));
});
const exchangeToken = Effect.fn("cloud.cli_token.exchange")(function* (
metadata: CloudCliOAuthConfig,
params: Record<string, string>,
) {
const response = yield* HttpClientRequest.post(metadata.tokenEndpoint).pipe(
HttpClientRequest.bodyUrlParams(params),
httpClient.execute,
Effect.flatMap(HttpClientResponse.schemaBodyJson(OAuthTokenResponse)),
);
const now = yield* Clock.currentTimeMillis;
return {
accessToken: response.access_token,
refreshToken: response.refresh_token ?? params.refresh_token ?? "",
expiresAtEpochMs: now + response.expires_in * 1_000,
} satisfies PersistedToken;
});
const refresh = Effect.fn("cloud.cli_token.refresh")(function* (token: PersistedToken) {
const metadata = yield* cloudCliOAuthConfig;
return yield* exchangeToken(metadata, {
grant_type: "refresh_token",
refresh_token: token.refreshToken,
client_id: metadata.clientId,
});
});
const login = Effect.fn("cloud.cli_token.login")(function* () {
const metadata = yield* cloudCliOAuthConfig;
const verifier = Encoding.encodeBase64Url(yield* crypto.randomBytes(32));
const challenge = Encoding.encodeBase64Url(
yield* crypto.digest("SHA-256", new TextEncoder().encode(verifier)),
);
const state = yield* crypto.randomUUIDv4;
const callback = yield* Deferred.make<string>();
const callbackRoute = HttpRouter.add(
"GET",
"/callback",
Effect.gen(function* () {
const request = yield* HttpServerRequest.HttpServerRequest;
const url = new URL(request.originalUrl, metadata.redirectUri);
const code = url.searchParams.get("code");
if (url.searchParams.get("state") !== state || !code) {
return HttpServerResponse.text("Invalid T3 Cloud authorization callback.", {
status: 400,
});
}
yield* Deferred.succeed(callback, code);
return yield* HttpServerResponse.html`
<html>
<body style="font-family: sans-serif; text-align: center; margin-top: 50px;">
<h1>T3 Cloud authorization complete</h1>
<p>You can close this window and return to your terminal.</p>
</body>
</html>
`;
}),
);
yield* HttpRouter.serve(callbackRoute, {
disableListenLog: true,
disableLogger: true,
}).pipe(
Layer.provide(
NodeHttpServer.layer(createServer, {
host: "127.0.0.1",
port: 34338,
disablePreemptiveShutdown: true,
}),
),
Layer.build,
);
const authorizationUrl = new URL(metadata.authorizationEndpoint);
authorizationUrl.searchParams.set("client_id", metadata.clientId);
authorizationUrl.searchParams.set("redirect_uri", metadata.redirectUri);
authorizationUrl.searchParams.set("response_type", "code");
authorizationUrl.searchParams.set("scope", metadata.scopes.join(" "));
authorizationUrl.searchParams.set("state", state);
authorizationUrl.searchParams.set("code_challenge", challenge);
authorizationUrl.searchParams.set("code_challenge_method", "S256");
yield* Console.log(`Open this URL to authorize T3 Cloud:\n${authorizationUrl.toString()}\n`);
const code = yield* Deferred.await(callback).pipe(
Effect.timeout(CLOUD_CLI_OAUTH_CALLBACK_TIMEOUT),
Effect.catchTag("TimeoutError", () =>
Effect.fail(
new CloudCliTokenManagerError({
message: "Timed out waiting for T3 Cloud authorization.",
}),
),
),
);
return yield* exchangeToken(metadata, {
grant_type: "authorization_code",
code,
redirect_uri: metadata.redirectUri,
client_id: metadata.clientId,
code_verifier: verifier,
});
});
const getExistingNoLock = Effect.fn("cloud.cli_token.get_existing_no_lock")(function* () {
const token = yield* read();
if (Option.isNone(token)) return token;
const now = yield* Clock.currentTimeMillis;
if (token.value.expiresAtEpochMs - CLOUD_CLI_OAUTH_REFRESH_EARLY_MS > now) {
return token;
}
return Option.some(yield* refresh(token.value).pipe(Effect.flatMap(persist)));
});
const getExisting = semaphore.withPermits(1)(
getExistingNoLock().pipe(wrapError("Could not refresh the T3 Cloud CLI credential.")),
);
const hasCredential = semaphore.withPermits(1)(
read().pipe(
Effect.map(Option.isSome),
wrapError("Could not read the stored T3 Cloud CLI credential."),
),
);
const get = semaphore.withPermits(1)(
Effect.gen(function* () {
const token = yield* getExistingNoLock();
return Option.isSome(token)
? token.value
: yield* Effect.scoped(login()).pipe(Effect.flatMap(persist));
}).pipe(wrapError("Could not authorize the T3 Cloud CLI.")),
);
return CloudCliTokenManager.of({ get, getExisting, hasCredential, clear });
});
export const layer = Layer.effect(CloudCliTokenManager, make);
+60 -1
View File
@@ -1,9 +1,19 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { describe, expect, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as Option from "effect/Option";
import * as PlatformError from "effect/PlatformError";
import { HttpClient } from "effect/unstable/http";
import * as EnvironmentAuth from "../auth/EnvironmentAuth.ts";
import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
import { consumeCloudReplayGuards } from "./http.ts";
import { ServerEnvironment } from "../environment/Services/ServerEnvironment.ts";
import * as CliTokenManager from "./CliTokenManager.ts";
import { consumeCloudReplayGuards, reconcileDesiredCloudLink } from "./http.ts";
import {
CloudManagedEndpointRuntime,
type CloudManagedEndpointRuntimeShape,
} from "./ManagedEndpointRuntime.ts";
const storeFailure = (tag: "AlreadyExists" | "PermissionDenied") =>
new ServerSecretStore.SecretStoreError({
@@ -58,3 +68,52 @@ describe("consumeCloudReplayGuards", () => {
}),
);
});
describe("reconcileDesiredCloudLink", () => {
it.effect("requires stored CLI authorization without exposing an HTTP endpoint", () =>
Effect.gen(function* () {
const error = yield* Effect.flip(reconcileDesiredCloudLink("http://127.0.0.1:3774"));
expect(error).toMatchObject({
_tag: "EnvironmentHttpUnauthorizedError",
message: "Run `t3 cloud link` to authorize this environment.",
});
}).pipe(
Effect.provideService(
ServerSecretStore.ServerSecretStore,
makeSecretStore(unusedSecretStoreOperation),
),
Effect.provideService(
ServerEnvironment,
ServerEnvironment.of({
getEnvironmentId: unusedSecretStoreOperation(),
getDescriptor: unusedSecretStoreOperation(),
}),
),
Effect.provideService(
CloudManagedEndpointRuntime,
CloudManagedEndpointRuntime.of({
applyConfig: unusedSecretStoreOperation,
} satisfies CloudManagedEndpointRuntimeShape),
),
Effect.provideService(
EnvironmentAuth.EnvironmentAuth,
EnvironmentAuth.EnvironmentAuth.of({} as EnvironmentAuth.EnvironmentAuthShape),
),
Effect.provideService(
CliTokenManager.CloudCliTokenManager,
CliTokenManager.CloudCliTokenManager.of({
get: unusedSecretStoreOperation(),
getExisting: Effect.succeed(Option.none()),
hasCredential: unusedSecretStoreOperation(),
clear: unusedSecretStoreOperation(),
}),
),
Effect.provideService(
HttpClient.HttpClient,
HttpClient.make(() => unusedSecretStoreOperation()),
),
Effect.provide(NodeServices.layer),
),
);
});
+244 -90
View File
@@ -20,6 +20,8 @@ import {
RelayEnvironmentHealthResponseProofPayload,
type RelayEnvironmentHealthResponse as RelayEnvironmentHealthResponseShape,
RelayEnvironmentConfigRequest,
RelayEnvironmentLinkChallengeResponse,
RelayEnvironmentLinkResponse,
RelayEnvironmentMintResponseProofPayload,
type RelayEnvironmentMintResponse as RelayEnvironmentMintResponseShape,
RelayEnvironmentLinkProof,
@@ -46,6 +48,7 @@ import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
import * as HttpEffect from "effect/unstable/http/HttpEffect";
import { HttpServerRequest, HttpServerResponse } from "effect/unstable/http";
import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/unstable/http";
import * as HttpApiBuilder from "effect/unstable/httpapi/HttpApiBuilder";
import * as EnvironmentAuth from "../auth/EnvironmentAuth.ts";
@@ -69,6 +72,9 @@ import {
RELAY_ISSUER_SECRET,
RELAY_URL_SECRET,
} from "./config.ts";
import { relayUrlConfig } from "./publicConfig.ts";
import * as CliState from "./CliState.ts";
import * as CliTokenManager from "./CliTokenManager.ts";
import { getOrCreateEnvironmentKeyPairFromSecretStore } from "./environmentKeys.ts";
const CLOUD_MINT_NONCE_PREFIX = "cloud-mint-nonce-";
@@ -95,6 +101,15 @@ const failEnvironmentCloudInternalError =
Effect.flatMap(() => Effect.fail(new EnvironmentHttpInternalServerError({ message }))),
);
const requireRelayUrl = relayUrlConfig.pipe(
Effect.mapError(
() =>
new EnvironmentHttpInternalServerError({
message: "T3CODE_RELAY_URL must be configured as a secure absolute HTTPS origin.",
}),
),
);
function bytesToString(bytes: Uint8Array): string {
return new TextDecoder().decode(bytes);
}
@@ -322,59 +337,83 @@ interface CloudHttpDependencies {
readonly environment: ServerEnvironmentShape;
readonly endpointRuntime: CloudManagedEndpointRuntimeShape;
readonly environmentAuth: EnvironmentAuth.EnvironmentAuthShape;
readonly cliTokenManager: CliTokenManager.CloudCliTokenManagerShape;
readonly httpClient: HttpClient.HttpClient;
}
const cloudHttpDependencies = Effect.gen(function* () {
return {
secrets: yield* ServerSecretStore.ServerSecretStore,
environment: yield* ServerEnvironment,
endpointRuntime: yield* CloudManagedEndpointRuntime,
environmentAuth: yield* EnvironmentAuth.EnvironmentAuth,
cliTokenManager: yield* CliTokenManager.CloudCliTokenManager,
httpClient: yield* HttpClient.HttpClient,
} satisfies CloudHttpDependencies;
});
const makeCloudLinkProof = Effect.fn("environment.cloud.makeLinkProof")(function* (
dependencies: CloudHttpDependencies,
request: RelayLinkProofRequest,
requestUrl: string,
) {
const keyPair = yield* getOrCreateEnvironmentKeyPairFromSecretStore(dependencies.secrets);
if (
!providerKindMatchesRequestedLinkScopes(request) ||
!isAllowedEndpointOrigin({
origin: request.origin,
requestUrl,
})
) {
return yield* new EnvironmentHttpBadRequestError({
message: "Invalid managed endpoint origin.",
});
}
const now = yield* DateTime.now;
const expiresAt = DateTime.add(now, { minutes: 5 });
const nowSeconds = Math.floor(now.epochMilliseconds / 1_000);
const descriptor = yield* dependencies.environment.getDescriptor;
const payload = {
iss: `t3-env:${descriptor.environmentId}`,
aud: normalizeRelayIssuer(request.relayIssuer),
sub: descriptor.environmentId,
jti: yield* Crypto.Crypto.pipe(Effect.flatMap((crypto) => crypto.randomUUIDv4)),
iat: nowSeconds,
exp: Math.floor(expiresAt.epochMilliseconds / 1_000),
challenge: request.challenge,
descriptor,
environmentId: descriptor.environmentId,
environmentPublicKey: normalizePemForSignedPayload(keyPair.publicKey),
endpoint: request.endpoint,
origin: request.origin,
scopes: ["agent_activity_notifications", "managed_tunnels"],
} satisfies RelayEnvironmentLinkProofPayload;
return yield* signRelayJwt({
privateKey: keyPair.privateKey,
typ: RELAY_LINK_PROOF_TYP,
payload,
}).pipe(
Effect.mapError(
(cause) =>
new EnvironmentAuth.ServerAuthInternalError({
message: "Failed to sign cloud link JWT.",
cause,
}),
),
);
});
const cloudLinkProofHandler = Effect.fn("environment.cloud.linkProof")(
function* (dependencies: CloudHttpDependencies, request: RelayLinkProofRequest) {
yield* requireEnvironmentScope(AuthRelayWriteScope);
const httpRequest = yield* HttpServerRequest.HttpServerRequest;
const keyPair = yield* getOrCreateEnvironmentKeyPairFromSecretStore(dependencies.secrets);
const requestUrl = requestAbsoluteUrl(httpRequest);
if (
requestUrl === null ||
hasForwardedAuthorityHeaders(httpRequest) ||
!providerKindMatchesRequestedLinkScopes(request) ||
!isAllowedEndpointOrigin({
origin: request.origin,
requestUrl,
})
) {
if (requestUrl === null || hasForwardedAuthorityHeaders(httpRequest)) {
return yield* new EnvironmentHttpBadRequestError({
message: "Invalid managed endpoint origin.",
});
}
const now = yield* DateTime.now;
const expiresAt = DateTime.add(now, { minutes: 5 });
const nowSeconds = Math.floor(now.epochMilliseconds / 1_000);
const descriptor = yield* dependencies.environment.getDescriptor;
const payload = {
iss: `t3-env:${descriptor.environmentId}`,
aud: normalizeRelayIssuer(request.relayIssuer),
sub: descriptor.environmentId,
jti: yield* Crypto.Crypto.pipe(Effect.flatMap((crypto) => crypto.randomUUIDv4)),
iat: nowSeconds,
exp: Math.floor(expiresAt.epochMilliseconds / 1_000),
challenge: request.challenge,
descriptor,
environmentId: descriptor.environmentId,
environmentPublicKey: normalizePemForSignedPayload(keyPair.publicKey),
endpoint: request.endpoint,
origin: request.origin,
scopes: ["agent_activity_notifications", "managed_tunnels"],
} satisfies RelayEnvironmentLinkProofPayload;
const proof = yield* signRelayJwt({
privateKey: keyPair.privateKey,
typ: RELAY_LINK_PROOF_TYP,
payload,
}).pipe(
Effect.mapError(
(cause) =>
new EnvironmentAuth.ServerAuthInternalError({
message: "Failed to sign cloud link JWT.",
cause,
}),
),
);
const proof = yield* makeCloudLinkProof(dependencies, request, requestUrl);
yield* appendCloudCredentialResponseHeaders;
return proof satisfies RelayEnvironmentLinkProof;
},
@@ -389,51 +428,55 @@ const cloudLinkProofHandler = Effect.fn("environment.cloud.linkProof")(
}),
);
const applyCloudRelayConfig = Effect.fn("environment.cloud.applyRelayConfig")(function* (
dependencies: CloudHttpDependencies,
payload: RelayEnvironmentConfigRequest,
) {
yield* validateRelayConfigPayload(payload);
yield* validateLinkedCloudUser({
secrets: dependencies.secrets,
cloudUserId: payload.cloudUserId,
});
yield* validateCloudMintPublicKey(payload.cloudMintPublicKey);
const endpointRuntimeStatus = yield* dependencies.endpointRuntime.applyConfig(
payload.endpointRuntime,
);
const ok =
endpointRuntimeStatus.status === "disabled" || endpointRuntimeStatus.status === "running";
if (!ok) {
return yield* new EnvironmentCloudEndpointUnavailableError({
message: "Managed endpoint runtime could not be started.",
endpointRuntimeStatus,
});
}
yield* dependencies.secrets.set(RELAY_URL_SECRET, stringToBytes(payload.relayUrl));
yield* dependencies.secrets.set(
RELAY_ISSUER_SECRET,
stringToBytes(payload.relayIssuer ?? payload.relayUrl),
);
yield* dependencies.secrets.set(CLOUD_LINKED_USER_ID, stringToBytes(payload.cloudUserId));
yield* dependencies.secrets.set(
RELAY_ENVIRONMENT_CREDENTIAL_SECRET,
stringToBytes(payload.environmentCredential),
);
yield* dependencies.secrets.set(CLOUD_MINT_PUBLIC_KEY, stringToBytes(payload.cloudMintPublicKey));
if (payload.endpointRuntime) {
const endpointRuntimeJson = yield* encodeEndpointRuntimeConfigJson(payload.endpointRuntime);
yield* dependencies.secrets.set(
CLOUD_ENDPOINT_RUNTIME_CONFIG,
stringToBytes(endpointRuntimeJson),
);
} else {
yield* dependencies.secrets.remove(CLOUD_ENDPOINT_RUNTIME_CONFIG);
}
return { ok, endpointRuntimeStatus } satisfies EnvironmentCloudRelayConfigResult;
});
const cloudRelayConfigHandler = Effect.fn("environment.cloud.relayConfig")(
function* (dependencies: CloudHttpDependencies, payload: RelayEnvironmentConfigRequest) {
yield* requireEnvironmentScope(AuthRelayWriteScope);
yield* validateRelayConfigPayload(payload);
yield* validateLinkedCloudUser({
secrets: dependencies.secrets,
cloudUserId: payload.cloudUserId,
});
yield* validateCloudMintPublicKey(payload.cloudMintPublicKey);
const endpointRuntimeStatus = yield* dependencies.endpointRuntime.applyConfig(
payload.endpointRuntime,
);
const ok =
endpointRuntimeStatus.status === "disabled" || endpointRuntimeStatus.status === "running";
if (!ok) {
return yield* new EnvironmentCloudEndpointUnavailableError({
message: "Managed endpoint runtime could not be started.",
endpointRuntimeStatus,
});
}
yield* dependencies.secrets.set(RELAY_URL_SECRET, stringToBytes(payload.relayUrl));
yield* dependencies.secrets.set(
RELAY_ISSUER_SECRET,
stringToBytes(payload.relayIssuer ?? payload.relayUrl),
);
yield* dependencies.secrets.set(CLOUD_LINKED_USER_ID, stringToBytes(payload.cloudUserId));
yield* dependencies.secrets.set(
RELAY_ENVIRONMENT_CREDENTIAL_SECRET,
stringToBytes(payload.environmentCredential),
);
yield* dependencies.secrets.set(
CLOUD_MINT_PUBLIC_KEY,
stringToBytes(payload.cloudMintPublicKey),
);
if (payload.endpointRuntime) {
const endpointRuntimeJson = yield* encodeEndpointRuntimeConfigJson(payload.endpointRuntime);
yield* dependencies.secrets.set(
CLOUD_ENDPOINT_RUNTIME_CONFIG,
stringToBytes(endpointRuntimeJson),
);
} else {
yield* dependencies.secrets.remove(CLOUD_ENDPOINT_RUNTIME_CONFIG);
}
return { ok, endpointRuntimeStatus } satisfies EnvironmentCloudRelayConfigResult;
return yield* applyCloudRelayConfig(dependencies, payload);
},
Effect.catchTag("ServerAuthInternalError", (error) =>
failEnvironmentCloudInternalError(error.message)(error.cause),
@@ -448,6 +491,121 @@ const cloudRelayConfigHandler = Effect.fn("environment.cloud.relayConfig")(
}),
);
const relayClientRequest = <A>(
dependencies: CloudHttpDependencies,
input: {
readonly url: string;
readonly token: string;
readonly payload: unknown;
readonly schema: Schema.Decoder<A>;
},
) =>
HttpClientRequest.post(input.url).pipe(
HttpClientRequest.bearerToken(input.token),
HttpClientRequest.bodyJson(input.payload),
Effect.flatMap(dependencies.httpClient.execute),
Effect.flatMap(HttpClientResponse.filterStatusOk),
Effect.flatMap(HttpClientResponse.schemaBodyJson(input.schema)),
Effect.mapError(
(cause) =>
new EnvironmentHttpInternalServerError({
message: `T3 Cloud relay request failed: ${String(cause)}`,
}),
),
);
const reconcileDesiredCloudLinkWith = Effect.fn("environment.cloud.reconcileDesiredLinkWith")(
function* (dependencies: CloudHttpDependencies, localOrigin: string) {
const localUrl = yield* Effect.try({
try: () => new URL(localOrigin),
catch: () =>
new EnvironmentHttpBadRequestError({
message: "Could not resolve local environment origin.",
}),
});
if (localUrl.origin !== localOrigin) {
return yield* new EnvironmentHttpBadRequestError({
message: "Could not resolve local environment origin.",
});
}
const localWsOrigin = localOrigin.replace(/^http/u, "ws");
const token = yield* dependencies.cliTokenManager.getExisting.pipe(
Effect.flatMap(
Option.match({
onNone: () =>
Effect.fail(
new EnvironmentHttpUnauthorizedError({
message: "Run `t3 cloud link` to authorize this environment.",
}),
),
onSome: Effect.succeed,
}),
),
);
const relayUrl = yield* requireRelayUrl;
const challenge = yield* relayClientRequest(dependencies, {
url: `${relayUrl}/v1/client/environment-link-challenges`,
token: token.accessToken,
payload: {
notificationsEnabled: true,
liveActivitiesEnabled: true,
managedTunnelsEnabled: true,
},
schema: RelayEnvironmentLinkChallengeResponse,
});
const proof = yield* makeCloudLinkProof(
dependencies,
{
challenge: challenge.challenge,
relayIssuer: relayUrl,
endpoint: {
httpBaseUrl: localOrigin,
wsBaseUrl: localWsOrigin,
providerKind: "cloudflare_tunnel",
},
origin: {
localHttpHost: localUrl.hostname,
localHttpPort: endpointRequestPort(localUrl),
},
},
localOrigin,
);
const link = yield* relayClientRequest(dependencies, {
url: `${relayUrl}/v1/client/environment-links`,
token: token.accessToken,
payload: {
proof,
notificationsEnabled: true,
liveActivitiesEnabled: true,
managedTunnelsEnabled: true,
},
schema: RelayEnvironmentLinkResponse,
});
yield* CliState.setCliDesiredCloudLink(true);
return yield* applyCloudRelayConfig(dependencies, {
relayUrl,
relayIssuer: link.relayIssuer,
cloudUserId: link.cloudUserId,
environmentCredential: link.environmentCredential,
cloudMintPublicKey: link.cloudMintPublicKey,
endpointRuntime: link.endpointRuntime,
});
},
Effect.catchTags({
CloudCliTokenManagerError: (error) =>
failEnvironmentCloudInternalError(error.message)(error.cause),
SecretStoreError: failEnvironmentCloudInternalError(
"Could not persist desired T3 Cloud link state.",
),
}),
);
export const reconcileDesiredCloudLink = Effect.fn("environment.cloud.reconcileDesiredLink")(
function* (localOrigin: string) {
return yield* reconcileDesiredCloudLinkWith(yield* cloudHttpDependencies, localOrigin);
},
);
const readCloudLinkState = Effect.fn("environment.cloud.readLinkState")(function* (
dependencies: CloudHttpDependencies,
) {
@@ -498,6 +656,7 @@ const cloudUnlinkHandler = Effect.fn("environment.cloud.unlink")(
],
{ concurrency: 7 },
);
yield* CliState.setCliDesiredCloudLink(false);
return { ok: true, endpointRuntimeStatus } satisfies EnvironmentCloudRelayConfigResult;
},
Effect.catchTag(
@@ -769,12 +928,7 @@ export const cloudHttpApiLayer = HttpApiBuilder.group(
EnvironmentHttpApi,
"cloud",
Effect.fnUntraced(function* (handlers) {
const dependencies: CloudHttpDependencies = {
secrets: yield* ServerSecretStore.ServerSecretStore,
environment: yield* ServerEnvironment,
endpointRuntime: yield* CloudManagedEndpointRuntime,
environmentAuth: yield* EnvironmentAuth.EnvironmentAuth,
};
const dependencies = yield* cloudHttpDependencies;
return handlers
.handle("linkProof", ({ payload }) => cloudLinkProofHandler(dependencies, payload))
.handle("relayConfig", ({ payload }) => cloudRelayConfigHandler(dependencies, payload))
@@ -0,0 +1,85 @@
import { assert, it } from "@effect/vitest";
import * as ConfigProvider from "effect/ConfigProvider";
import * as Effect from "effect/Effect";
import { makeCloudCliOAuthConfig, makeRelayUrlConfig } from "./publicConfig.ts";
const provideEnv = (env: Readonly<Record<string, string>>) =>
Effect.provide(ConfigProvider.layer(ConfigProvider.fromEnv({ env })));
it.effect("uses the statically injected relay URL when no runtime override exists", () =>
Effect.gen(function* () {
const relayUrl = yield* makeRelayUrlConfig("https://embedded.example.test///").pipe(
provideEnv({}),
);
assert.equal(relayUrl, "https://embedded.example.test");
}),
);
it.effect("prefers a runtime relay URL override over the statically injected value", () =>
Effect.gen(function* () {
const relayUrl = yield* makeRelayUrlConfig("https://embedded.example.test").pipe(
provideEnv({ T3CODE_RELAY_URL: "https://runtime.example.test///" }),
);
assert.equal(relayUrl, "https://runtime.example.test");
}),
);
it.effect("requires a relay URL when the server bundle has no injected value", () =>
makeRelayUrlConfig("").pipe(provideEnv({}), Effect.flip),
);
it.effect("rejects an insecure runtime relay URL override", () =>
makeRelayUrlConfig("https://embedded.example.test").pipe(
provideEnv({ T3CODE_RELAY_URL: "http://runtime.example.test" }),
Effect.flip,
),
);
it.effect("rejects an injected relay URL with a non-origin path", () =>
makeRelayUrlConfig("https://embedded.example.test/path").pipe(provideEnv({}), Effect.flip),
);
it.effect("derives direct Clerk OAuth endpoints from statically injected public config", () =>
Effect.gen(function* () {
const config = yield* makeCloudCliOAuthConfig({
clerkPublishableKeyFallback: "pk_test_Y2xlcmsuZXhhbXBsZS50ZXN0JA==",
clerkCliOAuthClientIdFallback: "oauth_client_embedded",
}).pipe(provideEnv({}));
assert.deepEqual(config, {
authorizationEndpoint: "https://clerk.example.test/oauth/authorize",
tokenEndpoint: "https://clerk.example.test/oauth/token",
clientId: "oauth_client_embedded",
redirectUri: "http://127.0.0.1:34338/callback",
scopes: ["openid", "profile", "email"],
});
}),
);
it.effect("prefers runtime Clerk OAuth config overrides over statically injected values", () =>
Effect.gen(function* () {
const config = yield* makeCloudCliOAuthConfig({
clerkPublishableKeyFallback: "pk_test_ZW1iZWRkZWQuZXhhbXBsZS50ZXN0JA==",
clerkCliOAuthClientIdFallback: "oauth_client_embedded",
}).pipe(
provideEnv({
T3CODE_CLERK_PUBLISHABLE_KEY: "pk_test_cnVudGltZS5leGFtcGxlLnRlc3Qk",
T3CODE_CLERK_CLI_OAUTH_CLIENT_ID: "oauth_client_runtime",
}),
);
assert.equal(config.authorizationEndpoint, "https://runtime.example.test/oauth/authorize");
assert.equal(config.tokenEndpoint, "https://runtime.example.test/oauth/token");
assert.equal(config.clientId, "oauth_client_runtime");
}),
);
it.effect("requires Clerk OAuth config when the server bundle has no injected values", () =>
makeCloudCliOAuthConfig({
clerkPublishableKeyFallback: "",
clerkCliOAuthClientIdFallback: "",
}).pipe(provideEnv({}), Effect.flip),
);
+110
View File
@@ -0,0 +1,110 @@
import { clerkFrontendApiUrlFromPublishableKey } from "@t3tools/shared/relayAuth";
import { normalizeSecureRelayUrl } from "@t3tools/shared/relayUrl";
import * as Config from "effect/Config";
import * as Effect from "effect/Effect";
import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
import * as SchemaIssue from "effect/SchemaIssue";
declare const __T3CODE_BUILD_RELAY_URL__: string | undefined;
declare const __T3CODE_BUILD_CLERK_PUBLISHABLE_KEY__: string | undefined;
declare const __T3CODE_BUILD_CLERK_CLI_OAUTH_CLIENT_ID__: string | undefined;
const CLOUD_CLI_OAUTH_REDIRECT_URI = "http://127.0.0.1:34338/callback";
const CLOUD_CLI_OAUTH_SCOPES = ["openid", "profile", "email"] as const;
function validateRelayUrl(value: string) {
const relayUrl = normalizeSecureRelayUrl(value);
return relayUrl === null
? Effect.fail(
new Config.ConfigError(
new Schema.SchemaError(
new SchemaIssue.InvalidValue(Option.some(value), {
message: "Relay URL must be a secure absolute HTTPS origin.",
}),
),
),
)
: Effect.succeed(relayUrl);
}
function readBuildTimeValue(value: string | undefined): string {
return typeof value === "undefined" ? "" : value.trim();
}
export const buildTimeRelayUrl =
typeof __T3CODE_BUILD_RELAY_URL__ === "undefined"
? ""
: (normalizeSecureRelayUrl(__T3CODE_BUILD_RELAY_URL__) ?? "");
export const buildTimeClerkPublishableKey = readBuildTimeValue(
typeof __T3CODE_BUILD_CLERK_PUBLISHABLE_KEY__ === "undefined"
? undefined
: __T3CODE_BUILD_CLERK_PUBLISHABLE_KEY__,
);
export const buildTimeClerkCliOAuthClientId = readBuildTimeValue(
typeof __T3CODE_BUILD_CLERK_CLI_OAUTH_CLIENT_ID__ === "undefined"
? undefined
: __T3CODE_BUILD_CLERK_CLI_OAUTH_CLIENT_ID__,
);
export function makeRelayUrlConfig(fallback = buildTimeRelayUrl) {
const runtimeConfig = Config.nonEmptyString("T3CODE_RELAY_URL");
return (fallback ? runtimeConfig.pipe(Config.withDefault(fallback)) : runtimeConfig).pipe(
Config.mapOrFail(validateRelayUrl),
);
}
export const relayUrlConfig = makeRelayUrlConfig();
function makePublicValueConfig(name: string, fallback: string) {
const runtimeConfig = Config.nonEmptyString(name);
return (fallback ? runtimeConfig.pipe(Config.withDefault(fallback)) : runtimeConfig).pipe(
Config.map((value) => value.trim()),
);
}
export interface CloudCliOAuthConfig {
readonly authorizationEndpoint: string;
readonly tokenEndpoint: string;
readonly clientId: string;
readonly redirectUri: string;
readonly scopes: typeof CLOUD_CLI_OAUTH_SCOPES;
}
export function makeCloudCliOAuthConfig({
clerkPublishableKeyFallback = buildTimeClerkPublishableKey,
clerkCliOAuthClientIdFallback = buildTimeClerkCliOAuthClientId,
}: {
readonly clerkPublishableKeyFallback?: string;
readonly clerkCliOAuthClientIdFallback?: string;
} = {}) {
return Config.all({
clerkPublishableKey: makePublicValueConfig(
"T3CODE_CLERK_PUBLISHABLE_KEY",
clerkPublishableKeyFallback,
),
clientId: makePublicValueConfig(
"T3CODE_CLERK_CLI_OAUTH_CLIENT_ID",
clerkCliOAuthClientIdFallback,
),
}).pipe(
Config.map(({ clerkPublishableKey, clientId }) => {
const clerkFrontendApiUrl = clerkFrontendApiUrlFromPublishableKey(clerkPublishableKey);
return {
authorizationEndpoint: `${clerkFrontendApiUrl}/oauth/authorize`,
tokenEndpoint: `${clerkFrontendApiUrl}/oauth/token`,
clientId,
redirectUri: CLOUD_CLI_OAUTH_REDIRECT_URI,
scopes: CLOUD_CLI_OAUTH_SCOPES,
} satisfies CloudCliOAuthConfig;
}),
);
}
export const cloudCliOAuthConfig = makeCloudCliOAuthConfig();
export const hasCloudPublicConfig = Boolean(
(normalizeSecureRelayUrl(process.env.T3CODE_RELAY_URL ?? "") ?? buildTimeRelayUrl) &&
(process.env.T3CODE_CLERK_PUBLISHABLE_KEY?.trim() || buildTimeClerkPublishableKey) &&
(process.env.T3CODE_CLERK_CLI_OAUTH_CLIENT_ID?.trim() || buildTimeClerkCliOAuthClientId),
);
+24
View File
@@ -132,6 +132,7 @@ import {
CloudManagedEndpointRuntime,
type CloudManagedEndpointRuntimeShape,
} from "./cloud/ManagedEndpointRuntime.ts";
import * as CloudCliTokenManager from "./cloud/CliTokenManager.ts";
import * as ProcessDiagnostics from "./diagnostics/ProcessDiagnostics.ts";
import * as ProcessResourceMonitor from "./diagnostics/ProcessResourceMonitor.ts";
import * as TraceDiagnostics from "./diagnostics/TraceDiagnostics.ts";
@@ -361,6 +362,7 @@ const buildAppUnderTest = (options?: {
repositoryIdentityResolver?: Partial<RepositoryIdentityResolverShape>;
cloudManagedEndpointRuntime?: Partial<CloudManagedEndpointRuntimeShape>;
relayClient?: Partial<RelayClient.RelayClientShape>;
cloudCliTokenManager?: Partial<CloudCliTokenManager.CloudCliTokenManagerShape>;
};
}) =>
Effect.gen(function* () {
@@ -778,6 +780,15 @@ const buildAppUnderTest = (options?: {
}),
),
),
Layer.provide(
Layer.mock(CloudCliTokenManager.CloudCliTokenManager)({
get: Effect.die(new Error("Unexpected T3 Cloud CLI authorization request.")),
getExisting: Effect.succeed(Option.none()),
hasCredential: Effect.succeed(false),
clear: Effect.void,
...options?.layers?.cloudCliTokenManager,
}),
),
Layer.provideMerge(makeAuthTestLayer()),
Layer.provideMerge(ServerSecretStore.layer),
Layer.provide(workspaceAndProjectServicesLayer),
@@ -2269,6 +2280,19 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
);
it.effect("does not expose internal cloud reconciliation over HTTP", () =>
Effect.gen(function* () {
yield* buildAppUnderTest();
const reconcileUrl = yield* getHttpServerUrl("/api/cloud/reconcile");
const response = yield* fetchEffect(reconcileUrl, {
method: "POST",
});
assert.equal(response.status, 404);
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
);
it.effect("unlinks local cloud state and disables the managed endpoint runtime", () =>
Effect.gen(function* () {
const appliedRuntimeConfigs: Array<unknown> = [];
+32 -2
View File
@@ -45,6 +45,7 @@ import { ProviderCommandReactorLive } from "./orchestration/Layers/ProviderComma
import { CheckpointReactorLive } from "./orchestration/Layers/CheckpointReactor.ts";
import { ThreadDeletionReactorLive } from "./orchestration/Layers/ThreadDeletionReactor.ts";
import * as AgentAwarenessRelay from "./relay/AgentAwarenessRelay.ts";
import { hasCloudPublicConfig } from "./cloud/publicConfig.ts";
import { ProviderRegistryLive } from "./provider/Layers/ProviderRegistry.ts";
import { ServerSettingsLive } from "./serverSettings.ts";
import { ProjectFaviconResolverLive } from "./project/Layers/ProjectFaviconResolver.ts";
@@ -68,8 +69,10 @@ import { ServerEnvironmentLive } from "./environment/Layers/ServerEnvironment.ts
import { authHttpApiLayer, environmentAuthenticatedAuthLayer } from "./auth/http.ts";
import * as ServerSecretStore from "./auth/ServerSecretStore.ts";
import * as EnvironmentAuth from "./auth/EnvironmentAuth.ts";
import { cloudHttpApiLayer } from "./cloud/http.ts";
import { cloudHttpApiLayer, reconcileDesiredCloudLink } from "./cloud/http.ts";
import * as CloudManagedEndpointRuntime from "./cloud/ManagedEndpointRuntime.ts";
import * as CloudCliTokenManager from "./cloud/CliTokenManager.ts";
import * as CloudCliState from "./cloud/CliState.ts";
import * as ProcessDiagnostics from "./diagnostics/ProcessDiagnostics.ts";
import * as ProcessResourceMonitor from "./diagnostics/ProcessResourceMonitor.ts";
import * as TraceDiagnostics from "./diagnostics/TraceDiagnostics.ts";
@@ -292,7 +295,12 @@ const RuntimeCoreDependenciesLive = ReactorLayerLive.pipe(
Layer.provideMerge(ServerEnvironmentLive),
Layer.provideMerge(AuthLayerLive),
Layer.provideMerge(ServerSecretStore.layer),
Layer.provideMerge(CloudManagedEndpointRuntimeLive),
Layer.provideMerge(
Layer.mergeAll(
CloudCliTokenManager.layer.pipe(Layer.provide(ServerSecretStore.layer)),
CloudManagedEndpointRuntimeLive,
),
),
);
const RuntimeDependenciesLive = RuntimeCoreDependenciesLive.pipe(
@@ -410,6 +418,27 @@ export const makeServerLayer = Layer.unwrap(
),
)
: Layer.empty;
const cloudDesiredLinkReconcileLayer = Layer.effectDiscard(
Effect.gen(function* () {
if (!hasCloudPublicConfig) return;
if (!(yield* CloudCliState.readCliDesiredCloudLink)) return;
const server = yield* HttpServer.HttpServer;
const address = server.address;
if (typeof address === "string" || !("port" in address)) return;
yield* Effect.forkScoped(
Effect.sleep("250 millis").pipe(
Effect.andThen(reconcileDesiredCloudLink(`http://127.0.0.1:${address.port}`)),
Effect.retry({ times: 4 }),
Effect.tap(() => Effect.logInfo("T3 Cloud desired link reconciled on startup")),
Effect.catch((cause) =>
Effect.logWarning("Failed to reconcile T3 Cloud desired link on startup", {
cause,
}),
),
),
);
}),
);
const serverApplicationLayer = Layer.mergeAll(
HttpRouter.serve(makeRoutesLayer, {
@@ -418,6 +447,7 @@ export const makeServerLayer = Layer.unwrap(
httpListeningLayer,
runtimeStateLayer,
tailscaleServeLayer,
cloudDesiredLinkReconcileLayer,
);
return serverApplicationLayer.pipe(
+12
View File
@@ -2,6 +2,7 @@ import "vite-plus/test/config";
import { defineConfig, mergeConfig } from "vite-plus";
import baseConfig from "../../vite.config.ts";
import { loadRepoEnv } from "../../scripts/lib/public-config.ts";
const bundledPackagePrefixes = [
"@pierre/diffs",
@@ -14,6 +15,8 @@ export function shouldBundleCliDependency(id: string): boolean {
return bundledPackagePrefixes.some((prefix) => id.startsWith(prefix));
}
const repoEnv = loadRepoEnv();
export default mergeConfig(
baseConfig,
defineConfig({
@@ -38,6 +41,15 @@ export default mergeConfig(
banner: {
js: "#!/usr/bin/env node\n",
},
define: {
__T3CODE_BUILD_RELAY_URL__: JSON.stringify(repoEnv.T3CODE_RELAY_URL?.trim() ?? ""),
__T3CODE_BUILD_CLERK_PUBLISHABLE_KEY__: JSON.stringify(
repoEnv.T3CODE_CLERK_PUBLISHABLE_KEY?.trim() ?? "",
),
__T3CODE_BUILD_CLERK_CLI_OAUTH_CLIENT_ID__: JSON.stringify(
repoEnv.T3CODE_CLERK_CLI_OAUTH_CLIENT_ID?.trim() ?? "",
),
},
},
test: {
// The server suite exercises sqlite, git, temp worktrees, and orchestration
+37 -3
View File
@@ -5,8 +5,17 @@ import {
InternalClerkProvider,
} from "@clerk/react/internal";
import type { ClerkProviderProps } from "@clerk/react";
import {
clerkFrontendApiHostnameFromPublishableKey,
isAllowedClerkFrontendApiHostname,
} from "@t3tools/shared/relayAuth";
import React, { useEffect, useState } from "react";
import {
makeDesktopClerkExternalAccountAdapter,
type DesktopClerkUser,
} from "./desktopClerkExternalAccounts";
type DesktopClerkUiCtor = NonNullable<Window["__internal_ClerkUICtor"]>;
interface ClerkFrontendApiRequest {
@@ -54,6 +63,8 @@ interface DesktopClerkProviderProps {
let desktopClerk: Clerk | null = null;
let desktopClerkFetchInstalled = false;
let desktopClerkUiLoad: Promise<DesktopClerkUiCtor> | null = null;
let desktopClerkFrontendApiHostname: string | null = null;
let desktopClerkExternalAccountCleanup: (() => void) | null = null;
const isNativeRequestClerk = (value: unknown): value is NativeRequestClerk => {
if (typeof value !== "object" || value === null) return false;
@@ -82,7 +93,7 @@ const clearStoredClientJwt = (): Promise<void> =>
const isClerkFrontendApiUrl = (url: URL): boolean =>
url.protocol === "https:" &&
(url.hostname.endsWith(".clerk.accounts.dev") || url.hostname.endsWith(".clerk.accounts.com"));
isAllowedClerkFrontendApiHostname(url.hostname, desktopClerkFrontendApiHostname);
const headersToRecord = (headers: Headers): Record<string, string> => {
const record: Record<string, string> = {};
@@ -92,7 +103,8 @@ const headersToRecord = (headers: Headers): Record<string, string> => {
return record;
};
function installDesktopClerkFetchProxy(): void {
function installDesktopClerkFetchProxy(publishableKey: string): void {
desktopClerkFrontendApiHostname = clerkFrontendApiHostnameFromPublishableKey(publishableKey);
if (desktopClerkFetchInstalled) return;
const bridge = window.desktopBridge;
if (!bridge) return;
@@ -125,6 +137,25 @@ function installDesktopClerkFetchProxy(): void {
desktopClerkFetchInstalled = true;
}
function installDesktopClerkExternalAccounts(clerk: Clerk): void {
desktopClerkExternalAccountCleanup?.();
desktopClerkExternalAccountCleanup = null;
const bridge = window.desktopBridge;
if (!bridge) return;
const adapter = makeDesktopClerkExternalAccountAdapter({ bridge });
const unsubscribe = clerk.addListener(({ user }) => {
if (user) {
adapter.installUser(user as DesktopClerkUser);
}
});
desktopClerkExternalAccountCleanup = () => {
unsubscribe();
adapter.dispose();
};
}
function loadDesktopClerkUi(publishableKey: string): Promise<DesktopClerkUiCtor> {
if (window.__internal_ClerkUICtor) {
return Promise.resolve(window.__internal_ClerkUICtor);
@@ -187,11 +218,13 @@ function loadDesktopClerkUi(publishableKey: string): Promise<DesktopClerkUiCtor>
}
function getDesktopClerkInstance(publishableKey: string): Clerk {
installDesktopClerkFetchProxy();
installDesktopClerkFetchProxy(publishableKey);
const hasKeyChanged = desktopClerk !== null && desktopClerk.publishableKey !== publishableKey;
if (hasKeyChanged) {
void clearStoredClientJwt();
desktopClerkExternalAccountCleanup?.();
desktopClerkExternalAccountCleanup = null;
desktopClerk = null;
}
@@ -200,6 +233,7 @@ function getDesktopClerkInstance(publishableKey: string): Clerk {
}
const nextClerk = new Clerk(publishableKey);
installDesktopClerkExternalAccounts(nextClerk);
if (!isNativeRequestClerk(nextClerk)) {
desktopClerk = nextClerk;
return nextClerk;
@@ -0,0 +1,78 @@
import { describe, expect, it, vi } from "vitest";
import {
makeDesktopClerkExternalAccountAdapter,
type DesktopClerkUser,
} from "./desktopClerkExternalAccounts";
describe("desktop Clerk external account adapter", () => {
it("replaces renderer redirects with native callbacks and reloads the user on return", async () => {
const callbacks: ((rawUrl: string) => void)[] = [];
const callbackCleanup = vi.fn();
const bridge = {
createCloudAuthRequest: vi
.fn()
.mockResolvedValueOnce("t3code://auth/callback?t3_state=add")
.mockResolvedValueOnce("t3code://auth/callback?t3_state=reconnect"),
onCloudAuthCallback: vi.fn((listener: (rawUrl: string) => void) => {
callbacks.push(listener);
return callbackCleanup;
}),
};
const reauthorize = vi.fn(async (_params: Record<string, unknown>) => account);
const account = { reauthorize };
const createExternalAccount = vi.fn(async (_params: Record<string, unknown>) => account);
const reload = vi.fn(async () => undefined);
const user = {
externalAccounts: [],
createExternalAccount,
reload,
} satisfies DesktopClerkUser;
const adapter = makeDesktopClerkExternalAccountAdapter({ bridge });
adapter.installUser(user);
await user.createExternalAccount({
redirectUrl: "http://127.0.0.1:3773/?__clerk_modal_state=state",
strategy: "oauth_microsoft",
});
expect(createExternalAccount).toHaveBeenCalledWith({
redirectUrl: "t3code://auth/callback?t3_state=add",
strategy: "oauth_microsoft",
});
callbacks[0]?.("t3code://auth/callback?t3_state=add");
await Promise.resolve();
expect(reload).toHaveBeenCalledOnce();
await account.reauthorize({
redirectUrl: "http://127.0.0.1:3773/?__clerk_modal_state=state",
});
expect(reauthorize).toHaveBeenCalledWith({
redirectUrl: "t3code://auth/callback?t3_state=reconnect",
});
});
it("cleans up the pending callback when Clerk rejects account creation", async () => {
const callbackCleanup = vi.fn();
const bridge = {
createCloudAuthRequest: vi.fn().mockResolvedValue("t3code://auth/callback?t3_state=failed"),
onCloudAuthCallback: vi.fn(() => callbackCleanup),
};
const createError = new Error("oauth provider unavailable");
const user = {
externalAccounts: [],
createExternalAccount: vi.fn(async (_params: Record<string, unknown>) => {
throw createError;
}),
reload: vi.fn(async () => undefined),
} satisfies DesktopClerkUser;
const adapter = makeDesktopClerkExternalAccountAdapter({ bridge });
adapter.installUser(user);
await expect(user.createExternalAccount({ strategy: "oauth_microsoft" })).rejects.toBe(
createError,
);
expect(callbackCleanup).toHaveBeenCalledOnce();
});
});
@@ -0,0 +1,112 @@
interface DesktopClerkExternalAccountParams {
readonly redirectUrl?: string;
readonly [key: string]: unknown;
}
interface DesktopClerkExternalAccount {
reauthorize: (params: DesktopClerkExternalAccountParams) => Promise<DesktopClerkExternalAccount>;
}
interface DesktopClerkUser {
readonly externalAccounts: readonly DesktopClerkExternalAccount[];
createExternalAccount: (
params: DesktopClerkExternalAccountParams,
) => Promise<DesktopClerkExternalAccount>;
reload: () => Promise<unknown>;
}
interface DesktopClerkExternalAccountBridge {
readonly createCloudAuthRequest: () => Promise<string>;
readonly onCloudAuthCallback: (listener: (rawUrl: string) => void) => () => void;
}
interface DesktopClerkExternalAccountAdapter {
readonly dispose: () => void;
readonly installUser: (user: DesktopClerkUser) => void;
}
interface MakeDesktopClerkExternalAccountAdapterInput {
readonly bridge: DesktopClerkExternalAccountBridge;
readonly reportError?: (message: string, error: unknown) => void;
}
// Clerk's profile component uses window.location.href as the OAuth callback and navigates the
// current window to the provider. Keep the upstream component intact while adapting its resource
// calls to the native callback bridge:
// https://github.com/clerk/javascript/blob/52861184477bee99c71552000311a289e91d3b59/packages/ui/src/components/UserProfile/ConnectedAccountsMenu.tsx
// https://github.com/clerk/javascript/blob/52861184477bee99c71552000311a289e91d3b59/packages/ui/src/components/UserProfile/ConnectedAccountsSection.tsx
export function makeDesktopClerkExternalAccountAdapter({
bridge,
reportError = console.error,
}: MakeDesktopClerkExternalAccountAdapterInput): DesktopClerkExternalAccountAdapter {
const installedAccounts = new WeakSet<object>();
const installedUsers = new WeakSet<object>();
let callbackGeneration = 0;
let callbackCleanup: (() => void) | null = null;
const clearCallback = () => {
callbackGeneration += 1;
callbackCleanup?.();
callbackCleanup = null;
};
const createRedirectUrl = async (user: DesktopClerkUser): Promise<string> => {
clearCallback();
const redirectUrl = await bridge.createCloudAuthRequest();
const generation = callbackGeneration;
callbackCleanup = bridge.onCloudAuthCallback(() => {
if (generation !== callbackGeneration) return;
clearCallback();
void user.reload().catch((error: unknown) => {
reportError("Failed to reload Clerk after desktop account linking.", error);
});
});
return redirectUrl;
};
const installAccount = (user: DesktopClerkUser, account: DesktopClerkExternalAccount): void => {
if (installedAccounts.has(account)) return;
installedAccounts.add(account);
const reauthorize = account.reauthorize.bind(account);
account.reauthorize = async (params) => {
const redirectUrl = await createRedirectUrl(user);
try {
const nextAccount = await reauthorize({ ...params, redirectUrl });
installAccount(user, nextAccount);
return nextAccount;
} catch (error) {
clearCallback();
throw error;
}
};
};
const installUser = (user: DesktopClerkUser): void => {
for (const account of user.externalAccounts) {
installAccount(user, account);
}
if (installedUsers.has(user)) return;
installedUsers.add(user);
const createExternalAccount = user.createExternalAccount.bind(user);
user.createExternalAccount = async (params) => {
const redirectUrl = await createRedirectUrl(user);
try {
const account = await createExternalAccount({ ...params, redirectUrl });
installAccount(user, account);
return account;
} catch (error) {
clearCallback();
throw error;
}
};
};
return {
dispose: clearCallback,
installUser,
};
}
export type { DesktopClerkExternalAccountAdapter, DesktopClerkUser };
+66 -8
View File
@@ -12,6 +12,7 @@ or `.env.local` file:
```dotenv
T3CODE_CLERK_PUBLISHABLE_KEY=<publishable key>
T3CODE_CLERK_JWT_TEMPLATE=<JWT template name>
T3CODE_CLERK_CLI_OAUTH_CLIENT_ID=<public OAuth application client ID>
T3CODE_RELAY_URL=https://relay.example.com
```
@@ -25,14 +26,19 @@ Configuration precedence is:
2. Repository-root `.env.local`.
3. Repository-root `.env`.
The Clerk publishable key, JWT template name, and relay URL are public identifiers, not secrets.
Web, desktop, and mobile builds statically inject them during their build step. A built artifact
does not need an environment file at runtime. CI release builds should set
`T3CODE_CLERK_PUBLISHABLE_KEY`, `T3CODE_CLERK_JWT_TEMPLATE`, and `T3CODE_RELAY_URL` before building.
EAS preview and production builds should define the same client-facing values in their EAS
The Clerk publishable key, JWT template name, CLI OAuth client ID, and relay URL are public
identifiers, not secrets.
Web, desktop, mobile, and bundled server builds statically inject the values they consume during
their build step. A built artifact does not need an environment file at runtime. CI release builds
should set `T3CODE_CLERK_PUBLISHABLE_KEY`, `T3CODE_CLERK_JWT_TEMPLATE`,
`T3CODE_CLERK_CLI_OAUTH_CLIENT_ID`, and `T3CODE_RELAY_URL` before building. EAS preview and
production builds only need the Clerk publishable key, JWT template name, and relay URL in their EAS
environment.
When any client-facing public value is absent, cloud UI is omitted.
When any client-facing public value is absent, cloud UI is omitted. When the CLI public values are
absent, the `t3 cloud` CLI command group is omitted. The bundled server still accepts runtime
overrides for self-hosted or operator-managed
deployments.
For a hosted relay deployment, copy `infra/relay/.env.example` to `infra/relay/.env`. The relay
deployment reads `RELAY_DOMAIN`, `RELAY_ZONE_NAME`, `CLERK_PUBLISHABLE_KEY`, and
@@ -45,7 +51,55 @@ environment or commit it to the repository.
The `prod` Alchemy stage owns the retained PlanetScale database. Non-production stages reference
that database and provision isolated PlanetScale branches, so deploy `prod` before creating a
preview or developer stage.
personal developer stage.
## Headless CLI OAuth Application
The `t3 cloud` commands authorize a headless environment with a separate Clerk OAuth application.
This uses an OAuth public client with PKCE, so the CLI stores no client secret.
In **Clerk Dashboard > OAuth applications**:
1. Create an OAuth application for the T3 CLI.
2. Enable the **Public** option so authorization-code exchange uses PKCE.
3. Add `http://127.0.0.1:34338/callback` as an allowed redirect URI.
4. Enable the `openid`, `profile`, and `email` scopes.
5. Set `T3CODE_CLERK_CLI_OAUTH_CLIENT_ID` in the repository-root `.env` file and release build
environment to the generated public client ID.
The CLI derives Clerk's frontend API URL from the publishable key and calls Clerk's
`/oauth/authorize` and `/oauth/token` endpoints directly. The relay is not involved in the OAuth
handshake; it only validates the issued Clerk bearer token when the CLI manages an environment link.
The CLI supports these headless operations:
```sh
t3 cloud login
t3 cloud link
t3 cloud status
t3 cloud unlink
t3 cloud logout
t3 serve
```
`t3 cloud login` opens the Clerk authorization flow and stores the CLI credential without enabling
cloud exposure. `t3 cloud link` installs the pinned managed `cloudflared` binary when needed,
authorizes when needed, and records durable intent to expose the environment. It works without a
running T3 server. The next `t3 serve` or `t3 start` reconciles the relay link and launches the
managed tunnel. `t3 cloud unlink` records disabled intent immediately, stops a reachable running
connector, and attempts to revoke the relay-side environment record. It retains the stored CLI
authorization so `t3 cloud link` can re-enable exposure without another browser flow. `t3 cloud
logout` performs the same cleanup and removes the stored CLI authorization.
The current OAuth callback listener binds to loopback port `34338`. When running the CLI over SSH,
forward that port before running `t3 cloud login` or `t3 cloud link`:
```sh
ssh -L 34338:127.0.0.1:34338 <host>
```
A relay-hosted callback broker can remove this port-forward requirement later without changing the
stored PKCE token model.
## JWT Template
@@ -74,7 +128,11 @@ t3code://auth/callback
```
The first entry is for local desktop development. The second is for packaged desktop builds.
The app also adds a request-scoped `t3_state` query parameter and validates it on callback.
The app also adds a request-scoped `t3_state` query parameter and validates it on callback. Initial
sign-in and linked-account OAuth flows both return through this bridge. The desktop provider keeps
Clerk's stock profile component, replaces its renderer-page callback with the custom-scheme callback,
and opens the provider URL in the system browser. Do not add the local renderer URL as an OAuth
redirect: an external browser cannot use it to reopen the packaged app.
The current mobile UI uses Clerk's native authentication view. If a future mobile browser OAuth
flow uses a custom redirect URI, add that exact URI to the same allowlist.
File diff suppressed because it is too large. Load diff
+26
View File
@@ -0,0 +1,26 @@
import { describe, expect, it } from "vitest";
import {
clerkFrontendApiHostnameFromPublishableKey,
isAllowedClerkFrontendApiHostname,
} from "./relayAuth.ts";
const clerkPublishableKey = (hostname: string): string => `pk_test_${btoa(`${hostname}$`)}`;
describe("Clerk relay auth", () => {
it("derives a custom Frontend API hostname from a Clerk publishable key", () => {
expect(clerkFrontendApiHostnameFromPublishableKey(clerkPublishableKey("clerk.t3.codes"))).toBe(
"clerk.t3.codes",
);
});
it("allows standard Clerk hosts and an exact configured custom hostname", () => {
expect(isAllowedClerkFrontendApiHostname("example.clerk.accounts.dev", null)).toBe(true);
expect(isAllowedClerkFrontendApiHostname("example.clerk.accounts.com", null)).toBe(true);
expect(isAllowedClerkFrontendApiHostname("clerk.t3.codes", "clerk.t3.codes")).toBe(true);
expect(isAllowedClerkFrontendApiHostname("attacker.example", "clerk.t3.codes")).toBe(false);
expect(isAllowedClerkFrontendApiHostname("nested.clerk.t3.codes", "clerk.t3.codes")).toBe(
false,
);
});
});
+24
View File
@@ -1,3 +1,27 @@
export function clerkFrontendApiUrlFromPublishableKey(publishableKey: string): string {
const encodedFrontendApi = publishableKey.split("_").slice(2).join("_");
const frontendApi = globalThis.atob(encodedFrontendApi).replace(/\$$/u, "");
if (frontendApi.length === 0 || frontendApi.includes("/")) {
throw new Error("Invalid Clerk publishable key.");
}
return `https://${frontendApi}`;
}
export function clerkFrontendApiHostnameFromPublishableKey(publishableKey: string): string {
return new URL(clerkFrontendApiUrlFromPublishableKey(publishableKey)).hostname;
}
export function isAllowedClerkFrontendApiHostname(
hostname: string,
configuredHostname: string | null,
): boolean {
return (
hostname.endsWith(".clerk.accounts.dev") ||
hostname.endsWith(".clerk.accounts.com") ||
hostname === configuredHostname
);
}
export function relayClerkTokenOptions(template: string) {
return {
template,
+7 -2
View File
@@ -19,6 +19,7 @@ describe("loadRepoEnv", () => {
const env = loadRepoEnv({ baseEnv: {}, repoRoot: makeTemporaryDirectory() });
expect(env.T3CODE_CLERK_PUBLISHABLE_KEY).toBeUndefined();
expect(env.T3CODE_CLERK_CLI_OAUTH_CLIENT_ID).toBeUndefined();
expect(env.VITE_CLERK_PUBLISHABLE_KEY).toBeUndefined();
expect(env.EXPO_PUBLIC_CLERK_PUBLISHABLE_KEY).toBeUndefined();
expect(env.T3CODE_CLERK_JWT_TEMPLATE).toBeUndefined();
@@ -32,11 +33,11 @@ describe("loadRepoEnv", () => {
const repoRoot = makeTemporaryDirectory();
writeFileSync(
join(repoRoot, ".env"),
"T3CODE_CLERK_PUBLISHABLE_KEY=pk_root\nT3CODE_CLERK_JWT_TEMPLATE=template_root\nT3CODE_RELAY_URL=https://root.example.test\n",
"T3CODE_CLERK_PUBLISHABLE_KEY=pk_root\nT3CODE_CLERK_JWT_TEMPLATE=template_root\nT3CODE_CLERK_CLI_OAUTH_CLIENT_ID=oauth_root\nT3CODE_RELAY_URL=https://root.example.test\n",
);
writeFileSync(
join(repoRoot, ".env.local"),
"T3CODE_CLERK_PUBLISHABLE_KEY=pk_local\nT3CODE_CLERK_JWT_TEMPLATE=template_local\nT3CODE_RELAY_URL=https://local.example.test\n",
"T3CODE_CLERK_PUBLISHABLE_KEY=pk_local\nT3CODE_CLERK_JWT_TEMPLATE=template_local\nT3CODE_CLERK_CLI_OAUTH_CLIENT_ID=oauth_local\nT3CODE_RELAY_URL=https://local.example.test\n",
);
expect(loadRepoEnv({ baseEnv: {}, repoRoot }).T3CODE_RELAY_URL).toBe(
@@ -47,12 +48,14 @@ describe("loadRepoEnv", () => {
baseEnv: {
T3CODE_CLERK_PUBLISHABLE_KEY: "pk_ci",
T3CODE_CLERK_JWT_TEMPLATE: "template_ci",
T3CODE_CLERK_CLI_OAUTH_CLIENT_ID: "oauth_ci",
T3CODE_RELAY_URL: "https://ci.example.test",
},
repoRoot,
}),
).toMatchObject({
T3CODE_CLERK_PUBLISHABLE_KEY: "pk_ci",
T3CODE_CLERK_CLI_OAUTH_CLIENT_ID: "oauth_ci",
VITE_CLERK_PUBLISHABLE_KEY: "pk_ci",
EXPO_PUBLIC_CLERK_PUBLISHABLE_KEY: "pk_ci",
T3CODE_CLERK_JWT_TEMPLATE: "template_ci",
@@ -68,11 +71,13 @@ describe("loadRepoEnv", () => {
resolvePublicConfig({
VITE_CLERK_PUBLISHABLE_KEY: "pk_legacy",
VITE_CLERK_JWT_TEMPLATE: "template_legacy",
T3CODE_CLERK_CLI_OAUTH_CLIENT_ID: "oauth_canonical",
VITE_T3CODE_RELAY_URL: "https://legacy.example.test",
}),
).toEqual({
clerkPublishableKey: "pk_legacy",
clerkJwtTemplate: "template_legacy",
clerkCliOAuthClientId: "oauth_canonical",
relayUrl: "https://legacy.example.test",
});
});
+7
View File
@@ -7,6 +7,7 @@ import * as NodeUtil from "node:util";
export interface T3CodePublicConfig {
readonly clerkPublishableKey: string | undefined;
readonly clerkJwtTemplate: string | undefined;
readonly clerkCliOAuthClientId: string | undefined;
readonly relayUrl: string | undefined;
}
@@ -45,6 +46,11 @@ export function loadRepoEnv({
EXPO_PUBLIC_CLERK_JWT_TEMPLATE: config.clerkJwtTemplate,
}
: {}),
...(config.clerkCliOAuthClientId
? {
T3CODE_CLERK_CLI_OAUTH_CLIENT_ID: config.clerkCliOAuthClientId,
}
: {}),
...(config.relayUrl
? {
T3CODE_RELAY_URL: config.relayUrl,
@@ -68,6 +74,7 @@ export function resolvePublicConfig(...sources: readonly Environment[]): T3CodeP
"VITE_CLERK_JWT_TEMPLATE",
"EXPO_PUBLIC_CLERK_JWT_TEMPLATE",
),
clerkCliOAuthClientId: firstNonEmpty(sources, "T3CODE_CLERK_CLI_OAUTH_CLIENT_ID"),
relayUrl: firstNonEmpty(sources, "T3CODE_RELAY_URL", "VITE_T3CODE_RELAY_URL"),
};
}