Skip to content
TypeScript

feat(server): use Clerk's device authorization grant for headless connect login (#11794)

Julius Marmingedc0869b605f6
diff --git a/apps/server/src/cli/connect.ts b/apps/server/src/cli/connect.ts
index b7c78e5ea68..e05913eb94e 100644
--- a/apps/server/src/cli/connect.ts
+++ b/apps/server/src/cli/connect.ts
@@ -20,7 +20,6 @@ import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as References from "effect/References";
import * as Schema from "effect/Schema";
-import * as Terminal from "effect/Terminal";
import { Command, Flag, GlobalFlag, Prompt } from "effect/unstable/cli";
import {
FetchHttpClient,
@@ -64,13 +63,14 @@ const jsonFlag = Flag.boolean("json").pipe(
const isCloudCliTokenManagerError = Schema.is(CliTokenManager.CloudCliTokenManagerError);
const headlessFlag = Flag.boolean("headless").pipe(
- Flag.withDescription("Authorize without a local browser using out-of-band OAuth."),
+ Flag.withDescription("Authorize without a local browser using the OAuth device flow."),
Flag.withDefault(false),
);
/**
* Inside an SSH session there is no local browser to complete the loopback
- * OAuth callback, so out-of-band OAuth is the only flow that can work.
+ * OAuth callback, so the device authorization grant is the only flow that
+ * can work.
*/
export const headlessSessionConfig = Config.all({
sshConnection: Config.string("SSH_CONNECTION").pipe(Config.option),
@@ -79,20 +79,21 @@ export const headlessSessionConfig = Config.all({
Config.map(({ sshConnection, sshTty }) => Option.isSome(sshConnection) || Option.isSome(sshTty)),
);
-const promptForOutOfBandOAuthCode = Effect.fn("cloud.cli.prompt_for_out_of_band_oauth_code")(
- function* ({ authorizeUrl, validate }: CliTokenManager.OutOfBandOAuthPromptInput) {
- yield* Console.log(formatHeadlessAuthorizationPrompt(authorizeUrl));
- return yield* Prompt.run(Prompt.text({ message: "Authorization code", validate }));
- },
-);
+const showDeviceAuthorizationPrompt = (prompt: CliTokenManager.DeviceAuthorizationPrompt) =>
+ Console.log(formatDeviceAuthorizationPrompt(prompt));
-function formatHeadlessAuthorizationPrompt(authorizeUrl: string): string {
+function formatDeviceAuthorizationPrompt(
+ prompt: CliTokenManager.DeviceAuthorizationPrompt,
+): string {
+ const minutes = Math.max(1, Math.round(Duration.toMinutes(prompt.expiresIn)));
return [
"Headless authorization",
"Open this URL on a device with a browser:",
- ` ${authorizeUrl}`,
+ ` ${prompt.verificationUriComplete ?? prompt.verificationUri}`,
+ "",
+ `Confirm this code when asked: ${prompt.userCode}`,
"",
- "After signing in, return here and enter the code shown in your browser.",
+ `Waiting for approval (expires in ${minutes} min). Press Ctrl+C to cancel.`,
].join("\n");
}
@@ -110,7 +111,7 @@ const authorizeCli = Effect.fn("cloud.cli.authorize")(function* (options: {
yield* Console.log("\nHeadless mode enabled. A new authorization link is ready below.");
}
// A stored credential whose refresh fails (revoked, expired grant) must
- // fall through to a fresh out-of-band authorization, not dead-end the command.
+ // fall through to a fresh device authorization, not dead-end the command.
const existing = yield* tokens.getExisting.pipe(
Effect.catchTag("CloudCliCredentialRefreshError", () =>
Console.log(
@@ -121,13 +122,11 @@ const authorizeCli = Effect.fn("cloud.cli.authorize")(function* (options: {
if (Option.isSome(existing)) {
return existing.value.identity ?? null;
}
- const { token, identity } = yield* CliTokenManager.outOfBandOAuthLogin(
- promptForOutOfBandOAuthCode,
+ const { token, identity } = yield* CliTokenManager.deviceAuthorizationLogin(
+ showDeviceAuthorizationPrompt,
).pipe(
Effect.mapError((cause) =>
- // Ctrl-C / EOF at the prompt is a QuitError; let it propagate so the CLI
- // cancels quietly instead of dumping an authorization error.
- Terminal.isQuitError(cause) || isCloudCliTokenManagerError(cause)
+ isCloudCliTokenManagerError(cause)
? cause
: new CliTokenManager.CloudCliAuthorizationError({ cause }),
),
diff --git a/apps/server/src/cloud/CliTokenManager.test.ts b/apps/server/src/cloud/CliTokenManager.test.ts
index 25ae3443dae..37f645cbd4f 100644
--- a/apps/server/src/cloud/CliTokenManager.test.ts
+++ b/apps/server/src/cloud/CliTokenManager.test.ts
@@ -1,21 +1,21 @@
-import { readConnectAuthorizeRequest } from "@t3tools/shared/connectAuth";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { assert, it } from "@effect/vitest";
import * as ConfigProvider from "effect/ConfigProvider";
-import * as Crypto from "effect/Crypto";
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 Fiber from "effect/Fiber";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Queue from "effect/Queue";
import * as Schema from "effect/Schema";
import * as Terminal from "effect/Terminal";
+import * as TestClock from "effect/testing/TestClock";
import * as HttpClient from "effect/unstable/http/HttpClient";
import * as HttpClientResponse from "effect/unstable/http/HttpClientResponse";
import * as CliTokenManager from "./CliTokenManager.ts";
-import type { OutOfBandOAuthPromptInput } from "./CliTokenManager.ts";
// pk_test_<base64 of "clerk.example.test$">
const TEST_ENV = {
@@ -54,44 +54,12 @@ const TestTokenResponseJson = Schema.fromJsonString(
);
const encodeTestTokenResponse = Schema.encodeSync(TestTokenResponseJson);
-const makeTokenEndpointLayer = (
- requests: Array<RecordedTokenRequest>,
- options?: { readonly idToken?: string },
-) =>
- Layer.succeed(
- HttpClient.HttpClient,
- HttpClient.make((request) =>
- Effect.sync(() => {
- const body =
- request.body._tag === "Uint8Array" ? new TextDecoder().decode(request.body.body) : "";
- requests.push({ url: request.url, params: new URLSearchParams(body) });
- return HttpClientResponse.fromWeb(
- request,
- new Response(
- encodeTestTokenResponse({
- access_token: "access-token-1",
- refresh_token: "refresh-token-1",
- id_token: options?.idToken ?? idTokenWithEmail,
- expires_in: 3600,
- token_type: "bearer",
- }),
- { status: 200, headers: { "content-type": "application/json" } },
- ),
- );
- }),
- ),
- );
-
const provideTestEnv = Effect.provide(
ConfigProvider.layer(ConfigProvider.fromEnv({ env: TEST_ENV })),
);
const isAuthorizationError = Schema.is(CliTokenManager.CloudCliAuthorizationError);
-class PromptRejectedError extends Schema.TaggedError<PromptRejectedError>()("PromptRejectedError", {
- message: Schema.String,
-}) {}
-
const makeTestTerminal = (queue: Queue.Queue<Terminal.UserInput>) =>
Terminal.make({
columns: Effect.succeed(80),
@@ -144,106 +112,215 @@ it.effect("finishes normally when the browser callback wins", () =>
}),
);
-it.layer(NodeServices.layer)("CliTokenManager.outOfBandOAuthLogin", (it) => {
- it.effect("prints a hosted authorize URL and exchanges the out-of-band code with PKCE", () =>
- Effect.gen(function* () {
- const requests: Array<RecordedTokenRequest> = [];
- let seenAuthorizeUrl = "";
-
- const { token, identity } = yield* CliTokenManager.outOfBandOAuthLogin(
- ({ authorizeUrl, validate }: OutOfBandOAuthPromptInput) =>
- Effect.gen(function* () {
- seenAuthorizeUrl = authorizeUrl;
- const request = readConnectAuthorizeRequest(new URL(authorizeUrl));
- assert.isNotNull(request);
- return yield* validate(`clerk-code-123.${request!.state}`).pipe(
- Effect.mapError((message) => new PromptRejectedError({ message })),
- );
+interface DeviceFlowServer {
+ readonly requests: Array<RecordedTokenRequest>;
+ /** Token endpoint replies, consumed in order; the last one repeats. */
+ readonly tokenReplies: Array<{ readonly status: number; readonly body: string }>;
+}
+
+const DEVICE_AUTHORIZATION_BODY = JSON.stringify({
+ device_code: "device-code-1",
+ user_code: "BCDF-GHJK",
+ verification_uri: "https://accounts.example.test/device",
+ verification_uri_complete: "https://accounts.example.test/device?user_code=BCDF-GHJK",
+ expires_in: 600,
+ interval: 5,
+});
+
+const oauthError = (error: string) => ({ status: 400, body: JSON.stringify({ error }) });
+const tokenGranted = {
+ status: 200,
+ body: encodeTestTokenResponse({
+ access_token: "access-token-1",
+ refresh_token: "refresh-token-1",
+ id_token: idTokenWithEmail,
+ expires_in: 3600,
+ token_type: "bearer",
+ }),
+};
+
+const makeDeviceFlowLayer = (server: DeviceFlowServer) =>
+ Layer.succeed(
+ HttpClient.HttpClient,
+ HttpClient.make((request) =>
+ Effect.sync(() => {
+ const body =
+ request.body._tag === "Uint8Array" ? new TextDecoder().decode(request.body.body) : "";
+ server.requests.push({ url: request.url, params: new URLSearchParams(body) });
+ const reply = request.url.endsWith("/oauth/device_authorization")
+ ? { status: 200, body: DEVICE_AUTHORIZATION_BODY }
+ : ((server.tokenReplies.length > 1
+ ? server.tokenReplies.shift()
+ : server.tokenReplies[0]) ?? oauthError("invalid_grant"));
+ return HttpClientResponse.fromWeb(
+ request,
+ new Response(reply.body, {
+ status: reply.status,
+ headers: { "content-type": "application/json" },
}),
- ).pipe(Effect.provide(makeTokenEndpointLayer(requests)), provideTestEnv);
+ );
+ }),
+ ),
+ );
+
+const tokenRequests = (requests: ReadonlyArray<RecordedTokenRequest>) =>
+ requests.filter((request) => request.url.endsWith("/oauth/token"));
- const authorizeUrl = new URL(seenAuthorizeUrl);
- assert.equal(authorizeUrl.origin, "https://hosted.example.test");
- assert.equal(authorizeUrl.pathname, "/connect");
- const request = readConnectAuthorizeRequest(authorizeUrl);
- assert.isNotNull(request);
- assert.match(request!.state, /^[A-Za-z0-9_-]{22}$/);
+it.layer(NodeServices.layer)("CliTokenManager.deviceAuthorizationLogin", (it) => {
+ it.effect("requests a device code, shows it, and polls until Clerk grants the token", () =>
+ Effect.gen(function* () {
+ const server: DeviceFlowServer = {
+ requests: [],
+ tokenReplies: [oauthError("authorization_pending"), tokenGranted],
+ };
+ const prompts: Array<CliTokenManager.DeviceAuthorizationPrompt> = [];
+ const fiber = yield* CliTokenManager.deviceAuthorizationLogin((prompt) =>
+ Effect.sync(() => {
+ prompts.push(prompt);
+ }),
+ ).pipe(Effect.provide(makeDeviceFlowLayer(server)), provideTestEnv, Effect.forkChild);
+
+ yield* TestClock.adjust(Duration.seconds(10));
+ const { token, identity } = yield* Fiber.join(fiber);
+
+ assert.deepEqual(prompts, [
+ {
+ verificationUri: "https://accounts.example.test/device",
+ verificationUriComplete: "https://accounts.example.test/device?user_code=BCDF-GHJK",
+ userCode: "BCDF-GHJK",
+ expiresIn: Duration.seconds(600),
+ },
+ ]);
assert.equal(token.accessToken, "access-token-1");
assert.equal(token.refreshToken, "refresh-token-1");
assert.equal(token.identity, "[email protected]");
- // The id_token's email claim is surfaced so connect can show the account.
assert.equal(identity, "[email protected]");
- assert.lengthOf(requests, 1);
- const exchange = requests[0]!;
- assert.equal(exchange.url, "https://clerk.example.test/oauth/token");
- assert.equal(exchange.params.get("grant_type"), "authorization_code");
- assert.equal(exchange.params.get("code"), "clerk-code-123");
- assert.equal(
- exchange.params.get("redirect_uri"),
- "https://hosted.example.test/connect/callback",
+ const authorization = server.requests[0]!;
+ assert.equal(authorization.url, "https://clerk.example.test/oauth/device_authorization");
+ assert.equal(authorization.params.get("client_id"), "oauth_client_test");
+ assert.equal(authorization.params.get("scope"), "openid profile email offline_access");
+
+ const polls = tokenRequests(server.requests);
+ assert.lengthOf(polls, 2);
+ for (const poll of polls) {
+ assert.equal(poll.url, "https://clerk.example.test/oauth/token");
+ assert.equal(poll.params.get("grant_type"), "urn:ietf:params:oauth:grant-type:device_code");
+ assert.equal(poll.params.get("device_code"), "device-code-1");
+ assert.equal(poll.params.get("client_id"), "oauth_client_test");
+ }
+ }),
+ );
+
+ it.effect("waits the advertised interval between polls and backs off on slow_down", () =>
+ Effect.gen(function* () {
+ const server: DeviceFlowServer = {
+ requests: [],
+ tokenReplies: [oauthError("slow_down"), oauthError("authorization_pending")],
+ };
+
+ const fiber = yield* CliTokenManager.deviceAuthorizationLogin(() => Effect.void).pipe(
+ Effect.provide(makeDeviceFlowLayer(server)),
+ provideTestEnv,
+ Effect.forkChild,
);
- assert.equal(exchange.params.get("client_id"), "oauth_client_test");
- // The verifier must hash to the challenge advertised in the authorize URL.
- const verifier = exchange.params.get("code_verifier");
- assert.isNotNull(verifier);
- const crypto = yield* Crypto.Crypto;
- const digest = yield* crypto.digest("SHA-256", new TextEncoder().encode(verifier!));
- assert.equal(Encoding.encodeBase64Url(digest), request!.challenge);
+
+ yield* TestClock.adjust(Duration.seconds(4));
+ assert.lengthOf(tokenRequests(server.requests), 0);
+ yield* TestClock.adjust(Duration.seconds(1));
+ assert.lengthOf(tokenRequests(server.requests), 1);
+ // slow_down widens the 5s interval to 10s.
+ yield* TestClock.adjust(Duration.seconds(9));
+ assert.lengthOf(tokenRequests(server.requests), 1);
+ yield* TestClock.adjust(Duration.seconds(1));
+ assert.lengthOf(tokenRequests(server.requests), 2);
+ yield* Fiber.interrupt(fiber);
}),
);
- it.effect("rejects out-of-band codes whose state does not match the request", () =>
+ it.effect("backs off after a transient upstream failure and keeps polling", () =>
Effect.gen(function* () {
- const requests: Array<RecordedTokenRequest> = [];
-
- const validationErrors: Array<string> = [];
- const result = yield* CliTokenManager.outOfBandOAuthLogin(
- ({ validate }: OutOfBandOAuthPromptInput) =>
- validate("clerk-code-123.wrong-state").pipe(
- Effect.tapError((message) => Effect.sync(() => validationErrors.push(message))),
- Effect.mapError((message) => new PromptRejectedError({ message })),
- ),
- ).pipe(Effect.provide(makeTokenEndpointLayer(requests)), provideTestEnv, Effect.flip);
-
- assert.lengthOf(requests, 0);
- assert.lengthOf(validationErrors, 1);
- assert.include(validationErrors[0], "different connect request");
- assert.instanceOf(result, PromptRejectedError);
+ const server: DeviceFlowServer = {
+ requests: [],
+ tokenReplies: [{ status: 503, body: "upstream unavailable" }, tokenGranted],
+ };
+
+ const fiber = yield* CliTokenManager.deviceAuthorizationLogin(() => Effect.void).pipe(
+ Effect.provide(makeDeviceFlowLayer(server)),
+ provideTestEnv,
+ Effect.forkChild,
+ );
+
+ yield* TestClock.adjust(Duration.seconds(5));
+ assert.lengthOf(tokenRequests(server.requests), 1);
+ // The 5xx widens the 5s interval to 10s before the retry.
+ yield* TestClock.adjust(Duration.seconds(9));
+ assert.lengthOf(tokenRequests(server.requests), 1);
+ yield* TestClock.adjust(Duration.seconds(1));
+ const { token } = yield* Fiber.join(fiber);
+ assert.lengthOf(tokenRequests(server.requests), 2);
+ assert.equal(token.accessToken, "access-token-1");
}),
);
- it.effect("ignores an id_token whose claims are not valid JSON", () =>
+ it.effect("fails with a denied error when the user rejects the request", () =>
Effect.gen(function* () {
- const requests: Array<RecordedTokenRequest> = [];
- const malformedIdToken = `header.${Encoding.encodeBase64Url("not-json")}.signature`;
-
- const { identity } = yield* CliTokenManager.outOfBandOAuthLogin(
- ({ authorizeUrl }: OutOfBandOAuthPromptInput) => {
- const request = readConnectAuthorizeRequest(new URL(authorizeUrl));
- assert.isNotNull(request);
- return Effect.succeed(`clerk-code-123.${request!.state}`);
- },
- ).pipe(
- Effect.provide(makeTokenEndpointLayer(requests, { idToken: malformedIdToken })),
+ const server: DeviceFlowServer = {
+ requests: [],
+ tokenReplies: [oauthError("access_denied")],
+ };
+
+ const fiber = yield* CliTokenManager.deviceAuthorizationLogin(() => Effect.void).pipe(
+ Effect.provide(makeDeviceFlowLayer(server)),
+ provideTestEnv,
+ Effect.flip,
+ Effect.forkChild,
+ );
+ yield* TestClock.adjust(Duration.seconds(5));
+ const result = yield* Fiber.join(fiber);
+
+ assert.instanceOf(result, CliTokenManager.CloudCliAuthorizationDeniedError);
+ assert.lengthOf(tokenRequests(server.requests), 1);
+ }),
+ );
+
+ it.effect("times out once the device code lifetime elapses", () =>
+ Effect.gen(function* () {
+ const server: DeviceFlowServer = {
+ requests: [],
+ tokenReplies: [oauthError("authorization_pending")],
+ };
+
+ const fiber = yield* CliTokenManager.deviceAuthorizationLogin(() => Effect.void).pipe(
+ Effect.provide(makeDeviceFlowLayer(server)),
provideTestEnv,
+ Effect.flip,
+ Effect.forkChild,
);
+ yield* TestClock.adjust(Duration.seconds(600));
+ const result = yield* Fiber.join(fiber);
- assert.isNull(identity);
- assert.lengthOf(requests, 1);
+ assert.instanceOf(result, CliTokenManager.CloudCliAuthorizationTimeoutError);
}),
);
- it.effect("fails without touching the token endpoint when the prompt returns garbage", () =>
+ it.effect("surfaces other OAuth errors as authorization failures", () =>
Effect.gen(function* () {
- const requests: Array<RecordedTokenRequest> = [];
+ const server: DeviceFlowServer = {
+ requests: [],
+ tokenReplies: [oauthError("invalid_client")],
+ };
- const result = yield* CliTokenManager.outOfBandOAuthLogin(() =>
- Effect.succeed("not-a-connect-code"),
- ).pipe(Effect.provide(makeTokenEndpointLayer(requests)), provideTestEnv, Effect.flip);
+ const fiber = yield* CliTokenManager.deviceAuthorizationLogin(() => Effect.void).pipe(
+ Effect.provide(makeDeviceFlowLayer(server)),
+ provideTestEnv,
+ Effect.flip,
+ Effect.forkChild,
+ );
+ yield* TestClock.adjust(Duration.seconds(5));
+ const result = yield* Fiber.join(fiber);
- assert.lengthOf(requests, 0);
assert.isTrue(isAuthorizationError(result));
}),
);
diff --git a/apps/server/src/cloud/CliTokenManager.ts b/apps/server/src/cloud/CliTokenManager.ts
index 8f7ac7bfc8d..4172578d45f 100644
--- a/apps/server/src/cloud/CliTokenManager.ts
+++ b/apps/server/src/cloud/CliTokenManager.ts
@@ -18,17 +18,14 @@ import * as Schema from "effect/Schema";
import * as Semaphore from "effect/Semaphore";
import * as Terminal from "effect/Terminal";
import * as HttpClient from "effect/unstable/http/HttpClient";
+import * as HttpClientError from "effect/unstable/http/HttpClientError";
import * as HttpClientRequest from "effect/unstable/http/HttpClientRequest";
import * as HttpClientResponse from "effect/unstable/http/HttpClientResponse";
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 {
- buildConnectAuthorizeRequestUrl,
- checkConnectAuthCode,
- connectCallbackUrl,
-} from "@t3tools/shared/connectAuth";
+import { buildConnectAuthorizeRequestUrl } from "@t3tools/shared/connectAuth";
import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
import * as ExternalLauncher from "../process/externalLauncher.ts";
@@ -42,6 +39,11 @@ import { renderLoopbackAuthorizationCompleteHtml } from "./cliAuthHtml.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 DEVICE_CODE_GRANT_TYPE = "urn:ietf:params:oauth:grant-type:device_code";
+// RFC 8628 defaults, used only when Clerk omits the field.
+const DEVICE_AUTHORIZATION_DEFAULT_INTERVAL = Duration.seconds(5);
+// RFC 8628 §3.5: a slow_down response means "add 5 seconds to the interval".
+const DEVICE_AUTHORIZATION_SLOW_DOWN_INCREMENT = Duration.seconds(5);
const boldTerminalText = (value: string): string => `\u001b[1m${value}\u001b[22m`;
function formatLoopbackAuthorizationPrompt(authorizationUrl: string): string {
@@ -136,6 +138,20 @@ const OAuthTokenResponse = Schema.Struct({
token_type: Schema.String,
});
+const OAuthErrorResponse = Schema.Struct({
+ error: Schema.String,
+ error_description: Schema.optional(Schema.String),
+});
+
+const DeviceAuthorizationResponse = Schema.Struct({
+ device_code: Schema.String,
+ user_code: Schema.String,
+ verification_uri: Schema.String,
+ verification_uri_complete: Schema.optional(Schema.String),
+ expires_in: Schema.Number,
+ interval: Schema.optional(Schema.Number),
+});
+
const OidcIdentityClaimsJson = Schema.fromJsonString(
Schema.Struct({
email: Schema.optional(Schema.String),
@@ -209,12 +225,22 @@ export class CloudCliAuthorizationTimeoutError extends Schema.TaggedError<CloudC
}
}
+export class CloudCliAuthorizationDeniedError extends Schema.TaggedError<CloudCliAuthorizationDeniedError>()(
+ "CloudCliAuthorizationDeniedError",
+ {},
+) {
+ override get message(): string {
+ return "T3 Connect authorization was denied in the browser.";
+ }
+}
+
export const CloudCliTokenManagerError = Schema.Union([
CloudCliCredentialRemovalError,
CloudCliCredentialRefreshError,
CloudCliCredentialReadError,
CloudCliAuthorizationError,
CloudCliAuthorizationTimeoutError,
+ CloudCliAuthorizationDeniedError,
]);
export type CloudCliTokenManagerError = typeof CloudCliTokenManagerError.Type;
@@ -241,29 +267,36 @@ function bytesToString(value: Uint8Array): string {
return new TextDecoder().decode(value);
}
-const exchangeToken = Effect.fn("cloud.cli_token.exchange")(function* (
- metadata: Pick<CloudCliOAuthConfig, "tokenEndpoint">,
+const readTokenResponse = Effect.fn("cloud.cli_token.read_token_response")(function* (
+ response: HttpClientResponse.HttpClientResponse,
params: Record<string, string>,
) {
- const httpClient = (yield* HttpClient.HttpClient).pipe(HttpClient.filterStatusOk);
- const response = yield* HttpClientRequest.post(metadata.tokenEndpoint).pipe(
- HttpClientRequest.bodyUrlParams(params),
- httpClient.execute,
- Effect.flatMap(HttpClientResponse.schemaBodyJson(OAuthTokenResponse)),
- );
+ const body = yield* HttpClientResponse.schemaBodyJson(OAuthTokenResponse)(response);
const now = yield* Clock.currentTimeMillis;
- const identity = idTokenIdentity(response.id_token);
+ const identity = idTokenIdentity(body.id_token);
return {
token: {
- accessToken: response.access_token,
- refreshToken: response.refresh_token ?? params.refresh_token ?? "",
- expiresAtEpochMs: now + response.expires_in * 1_000,
+ accessToken: body.access_token,
+ refreshToken: body.refresh_token ?? params.refresh_token ?? "",
+ expiresAtEpochMs: now + body.expires_in * 1_000,
...(identity === null ? {} : { identity }),
} satisfies PersistedToken,
identity,
};
});
+const exchangeToken = Effect.fn("cloud.cli_token.exchange")(function* (
+ metadata: Pick<CloudCliOAuthConfig, "tokenEndpoint">,
+ params: Record<string, string>,
+) {
+ const httpClient = (yield* HttpClient.HttpClient).pipe(HttpClient.filterStatusOk);
+ const response = yield* HttpClientRequest.post(metadata.tokenEndpoint).pipe(
+ HttpClientRequest.bodyUrlParams(params),
+ httpClient.execute,
+ );
+ return yield* readTokenResponse(response, params);
+});
+
const makePkceRequest = Effect.gen(function* () {
const crypto = yield* Crypto.Crypto;
const verifier = Encoding.encodeBase64Url(yield* crypto.randomBytes(32));
@@ -274,61 +307,118 @@ const makePkceRequest = Effect.gen(function* () {
return { verifier, challenge, state };
});
-export interface OutOfBandOAuthPromptInput {
- readonly authorizeUrl: string;
- readonly validate: (value: string) => Effect.Effect<string, string>;
+export interface DeviceAuthorizationPrompt {
+ readonly verificationUri: string;
+ readonly verificationUriComplete: string | undefined;
+ readonly userCode: string;
+ readonly expiresIn: Duration.Duration;
}
+const isTransportError = (error: unknown) =>
+ HttpClientError.isHttpClientError(error) && error.reason._tag === "TransportError";
+
/**
- * Out-of-band OAuth for machines without a local browser (SSH). The user
- * opens the hosted /connect URL elsewhere, signs in, and enters the displayed
- * code in this terminal. The PKCE verifier never leaves this process, so the
- * authorization code is useless to an observer, and the state bundled into
- * the blob preserves the loopback flow's CSRF check.
+ * Polls Clerk's token endpoint until the user approves or denies the device
+ * request in the browser (RFC 8628 §3.4/3.5). `authorization_pending` keeps
+ * waiting, while `slow_down` and transient failures widen the interval before
+ * the next tick; the caller bounds the whole loop with the device code's
+ * lifetime.
*/
-export const outOfBandOAuthLogin = Effect.fn("cloud.cli_token.out_of_band_oauth_login")(function* <
- E,
- R,
->(promptForCode: (input: OutOfBandOAuthPromptInput) => Effect.Effect<string, E, R>) {
- const metadata = yield* cloudCliOAuthConfig;
- const hostedAppUrl = yield* hostedAppUrlConfig;
- const { verifier, challenge, state } = yield* makePkceRequest;
-
- const authorizationCode = yield* promptForCode({
- authorizeUrl: buildConnectAuthorizeRequestUrl({ hostedAppUrl, state, challenge }),
- validate: (value) => {
- const checked = checkConnectAuthCode(value, state);
- return typeof checked === "string" ? Effect.fail(checked) : Effect.succeed(value);
- },
- }).pipe(
- // Clerk authorization codes expire on this horizon anyway; matching the
- // loopback flow's timeout turns an abandoned prompt into a clear error.
- Effect.timeout(CLOUD_CLI_OAUTH_CALLBACK_TIMEOUT),
- Effect.catchTag("TimeoutError", (cause) =>
- Effect.fail(new CloudCliAuthorizationTimeoutError({ cause })),
- ),
- );
- // promptForCode is caller-supplied, so re-check the returned value rather
- // than trusting that the prompt ran validate.
- const authCode = checkConnectAuthCode(authorizationCode, state);
- if (typeof authCode === "string") {
- return yield* new CloudCliAuthorizationError({ cause: authCode });
- }
-
- return yield* exchangeToken(metadata, {
- grant_type: "authorization_code",
- code: authCode.code,
- redirect_uri: connectCallbackUrl(hostedAppUrl),
+const pollDeviceToken = Effect.fn("cloud.cli_token.poll_device_token")(function* (
+ metadata: Pick<CloudCliOAuthConfig, "tokenEndpoint" | "clientId">,
+ deviceCode: string,
+ initialInterval: Duration.Duration,
+) {
+ const httpClient = yield* HttpClient.HttpClient;
+ const params = {
+ grant_type: DEVICE_CODE_GRANT_TYPE,
+ device_code: deviceCode,
client_id: metadata.clientId,
- code_verifier: verifier,
- });
+ };
+ let interval = initialInterval;
+ while (true) {
+ yield* Effect.sleep(interval);
+ const response = yield* HttpClientRequest.post(metadata.tokenEndpoint).pipe(
+ HttpClientRequest.bodyUrlParams(params),
+ httpClient.execute,
+ Effect.map(Option.some),
+ Effect.catchIf(isTransportError, () => Effect.succeedNone),
+ );
+ // Transport failures and upstream 5xx are transient while the device code
+ // is still valid. RFC 8628 §3.5 asks clients to back off before retrying,
+ // so widen the interval like slow_down; drain the body so the connection
+ // returns to the pool for the next poll.
+ if (Option.isNone(response) || response.value.status >= 500) {
+ if (Option.isSome(response)) yield* Effect.ignore(response.value.text);
+ interval = Duration.sum(interval, DEVICE_AUTHORIZATION_SLOW_DOWN_INCREMENT);
+ continue;
+ }
+ if (response.value.status >= 200 && response.value.status < 300) {
+ return yield* readTokenResponse(response.value, params);
+ }
+ const failure = yield* HttpClientResponse.schemaBodyJson(OAuthErrorResponse)(response.value);
+ switch (failure.error) {
+ case "authorization_pending":
+ continue;
+ case "slow_down":
+ interval = Duration.sum(interval, DEVICE_AUTHORIZATION_SLOW_DOWN_INCREMENT);
+ continue;
+ case "expired_token":
+ return yield* new CloudCliAuthorizationTimeoutError({ cause: failure });
+ case "access_denied":
+ return yield* new CloudCliAuthorizationDeniedError();
+ default:
+ return yield* new CloudCliAuthorizationError({
+ cause: failure.error_description ?? failure.error,
+ });
+ }
+ }
});
+/**
+ * OAuth device authorization grant for machines without a local browser
+ * (SSH). Clerk issues a short user code; the user approves it on Clerk's
+ * hosted device page from any browser while this process polls the token
+ * endpoint. Nothing is typed into the terminal and no redirect URI is
+ * involved, so the hosted app plays no part in this flow.
+ */
+export const deviceAuthorizationLogin = Effect.fn("cloud.cli_token.device_authorization_login")(
+ function* <E, R>(showPrompt: (prompt: DeviceAuthorizationPrompt) => Effect.Effect<void, E, R>) {
+ const metadata = yield* cloudCliOAuthConfig;
+ const httpClient = (yield* HttpClient.HttpClient).pipe(HttpClient.filterStatusOk);
+ const authorization = yield* HttpClientRequest.post(metadata.deviceAuthorizationEndpoint).pipe(
+ HttpClientRequest.bodyUrlParams({
+ client_id: metadata.clientId,
+ scope: metadata.scopes.join(" "),
+ }),
+ httpClient.execute,
+ Effect.flatMap(HttpClientResponse.schemaBodyJson(DeviceAuthorizationResponse)),
+ );
+ // Clerk's advertised lifetime and interval are authoritative.
+ const expiresIn = Duration.seconds(authorization.expires_in);
+ const interval =
+ authorization.interval === undefined
+ ? DEVICE_AUTHORIZATION_DEFAULT_INTERVAL
+ : Duration.seconds(authorization.interval);
+ yield* showPrompt({
+ verificationUri: authorization.verification_uri,
+ verificationUriComplete: authorization.verification_uri_complete,
+ userCode: authorization.user_code,
+ expiresIn,
+ });
+ return yield* pollDeviceToken(metadata, authorization.device_code, interval).pipe(
+ Effect.timeout(expiresIn),
+ Effect.catchTag("TimeoutError", (cause) =>
+ Effect.fail(new CloudCliAuthorizationTimeoutError({ cause })),
+ ),
+ );
+ },
+);
+
/** @public Service construction is part of the canonical Effect module API. */
export const make = Effect.gen(function* () {
- // Capture exactly the services the login/refresh flows need at build time
- // (matching the behavior before the out-of-band flow captured the instances), not
- // the whole ambient context.
+ // Capture exactly the services the login/refresh flows need at build time,
+ // not the whole ambient context.
const crypto = yield* Crypto.Crypto;
const httpClient = yield* HttpClient.HttpClient;
const services = Context.make(Crypto.Crypto, crypto).pipe(
@@ -461,7 +551,7 @@ export const make = Effect.gen(function* () {
Effect.gen(function* () {
// A stored credential that can't be read or refreshed (corrupt, revoked,
// expired grant) must fall through to a fresh login rather than dead-end
- // the command — authorizeCli applies the same fallback to out-of-band
+ // the command — authorizeCli applies the same fallback to device
// authorization.
const token = yield* getExistingNoLock().pipe(
Effect.orElseSucceed(() => Option.none<PersistedToken>()),
diff --git a/apps/server/src/cloud/publicConfig.test.ts b/apps/server/src/cloud/publicConfig.test.ts
index f8324f9478e..02276e87d6d 100644
--- a/apps/server/src/cloud/publicConfig.test.ts
+++ b/apps/server/src/cloud/publicConfig.test.ts
@@ -91,10 +91,11 @@ it.effect("derives direct Clerk OAuth endpoints from statically injected public
assert.deepEqual(config, {
tokenEndpoint: "https://clerk.example.test/oauth/token",
+ deviceAuthorizationEndpoint: "https://clerk.example.test/oauth/device_authorization",
clientId: "oauth_client_embedded",
loopbackPort: 34338,
redirectUri: "http://127.0.0.1:34338/callback",
- scopes: ["openid", "profile", "email"],
+ scopes: ["openid", "profile", "email", "offline_access"],
});
}),
);
diff --git a/apps/server/src/cloud/publicConfig.ts b/apps/server/src/cloud/publicConfig.ts
index d60a09b6dec..6fcffdf8f5e 100644
--- a/apps/server/src/cloud/publicConfig.ts
+++ b/apps/server/src/cloud/publicConfig.ts
@@ -152,11 +152,13 @@ function makePublicValueConfig(name: string, fallback: string) {
/**
* The CLI never calls Clerk's /oauth/authorize itself: the browser leg goes
* through the hosted /connect page, which builds the authorize URL after a
- * Clerk session exists (see CliTokenManager.login). Only the token endpoint
- * is contacted directly.
+ * Clerk session exists (see CliTokenManager.login). The token endpoint and,
+ * for headless hosts, the device authorization endpoint are contacted
+ * directly.
*/
export interface CloudCliOAuthConfig {
readonly tokenEndpoint: string;
+ readonly deviceAuthorizationEndpoint: string;
readonly clientId: string;
readonly loopbackPort: number;
readonly redirectUri: string;
@@ -195,6 +197,7 @@ export function makeCloudCliOAuthConfig({
(clerkFrontendApiUrl) =>
({
tokenEndpoint: `${clerkFrontendApiUrl}/oauth/token`,
+ deviceAuthorizationEndpoint: `${clerkFrontendApiUrl}/oauth/device_authorization`,
clientId,
loopbackPort: CLOUD_CLI_OAUTH_LOOPBACK_PORT,
redirectUri: connectLoopbackRedirectUri(CLOUD_CLI_OAUTH_LOOPBACK_PORT),
diff --git a/apps/web/src/cloud/connectCliAuth.test.ts b/apps/web/src/cloud/connectCliAuth.test.ts
index 3d41c416633..aaddd9ce0db 100644
--- a/apps/web/src/cloud/connectCliAuth.test.ts
+++ b/apps/web/src/cloud/connectCliAuth.test.ts
@@ -4,7 +4,6 @@ import {
buildConnectCliClerkAuthorizeUrl,
connectCliSignInRedirectUrl,
hasConnectCliAuthConfig,
- readConnectCliCallbackResult,
} from "./connectCliAuth";
// Any pk_test_* key decodes to <base64 hostname>.clerk.accounts.dev.
@@ -25,48 +24,34 @@ describe("connectCliAuth", () => {
expect(hasConnectCliAuthConfig()).toBe(true);
});
- it("builds the Clerk authorize URL with the configured hosted origin's callback", () => {
+ it("builds a PKCE authorize URL that redirects to the CLI's loopback listener", () => {
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",
+ loopbackPort: 34338,
});
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("redirect_uri")).toBe("http://127.0.0.1:34338/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("redirects straight to the CLI's loopback listener when the request carries a port", () => {
- vi.stubEnv("VITE_CLERK_PUBLISHABLE_KEY", TEST_PUBLISHABLE_KEY);
- vi.stubEnv("VITE_CLERK_CLI_OAUTH_CLIENT_ID", "oauthapp_123");
-
- const authorizeUrl = buildConnectCliClerkAuthorizeUrl({
- state: "state-1",
- challenge: "challenge-1",
- loopbackPort: 34338,
- });
- expect(authorizeUrl).not.toBeNull();
-
- const url = new URL(authorizeUrl!);
- expect(url.searchParams.get("redirect_uri")).toBe("http://127.0.0.1:34338/callback");
- expect(url.searchParams.get("state")).toBe("state-1");
- });
-
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" }),
+ buildConnectCliClerkAuthorizeUrl({
+ state: "state-1",
+ challenge: "challenge-1",
+ loopbackPort: 34338,
+ }),
).toBeNull();
});
@@ -74,9 +59,10 @@ describe("connectCliAuth", () => {
vi.stubEnv("VITE_CLERK_PUBLISHABLE_KEY", TEST_PUBLISHABLE_KEY);
vi.stubEnv("VITE_CLERK_CLI_OAUTH_CLIENT_ID", "oauthapp_123");
- const connectUrl = "https://app.t3.codes/connect#state=state-1&challenge=challenge-1";
+ const connectUrl =
+ "https://app.t3.codes/connect#state=state-1&challenge=challenge-1&port=34338";
const redirectUrl = connectCliSignInRedirectUrl(
- { state: "state-1", challenge: "challenge-1" },
+ { state: "state-1", challenge: "challenge-1", loopbackPort: 34338 },
connectUrl,
);
@@ -87,23 +73,13 @@ describe("connectCliAuth", () => {
it("falls back to the current URL when the authorize URL cannot be built", () => {
vi.stubEnv("VITE_CLERK_PUBLISHABLE_KEY", TEST_PUBLISHABLE_KEY);
- const connectUrl = "https://app.t3.codes/connect#state=state-1&challenge=challenge-1";
+ const connectUrl =
+ "https://app.t3.codes/connect#state=state-1&challenge=challenge-1&port=34338";
expect(
- connectCliSignInRedirectUrl({ state: "state-1", challenge: "challenge-1" }, connectUrl),
- ).toBe(connectUrl);
- });
-
- 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"),
+ connectCliSignInRedirectUrl(
+ { state: "state-1", challenge: "challenge-1", loopbackPort: 34338 },
+ connectUrl,
),
- ).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();
+ ).toBe(connectUrl);
});
});
diff --git a/apps/web/src/cloud/connectCliAuth.ts b/apps/web/src/cloud/connectCliAuth.ts
index 0bc65080cf8..03b311fdca1 100644
--- a/apps/web/src/cloud/connectCliAuth.ts
+++ b/apps/web/src/cloud/connectCliAuth.ts
@@ -1,17 +1,14 @@
import {
buildConnectClerkAuthorizeUrl,
- connectCallbackUrl,
connectLoopbackRedirectUri,
CONNECT_OAUTH_SCOPES,
type ConnectAuthorizeRequest,
} from "@t3tools/shared/connectAuth";
import { clerkFrontendApiUrlFromPublishableKey } from "@t3tools/shared/relayAuth";
-import { configuredHostedAppUrl, isHostedStaticApp } from "../hostedPairing";
+import { isHostedStaticApp } from "../hostedPairing";
import { hasCloudPublicConfig, resolveCloudPublicConfig, trimNonEmpty } from "./publicConfig";
-const CONNECT_CLI_AUTH_STATE_STORAGE_KEY = "t3code-connect-cli-auth-state";
-
function resolveConnectCliOAuthClientId(): string | null {
return trimNonEmpty(import.meta.env.VITE_CLERK_CLI_OAUTH_CLIENT_ID as string | undefined);
}
@@ -23,7 +20,7 @@ export function hasConnectCliAuthConfig(): boolean {
}
/**
- * Gate for the /connect routes: the CLI handshake only exists on the hosted
+ * Gate for the /connect route: 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.
*/
@@ -33,13 +30,9 @@ export function connectCliAuthRoutesEnabled(): boolean {
/**
* 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.
- *
- * A request carrying a loopback port came from a CLI with a local callback
- * listener: the authorization code must return to `127.0.0.1` directly, so
- * the hosted callback page never sees it. Clerk enforces its registered
- * redirect URI allowlist either way.
+ * authorization code returns to the CLI's `127.0.0.1` listener directly, so
+ * this page never sees it. Clerk enforces its registered redirect URI
+ * allowlist either way.
*/
export function buildConnectCliClerkAuthorizeUrl(request: ConnectAuthorizeRequest): string | null {
const { clerkPublishableKey } = resolveCloudPublicConfig();
@@ -50,10 +43,7 @@ export function buildConnectCliClerkAuthorizeUrl(request: ConnectAuthorizeReques
return buildConnectClerkAuthorizeUrl({
authorizationEndpoint: `${clerkFrontendApiUrlFromPublishableKey(clerkPublishableKey)}/oauth/authorize`,
clientId,
- redirectUri:
- request.loopbackPort === undefined
- ? connectCallbackUrl(configuredHostedAppUrl())
- : connectLoopbackRedirectUri(request.loopbackPort),
+ redirectUri: connectLoopbackRedirectUri(request.loopbackPort),
scopes: CONNECT_OAUTH_SCOPES,
state: request.state,
challenge: request.challenge,
@@ -76,42 +66,3 @@ export function connectCliSignInRedirectUrl(
): string {
return buildConnectCliClerkAuthorizeUrl(request) ?? currentHref;
}
-
-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 };
-}
diff --git a/apps/web/src/components/cloud/ConnectCliAuthSurface.tsx b/apps/web/src/components/cloud/ConnectCliAuthSurface.tsx
index 5d5c280bb81..afe0dbc31c5 100644
--- a/apps/web/src/components/cloud/ConnectCliAuthSurface.tsx
+++ b/apps/web/src/components/cloud/ConnectCliAuthSurface.tsx
@@ -1,16 +1,12 @@
-import { useAuth, useClerk, useUser } from "@clerk/react";
-import { encodeConnectAuthCode, readConnectAuthorizeRequest } from "@t3tools/shared/connectAuth";
+import { useAuth, useClerk } from "@clerk/react";
+import { readConnectAuthorizeRequest } from "@t3tools/shared/connectAuth";
import { useCallback, useEffect, useRef, useState } from "react";
import {
buildConnectCliClerkAuthorizeUrl,
connectCliSignInRedirectUrl,
- readConnectCliAuthState,
- readConnectCliCallbackResult,
- rememberConnectCliAuthState,
} from "../../cloud/connectCliAuth";
import { isElectron } from "../../env";
-import { useCopyToClipboard } from "../../hooks/useCopyToClipboard";
import { AuthSurfaceShell } from "../auth/AuthSurfaceShell";
import { resolveClerkSignInProps } from "../clerk/authRedirect";
import { Button } from "../ui/button";
@@ -45,10 +41,10 @@ const invalidLinkMessage = {
} as const;
/**
- * /connect: the URL the CLI prints for both flows. Waits for a Clerk session,
- * then forwards the CLI's PKCE request to Clerk's authorize endpoint — with a
- * loopback redirect URI when the request carries a port, so the code returns
- * straight to the waiting CLI, and the hosted callback page otherwise.
+ * /connect: the URL the CLI prints for the loopback flow. Waits for a Clerk
+ * session, then forwards the CLI's PKCE request to Clerk's authorize endpoint
+ * with the loopback redirect URI so the code returns straight to the waiting
+ * CLI. Headless hosts use Clerk's device authorization page instead.
*/
export function ConnectCliAuthorizeSurface() {
const [request] = useState(() => readConnectAuthorizeRequest(new URL(window.location.href)));
@@ -61,9 +57,6 @@ export function ConnectCliAuthorizeSurface() {
if (!request) {
return;
}
- // Clerk redirects to the authorize endpoint itself once sign-in completes,
- // so the callback's state check has to be armed before handing off.
- rememberConnectCliAuthState(request.state);
clerk.openSignIn(
resolveClerkSignInProps(
connectCliSignInRedirectUrl(request, window.location.href),
@@ -88,7 +81,6 @@ export function ConnectCliAuthorizeSurface() {
return;
}
redirecting.current = true;
- rememberConnectCliAuthState(request.state);
window.location.assign(authorizeUrl);
}, [isLoaded, isSignedIn, openSignIn, request]);
@@ -103,11 +95,7 @@ export function ConnectCliAuthorizeSurface() {
return (
<AuthSurfaceShell>
<ConnectCliAuthMessage
- eyebrow={
- request.loopbackPort === undefined
- ? "Step 1 of 2 · Browser authorization"
- : "Browser authorization"
- }
+ eyebrow="Browser authorization"
title="Connecting your terminal"
description={
isSignedIn
@@ -125,85 +113,3 @@ export function ConnectCliAuthorizeSurface() {
</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>
- );
-}
diff --git a/apps/web/src/hostedPairing.ts b/apps/web/src/hostedPairing.ts
index 87c352244e5..f3f056522bf 100644
--- a/apps/web/src/hostedPairing.ts
+++ b/apps/web/src/hostedPairing.ts
@@ -10,7 +10,7 @@ export interface HostedPairingRequest {
export type HostedAppChannel = "latest" | "nightly";
-export function configuredHostedAppUrl(): string {
+function configuredHostedAppUrl(): string {
return import.meta.env.VITE_HOSTED_APP_URL?.trim() || DEFAULT_HOSTED_APP_URL;
}
diff --git a/apps/web/src/routeTree.gen.ts b/apps/web/src/routeTree.gen.ts
index 4ce1c3557ee..f6ba4dece7f 100644
--- a/apps/web/src/routeTree.gen.ts
+++ b/apps/web/src/routeTree.gen.ts
@@ -29,7 +29,6 @@ import { Route as SettingsConnectionsRouteImport } from './routes/settings.conne
import { Route as SettingsArchivedRouteImport } from './routes/settings.archived'
import { Route as SettingsAppearanceRouteImport } from './routes/settings.appearance'
import { Route as ProjectsProjectKeyRouteImport } from './routes/projects.$projectKey'
-import { Route as ConnectCallbackRouteImport } from './routes/connect_.callback'
import { Route as ChatPullRequestsRouteImport } from './routes/_chat.pull-requests'
import { Route as ChatDraftDraftIdRouteImport } from './routes/_chat.draft.$draftId'
import { Route as ChatEnvironmentIdThreadIdRouteImport } from './routes/_chat.$environmentId.$threadId'
@@ -134,11 +133,6 @@ const ProjectsProjectKeyRoute = ProjectsProjectKeyRouteImport.update({
path: '/projects/$projectKey',
getParentRoute: () => rootRouteImport,
} as any)
-const ConnectCallbackRoute = ConnectCallbackRouteImport.update({
- id: '/connect_/callback',
- path: '/connect/callback',
- getParentRoute: () => rootRouteImport,
-} as any)
const ChatPullRequestsRoute = ChatPullRequestsRouteImport.update({
id: '/pull-requests',
path: '/pull-requests',
@@ -164,7 +158,6 @@ export interface FileRoutesByFullPath {
'/usage': typeof UsageRoute
'/welcome': typeof WelcomeRoute
'/pull-requests': typeof ChatPullRequestsRoute
- '/connect/callback': typeof ConnectCallbackRoute
'/projects/$projectKey': typeof ProjectsProjectKeyRoute
'/settings/appearance': typeof SettingsAppearanceRoute
'/settings/archived': typeof SettingsArchivedRoute
@@ -188,7 +181,6 @@ export interface FileRoutesByTo {
'/usage': typeof UsageRoute
'/welcome': typeof WelcomeRoute
'/pull-requests': typeof ChatPullRequestsRoute
- '/connect/callback': typeof ConnectCallbackRoute
'/projects/$projectKey': typeof ProjectsProjectKeyRoute
'/settings/appearance': typeof SettingsAppearanceRoute
'/settings/archived': typeof SettingsArchivedRoute
@@ -215,7 +207,6 @@ export interface FileRoutesById {
'/usage': typeof UsageRoute
'/welcome': typeof WelcomeRoute
'/_chat/pull-requests': typeof ChatPullRequestsRoute
- '/connect_/callback': typeof ConnectCallbackRoute
'/projects/$projectKey': typeof ProjectsProjectKeyRoute
'/settings/appearance': typeof SettingsAppearanceRoute
'/settings/archived': typeof SettingsArchivedRoute
@@ -243,7 +234,6 @@ export interface FileRouteTypes {
| '/usage'
| '/welcome'
| '/pull-requests'
- | '/connect/callback'
| '/projects/$projectKey'
| '/settings/appearance'
| '/settings/archived'
@@ -267,7 +257,6 @@ export interface FileRouteTypes {
| '/usage'
| '/welcome'
| '/pull-requests'
- | '/connect/callback'
| '/projects/$projectKey'
| '/settings/appearance'
| '/settings/archived'
@@ -293,7 +282,6 @@ export interface FileRouteTypes {
| '/usage'
| '/welcome'
| '/_chat/pull-requests'
- | '/connect_/callback'
| '/projects/$projectKey'
| '/settings/appearance'
| '/settings/archived'
@@ -319,7 +307,6 @@ export interface RootRouteChildren {
SettingsRoute: typeof SettingsRouteWithChildren
UsageRoute: typeof UsageRoute
WelcomeRoute: typeof WelcomeRoute
- ConnectCallbackRoute: typeof ConnectCallbackRoute
ProjectsProjectKeyRoute: typeof ProjectsProjectKeyRoute
}
@@ -465,13 +452,6 @@ declare module '@tanstack/react-router' {
preLoaderRoute: typeof ProjectsProjectKeyRouteImport
parentRoute: typeof rootRouteImport
}
- '/connect_/callback': {
- id: '/connect_/callback'
- path: '/connect/callback'
- fullPath: '/connect/callback'
- preLoaderRoute: typeof ConnectCallbackRouteImport
- parentRoute: typeof rootRouteImport
- }
'/_chat/pull-requests': {
id: '/_chat/pull-requests'
path: '/pull-requests'
@@ -553,7 +533,6 @@ const rootRouteChildren: RootRouteChildren = {
SettingsRoute: SettingsRouteWithChildren,
UsageRoute: UsageRoute,
WelcomeRoute: WelcomeRoute,
- ConnectCallbackRoute: ConnectCallbackRoute,
ProjectsProjectKeyRoute: ProjectsProjectKeyRoute,
}
export const routeTree = rootRouteImport
diff --git a/apps/web/src/routes/__root.tsx b/apps/web/src/routes/__root.tsx
index 4db30275ee6..165f475c8f2 100644
--- a/apps/web/src/routes/__root.tsx
+++ b/apps/web/src/routes/__root.tsx
@@ -151,7 +151,7 @@ function RootRouteView() {
};
}, [pathname]);
- if (pathname === "/pair" || pathname === "/connect" || pathname.startsWith("/connect/")) {
+ if (pathname === "/pair" || pathname === "/connect") {
return (
<>
<DocumentTitleSync />
diff --git a/apps/web/src/routes/connect_.callback.tsx b/apps/web/src/routes/connect_.callback.tsx
deleted file mode 100644
index a5beee0b9d3..00000000000
--- a/apps/web/src/routes/connect_.callback.tsx
+++ /dev/null
@@ -1,13 +0,0 @@
-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,
-});
diff --git a/docs/internals/t3-connect.md b/docs/internals/t3-connect.md
index bf02eb3538b..d0329295f4b 100644
--- a/docs/internals/t3-connect.md
+++ b/docs/internals/t3-connect.md
@@ -72,10 +72,15 @@ different credentials. The relay accepts both session-template JWTs and CLI
OAuth tokens; requiring a JWT template for the CLI would reject valid logins.
The CLI is a public OAuth client using PKCE and stores no client secret.
-CLI authorization starts on the hosted `/connect` page so sign-in completes
-before entering Clerk's authorize endpoint. Sending a signed-out browser
-straight to that endpoint loses the authorize parameters during the sign-in
-redirect. The [shared flow](../../packages/shared/src/connectAuth.ts) preserves
-PKCE and state for both loopback and pasted-code callbacks. SSH and headless
-sessions use the pasted-code flow because the browser cannot ordinarily reach a
-listener on the remote machine.
+Loopback CLI authorization starts on the hosted `/connect` page so sign-in
+completes before entering Clerk's authorize endpoint. Sending a signed-out
+browser straight to that endpoint loses the authorize parameters during the
+sign-in redirect. The [shared flow](../../packages/shared/src/connectAuth.ts)
+preserves PKCE and state for the loopback callback.
+
+SSH and headless sessions use Clerk's OAuth device authorization grant because
+the browser cannot ordinarily reach a listener on the remote machine. The CLI
+polls Clerk's token endpoint directly while the user approves a short code on
+Clerk's hosted device page; the hosted app plays no part and there is no
+redirect URI or PKCE. The grant must be enabled on the CLI OAuth application
+or the device endpoint returns an error before any prompt is shown.
diff --git a/docs/operations/connect-setup.md b/docs/operations/connect-setup.md
index 86697d2798c..febc6f82e68 100644
--- a/docs/operations/connect-setup.md
+++ b/docs/operations/connect-setup.md
@@ -39,11 +39,12 @@ depend on. The deploy wrapper writes the resulting relay URL back to the root `.
In Clerk's OAuth applications settings:
1. Create a public OAuth application for the T3 CLI, using authorization-code exchange with PKCE.
-2. Allow both redirect URIs: `http://127.0.0.1:34338/callback` and
- `https://app.t3.codes/connect/callback`. A custom `T3CODE_HOSTED_APP_URL` needs its own
- `/connect/callback` URL. Headless and SSH authorization depend on the hosted redirect.
-3. Enable the `openid`, `profile`, and `email` scopes.
-4. Set `T3CODE_CLERK_CLI_OAUTH_CLIENT_ID` to the generated public client ID in local and release
+2. Allow the redirect URI `http://127.0.0.1:34338/callback`.
+3. Enable the `openid`, `profile`, `email`, and `offline_access` scopes.
+4. Enable **Device authorization grant** on the application. Headless and SSH authorization use
+ it, and Clerk only advertises the device endpoint once it is on. The feature is in beta and
+ Clerk enables it per account on request.
+5. Set `T3CODE_CLERK_CLI_OAUTH_CLIENT_ID` to the generated public client ID in local and release
build environments.
## JWT template
diff --git a/docs/user/remote-access.md b/docs/user/remote-access.md
index 939140aee69..ade33233718 100644
--- a/docs/user/remote-access.md
+++ b/docs/user/remote-access.md
@@ -21,8 +21,9 @@ server with `npx t3 serve`. Saving your sign-in alone does not make the machine
reachable.
On your other device, sign in to the same T3 Connect account and choose the
-environment. Over SSH, the CLI prints a browser link and accepts the returned
-authorization code, so you do not need to forward an OAuth callback port.
+environment. Over SSH, the CLI prints a browser link and a short code. Open the
+link on any device, confirm the code matches, and approve. The CLI continues on
+its own, so you do not need to forward an OAuth callback port.
T3 Connect renews access credentials when needed without disconnecting a healthy
connection. Pull request diffs and provider settings keep working after the
diff --git a/packages/shared/src/connectAuth.test.ts b/packages/shared/src/connectAuth.test.ts
index 275a958f274..b6f1d4055d4 100644
--- a/packages/shared/src/connectAuth.test.ts
+++ b/packages/shared/src/connectAuth.test.ts
@@ -3,19 +3,17 @@ import { describe, expect, it } from "vite-plus/test";
import {
buildConnectAuthorizeRequestUrl,
buildConnectClerkAuthorizeUrl,
- connectCallbackUrl,
connectLoopbackRedirectUri,
- encodeConnectAuthCode,
- parseConnectAuthCode,
readConnectAuthorizeRequest,
} from "./connectAuth.ts";
describe("connectAuth", () => {
- it("round-trips state and challenge through the authorize URL fragment", () => {
+ it("round-trips state, challenge, and loopback port through the authorize URL fragment", () => {
const url = buildConnectAuthorizeRequestUrl({
hostedAppUrl: "https://app.t3.codes",
state: "q7mK9xV2pL4nR8sT6wYzAQ",
challenge: "E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM",
+ loopbackPort: 34338,
});
const parsed = new URL(url);
@@ -25,33 +23,22 @@ describe("connectAuth", () => {
expect(readConnectAuthorizeRequest(parsed)).toEqual({
state: "q7mK9xV2pL4nR8sT6wYzAQ",
challenge: "E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM",
+ loopbackPort: 34338,
});
+ expect(connectLoopbackRedirectUri(34338)).toBe("http://127.0.0.1:34338/callback");
});
- it("rejects authorize requests missing state or challenge", () => {
+ it("rejects authorize requests missing state, challenge, or port", () => {
expect(readConnectAuthorizeRequest(new URL("https://app.t3.codes/connect"))).toBeNull();
expect(
- readConnectAuthorizeRequest(new URL("https://app.t3.codes/connect#state=abc")),
+ readConnectAuthorizeRequest(new URL("https://app.t3.codes/connect#state=abc&port=34338")),
).toBeNull();
expect(
- readConnectAuthorizeRequest(new URL("https://app.t3.codes/connect#challenge=abc")),
+ readConnectAuthorizeRequest(new URL("https://app.t3.codes/connect#challenge=abc&port=34338")),
+ ).toBeNull();
+ expect(
+ readConnectAuthorizeRequest(new URL("https://app.t3.codes/connect#state=abc&challenge=abc")),
).toBeNull();
- });
-
- it("round-trips the loopback port through the authorize URL fragment", () => {
- const url = buildConnectAuthorizeRequestUrl({
- hostedAppUrl: "https://app.t3.codes",
- state: "state-1",
- challenge: "challenge-1",
- loopbackPort: 34338,
- });
-
- expect(readConnectAuthorizeRequest(new URL(url))).toEqual({
- state: "state-1",
- challenge: "challenge-1",
- loopbackPort: 34338,
- });
- expect(connectLoopbackRedirectUri(34338)).toBe("http://127.0.0.1:34338/callback");
});
it("rejects authorize requests whose loopback port is corrupted", () => {
@@ -68,8 +55,8 @@ describe("connectAuth", () => {
buildConnectClerkAuthorizeUrl({
authorizationEndpoint: "https://clerk.t3.codes/oauth/authorize",
clientId: "oauthapp_123",
- redirectUri: connectCallbackUrl("https://app.t3.codes"),
- scopes: ["openid", "profile", "email"],
+ redirectUri: connectLoopbackRedirectUri(34338),
+ scopes: ["openid", "profile", "email", "offline_access"],
state: "state-1",
challenge: "challenge-1",
}),
@@ -78,27 +65,11 @@ describe("connectAuth", () => {
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("redirect_uri")).toBe("http://127.0.0.1:34338/callback");
expect(url.searchParams.get("response_type")).toBe("code");
- expect(url.searchParams.get("scope")).toBe("openid profile email");
+ expect(url.searchParams.get("scope")).toBe("openid profile email offline_access");
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();
- });
});
diff --git a/packages/shared/src/connectAuth.ts b/packages/shared/src/connectAuth.ts
index e2a2af10664..0d9b089c34d 100644
--- a/packages/shared/src/connectAuth.ts
+++ b/packages/shared/src/connectAuth.ts
@@ -3,11 +3,9 @@ import { readHashParams } from "./remote.ts";
const CONNECT_AUTH_STATE_PARAM = "state";
const CONNECT_AUTH_CHALLENGE_PARAM = "challenge";
const CONNECT_AUTH_PORT_PARAM = "port";
-const CONNECT_AUTH_CODE_SEPARATOR = ".";
const CONNECT_LOOPBACK_CALLBACK_PATH = "/callback";
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
@@ -17,20 +15,20 @@ const CONNECT_CALLBACK_PATH = "/connect/callback";
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.
+ * Requested at authorize time by the hosted page and by the CLI's device
+ * authorization request; keep both sides on this single definition.
+ * `offline_access` asks Clerk for the refresh token the CLI relies on.
*/
-export const CONNECT_OAUTH_SCOPES = ["openid", "profile", "email"] as const;
+export const CONNECT_OAUTH_SCOPES = ["openid", "profile", "email", "offline_access"] as const;
export interface ConnectAuthorizeRequest {
readonly state: string;
readonly challenge: string;
/**
- * Present when a loopback CLI initiated the request: the hosted /connect
- * page then asks Clerk to redirect the authorization code straight to
- * `http://127.0.0.1:<port>/callback` instead of the hosted callback page.
+ * The hosted /connect page asks Clerk to redirect the authorization code
+ * straight to `http://127.0.0.1:<port>/callback` on the waiting CLI.
*/
- readonly loopbackPort?: number;
+ readonly loopbackPort: number;
}
/**
@@ -38,26 +36,25 @@ export interface ConnectAuthorizeRequest {
* `code_challenge` ride the fragment so they never reach the hosted app's
* server or CDN logs; neither is a secret.
*
- * Both CLI flows route through the hosted /connect page rather than hitting
+ * The CLI routes through the hosted /connect page rather than hitting
* Clerk's /oauth/authorize directly: a signed-out browser sent straight to
* /oauth/authorize goes through Clerk's sign-in redirect, which does not
* reliably preserve the authorize query parameters (state, response_type,
* code_challenge). The hosted page waits for a Clerk session first, then
- * forwards the request with the parameters intact.
+ * forwards the request with the parameters intact. Headless hosts use the
+ * OAuth device authorization grant instead and never involve this page.
*/
export function buildConnectAuthorizeRequestUrl(input: {
readonly hostedAppUrl: string;
readonly state: string;
readonly challenge: string;
- readonly loopbackPort?: number;
+ readonly loopbackPort: number;
}): 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],
- ...(input.loopbackPort === undefined
- ? []
- : [[CONNECT_AUTH_PORT_PARAM, String(input.loopbackPort)] as [string, string]]),
+ [CONNECT_AUTH_PORT_PARAM, String(input.loopbackPort)],
]).toString();
return url.toString();
}
@@ -66,18 +63,8 @@ export function readConnectAuthorizeRequest(url: URL): ConnectAuthorizeRequest |
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;
- }
- const port = params.get(CONNECT_AUTH_PORT_PARAM);
- if (port === null) {
- return { state, challenge };
- }
- // A present-but-invalid port means the link was corrupted; reject the whole
- // request rather than silently downgrading a loopback flow to the
- // out-of-band one, which would strand the waiting CLI.
- const loopbackPort = parseLoopbackPort(port.trim());
- if (loopbackPort === null) {
+ const loopbackPort = parseLoopbackPort(params.get(CONNECT_AUTH_PORT_PARAM)?.trim() ?? "");
+ if (!state || !challenge || loopbackPort === null) {
return null;
}
return { state, challenge, loopbackPort };
@@ -99,10 +86,6 @@ export function connectLoopbackRedirectUri(port: number): string {
return `http://127.0.0.1:${port}${CONNECT_LOOPBACK_CALLBACK_PATH}`;
}
-export function connectCallbackUrl(hostedAppUrl: string): string {
- return new URL(CONNECT_CALLBACK_PATH, hostedAppUrl).toString();
-}
-
export function buildConnectClerkAuthorizeUrl(input: {
readonly authorizationEndpoint: string;
readonly clientId: string;
@@ -121,50 +104,3 @@ export function buildConnectClerkAuthorizeUrl(input: {
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 };
-}