feat: add headless t3 connect setup for SSH hosts (#3749)

Co-authored-by: Claude Fable 5 <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
Co-authored-by: codex <[email protected]>
This commit is contained in:
authored and GitHub committed 2026-07-19 18:59:23 +02:00
1 parent 53e3c98a55
commit 7a820abfdd
35 files changed
+3018 -145

No files matched your search

+69
View File
@@ -0,0 +1,69 @@
import { afterEach, describe, expect, it, vi } from "vite-plus/test";
import {
buildConnectCliClerkAuthorizeUrl,
hasConnectCliAuthConfig,
readConnectCliCallbackResult,
} from "./connectCliAuth";
// Any pk_test_* key decodes to <base64 hostname>.clerk.accounts.dev.
const TEST_PUBLISHABLE_KEY = `pk_test_${btoa("witty-mole-42.clerk.accounts.dev$")}`;
describe("connectCliAuth", () => {
afterEach(() => {
vi.unstubAllEnvs();
});
it("requires both the publishable key and the CLI OAuth client id", () => {
vi.stubEnv("VITE_CLERK_PUBLISHABLE_KEY", TEST_PUBLISHABLE_KEY);
vi.stubEnv("VITE_CLERK_JWT_TEMPLATE", "t3-relay");
vi.stubEnv("VITE_T3CODE_RELAY_URL", "https://relay.example.com");
expect(hasConnectCliAuthConfig()).toBe(false);
vi.stubEnv("VITE_CLERK_CLI_OAUTH_CLIENT_ID", "oauthapp_123");
expect(hasConnectCliAuthConfig()).toBe(true);
});
it("builds the Clerk authorize URL with the configured hosted origin's callback", () => {
vi.stubEnv("VITE_CLERK_PUBLISHABLE_KEY", TEST_PUBLISHABLE_KEY);
vi.stubEnv("VITE_CLERK_CLI_OAUTH_CLIENT_ID", "oauthapp_123");
vi.stubEnv("VITE_HOSTED_APP_URL", "https://nightly.app.t3.codes");
const authorizeUrl = buildConnectCliClerkAuthorizeUrl({
state: "state-1",
challenge: "challenge-1",
});
expect(authorizeUrl).not.toBeNull();
const url = new URL(authorizeUrl!);
expect(url.hostname).toBe("witty-mole-42.clerk.accounts.dev");
expect(url.pathname).toBe("/oauth/authorize");
expect(url.searchParams.get("redirect_uri")).toBe(
"https://nightly.app.t3.codes/connect/callback",
);
expect(url.searchParams.get("state")).toBe("state-1");
expect(url.searchParams.get("code_challenge")).toBe("challenge-1");
expect(url.searchParams.get("code_challenge_method")).toBe("S256");
});
it("returns null when the CLI OAuth client id is not configured", () => {
vi.stubEnv("VITE_CLERK_PUBLISHABLE_KEY", TEST_PUBLISHABLE_KEY);
expect(
buildConnectCliClerkAuthorizeUrl({ state: "state-1", challenge: "challenge-1" }),
).toBeNull();
});
it("reads the code and state Clerk echoes back to the callback", () => {
expect(
readConnectCliCallbackResult(
new URL("https://app.t3.codes/connect/callback?code=abc&state=state-1"),
),
).toEqual({ code: "abc", state: "state-1" });
expect(
readConnectCliCallbackResult(new URL("https://app.t3.codes/connect/callback?code=abc")),
).toBeNull();
expect(
readConnectCliCallbackResult(new URL("https://app.t3.codes/connect/callback?state=s")),
).toBeNull();
});
});
+91
View File
@@ -0,0 +1,91 @@
import {
buildConnectClerkAuthorizeUrl,
connectCallbackUrl,
CONNECT_OAUTH_SCOPES,
type ConnectAuthorizeRequest,
} from "@t3tools/shared/connectAuth";
import { clerkFrontendApiUrlFromPublishableKey } from "@t3tools/shared/relayAuth";
import { configuredHostedAppUrl, isHostedStaticApp } from "../hostedPairing";
import { hasCloudPublicConfig, resolveCloudPublicConfig, trimNonEmpty } from "./publicConfig";
const CONNECT_CLI_AUTH_STATE_STORAGE_KEY = "t3code-connect-cli-auth-state";
export function resolveConnectCliOAuthClientId(): string | null {
return trimNonEmpty(import.meta.env.VITE_CLERK_CLI_OAUTH_CLIENT_ID as string | undefined);
}
export function hasConnectCliAuthConfig(): boolean {
return Boolean(
resolveCloudPublicConfig().clerkPublishableKey && resolveConnectCliOAuthClientId(),
);
}
/**
* Gate for the /connect routes: the CLI handshake only exists on the hosted
* deployment (the same bundle ships inside local instances) and needs the
* Clerk CLI OAuth client configured at build time.
*/
export function connectCliAuthRoutesEnabled(): boolean {
return isHostedStaticApp() && hasCloudPublicConfig() && hasConnectCliAuthConfig();
}
/**
* Builds the Clerk authorize URL for a CLI-initiated connect request. The
* state is mirrored into sessionStorage so the callback page can verify the
* response matches a request this browser actually started.
*/
export function buildConnectCliClerkAuthorizeUrl(request: ConnectAuthorizeRequest): string | null {
const { clerkPublishableKey } = resolveCloudPublicConfig();
const clientId = resolveConnectCliOAuthClientId();
if (!clerkPublishableKey || !clientId) {
return null;
}
return buildConnectClerkAuthorizeUrl({
authorizationEndpoint: `${clerkFrontendApiUrlFromPublishableKey(clerkPublishableKey)}/oauth/authorize`,
clientId,
redirectUri: connectCallbackUrl(configuredHostedAppUrl()),
scopes: CONNECT_OAUTH_SCOPES,
state: request.state,
challenge: request.challenge,
});
}
export function rememberConnectCliAuthState(state: string): void {
try {
window.sessionStorage.setItem(CONNECT_CLI_AUTH_STATE_STORAGE_KEY, state);
} catch {
// Session storage can be unavailable (e.g. blocked). The callback page
// then falls back to trusting the state Clerk echoed back.
}
}
/**
* Read-only on purpose: this runs during render, where a removal would be
* consumed by React's double-invoked/discarded renders (StrictMode) and
* silently disable the state check. The value is not a secret and is
* overwritten by the next /connect visit.
*/
export function readConnectCliAuthState(): string | null {
try {
return window.sessionStorage.getItem(CONNECT_CLI_AUTH_STATE_STORAGE_KEY);
} catch {
return null;
}
}
export interface ConnectCliCallbackResult {
readonly code: string;
readonly state: string;
}
export function readConnectCliCallbackResult(
url: URL = new URL(window.location.href),
): ConnectCliCallbackResult | null {
const code = url.searchParams.get("code")?.trim() ?? "";
const state = url.searchParams.get("state")?.trim() ?? "";
if (!code || !state) {
return null;
}
return { code, state };
}
+1 -1
View File
@@ -24,7 +24,7 @@ export interface CloudPublicConfig {
};
}
function trimNonEmpty(value: string | undefined): string | null {
export function trimNonEmpty(value: string | undefined): string | null {
return value?.trim() || null;
}
@@ -38,11 +38,15 @@ export function SidebarStageBackdrop({ variant }: { variant: SidebarStageBackdro
aria-hidden
className="sidebar-stage-backdrop pointer-events-none absolute inset-x-0 top-0 z-0 h-20 select-none overflow-hidden"
>
{variant === "nightly" ? <NightlySkyArt /> : <DevBlueprintArt />}
<StageBackdropArt variant={variant} />
</div>
);
}
export function StageBackdropArt({ variant }: { variant: SidebarStageBackdropVariant }) {
return variant === "nightly" ? <NightlySkyArt /> : <DevBlueprintArt />;
}
const NIGHTLY_STARS: ReadonlyArray<{
cx: number;
cy: number;
@@ -0,0 +1,44 @@
import type { ReactNode } from "react";
import { APP_DISPLAY_NAME, APP_STAGE_LABEL } from "../../branding";
import { resolveSidebarStageBackdropVariant, StageBackdropArt } from "../SidebarStageBackdrop";
/**
* Full-screen card for standalone auth pages, mirroring the pairing surface's
* treatment. Used by the CLI-connect authorize and callback surfaces.
*/
export function AuthSurfaceShell({ children }: { readonly children: ReactNode }) {
const stageVariant = resolveSidebarStageBackdropVariant(APP_STAGE_LABEL);
return (
<div className="relative flex min-h-screen items-center justify-center overflow-hidden bg-background px-4 py-10 text-foreground sm:px-6">
<div className="pointer-events-none absolute inset-0 opacity-80">
<div className="absolute inset-x-0 top-0 h-72 bg-[radial-gradient(48rem_20rem_at_top,color-mix(in_srgb,var(--color-blue-500)_12%,transparent),transparent)]" />
<div className="absolute inset-0 bg-[linear-gradient(145deg,color-mix(in_srgb,var(--background)_94%,var(--color-black))_0%,var(--background)_62%)]" />
</div>
<section className="relative w-full max-w-xl overflow-hidden rounded-2xl border border-border/80 bg-card/94 shadow-2xl shadow-black/20 backdrop-blur-md">
<header className="relative h-24 overflow-hidden bg-[linear-gradient(135deg,#1e61de,#17348e)] text-white">
{stageVariant ? (
<div className="absolute inset-0" aria-hidden>
<StageBackdropArt variant={stageVariant} />
</div>
) : (
<div
aria-hidden
className="absolute inset-0 bg-[radial-gradient(circle_at_75%_25%,rgba(136,204,255,0.5),transparent_38%),linear-gradient(135deg,#2468df,#172f82)]"
/>
)}
<div className="absolute inset-0 bg-[linear-gradient(to_bottom,transparent_20%,rgba(7,18,55,0.46)_100%)]" />
<div className="relative h-full p-5 sm:p-6">
<p className="text-[10px] font-semibold tracking-[0.2em] text-white/80 uppercase">
{APP_DISPLAY_NAME}
</p>
</div>
</header>
<div className="p-6 sm:p-8">{children}</div>
</section>
</div>
);
}
@@ -0,0 +1,188 @@
import { useAuth, useClerk, useUser } from "@clerk/react";
import { encodeConnectAuthCode, readConnectAuthorizeRequest } from "@t3tools/shared/connectAuth";
import { useEffect, useRef, useState } from "react";
import {
buildConnectCliClerkAuthorizeUrl,
readConnectCliAuthState,
readConnectCliCallbackResult,
rememberConnectCliAuthState,
} from "../../cloud/connectCliAuth";
import { useCopyToClipboard } from "../../hooks/useCopyToClipboard";
import { AuthSurfaceShell } from "../auth/AuthSurfaceShell";
import { Button } from "../ui/button";
function ConnectCliAuthMessage({
eyebrow,
title,
description,
}: {
readonly eyebrow?: string;
readonly title: string;
readonly description: string;
}) {
return (
<>
{eyebrow ? (
<p className="text-[10px] font-semibold tracking-[0.18em] text-blue-600 uppercase dark:text-blue-400">
{eyebrow}
</p>
) : null}
<h1 className="mt-2 text-2xl font-semibold tracking-tight sm:text-3xl">{title}</h1>
<p className="mt-2 text-sm leading-relaxed text-muted-foreground">{description}</p>
</>
);
}
const invalidLinkMessage = {
eyebrow: "Authorization request",
title: "This connect link is incomplete",
description:
"The link is missing its authorization request. Re-run `t3 connect` in your terminal and open the freshly printed URL.",
} as const;
/**
* /connect: the URL a headless CLI prints. Waits for a Clerk session, then
* forwards the CLI's PKCE request to Clerk's authorize endpoint.
*/
export function ConnectCliAuthorizeSurface() {
const [request] = useState(() => readConnectAuthorizeRequest(new URL(window.location.href)));
const clerk = useClerk();
const { isLoaded, isSignedIn } = useAuth();
const signInOpened = useRef(false);
const redirecting = useRef(false);
useEffect(() => {
if (!request || !isLoaded || redirecting.current) {
return;
}
if (!isSignedIn) {
if (!signInOpened.current) {
signInOpened.current = true;
clerk.openSignIn({ forceRedirectUrl: window.location.href });
}
return;
}
const authorizeUrl = buildConnectCliClerkAuthorizeUrl(request);
if (!authorizeUrl) {
return;
}
redirecting.current = true;
rememberConnectCliAuthState(request.state);
window.location.assign(authorizeUrl);
}, [clerk, isLoaded, isSignedIn, request]);
if (!request) {
return (
<AuthSurfaceShell>
<ConnectCliAuthMessage {...invalidLinkMessage} />
</AuthSurfaceShell>
);
}
return (
<AuthSurfaceShell>
<ConnectCliAuthMessage
eyebrow="Step 1 of 2 · Browser authorization"
title="Connecting your terminal"
description={
isSignedIn
? "Redirecting to authorize T3 Connect for your CLI…"
: "Sign in to continue authorizing T3 Connect for your CLI."
}
/>
{isLoaded && !isSignedIn ? (
<div className="mt-6">
<Button
type="button"
onClick={() => clerk.openSignIn({ forceRedirectUrl: window.location.href })}
>
Sign in
</Button>
</div>
) : null}
</AuthSurfaceShell>
);
}
/**
* /connect/callback: Clerk's redirect target. Shows the one-time code the
* user enters in the waiting terminal.
*/
export function ConnectCliCallbackSurface() {
const [result] = useState(readConnectCliCallbackResult);
const [expectedState] = useState(readConnectCliAuthState);
const { user } = useUser();
const { copyToClipboard, isCopied } = useCopyToClipboard({ target: "authentication code" });
if (!result) {
return (
<AuthSurfaceShell>
<ConnectCliAuthMessage
eyebrow="Step 2 of 2 · Terminal handoff"
title="Authorization did not complete"
description="No authorization code was returned. Re-run `t3 connect` in your terminal and try again."
/>
</AuthSurfaceShell>
);
}
// Fail closed: the legitimate callback always lands in the same browser
// that visited /connect (which recorded the state), so a missing or
// mismatched state means this page was reached some other way — the CSRF
// shape the state parameter exists to stop. Refuse to display a code.
if (expectedState === null || expectedState !== result.state) {
return (
<AuthSurfaceShell>
<ConnectCliAuthMessage
eyebrow="Step 2 of 2 · Terminal handoff"
title="This code belongs to a different request"
description="This authorization response does not match a connect request started in this browser. Re-run `t3 connect` in your terminal and open the freshly printed URL in this browser."
/>
</AuthSurfaceShell>
);
}
const accountLabel = user?.primaryEmailAddress?.emailAddress ?? user?.username ?? null;
const authCode = encodeConnectAuthCode(result);
return (
<AuthSurfaceShell>
<ConnectCliAuthMessage
eyebrow="Step 2 of 2 · Terminal handoff"
title="Almost connected"
description={
accountLabel
? `Enter this code in your waiting terminal to connect it as ${accountLabel}.`
: "Enter this code in your waiting terminal to finish connecting."
}
/>
<div className="mt-6 overflow-hidden rounded-xl border border-border/80 bg-background/65">
<div className="flex items-center justify-between border-b border-border/70 px-4 py-2.5">
<span className="text-[10px] font-semibold tracking-[0.16em] text-muted-foreground uppercase">
One-time authorization code
</span>
<span className="font-mono text-[10px] text-muted-foreground">expires shortly</span>
</div>
<code
className="block p-4 font-mono text-sm leading-relaxed break-all select-all"
data-testid="connect-auth-code"
>
{authCode}
</code>
</div>
<div className="mt-4 flex items-center gap-3">
<Button type="button" onClick={() => copyToClipboard(authCode)}>
{isCopied ? "Copied!" : "Copy authorization code"}
</Button>
</div>
<p className="mt-6 text-xs leading-relaxed text-muted-foreground">
Only enter this code in a terminal session you started yourself. Anyone holding it can link
their machine to your T3 Connect account while it is valid.
</p>
</AuthSurfaceShell>
);
}
+2 -2
View File
@@ -1,6 +1,6 @@
import { getPairingTokenFromUrl, setPairingTokenOnUrl } from "./pairingUrl";
import { DEFAULT_HOSTED_APP_URL } from "@t3tools/shared/connectAuth";
const DEFAULT_HOSTED_APP_URL = "https://app.t3.codes";
import { getPairingTokenFromUrl, setPairingTokenOnUrl } from "./pairingUrl";
export interface HostedPairingRequest {
readonly host: string;
+42
View File
@@ -11,6 +11,7 @@
import { Route as rootRouteImport } from './routes/__root'
import { Route as SettingsRouteImport } from './routes/settings'
import { Route as PairRouteImport } from './routes/pair'
import { Route as ConnectRouteImport } from './routes/connect'
import { Route as ChatRouteImport } from './routes/_chat'
import { Route as ChatIndexRouteImport } from './routes/_chat.index'
import { Route as SettingsSourceControlRouteImport } from './routes/settings.source-control'
@@ -20,6 +21,7 @@ import { Route as SettingsGeneralRouteImport } from './routes/settings.general'
import { Route as SettingsDiagnosticsRouteImport } from './routes/settings.diagnostics'
import { Route as SettingsConnectionsRouteImport } from './routes/settings.connections'
import { Route as SettingsArchivedRouteImport } from './routes/settings.archived'
import { Route as ConnectCallbackRouteImport } from './routes/connect_.callback'
import { Route as ChatDraftDraftIdRouteImport } from './routes/_chat.draft.$draftId'
import { Route as ChatEnvironmentIdThreadIdRouteImport } from './routes/_chat.$environmentId.$threadId'
@@ -33,6 +35,11 @@ const PairRoute = PairRouteImport.update({
path: '/pair',
getParentRoute: () => rootRouteImport,
} as any)
const ConnectRoute = ConnectRouteImport.update({
id: '/connect',
path: '/connect',
getParentRoute: () => rootRouteImport,
} as any)
const ChatRoute = ChatRouteImport.update({
id: '/_chat',
getParentRoute: () => rootRouteImport,
@@ -77,6 +84,11 @@ const SettingsArchivedRoute = SettingsArchivedRouteImport.update({
path: '/archived',
getParentRoute: () => SettingsRoute,
} as any)
const ConnectCallbackRoute = ConnectCallbackRouteImport.update({
id: '/connect_/callback',
path: '/connect/callback',
getParentRoute: () => rootRouteImport,
} as any)
const ChatDraftDraftIdRoute = ChatDraftDraftIdRouteImport.update({
id: '/draft/$draftId',
path: '/draft/$draftId',
@@ -91,8 +103,10 @@ const ChatEnvironmentIdThreadIdRoute =
export interface FileRoutesByFullPath {
'/': typeof ChatIndexRoute
'/connect': typeof ConnectRoute
'/pair': typeof PairRoute
'/settings': typeof SettingsRouteWithChildren
'/connect/callback': typeof ConnectCallbackRoute
'/settings/archived': typeof SettingsArchivedRoute
'/settings/connections': typeof SettingsConnectionsRoute
'/settings/diagnostics': typeof SettingsDiagnosticsRoute
@@ -104,8 +118,10 @@ export interface FileRoutesByFullPath {
'/draft/$draftId': typeof ChatDraftDraftIdRoute
}
export interface FileRoutesByTo {
'/connect': typeof ConnectRoute
'/pair': typeof PairRoute
'/settings': typeof SettingsRouteWithChildren
'/connect/callback': typeof ConnectCallbackRoute
'/settings/archived': typeof SettingsArchivedRoute
'/settings/connections': typeof SettingsConnectionsRoute
'/settings/diagnostics': typeof SettingsDiagnosticsRoute
@@ -120,8 +136,10 @@ export interface FileRoutesByTo {
export interface FileRoutesById {
__root__: typeof rootRouteImport
'/_chat': typeof ChatRouteWithChildren
'/connect': typeof ConnectRoute
'/pair': typeof PairRoute
'/settings': typeof SettingsRouteWithChildren
'/connect_/callback': typeof ConnectCallbackRoute
'/settings/archived': typeof SettingsArchivedRoute
'/settings/connections': typeof SettingsConnectionsRoute
'/settings/diagnostics': typeof SettingsDiagnosticsRoute
@@ -137,8 +155,10 @@ export interface FileRouteTypes {
fileRoutesByFullPath: FileRoutesByFullPath
fullPaths:
| '/'
| '/connect'
| '/pair'
| '/settings'
| '/connect/callback'
| '/settings/archived'
| '/settings/connections'
| '/settings/diagnostics'
@@ -150,8 +170,10 @@ export interface FileRouteTypes {
| '/draft/$draftId'
fileRoutesByTo: FileRoutesByTo
to:
| '/connect'
| '/pair'
| '/settings'
| '/connect/callback'
| '/settings/archived'
| '/settings/connections'
| '/settings/diagnostics'
@@ -165,8 +187,10 @@ export interface FileRouteTypes {
id:
| '__root__'
| '/_chat'
| '/connect'
| '/pair'
| '/settings'
| '/connect_/callback'
| '/settings/archived'
| '/settings/connections'
| '/settings/diagnostics'
@@ -181,8 +205,10 @@ export interface FileRouteTypes {
}
export interface RootRouteChildren {
ChatRoute: typeof ChatRouteWithChildren
ConnectRoute: typeof ConnectRoute
PairRoute: typeof PairRoute
SettingsRoute: typeof SettingsRouteWithChildren
ConnectCallbackRoute: typeof ConnectCallbackRoute
}
declare module '@tanstack/react-router' {
@@ -201,6 +227,13 @@ declare module '@tanstack/react-router' {
preLoaderRoute: typeof PairRouteImport
parentRoute: typeof rootRouteImport
}
'/connect': {
id: '/connect'
path: '/connect'
fullPath: '/connect'
preLoaderRoute: typeof ConnectRouteImport
parentRoute: typeof rootRouteImport
}
'/_chat': {
id: '/_chat'
path: ''
@@ -264,6 +297,13 @@ declare module '@tanstack/react-router' {
preLoaderRoute: typeof SettingsArchivedRouteImport
parentRoute: typeof SettingsRoute
}
'/connect_/callback': {
id: '/connect_/callback'
path: '/connect/callback'
fullPath: '/connect/callback'
preLoaderRoute: typeof ConnectCallbackRouteImport
parentRoute: typeof rootRouteImport
}
'/_chat/draft/$draftId': {
id: '/_chat/draft/$draftId'
path: '/draft/$draftId'
@@ -321,8 +361,10 @@ const SettingsRouteWithChildren = SettingsRoute._addFileChildren(
const rootRouteChildren: RootRouteChildren = {
ChatRoute: ChatRouteWithChildren,
ConnectRoute: ConnectRoute,
PairRoute: PairRoute,
SettingsRoute: SettingsRouteWithChildren,
ConnectCallbackRoute: ConnectCallbackRoute,
}
export const routeTree = rootRouteImport
._addFileChildren(rootRouteChildren)
+1 -1
View File
@@ -97,7 +97,7 @@ function RootRouteView() {
};
}, [pathname]);
if (pathname === "/pair") {
if (pathname === "/pair" || pathname === "/connect" || pathname.startsWith("/connect/")) {
return (
<>
<DocumentTitleSync />
+13
View File
@@ -0,0 +1,13 @@
import { createFileRoute, redirect } from "@tanstack/react-router";
import { connectCliAuthRoutesEnabled } from "../cloud/connectCliAuth";
import { ConnectCliAuthorizeSurface } from "../components/cloud/ConnectCliAuthSurface";
export const Route = createFileRoute("/connect")({
beforeLoad: () => {
if (!connectCliAuthRoutesEnabled()) {
throw redirect({ to: "/", replace: true });
}
},
component: ConnectCliAuthorizeSurface,
});
+13
View File
@@ -0,0 +1,13 @@
import { createFileRoute, redirect } from "@tanstack/react-router";
import { connectCliAuthRoutesEnabled } from "../cloud/connectCliAuth";
import { ConnectCliCallbackSurface } from "../components/cloud/ConnectCliAuthSurface";
export const Route = createFileRoute("/connect_/callback")({
beforeLoad: () => {
if (!connectCliAuthRoutesEnabled()) {
throw redirect({ to: "/", replace: true });
}
},
component: ConnectCliCallbackSurface,
});
+1
View File
@@ -9,6 +9,7 @@ interface ImportMetaEnv {
readonly VITE_HOSTED_APP_CHANNEL: string;
readonly VITE_CLERK_PUBLISHABLE_KEY: string;
readonly VITE_CLERK_JWT_TEMPLATE: string;
readonly VITE_CLERK_CLI_OAUTH_CLIENT_ID: string;
readonly VITE_RELAY_OTLP_TRACES_URL: string;
readonly VITE_RELAY_OTLP_TRACES_DATASET: string;
readonly VITE_RELAY_OTLP_TRACES_TOKEN: string;