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

CliTokenManager.ts

491 lines18.3 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 buildConnectClerkAuthorizeUrl,
30 checkConnectAuthCode,
31 connectCallbackUrl,
32} from "@t3tools/shared/connectAuth";
33​
34import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
35import * as ExternalLauncher from "../process/externalLauncher.ts";
36import {
37 cloudCliOAuthConfig,
38 hostedAppUrlConfig,
39 type CloudCliOAuthConfig,
40} from "./publicConfig.ts";
41import { renderLoopbackAuthorizationCompleteHtml } from "./cliAuthHtml.ts";
42​
43const CLOUD_CLI_OAUTH_TOKEN_SECRET = "cloud-cli-oauth-token";
44const CLOUD_CLI_OAUTH_CALLBACK_TIMEOUT = Duration.minutes(10);
45const CLOUD_CLI_OAUTH_REFRESH_EARLY_MS = Duration.toMillis(Duration.minutes(5));
46const boldTerminalText = (value: string): string => `\u001b[1m${value}\u001b[22m`;
47​
48export function formatLoopbackAuthorizationPrompt(authorizationUrl: string): string {
49 return [
50 "Open this URL to authorize T3 Connect:",
51 ` ${authorizationUrl}`,
52 "",
53 `Press ${boldTerminalText("Enter")} to open it in your browser.`,
54 `No browser on this device? Press ${boldTerminalText("H")} to switch to headless mode.`,
55 ].join("\n");
57​
58export type LoopbackAuthorizationResult =
59 | { readonly _tag: "AuthorizationCode"; readonly code: string }
60 | { readonly _tag: "HeadlessRequested" };
61​
62const readLoopbackAuthorizationAction = Effect.fn(
63 "cloud.cli_token.read_loopback_authorization_action",
64)(function* (input: Queue.Dequeue<Terminal.UserInput, Cause.Done>) {
65 while (true) {
66 const event = yield* Queue.take(input).pipe(Effect.mapError(() => new Terminal.QuitError({})));
67 const keyName = event.key.name.toLowerCase();
68 if (!event.key.ctrl && !event.key.meta && keyName === "h") {
69 return "headless" as const;
70 }
71 if (keyName === "enter" || keyName === "return") {
72 return "open-browser" as const;
73 }
74 }
75});
76​
77export const waitForLoopbackAuthorization = Effect.fn(
78 "cloud.cli_token.wait_for_loopback_authorization",
79)(function* <E, R>(input: {
80 readonly authorizationUrl: string;
81 readonly callback: Effect.Effect<string, E, R>;
82 readonly terminal: Terminal.Terminal;
83 readonly launchBrowser: (
84 url: string,
85 ) => Effect.Effect<void, ExternalLauncher.ExternalLauncherError>;
86}) {
87 return yield* Effect.scoped(
88 Effect.gen(function* () {
89 const terminalInput = yield* input.terminal.readInput;
90 while (true) {
91 const result = yield* Effect.raceFirst(
92 input.callback.pipe(
93 Effect.map(
94 (code): LoopbackAuthorizationResult => ({ _tag: "AuthorizationCode", 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 { 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: 34338,
396 disablePreemptiveShutdown: true,
397 }),
398 ),
399 Layer.build,
400 );
401 const authorizationUrl = buildConnectClerkAuthorizeUrl({
402 authorizationEndpoint: metadata.authorizationEndpoint,
403 clientId: metadata.clientId,
404 redirectUri: metadata.redirectUri,
405 scopes: metadata.scopes,
406 state,
407 challenge,
408 });
409 yield* Console.log(formatLoopbackAuthorizationPrompt(authorizationUrl));
410 const authorization = yield* waitForLoopbackAuthorization({
411 authorizationUrl,
412 callback: Deferred.await(callback).pipe(
413 Effect.timeout(CLOUD_CLI_OAUTH_CALLBACK_TIMEOUT),
414 Effect.catchTag("TimeoutError", (cause) =>
415 Effect.fail(new CloudCliAuthorizationTimeoutError({ cause })),
416 ),
417 ),
418 terminal,
419 launchBrowser: externalLauncher.launchBrowser,
420 });
421 if (authorization._tag === "HeadlessRequested") {
422 return authorization;
423 }
424 const { token } = yield* exchangeToken(metadata, {
425 grant_type: "authorization_code",
426 code: authorization.code,
427 redirect_uri: metadata.redirectUri,
428 client_id: metadata.clientId,
429 code_verifier: verifier,
430 });
431 return { _tag: "Authorized", token } as const;
432 });
433​
434 const getExistingNoLock = Effect.fn("cloud.cli_token.get_existing_no_lock")(function* () {
435 const token = yield* read();
436 if (Option.isNone(token)) return token;
437 const now = yield* Clock.currentTimeMillis;
438 if (token.value.expiresAtEpochMs - CLOUD_CLI_OAUTH_REFRESH_EARLY_MS > now) {
439 return token;
440 }
441 return Option.some(yield* refresh(token.value).pipe(Effect.flatMap(persist)));
442 });
443​
444 const getExisting = semaphore.withPermits(1)(
445 getExistingNoLock().pipe(
446 Effect.mapError((cause) => new CloudCliCredentialRefreshError({ cause })),
447 Effect.provide(services),
448 ),
449 );
450 const hasCredential = semaphore.withPermits(1)(
451 read().pipe(
452 Effect.map(Option.isSome),
453 Effect.mapError((cause) => new CloudCliCredentialReadError({ cause })),
454 ),
455 );
456 const get = semaphore.withPermits(1)(
457 Effect.gen(function* () {
458 // A stored credential that can't be read or refreshed (corrupt, revoked,
459 // expired grant) must fall through to a fresh login rather than dead-end
460 // the command — authorizeCli applies the same fallback to out-of-band
461 // authorization.
462 const token = yield* getExistingNoLock().pipe(
463 Effect.orElseSucceed(() => Option.none<PersistedToken>()),
464 );
465 if (Option.isSome(token)) {
466 return { _tag: "Authorized", token: token.value } as const;
467 }
468 const authorization = yield* Effect.scoped(login());
469 return authorization._tag === "Authorized"
470 ? ({ _tag: "Authorized", token: yield* persist(authorization.token) } as const)
471 : authorization;
472 }).pipe(
473 Effect.mapError((cause) =>
474 Terminal.isQuitError(cause) ? cause : new CloudCliAuthorizationError({ cause }),
475 ),
476 Effect.provide(services),
477 ),
478 );
479 const store = Effect.fn("cloud.cli_token.store")(function* (token: PersistedToken) {
480 yield* semaphore.withPermits(1)(
481 persist(token).pipe(
482 Effect.asVoid,
483 Effect.mapError((cause) => new CloudCliAuthorizationError({ cause })),
484 ),
485 );
486 });
487​
488 return CloudCliTokenManager.of({ get, getExisting, hasCredential, store, clear });
489});
490​
491export const layer = Layer.effect(CloudCliTokenManager, make);