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 Encoding from "effect/Encoding";
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/unstable/http/HttpClient";
21import * as HttpClientRequest from "effect/unstable/http/HttpClientRequest";
22import * as HttpClientResponse from "effect/unstable/http/HttpClientResponse";
23import * as HttpRouter from "effect/unstable/http/HttpRouter";
24import * as HttpServerRequest from "effect/unstable/http/HttpServerRequest";
25import * as HttpServerResponse from "effect/unstable/http/HttpServerResponse";
26
27import {
28 buildConnectAuthorizeRequestUrl,
29 checkConnectAuthCode,
30 connectCallbackUrl,
31} from "@t3tools/shared/connectAuth";
32
33import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
34import * as ExternalLauncher from "../process/externalLauncher.ts";
35import {
36 cloudCliOAuthConfig,
37 hostedAppUrlConfig,
38 type CloudCliOAuthConfig,
39} from "./publicConfig.ts";
40import { renderLoopbackAuthorizationCompleteHtml } from "./cliAuthHtml.ts";
41
42const CLOUD_CLI_OAUTH_TOKEN_SECRET = "cloud-cli-oauth-token";
43const CLOUD_CLI_OAUTH_CALLBACK_TIMEOUT = Duration.minutes(10);
44const CLOUD_CLI_OAUTH_REFRESH_EARLY_MS = Duration.toMillis(Duration.minutes(5));
45const boldTerminalText = (value: string): string => `\u001b[1m${value}\u001b[22m`;
46
47function formatLoopbackAuthorizationPrompt(authorizationUrl: string): string {
48 return [
49 "Open this URL to authorize T3 Connect:",
50 ` ${authorizationUrl}`,
51 "",
52 `Press ${boldTerminalText("Enter")} to open it in your browser.`,
53 `No browser on this device? Press ${boldTerminalText("H")} to switch to headless mode.`,
54 ].join("\n");
55}
56
57export type LoopbackAuthorizationResult =
58 | { readonly _tag: "AuthorizationCode"; readonly code: string }
59 | { readonly _tag: "HeadlessRequested" };
60
61const readLoopbackAuthorizationAction = Effect.fn(
62 "cloud.cli_token.read_loopback_authorization_action",
63)(function* (input: Queue.Dequeue<Terminal.UserInput, Cause.Done>) {
64 while (true) {
65 const event = yield* Queue.take(input).pipe(Effect.mapError(() => new Terminal.QuitError({})));
66 const keyName = event.key.name.toLowerCase();
67 if (!event.key.ctrl && !event.key.meta && keyName === "h") {
68 return "headless" as const;
69 }
70 if (keyName === "enter" || keyName === "return") {
71 return "open-browser" as const;
72 }
73 }
74});
75
76export const waitForLoopbackAuthorization = Effect.fn(
77 "cloud.cli_token.wait_for_loopback_authorization",
78)(function* <E, R>(input: {
79 readonly authorizationUrl: string;
80 readonly callback: Effect.Effect<string, E, R>;
81 readonly terminal: Terminal.Terminal;
82 readonly launchBrowser: (
83 url: string,
84 ) => Effect.Effect<void, ExternalLauncher.ExternalLauncherError>;
85}) {
86 return yield* Effect.scoped(
87 Effect.gen(function* () {
88 const terminalInput = yield* input.terminal.readInput;
89 while (true) {
90 const result = yield* Effect.raceFirst(
91 input.callback.pipe(
92 Effect.map((code): LoopbackAuthorizationResult => ({
93 _tag: "AuthorizationCode",
94 code,
95 })),
96 ),
97 readLoopbackAuthorizationAction(terminalInput),
98 );
99 if (typeof result !== "string") {
100 return result;
101 }
102 if (result === "headless") {
103 return { _tag: "HeadlessRequested" } as const;
104 }
105 yield* input
106 .launchBrowser(input.authorizationUrl)
107 .pipe(
108 Effect.catch(() =>
109 Console.warn(
110 `Could not open a browser on this device. Open the URL above manually, or press ${boldTerminalText("H")} to switch to headless mode.`,
111 ),
112 ),
113 );
114 }
115 }),
116 );
117});
118
119const PersistedToken = Schema.Struct({
120 accessToken: Schema.String,
121 refreshToken: Schema.String,
122 expiresAtEpochMs: Schema.Number,
123 identity: Schema.optional(Schema.String),
124});
125export type PersistedToken = typeof PersistedToken.Type;
126
127const PersistedTokenJson = Schema.fromJsonString(PersistedToken);
128const decodePersistedToken = Schema.decodeUnknownEffect(PersistedTokenJson);
129const encodePersistedToken = Schema.encodeEffect(PersistedTokenJson);
130
131const OAuthTokenResponse = Schema.Struct({
132 access_token: Schema.String,
133 refresh_token: Schema.optional(Schema.String),
134 id_token: Schema.optional(Schema.String),
135 expires_in: Schema.Number,
136 token_type: Schema.String,
137});
138
139const OidcIdentityClaimsJson = Schema.fromJsonString(
140 Schema.Struct({
141 email: Schema.optional(Schema.String),
142 preferred_username: Schema.optional(Schema.String),
143 sub: Schema.optional(Schema.String),
144 }),
145);
146const decodeOidcIdentityClaimsJson = Schema.decodeUnknownOption(OidcIdentityClaimsJson);
147
148/**
149 * Best-effort read of the `email` (or fallback) claim from an OIDC id_token.
150 * Only used to show the operator which account they linked, so a malformed
151 * token degrades to "no identity" rather than an error.
152 */
153function idTokenIdentity(idToken: string | undefined): string | null {
154 if (!idToken) return null;
155 const payload = idToken.split(".")[1];
156 if (!payload) return null;
157 const decoded = Encoding.decodeBase64UrlString(payload);
158 if (decoded._tag !== "Success") return null;
159 const claims = decodeOidcIdentityClaimsJson(decoded.success);
160 if (Option.isNone(claims)) return null;
161 for (const value of [claims.value.email, claims.value.preferred_username, claims.value.sub]) {
162 if (typeof value === "string" && value.length > 0) return value;
163 }
164 return null;
165}
166
167export class CloudCliCredentialRemovalError extends Schema.TaggedError<CloudCliCredentialRemovalError>()(
168 "CloudCliCredentialRemovalError",
169 { cause: Schema.Defect() },
170) {
171 override get message(): string {
172 return "Could not remove the stored T3 Connect CLI credential.";
173 }
174}
175
176export class CloudCliCredentialRefreshError extends Schema.TaggedError<CloudCliCredentialRefreshError>()(
177 "CloudCliCredentialRefreshError",
178 { cause: Schema.Defect() },
179) {
180 override get message(): string {
181 return "Could not refresh the T3 Connect CLI credential.";
182 }
183}
184
185export class CloudCliCredentialReadError extends Schema.TaggedError<CloudCliCredentialReadError>()(
186 "CloudCliCredentialReadError",
187 { cause: Schema.Defect() },
188) {
189 override get message(): string {
190 return "Could not read the stored T3 Connect CLI credential.";
191 }
192}
193
194export class CloudCliAuthorizationError extends Schema.TaggedError<CloudCliAuthorizationError>()(
195 "CloudCliAuthorizationError",
196 { cause: Schema.Defect() },
197) {
198 override get message(): string {
199 return "Could not authorize the T3 Connect CLI.";
200 }
201}
202
203export class CloudCliAuthorizationTimeoutError extends Schema.TaggedError<CloudCliAuthorizationTimeoutError>()(
204 "CloudCliAuthorizationTimeoutError",
205 { cause: Schema.Defect() },
206) {
207 override get message(): string {
208 return "Timed out waiting for T3 Connect authorization.";
209 }
210}
211
212export const CloudCliTokenManagerError = Schema.Union([
213 CloudCliCredentialRemovalError,
214 CloudCliCredentialRefreshError,
215 CloudCliCredentialReadError,
216 CloudCliAuthorizationError,
217 CloudCliAuthorizationTimeoutError,
218]);
219export type CloudCliTokenManagerError = typeof CloudCliTokenManagerError.Type;
220
221export class CloudCliTokenManager extends Context.Service<
222 CloudCliTokenManager,
223 {
224 readonly get: Effect.Effect<
225 | { readonly _tag: "Authorized"; readonly token: PersistedToken }
226 | { readonly _tag: "HeadlessRequested" },
227 CloudCliTokenManagerError | Terminal.QuitError
228 >;
229 readonly getExisting: Effect.Effect<Option.Option<PersistedToken>, CloudCliTokenManagerError>;
230 readonly hasCredential: Effect.Effect<boolean, CloudCliTokenManagerError>;
231 readonly store: (token: PersistedToken) => Effect.Effect<void, CloudCliTokenManagerError>;
232 readonly clear: Effect.Effect<void, CloudCliTokenManagerError>;
233 }
234>()("t3/cloud/CliTokenManager/CloudCliTokenManager") {}
235
236function stringToBytes(value: string): Uint8Array {
237 return new TextEncoder().encode(value);
238}
239
240function bytesToString(value: Uint8Array): string {
241 return new TextDecoder().decode(value);
242}
243
244const exchangeToken = Effect.fn("cloud.cli_token.exchange")(function* (
245 metadata: Pick<CloudCliOAuthConfig, "tokenEndpoint">,
246 params: Record<string, string>,
247) {
248 const httpClient = (yield* HttpClient.HttpClient).pipe(HttpClient.filterStatusOk);
249 const response = yield* HttpClientRequest.post(metadata.tokenEndpoint).pipe(
250 HttpClientRequest.bodyUrlParams(params),
251 httpClient.execute,
252 Effect.flatMap(HttpClientResponse.schemaBodyJson(OAuthTokenResponse)),
253 );
254 const now = yield* Clock.currentTimeMillis;
255 const identity = idTokenIdentity(response.id_token);
256 return {
257 token: {
258 accessToken: response.access_token,
259 refreshToken: response.refresh_token ?? params.refresh_token ?? "",
260 expiresAtEpochMs: now + response.expires_in * 1_000,
261 ...(identity === null ? {} : { identity }),
262 } satisfies PersistedToken,
263 identity,
264 };
265});
266
267const makePkceRequest = Effect.gen(function* () {
268 const crypto = yield* Crypto.Crypto;
269 const verifier = Encoding.encodeBase64Url(yield* crypto.randomBytes(32));
270 const challenge = Encoding.encodeBase64Url(
271 yield* crypto.digest("SHA-256", new TextEncoder().encode(verifier)),
272 );
273 const state = Encoding.encodeBase64Url(yield* crypto.randomBytes(16));
274 return { verifier, challenge, state };
275});
276
277export interface OutOfBandOAuthPromptInput {
278 readonly authorizeUrl: string;
279 readonly validate: (value: string) => Effect.Effect<string, string>;
280}
281
282/**
283 * Out-of-band OAuth for machines without a local browser (SSH). The user
284 * opens the hosted /connect URL elsewhere, signs in, and enters the displayed
285 * code in this terminal. The PKCE verifier never leaves this process, so the
286 * authorization code is useless to an observer, and the state bundled into
287 * the blob preserves the loopback flow's CSRF check.
288 */
289export const outOfBandOAuthLogin = Effect.fn("cloud.cli_token.out_of_band_oauth_login")(function* <
290 E,
291 R,
292>(promptForCode: (input: OutOfBandOAuthPromptInput) => Effect.Effect<string, E, R>) {
293 const metadata = yield* cloudCliOAuthConfig;
294 const hostedAppUrl = yield* hostedAppUrlConfig;
295 const { verifier, challenge, state } = yield* makePkceRequest;
296
297 const authorizationCode = yield* promptForCode({
298 authorizeUrl: buildConnectAuthorizeRequestUrl({ hostedAppUrl, state, challenge }),
299 validate: (value) => {
300 const checked = checkConnectAuthCode(value, state);
301 return typeof checked === "string" ? Effect.fail(checked) : Effect.succeed(value);
302 },
303 }).pipe(
304 // Clerk authorization codes expire on this horizon anyway; matching the
305 // loopback flow's timeout turns an abandoned prompt into a clear error.
306 Effect.timeout(CLOUD_CLI_OAUTH_CALLBACK_TIMEOUT),
307 Effect.catchTag("TimeoutError", (cause) =>
308 Effect.fail(new CloudCliAuthorizationTimeoutError({ cause })),
309 ),
310 );
311 // promptForCode is caller-supplied, so re-check the returned value rather
312 // than trusting that the prompt ran validate.
313 const authCode = checkConnectAuthCode(authorizationCode, state);
314 if (typeof authCode === "string") {
315 return yield* new CloudCliAuthorizationError({ cause: authCode });
316 }
317
318 return yield* exchangeToken(metadata, {
319 grant_type: "authorization_code",
320 code: authCode.code,
321 redirect_uri: connectCallbackUrl(hostedAppUrl),
322 client_id: metadata.clientId,
323 code_verifier: verifier,
324 });
325});
326
327/** @public Service construction is part of the canonical Effect module API. */
328export const make = Effect.gen(function* () {
329 // Capture exactly the services the login/refresh flows need at build time
330 // (matching the behavior before the out-of-band flow captured the instances), not
331 // the whole ambient context.
332 const crypto = yield* Crypto.Crypto;
333 const httpClient = yield* HttpClient.HttpClient;
334 const services = Context.make(Crypto.Crypto, crypto).pipe(
335 Context.add(HttpClient.HttpClient, httpClient),
336 );
337 const secrets = yield* ServerSecretStore.ServerSecretStore;
338 const terminal = yield* Terminal.Terminal;
339 const externalLauncher = yield* ExternalLauncher.ExternalLauncher;
340 const semaphore = yield* Semaphore.make(1);
341 const persist = Effect.fn("cloud.cli_token.persist")(function* (token: PersistedToken) {
342 const encoded = yield* encodePersistedToken(token);
343 yield* secrets.set(CLOUD_CLI_OAUTH_TOKEN_SECRET, stringToBytes(encoded));
344 return token;
345 });
346
347 const clear = secrets
348 .remove(CLOUD_CLI_OAUTH_TOKEN_SECRET)
349 .pipe(Effect.mapError((cause) => new CloudCliCredentialRemovalError({ cause })));
350
351 const read = Effect.fn("cloud.cli_token.read")(function* () {
352 const encoded = yield* secrets.get(CLOUD_CLI_OAUTH_TOKEN_SECRET);
353 if (Option.isNone(encoded)) return Option.none<PersistedToken>();
354 return Option.some(yield* decodePersistedToken(bytesToString(encoded.value)));
355 });
356
357 const refresh = Effect.fn("cloud.cli_token.refresh")(function* (token: PersistedToken) {
358 const metadata = yield* cloudCliOAuthConfig;
359 const { token: refreshed } = yield* exchangeToken(metadata, {
360 grant_type: "refresh_token",
361 refresh_token: token.refreshToken,
362 client_id: metadata.clientId,
363 });
364 return refreshed.identity === undefined && token.identity !== undefined
365 ? { ...refreshed, identity: token.identity }
366 : refreshed;
367 });
368
369 const login = Effect.fn("cloud.cli_token.login")(function* () {
370 const metadata = yield* cloudCliOAuthConfig;
371 const hostedAppUrl = yield* hostedAppUrlConfig;
372 const { verifier, challenge, state } = yield* makePkceRequest;
373 const callback = yield* Deferred.make<string>();
374 const callbackRoute = HttpRouter.add(
375 "GET",
376 "/callback",
377 Effect.gen(function* () {
378 const request = yield* HttpServerRequest.HttpServerRequest;
379 const url = new URL(request.originalUrl, metadata.redirectUri);
380 const code = url.searchParams.get("code");
381 if (url.searchParams.get("state") !== state || !code) {
382 return HttpServerResponse.text("Invalid T3 Connect authorization callback.", {
383 status: 400,
384 });
385 }
386 yield* Deferred.succeed(callback, code);
387 return HttpServerResponse.html(renderLoopbackAuthorizationCompleteHtml());
388 }),
389 );
390 yield* HttpRouter.serve(callbackRoute, {
391 disableListenLog: true,
392 disableLogger: true,
393 }).pipe(
394 Layer.provide(
395 NodeHttpServer.layer(NodeHttp.createServer, {
396 host: "127.0.0.1",
397 port: metadata.loopbackPort,
398 disablePreemptiveShutdown: true,
399 }),
400 ),
401 Layer.build,
402 );
403 // The hosted /connect page establishes a Clerk session before forwarding
404 // the request to /oauth/authorize with the loopback redirect URI. Sending
405 // a signed-out browser to /oauth/authorize directly loses the authorize
406 // parameters across Clerk's sign-in redirect (#5051).
407 const authorizationUrl = buildConnectAuthorizeRequestUrl({
408 hostedAppUrl,
409 state,
410 challenge,
411 loopbackPort: metadata.loopbackPort,
412 });
413 yield* Console.log(formatLoopbackAuthorizationPrompt(authorizationUrl));
414 const authorization = yield* waitForLoopbackAuthorization({
415 authorizationUrl,
416 callback: Deferred.await(callback).pipe(
417 Effect.timeout(CLOUD_CLI_OAUTH_CALLBACK_TIMEOUT),
418 Effect.catchTag("TimeoutError", (cause) =>
419 Effect.fail(new CloudCliAuthorizationTimeoutError({ cause })),
420 ),
421 ),
422 terminal,
423 launchBrowser: externalLauncher.launchBrowser,
424 });
425 if (authorization._tag === "HeadlessRequested") {
426 return authorization;
427 }
428 const { token } = yield* exchangeToken(metadata, {
429 grant_type: "authorization_code",
430 code: authorization.code,
431 redirect_uri: metadata.redirectUri,
432 client_id: metadata.clientId,
433 code_verifier: verifier,
434 });
435 return { _tag: "Authorized", token } as const;
436 });
437
438 const getExistingNoLock = Effect.fn("cloud.cli_token.get_existing_no_lock")(function* () {
439 const token = yield* read();
440 if (Option.isNone(token)) return token;
441 const now = yield* Clock.currentTimeMillis;
442 if (token.value.expiresAtEpochMs - CLOUD_CLI_OAUTH_REFRESH_EARLY_MS > now) {
443 return token;
444 }
445 return Option.some(yield* refresh(token.value).pipe(Effect.flatMap(persist)));
446 });
447
448 const getExisting = semaphore.withPermits(1)(
449 getExistingNoLock().pipe(
450 Effect.mapError((cause) => new CloudCliCredentialRefreshError({ cause })),
451 Effect.provide(services),
452 ),
453 );
454 const hasCredential = semaphore.withPermits(1)(
455 read().pipe(
456 Effect.map(Option.isSome),
457 Effect.mapError((cause) => new CloudCliCredentialReadError({ cause })),
458 ),
459 );
460 const get = semaphore.withPermits(1)(
461 Effect.gen(function* () {
462 // A stored credential that can't be read or refreshed (corrupt, revoked,
463 // expired grant) must fall through to a fresh login rather than dead-end
464 // the command — authorizeCli applies the same fallback to out-of-band
465 // authorization.
466 const token = yield* getExistingNoLock().pipe(
467 Effect.orElseSucceed(() => Option.none<PersistedToken>()),
468 );
469 if (Option.isSome(token)) {
470 return { _tag: "Authorized", token: token.value } as const;
471 }
472 const authorization = yield* Effect.scoped(login());
473 return authorization._tag === "Authorized"
474 ? ({ _tag: "Authorized", token: yield* persist(authorization.token) } as const)
475 : authorization;
476 }).pipe(
477 Effect.mapError((cause) =>
478 Terminal.isQuitError(cause) ? cause : new CloudCliAuthorizationError({ cause }),
479 ),
480 Effect.provide(services),
481 ),
482 );
483 const store = Effect.fn("cloud.cli_token.store")(function* (token: PersistedToken) {
484 yield* semaphore.withPermits(1)(
485 persist(token).pipe(
486 Effect.asVoid,
487 Effect.mapError((cause) => new CloudCliAuthorizationError({ cause })),
488 ),
489 );
490 });
491
492 return CloudCliTokenManager.of({ get, getExisting, hasCredential, store, clear });
493});
494
495export const layer = Layer.effect(CloudCliTokenManager, make);