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