Open History to see the last commit
1// @effect-diagnostics nodeBuiltinImport:off - The CLI loopback OAuth callback is a Node HTTP boundary.
2import * as NodeHttp from "node:http";
3
4import * as NodeHttpServer from "@effect/platform-node/NodeHttpServer";
5import * as Clock from "effect/Clock";
6import * as Cause from "effect/Cause";
7import * as Console from "effect/Console";
8import * as Context from "effect/Context";
9import * as Crypto from "effect/Crypto";
10import * as Deferred from "effect/Deferred";
11import * as Duration from "effect/Duration";
12import * as Effect from "effect/Effect";
13import * as Base64Url from "effect/encoding/Base64Url";
14import * as Layer from "effect/Layer";
15import * as Option from "effect/Option";
16import * as Queue from "effect/Queue";
17import * as Schema from "effect/Schema";
18import * as Semaphore from "effect/Semaphore";
19import * as Terminal from "effect/Terminal";
20import * as HttpClient from "effect/http/HttpClient";
21import * as HttpClientError from "effect/http/HttpClientError";
22import * as HttpClientRequest from "effect/http/HttpClientRequest";
23import * as HttpClientResponse from "effect/http/HttpClientResponse";
24import * as HttpRouter from "effect/http/HttpRouter";
25import * as HttpServerRequest from "effect/http/HttpServerRequest";
26import * as HttpServerResponse from "effect/http/HttpServerResponse";
27
28import { buildConnectAuthorizeRequestUrl } from "@t3tools/shared/connectAuth";
29
30import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
31import * as ExternalLauncher from "../process/externalLauncher.ts";
32import {
33 cloudCliOAuthConfig,
34 hostedAppUrlConfig,
35 type CloudCliOAuthConfig,
36} from "./publicConfig.ts";
37import { renderLoopbackAuthorizationCompleteHtml } from "./cliAuthHtml.ts";
38
39const CLOUD_CLI_OAUTH_TOKEN_SECRET = "cloud-cli-oauth-token";
40const CLOUD_CLI_OAUTH_CALLBACK_TIMEOUT = Duration.minutes(10);
41const CLOUD_CLI_OAUTH_REFRESH_EARLY_MS = Duration.toMillis(Duration.minutes(5));
42const DEVICE_CODE_GRANT_TYPE = "urn:ietf:params:oauth:grant-type:device_code";
43// RFC 8628 defaults, used only when Clerk omits the field.
44const DEVICE_AUTHORIZATION_DEFAULT_INTERVAL = Duration.seconds(5);
45// RFC 8628 §3.5: a slow_down response means "add 5 seconds to the interval".
46const DEVICE_AUTHORIZATION_SLOW_DOWN_INCREMENT = Duration.seconds(5);
47const boldTerminalText = (value: string): string => `\u001b[1m${value}\u001b[22m`;
48
49function formatLoopbackAuthorizationPrompt(authorizationUrl: string): string {
50 return [
51 "Open this URL to authorize T3 Connect:",
52 ` ${authorizationUrl}`,
53 "",
54 `Press ${boldTerminalText("Enter")} to open it in your browser.`,
55 `No browser on this device? Press ${boldTerminalText("H")} to switch to headless mode.`,
56 ].join("\n");
57}
58
59export type LoopbackAuthorizationResult =
60 | { readonly _tag: "AuthorizationCode"; readonly code: string }
61 | { readonly _tag: "HeadlessRequested" };
62
63const readLoopbackAuthorizationAction = Effect.fn(
64 "cloud.cli_token.read_loopback_authorization_action",
65)(function* (input: Queue.Dequeue<Terminal.UserInput, Cause.Done>) {
66 while (true) {
67 const event = yield* Queue.take(input).pipe(Effect.mapError(() => new Terminal.QuitError({})));
68 const keyName = event.key.name.toLowerCase();
69 if (!event.key.ctrl && !event.key.meta && keyName === "h") {
70 return "headless" as const;
71 }
72 if (keyName === "enter" || keyName === "return") {
73 return "open-browser" as const;
74 }
75 }
76});
77
78export const waitForLoopbackAuthorization = Effect.fn(
79 "cloud.cli_token.wait_for_loopback_authorization",
80)(function* <E, R>(input: {
81 readonly authorizationUrl: string;
82 readonly callback: Effect.Effect<string, E, R>;
83 readonly terminal: Terminal.Terminal;
84 readonly launchBrowser: (
85 url: string,
86 ) => Effect.Effect<void, ExternalLauncher.ExternalLauncherError>;
87}) {
88 return yield* Effect.scoped(
89 Effect.gen(function* () {
90 const terminalInput = yield* input.terminal.readInput;
91 while (true) {
92 const result = yield* Effect.raceFirst(
93 input.callback.pipe(
94 Effect.map((code): LoopbackAuthorizationResult => ({
95 _tag: "AuthorizationCode",
96 code,
97 })),
98 ),
99 readLoopbackAuthorizationAction(terminalInput),
100 );
101 if (typeof result !== "string") {
102 return result;
103 }
104 if (result === "headless") {
105 return { _tag: "HeadlessRequested" } as const;
106 }
107 yield* input
108 .launchBrowser(input.authorizationUrl)
109 .pipe(
110 Effect.catch(() =>
111 Console.warn(
112 `Could not open a browser on this device. Open the URL above manually, or press ${boldTerminalText("H")} to switch to headless mode.`,
113 ),
114 ),
115 );
116 }
117 }),
118 );
119});
120
121const PersistedToken = Schema.Struct({
122 accessToken: Schema.String,
123 refreshToken: Schema.String,
124 expiresAtEpochMs: Schema.Number,
125 identity: Schema.optional(Schema.String),
126});
127export type PersistedToken = typeof PersistedToken.Type;
128
129const PersistedTokenJson = Schema.fromJsonString(PersistedToken);
130const decodePersistedToken = Schema.decodeUnknownEffect(PersistedTokenJson);
131const encodePersistedToken = Schema.encodeEffect(PersistedTokenJson);
132
133const OAuthTokenResponse = Schema.Struct({
134 access_token: Schema.String,
135 refresh_token: Schema.optional(Schema.String),
136 id_token: Schema.optional(Schema.String),
137 expires_in: Schema.Number,
138 token_type: Schema.String,
139});
140
141const OAuthErrorResponse = Schema.Struct({
142 error: Schema.String,
143 error_description: Schema.optional(Schema.String),
144});
145
146const DeviceAuthorizationResponse = Schema.Struct({
147 device_code: Schema.String,
148 user_code: Schema.String,
149 verification_uri: Schema.String,
150 verification_uri_complete: Schema.optional(Schema.String),
151 expires_in: Schema.Number,
152 interval: Schema.optional(Schema.Number),
153});
154
155const OidcIdentityClaimsJson = Schema.fromJsonString(
156 Schema.Struct({
157 email: Schema.optional(Schema.String),
158 preferred_username: Schema.optional(Schema.String),
159 sub: Schema.optional(Schema.String),
160 }),
161);
162const decodeOidcIdentityClaimsJson = Schema.decodeUnknownOption(OidcIdentityClaimsJson);
163
164/**
165 * Best-effort read of the `email` (or fallback) claim from an OIDC id_token.
166 * Only used to show the operator which account they linked, so a malformed
167 * token degrades to "no identity" rather than an error.
168 */
169function idTokenIdentity(idToken: string | undefined): string | null {
170 if (!idToken) return null;
171 const payload = idToken.split(".")[1];
172 if (!payload) return null;
173 const decoded = Base64Url.decodeString(payload);
174 if (decoded._tag !== "Success") return null;
175 const claims = decodeOidcIdentityClaimsJson(decoded.success);
176 if (Option.isNone(claims)) return null;
177 for (const value of [claims.value.email, claims.value.preferred_username, claims.value.sub]) {
178 if (typeof value === "string" && value.length > 0) return value;
179 }
180 return null;
181}
182
183export class CloudCliCredentialRemovalError extends Schema.TaggedError<CloudCliCredentialRemovalError>()(
184 "CloudCliCredentialRemovalError",
185 { cause: Schema.Defect() },
186) {
187 override get message(): string {
188 return "Could not remove the stored T3 Connect CLI credential.";
189 }
190}
191
192export class CloudCliCredentialRefreshError extends Schema.TaggedError<CloudCliCredentialRefreshError>()(
193 "CloudCliCredentialRefreshError",
194 { cause: Schema.Defect() },
195) {
196 override get message(): string {
197 return "Could not refresh the T3 Connect CLI credential.";
198 }
199}
200
201export class CloudCliCredentialReadError extends Schema.TaggedError<CloudCliCredentialReadError>()(
202 "CloudCliCredentialReadError",
203 { cause: Schema.Defect() },
204) {
205 override get message(): string {
206 return "Could not read the stored T3 Connect CLI credential.";
207 }
208}
209
210export class CloudCliAuthorizationError extends Schema.TaggedError<CloudCliAuthorizationError>()(
211 "CloudCliAuthorizationError",
212 { cause: Schema.Defect() },
213) {
214 override get message(): string {
215 return "Could not authorize the T3 Connect CLI.";
216 }
217}
218
219export class CloudCliAuthorizationTimeoutError extends Schema.TaggedError<CloudCliAuthorizationTimeoutError>()(
220 "CloudCliAuthorizationTimeoutError",
221 { cause: Schema.Defect() },
222) {
223 override get message(): string {
224 return "Timed out waiting for T3 Connect authorization.";
225 }
226}
227
228export class CloudCliAuthorizationDeniedError extends Schema.TaggedError<CloudCliAuthorizationDeniedError>()(
229 "CloudCliAuthorizationDeniedError",
230 {},
231) {
232 override get message(): string {
233 return "T3 Connect authorization was denied in the browser.";
234 }
235}
236
237export const CloudCliTokenManagerError = Schema.Union([
238 CloudCliCredentialRemovalError,
239 CloudCliCredentialRefreshError,
240 CloudCliCredentialReadError,
241 CloudCliAuthorizationError,
242 CloudCliAuthorizationTimeoutError,
243 CloudCliAuthorizationDeniedError,
244]);
245export type CloudCliTokenManagerError = typeof CloudCliTokenManagerError.Type;
246
247export class CloudCliTokenManager extends Context.Service<
248 CloudCliTokenManager,
249 {
250 readonly get: Effect.Effect<
251 | { readonly _tag: "Authorized"; readonly token: PersistedToken }
252 | { readonly _tag: "HeadlessRequested" },
253 CloudCliTokenManagerError | Terminal.QuitError
254 >;
255 readonly getExisting: Effect.Effect<Option.Option<PersistedToken>, CloudCliTokenManagerError>;
256 readonly hasCredential: Effect.Effect<boolean, CloudCliTokenManagerError>;
257 readonly store: (token: PersistedToken) => Effect.Effect<void, CloudCliTokenManagerError>;
258 readonly clear: Effect.Effect<void, CloudCliTokenManagerError>;
259 }
260>()("t3/cloud/CliTokenManager/CloudCliTokenManager") {}
261
262function stringToBytes(value: string): Uint8Array {
263 return new TextEncoder().encode(value);
264}
265
266function bytesToString(value: Uint8Array): string {
267 return new TextDecoder().decode(value);
268}
269
270const readTokenResponse = Effect.fn("cloud.cli_token.read_token_response")(function* (
271 response: HttpClientResponse.HttpClientResponse,
272 params: Record<string, string>,
273) {
274 const body = yield* HttpClientResponse.schemaBodyJson(OAuthTokenResponse)(response);
275 const now = yield* Clock.currentTimeMillis;
276 const identity = idTokenIdentity(body.id_token);
277 return {
278 token: {
279 accessToken: body.access_token,
280 refreshToken: body.refresh_token ?? params.refresh_token ?? "",
281 expiresAtEpochMs: now + body.expires_in * 1_000,
282 ...(identity === null ? {} : { identity }),
283 } satisfies PersistedToken,
284 identity,
285 };
286});
287
288const exchangeToken = Effect.fn("cloud.cli_token.exchange")(function* (
289 metadata: Pick<CloudCliOAuthConfig, "tokenEndpoint">,
290 params: Record<string, string>,
291) {
292 const httpClient = (yield* HttpClient.HttpClient).pipe(HttpClient.filterStatusOk);
293 const response = yield* HttpClientRequest.post(metadata.tokenEndpoint).pipe(
294 HttpClientRequest.bodyUrlParams(params),
295 httpClient.execute,
296 );
297 return yield* readTokenResponse(response, params);
298});
299
300const makePkceRequest = Effect.gen(function* () {
301 const crypto = yield* Crypto.Crypto;
302 const verifier = Base64Url.encode(yield* crypto.randomBytes(32));
303 const challenge = Base64Url.encode(
304 yield* crypto.digest("SHA-256", new TextEncoder().encode(verifier)),
305 );
306 const state = Base64Url.encode(yield* crypto.randomBytes(16));
307 return { verifier, challenge, state };
308});
309
310export interface DeviceAuthorizationPrompt {
311 readonly verificationUri: string;
312 readonly verificationUriComplete: string | undefined;
313 readonly userCode: string;
314 readonly expiresIn: Duration.Duration;
315}
316
317const isTransportError = (error: unknown) =>
318 HttpClientError.isHttpClientError(error) && error.reason._tag === "TransportError";
319
320/**
321 * Polls Clerk's token endpoint until the user approves or denies the device
322 * request in the browser (RFC 8628 §3.4/3.5). `authorization_pending` keeps
323 * waiting, while `slow_down` and transient failures widen the interval before
324 * the next tick; the caller bounds the whole loop with the device code's
325 * lifetime.
326 */
327const pollDeviceToken = Effect.fn("cloud.cli_token.poll_device_token")(function* (
328 metadata: Pick<CloudCliOAuthConfig, "tokenEndpoint" | "clientId">,
329 deviceCode: string,
330 initialInterval: Duration.Duration,
331) {
332 const httpClient = yield* HttpClient.HttpClient;
333 const params = {
334 grant_type: DEVICE_CODE_GRANT_TYPE,
335 device_code: deviceCode,
336 client_id: metadata.clientId,
337 };
338 let interval = initialInterval;
339 while (true) {
340 yield* Effect.sleep(interval);
341 const response = yield* HttpClientRequest.post(metadata.tokenEndpoint).pipe(
342 HttpClientRequest.bodyUrlParams(params),
343 httpClient.execute,
344 Effect.asSome,
345 Effect.catchIf(isTransportError, () => Effect.succeedNone),
346 );
347 // Transport failures and upstream 5xx are transient while the device code
348 // is still valid. RFC 8628 §3.5 asks clients to back off before retrying,
349 // so widen the interval like slow_down; drain the body so the connection
350 // returns to the pool for the next poll.
351 if (Option.isNone(response) || response.value.status >= 500) {
352 if (Option.isSome(response)) yield* Effect.ignore(response.value.text);
353 interval = Duration.sum(interval, DEVICE_AUTHORIZATION_SLOW_DOWN_INCREMENT);
354 continue;
355 }
356 if (response.value.status >= 200 && response.value.status < 300) {
357 return yield* readTokenResponse(response.value, params);
358 }
359 const failure = yield* HttpClientResponse.schemaBodyJson(OAuthErrorResponse)(response.value);
360 switch (failure.error) {
361 case "authorization_pending":
362 continue;
363 case "slow_down":
364 interval = Duration.sum(interval, DEVICE_AUTHORIZATION_SLOW_DOWN_INCREMENT);
365 continue;
366 case "expired_token":
367 return yield* new CloudCliAuthorizationTimeoutError({ cause: failure });
368 case "access_denied":
369 return yield* new CloudCliAuthorizationDeniedError();
370 default:
371 return yield* new CloudCliAuthorizationError({
372 cause: failure.error_description ?? failure.error,
373 });
374 }
375 }
376});
377
378/**
379 * OAuth device authorization grant for machines without a local browser
380 * (SSH). Clerk issues a short user code; the user approves it on Clerk's
381 * hosted device page from any browser while this process polls the token
382 * endpoint. Nothing is typed into the terminal and no redirect URI is
383 * involved, so the hosted app plays no part in this flow.
384 */
385export const deviceAuthorizationLogin = Effect.fn("cloud.cli_token.device_authorization_login")(
386 function* <E, R>(showPrompt: (prompt: DeviceAuthorizationPrompt) => Effect.Effect<void, E, R>) {
387 const metadata = yield* cloudCliOAuthConfig;
388 const httpClient = (yield* HttpClient.HttpClient).pipe(HttpClient.filterStatusOk);
389 const authorization = yield* HttpClientRequest.post(metadata.deviceAuthorizationEndpoint).pipe(
390 HttpClientRequest.bodyUrlParams({
391 client_id: metadata.clientId,
392 scope: metadata.scopes.join(" "),
393 }),
394 httpClient.execute,
395 Effect.flatMap(HttpClientResponse.schemaBodyJson(DeviceAuthorizationResponse)),
396 );
397 // Clerk's advertised lifetime and interval are authoritative.
398 const expiresIn = Duration.seconds(authorization.expires_in);
399 const interval =
400 authorization.interval === undefined
401 ? DEVICE_AUTHORIZATION_DEFAULT_INTERVAL
402 : Duration.seconds(authorization.interval);
403 yield* showPrompt({
404 verificationUri: authorization.verification_uri,
405 verificationUriComplete: authorization.verification_uri_complete,
406 userCode: authorization.user_code,
407 expiresIn,
408 });
409 return yield* pollDeviceToken(metadata, authorization.device_code, interval).pipe(
410 Effect.timeout(expiresIn),
411 Effect.catchTags({
412 TimeoutError: (cause) => Effect.fail(new CloudCliAuthorizationTimeoutError({ cause })),
413 }),
414 );
415 },
416);
417
418/** @public Service construction is part of the canonical Effect module API. */
419export const make = Effect.gen(function* () {
420 // Capture exactly the services the login/refresh flows need at build time,
421 // not the whole ambient context.
422 const crypto = yield* Crypto.Crypto;
423 const httpClient = yield* HttpClient.HttpClient;
424 const services = Context.make(Crypto.Crypto, crypto).pipe(
425 Context.add(HttpClient.HttpClient, httpClient),
426 );
427 const secrets = yield* ServerSecretStore.ServerSecretStore;
428 const terminal = yield* Terminal.Terminal;
429 const externalLauncher = yield* ExternalLauncher.ExternalLauncher;
430 const semaphore = yield* Semaphore.make(1);
431 const persist = Effect.fn("cloud.cli_token.persist")(function* (token: PersistedToken) {
432 const encoded = yield* encodePersistedToken(token);
433 yield* secrets.set(CLOUD_CLI_OAUTH_TOKEN_SECRET, stringToBytes(encoded));
434 return token;
435 });
436
437 const clear = secrets
438 .remove(CLOUD_CLI_OAUTH_TOKEN_SECRET)
439 .pipe(Effect.mapError((cause) => new CloudCliCredentialRemovalError({ cause })));
440
441 const read = Effect.fn("cloud.cli_token.read")(function* () {
442 const encoded = yield* secrets.get(CLOUD_CLI_OAUTH_TOKEN_SECRET);
443 if (Option.isNone(encoded)) return Option.none<PersistedToken>();
444 return Option.some(yield* decodePersistedToken(bytesToString(encoded.value)));
445 });
446
447 const refresh = Effect.fn("cloud.cli_token.refresh")(function* (token: PersistedToken) {
448 const metadata = yield* cloudCliOAuthConfig;
449 const { token: refreshed } = yield* exchangeToken(metadata, {
450 grant_type: "refresh_token",
451 refresh_token: token.refreshToken,
452 client_id: metadata.clientId,
453 });
454 return refreshed.identity === undefined && token.identity !== undefined
455 ? { ...refreshed, identity: token.identity }
456 : refreshed;
457 });
458
459 const login = Effect.fn("cloud.cli_token.login")(function* () {
460 const metadata = yield* cloudCliOAuthConfig;
461 const hostedAppUrl = yield* hostedAppUrlConfig;
462 const { verifier, challenge, state } = yield* makePkceRequest;
463 const callback = yield* Deferred.make<string>();
464 const layerCallbackRoute = HttpRouter.add(
465 "GET",
466 "/callback",
467 Effect.gen(function* () {
468 const request = yield* HttpServerRequest.HttpServerRequest;
469 const url = new URL(request.originalUrl, metadata.redirectUri);
470 const code = url.searchParams.get("code");
471 if (url.searchParams.get("state") !== state || !code) {
472 return HttpServerResponse.text("Invalid T3 Connect authorization callback.", {
473 status: 400,
474 });
475 }
476 yield* Deferred.succeed(callback, code);
477 return HttpServerResponse.html(renderLoopbackAuthorizationCompleteHtml());
478 }),
479 );
480 yield* HttpRouter.serve(layerCallbackRoute, {
481 disableListenLog: true,
482 disableLogger: true,
483 }).pipe(
484 Layer.provide(
485 NodeHttpServer.layer(NodeHttp.createServer, {
486 host: "127.0.0.1",
487 port: metadata.loopbackPort,
488 disablePreemptiveShutdown: true,
489 }),
490 ),
491 Layer.build,
492 );
493 // The hosted /connect page establishes a Clerk session before forwarding
494 // the request to /oauth/authorize with the loopback redirect URI. Sending
495 // a signed-out browser to /oauth/authorize directly loses the authorize
496 // parameters across Clerk's sign-in redirect (#5051).
497 const authorizationUrl = buildConnectAuthorizeRequestUrl({
498 hostedAppUrl,
499 state,
500 challenge,
501 loopbackPort: metadata.loopbackPort,
502 });
503 yield* Console.log(formatLoopbackAuthorizationPrompt(authorizationUrl));
504 const authorization = yield* waitForLoopbackAuthorization({
505 authorizationUrl,
506 callback: Deferred.await(callback).pipe(
507 Effect.timeout(CLOUD_CLI_OAUTH_CALLBACK_TIMEOUT),
508 Effect.catchTags({
509 TimeoutError: (cause) => Effect.fail(new CloudCliAuthorizationTimeoutError({ cause })),
510 }),
511 ),
512 terminal,
513 launchBrowser: externalLauncher.launchBrowser,
514 });
515 if (authorization._tag === "HeadlessRequested") {
516 return authorization;
517 }
518 const { token } = yield* exchangeToken(metadata, {
519 grant_type: "authorization_code",
520 code: authorization.code,
521 redirect_uri: metadata.redirectUri,
522 client_id: metadata.clientId,
523 code_verifier: verifier,
524 });
525 return { _tag: "Authorized", token } as const;
526 });
527
528 const getExistingNoLock = Effect.fn("cloud.cli_token.get_existing_no_lock")(function* () {
529 const token = yield* read();
530 if (Option.isNone(token)) return token;
531 const now = yield* Clock.currentTimeMillis;
532 if (token.value.expiresAtEpochMs - CLOUD_CLI_OAUTH_REFRESH_EARLY_MS > now) {
533 return token;
534 }
535 return Option.some(yield* refresh(token.value).pipe(Effect.flatMap(persist)));
536 });
537
538 const getExisting = semaphore.withPermits(1)(
539 getExistingNoLock().pipe(
540 Effect.mapError((cause) => new CloudCliCredentialRefreshError({ cause })),
541 Effect.provide(services),
542 ),
543 );
544 const hasCredential = semaphore.withPermits(1)(
545 read().pipe(
546 Effect.map(Option.isSome),
547 Effect.mapError((cause) => new CloudCliCredentialReadError({ cause })),
548 ),
549 );
550 const get = semaphore.withPermits(1)(
551 Effect.gen(function* () {
552 // A stored credential that can't be read or refreshed (corrupt, revoked,
553 // expired grant) must fall through to a fresh login rather than dead-end
554 // the command — authorizeCli applies the same fallback to device
555 // authorization.
556 const token = yield* getExistingNoLock().pipe(
557 Effect.orElseSucceed(() => Option.none<PersistedToken>()),
558 );
559 if (Option.isSome(token)) {
560 return { _tag: "Authorized", token: token.value } as const;
561 }
562 const authorization = yield* Effect.scoped(login());
563 return authorization._tag === "Authorized"
564 ? ({ _tag: "Authorized", token: yield* persist(authorization.token) } as const)
565 : authorization;
566 }).pipe(
567 Effect.mapError((cause) =>
568 Terminal.isQuitError(cause) ? cause : new CloudCliAuthorizationError({ cause }),
569 ),
570 Effect.provide(services),
571 ),
572 );
573 const store = Effect.fn("cloud.cli_token.store")(function* (token: PersistedToken) {
574 yield* semaphore.withPermits(1)(
575 persist(token).pipe(
576 Effect.asVoid,
577 Effect.mapError((cause) => new CloudCliAuthorizationError({ cause })),
578 ),
579 );
580 });
581
582 return CloudCliTokenManager.of({ get, getExisting, hasCredential, store, clear });
583});
584
585export const layer = Layer.effect(CloudCliTokenManager, make);