Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

CliTokenManager.ts

494 lines18.5 KB

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");
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;
166​
167export class CloudCliCredentialRemovalError extends Schema.TaggedErrorClass<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 }
175​
176export class CloudCliCredentialRefreshError extends Schema.TaggedErrorClass<CloudCliCredentialRefreshError>()(
177 "CloudCliCredentialRefreshError",
178 { cause: Schema.Defect() },
179) {
180 override get message(): string {
181 return "Could not refresh the T3 Connect CLI credential.";
182 }
184​
185export class CloudCliCredentialReadError extends Schema.TaggedErrorClass<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 }
193​
194export class CloudCliAuthorizationError extends Schema.TaggedErrorClass<CloudCliAuthorizationError>()(
195 "CloudCliAuthorizationError",
196 { cause: Schema.Defect() },
197) {
198 override get message(): string {
199 return "Could not authorize the T3 Connect CLI.";
200 }
202​
203export class CloudCliAuthorizationTimeoutError extends Schema.TaggedErrorClass<CloudCliAuthorizationTimeoutError>()(
204 "CloudCliAuthorizationTimeoutError",
205 { cause: Schema.Defect() },
206) {
207 override get message(): string {
208 return "Timed out waiting for T3 Connect authorization.";
209 }
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);
239​
240function bytesToString(value: Uint8Array): string {
241 return new TextDecoder().decode(value);
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>;
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​
327export const make = Effect.gen(function* () {
328 // Capture exactly the services the login/refresh flows need at build time
329 // (matching the behavior before the out-of-band flow captured the instances), not
330 // the whole ambient context.
331 const crypto = yield* Crypto.Crypto;
332 const httpClient = yield* HttpClient.HttpClient;
333 const services = Context.make(Crypto.Crypto, crypto).pipe(
334 Context.add(HttpClient.HttpClient, httpClient),
335 );
336 const secrets = yield* ServerSecretStore.ServerSecretStore;
337 const terminal = yield* Terminal.Terminal;
338 const externalLauncher = yield* ExternalLauncher.ExternalLauncher;
339 const semaphore = yield* Semaphore.make(1);
340 const persist = Effect.fn("cloud.cli_token.persist")(function* (token: PersistedToken) {
341 const encoded = yield* encodePersistedToken(token);
342 yield* secrets.set(CLOUD_CLI_OAUTH_TOKEN_SECRET, stringToBytes(encoded));
343 return token;
344 });
345​
346 const clear = secrets
347 .remove(CLOUD_CLI_OAUTH_TOKEN_SECRET)
348 .pipe(Effect.mapError((cause) => new CloudCliCredentialRemovalError({ cause })));
349​
350 const read = Effect.fn("cloud.cli_token.read")(function* () {
351 const encoded = yield* secrets.get(CLOUD_CLI_OAUTH_TOKEN_SECRET);
352 if (Option.isNone(encoded)) return Option.none<PersistedToken>();
353 return Option.some(yield* decodePersistedToken(bytesToString(encoded.value)));
354 });
355​
356 const refresh = Effect.fn("cloud.cli_token.refresh")(function* (token: PersistedToken) {
357 const metadata = yield* cloudCliOAuthConfig;
358 const { token: refreshed } = yield* exchangeToken(metadata, {
359 grant_type: "refresh_token",
360 refresh_token: token.refreshToken,
361 client_id: metadata.clientId,
362 });
363 return refreshed.identity === undefined && token.identity !== undefined
364 ? { ...refreshed, identity: token.identity }
365 : refreshed;
366 });
367​
368 const login = Effect.fn("cloud.cli_token.login")(function* () {
369 const metadata = yield* cloudCliOAuthConfig;
370 const hostedAppUrl = yield* hostedAppUrlConfig;
371 const { verifier, challenge, state } = yield* makePkceRequest;
372 const callback = yield* Deferred.make<string>();
373 const callbackRoute = HttpRouter.add(
374 "GET",
375 "/callback",
376 Effect.gen(function* () {
377 const request = yield* HttpServerRequest.HttpServerRequest;
378 const url = new URL(request.originalUrl, metadata.redirectUri);
379 const code = url.searchParams.get("code");
380 if (url.searchParams.get("state") !== state || !code) {
381 return HttpServerResponse.text("Invalid T3 Connect authorization callback.", {
382 status: 400,
383 });
384 }
385 yield* Deferred.succeed(callback, code);
386 return HttpServerResponse.html(renderLoopbackAuthorizationCompleteHtml());
387 }),
388 );
389 yield* HttpRouter.serve(callbackRoute, {
390 disableListenLog: true,
391 disableLogger: true,
392 }).pipe(
393 Layer.provide(
394 NodeHttpServer.layer(NodeHttp.createServer, {
395 host: "127.0.0.1",
396 port: metadata.loopbackPort,
397 disablePreemptiveShutdown: true,
398 }),
399 ),
400 Layer.build,
401 );
402 // The hosted /connect page establishes a Clerk session before forwarding
403 // the request to /oauth/authorize with the loopback redirect URI. Sending
404 // a signed-out browser to /oauth/authorize directly loses the authorize
405 // parameters across Clerk's sign-in redirect (#5051).
406 const authorizationUrl = buildConnectAuthorizeRequestUrl({
407 hostedAppUrl,
408 state,
409 challenge,
410 loopbackPort: metadata.loopbackPort,
411 });
412 yield* Console.log(formatLoopbackAuthorizationPrompt(authorizationUrl));
413 const authorization = yield* waitForLoopbackAuthorization({
414 authorizationUrl,
415 callback: Deferred.await(callback).pipe(
416 Effect.timeout(CLOUD_CLI_OAUTH_CALLBACK_TIMEOUT),
417 Effect.catchTag("TimeoutError", (cause) =>
418 Effect.fail(new CloudCliAuthorizationTimeoutError({ cause })),
419 ),
420 ),
421 terminal,
422 launchBrowser: externalLauncher.launchBrowser,
423 });
424 if (authorization._tag === "HeadlessRequested") {
425 return authorization;
426 }
427 const { token } = yield* exchangeToken(metadata, {
428 grant_type: "authorization_code",
429 code: authorization.code,
430 redirect_uri: metadata.redirectUri,
431 client_id: metadata.clientId,
432 code_verifier: verifier,
433 });
434 return { _tag: "Authorized", token } as const;
435 });
436​
437 const getExistingNoLock = Effect.fn("cloud.cli_token.get_existing_no_lock")(function* () {
438 const token = yield* read();
439 if (Option.isNone(token)) return token;
440 const now = yield* Clock.currentTimeMillis;
441 if (token.value.expiresAtEpochMs - CLOUD_CLI_OAUTH_REFRESH_EARLY_MS > now) {
442 return token;
443 }
444 return Option.some(yield* refresh(token.value).pipe(Effect.flatMap(persist)));
445 });
446​
447 const getExisting = semaphore.withPermits(1)(
448 getExistingNoLock().pipe(
449 Effect.mapError((cause) => new CloudCliCredentialRefreshError({ cause })),
450 Effect.provide(services),
451 ),
452 );
453 const hasCredential = semaphore.withPermits(1)(
454 read().pipe(
455 Effect.map(Option.isSome),
456 Effect.mapError((cause) => new CloudCliCredentialReadError({ cause })),
457 ),
458 );
459 const get = semaphore.withPermits(1)(
460 Effect.gen(function* () {
461 // A stored credential that can't be read or refreshed (corrupt, revoked,
462 // expired grant) must fall through to a fresh login rather than dead-end
463 // the command — authorizeCli applies the same fallback to out-of-band
464 // authorization.
465 const token = yield* getExistingNoLock().pipe(
466 Effect.orElseSucceed(() => Option.none<PersistedToken>()),
467 );
468 if (Option.isSome(token)) {
469 return { _tag: "Authorized", token: token.value } as const;
470 }
471 const authorization = yield* Effect.scoped(login());
472 return authorization._tag === "Authorized"
473 ? ({ _tag: "Authorized", token: yield* persist(authorization.token) } as const)
474 : authorization;
475 }).pipe(
476 Effect.mapError((cause) =>
477 Terminal.isQuitError(cause) ? cause : new CloudCliAuthorizationError({ cause }),
478 ),
479 Effect.provide(services),
480 ),
481 );
482 const store = Effect.fn("cloud.cli_token.store")(function* (token: PersistedToken) {
483 yield* semaphore.withPermits(1)(
484 persist(token).pipe(
485 Effect.asVoid,
486 Effect.mapError((cause) => new CloudCliAuthorizationError({ cause })),
487 ),
488 );
489 });
490​
491 return CloudCliTokenManager.of({ get, getExisting, hasCredential, store, clear });
492});
493​
494export const layer = Layer.effect(CloudCliTokenManager, make);