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

CliTokenManager.ts

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