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

+4
View File
@@ -135,6 +135,10 @@
"types": "./src/cliArgs.ts",
"import": "./src/cliArgs.ts"
},
"./connectAuth": {
"types": "./src/connectAuth.ts",
"import": "./src/connectAuth.ts"
},
"./path": {
"types": "./src/path.ts",
"import": "./src/path.ts"
+78
View File
@@ -0,0 +1,78 @@
import { describe, expect, it } from "vite-plus/test";
import {
buildConnectAuthorizeRequestUrl,
buildConnectClerkAuthorizeUrl,
connectCallbackUrl,
encodeConnectAuthCode,
parseConnectAuthCode,
readConnectAuthorizeRequest,
} from "./connectAuth.ts";
describe("connectAuth", () => {
it("round-trips state and challenge through the authorize URL fragment", () => {
const url = buildConnectAuthorizeRequestUrl({
hostedAppUrl: "https://app.t3.codes",
state: "q7mK9xV2pL4nR8sT6wYzAQ",
challenge: "E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM",
});
const parsed = new URL(url);
expect(parsed.origin).toBe("https://app.t3.codes");
expect(parsed.pathname).toBe("/connect");
expect(parsed.search).toBe("");
expect(readConnectAuthorizeRequest(parsed)).toEqual({
state: "q7mK9xV2pL4nR8sT6wYzAQ",
challenge: "E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM",
});
});
it("rejects authorize requests missing state or challenge", () => {
expect(readConnectAuthorizeRequest(new URL("https://app.t3.codes/connect"))).toBeNull();
expect(
readConnectAuthorizeRequest(new URL("https://app.t3.codes/connect#state=abc")),
).toBeNull();
expect(
readConnectAuthorizeRequest(new URL("https://app.t3.codes/connect#challenge=abc")),
).toBeNull();
});
it("builds a PKCE authorize URL against the Clerk endpoint", () => {
const url = new URL(
buildConnectClerkAuthorizeUrl({
authorizationEndpoint: "https://clerk.t3.codes/oauth/authorize",
clientId: "oauthapp_123",
redirectUri: connectCallbackUrl("https://app.t3.codes"),
scopes: ["openid", "profile", "email"],
state: "state-1",
challenge: "challenge-1",
}),
);
expect(url.origin).toBe("https://clerk.t3.codes");
expect(url.pathname).toBe("/oauth/authorize");
expect(url.searchParams.get("client_id")).toBe("oauthapp_123");
expect(url.searchParams.get("redirect_uri")).toBe("https://app.t3.codes/connect/callback");
expect(url.searchParams.get("response_type")).toBe("code");
expect(url.searchParams.get("scope")).toBe("openid profile email");
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("round-trips the out-of-band authorization code and preserves dots inside it", () => {
const blob = encodeConnectAuthCode({ code: "az9.code.chunk", state: "state-uuid" });
expect(parseConnectAuthCode(blob)).toEqual({ code: "az9.code.chunk", state: "state-uuid" });
expect(parseConnectAuthCode(` ${blob}\n`)).toEqual({
code: "az9.code.chunk",
state: "state-uuid",
});
});
it("rejects malformed out-of-band authorization codes", () => {
expect(parseConnectAuthCode("")).toBeNull();
expect(parseConnectAuthCode("no-separator")).toBeNull();
expect(parseConnectAuthCode(".leading")).toBeNull();
expect(parseConnectAuthCode("trailing.")).toBeNull();
});
});
+124
View File
@@ -0,0 +1,124 @@
import { readHashParams } from "./remote.ts";
const CONNECT_AUTH_STATE_PARAM = "state";
const CONNECT_AUTH_CHALLENGE_PARAM = "challenge";
const CONNECT_AUTH_CODE_SEPARATOR = ".";
const CONNECT_AUTHORIZE_PATH = "/connect";
const CONNECT_CALLBACK_PATH = "/connect/callback";
/**
* The CLI prints URLs against this origin and the web bundle uses it to
* decide whether it is the hosted deployment — the two must agree, so the
* default lives here.
*/
export const DEFAULT_HOSTED_APP_URL = "https://app.t3.codes";
/**
* Requested at authorize time by the hosted page and honored by the CLI's
* token exchange; keep both sides on this single definition.
*/
export const CONNECT_OAUTH_SCOPES = ["openid", "profile", "email"] as const;
export interface ConnectAuthorizeRequest {
readonly state: string;
readonly challenge: string;
}
/**
* The URL a headless CLI prints for the user to open on a machine with a
* browser. `state` and `code_challenge` ride the fragment so they never reach
* the hosted app's server or CDN logs; neither is a secret.
*/
export function buildConnectAuthorizeRequestUrl(input: {
readonly hostedAppUrl: string;
readonly state: string;
readonly challenge: string;
}): string {
const url = new URL(CONNECT_AUTHORIZE_PATH, input.hostedAppUrl);
url.hash = new URLSearchParams([
[CONNECT_AUTH_STATE_PARAM, input.state],
[CONNECT_AUTH_CHALLENGE_PARAM, input.challenge],
]).toString();
return url.toString();
}
export function readConnectAuthorizeRequest(url: URL): ConnectAuthorizeRequest | null {
const params = readHashParams(url);
const state = params.get(CONNECT_AUTH_STATE_PARAM)?.trim() ?? "";
const challenge = params.get(CONNECT_AUTH_CHALLENGE_PARAM)?.trim() ?? "";
if (!state || !challenge) {
return null;
}
return { state, challenge };
}
export function connectCallbackUrl(hostedAppUrl: string): string {
return new URL(CONNECT_CALLBACK_PATH, hostedAppUrl).toString();
}
export function buildConnectClerkAuthorizeUrl(input: {
readonly authorizationEndpoint: string;
readonly clientId: string;
readonly redirectUri: string;
readonly scopes: ReadonlyArray<string>;
readonly state: string;
readonly challenge: string;
}): string {
const url = new URL(input.authorizationEndpoint);
url.searchParams.set("client_id", input.clientId);
url.searchParams.set("redirect_uri", input.redirectUri);
url.searchParams.set("response_type", "code");
url.searchParams.set("scope", input.scopes.join(" "));
url.searchParams.set("state", input.state);
url.searchParams.set("code_challenge", input.challenge);
url.searchParams.set("code_challenge_method", "S256");
return url.toString();
}
export interface ConnectAuthCode {
readonly code: string;
readonly state: string;
}
/**
* The single blob the hosted callback page displays and the CLI accepts.
* Bundling `state` with the authorization code lets the CLI keep the loopback
* flow's CSRF check without any backend: it verifies the returned state
* matches the one it generated. Clerk authorization codes and the CLI's
* base64url states never contain ".".
*/
export function encodeConnectAuthCode(input: ConnectAuthCode): string {
return `${input.code}${CONNECT_AUTH_CODE_SEPARATOR}${input.state}`;
}
/**
* Validates an out-of-band authorization code against the state of the request this process
* generated. Returns the parsed code or a user-facing error message; both
* the prompt's live validation and the authoritative post-prompt check go
* through here so they cannot drift.
*/
export function checkConnectAuthCode(
blob: string,
expectedState: string,
): ConnectAuthCode | string {
const parsed = parseConnectAuthCode(blob);
if (parsed === null) {
return "That does not look like a T3 Connect code. Copy the full code.";
}
if (parsed.state !== expectedState) {
return "That code belongs to a different connect request. Open the URL above and try again.";
}
return parsed;
}
export function parseConnectAuthCode(blob: string): ConnectAuthCode | null {
const trimmed = blob.trim();
const separatorIndex = trimmed.lastIndexOf(CONNECT_AUTH_CODE_SEPARATOR);
if (separatorIndex <= 0 || separatorIndex === trimmed.length - 1) {
return null;
}
const code = trimmed.slice(0, separatorIndex);
const state = trimmed.slice(separatorIndex + 1);
return { code, state };
}
+14
View File
@@ -30,4 +30,18 @@ export const HostProcessEnvironment = Context.Reference<NodeJS.ProcessEnv>(
},
);
export const HostProcessExecutablePath = Context.Reference<string>(
"@t3tools/shared/hostProcess/HostProcessExecutablePath",
{
defaultValue: () => process.execPath,
},
);
export const HostProcessArguments = Context.Reference<ReadonlyArray<string>>(
"@t3tools/shared/hostProcess/HostProcessArguments",
{
defaultValue: () => process.argv,
},
);
export const isHostWindows = Effect.map(HostProcessPlatform, (platform) => platform === "win32");
+1 -1
View File
@@ -5,7 +5,7 @@ const HOSTED_PAIRING_HOST_PARAM = "host";
const HOSTED_PAIRING_LABEL_PARAM = "label";
const SUPPORTED_REMOTE_BACKEND_PROTOCOLS = new Set(["http:", "https:", "ws:", "wss:"]);
const readHashParams = (url: URL): URLSearchParams =>
export const readHashParams = (url: URL): URLSearchParams =>
new URLSearchParams(url.hash.startsWith("#") ? url.hash.slice(1) : url.hash);
export class RemoteBackendUrlMissingError extends Schema.TaggedErrorClass<RemoteBackendUrlMissingError>()(