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

CliTokenManager.ts

649 lines24.2 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});
149const OAuthRefreshErrorCode = Schema.Literals([
150 "invalid_grant",
151 "invalid_client",
152 "unauthorized_client",
153 "unsupported_grant_type",
154 "invalid_request",
155 "invalid_scope",
156 "access_denied",
157]);
158const decodeOAuthRefreshErrorResponse = Schema.decodeUnknownOption(
159 Schema.Struct({ error: OAuthRefreshErrorCode }),
160);
161​
162const isPermanentRefreshStatus = (status: number): boolean =>
163 status >= 400 && status < 500 && status !== 408 && status !== 429;
164​
165const DeviceAuthorizationResponse = Schema.Struct({
166 device_code: Schema.String,
167 user_code: Schema.String,
168 verification_uri: Schema.String,
169 verification_uri_complete: Schema.optional(Schema.String),
170 expires_in: Schema.Number,
171 interval: Schema.optional(Schema.Number),
172});
173​
174const OidcIdentityClaimsJson = Schema.fromJsonString(
175 Schema.Struct({
176 email: Schema.optional(Schema.String),
177 preferred_username: Schema.optional(Schema.String),
178 sub: Schema.optional(Schema.String),
179 }),
180);
181const decodeOidcIdentityClaimsJson = Schema.decodeUnknownOption(OidcIdentityClaimsJson);
182​
183function idTokenIdentity(idToken: string | undefined): string | null {
184 if (!idToken) return null;
185 const payload = idToken.split(".")[1];
186 if (!payload) return null;
187 const decoded = Base64Url.decodeString(payload);
188 if (decoded._tag !== "Success") return null;
189 const claims = decodeOidcIdentityClaimsJson(decoded.success);
190 if (Option.isNone(claims)) return null;
191 for (const value of [claims.value.email, claims.value.preferred_username, claims.value.sub]) {
192 if (typeof value === "string" && value.length > 0) return value;
193 }
194 return null;
196​
197export class CloudCliCredentialRemovalError extends Schema.TaggedError<CloudCliCredentialRemovalError>()(
198 "CloudCliCredentialRemovalError",
199 { cause: Schema.Defect() },
200) {
201 override get message(): string {
202 return "Could not remove the stored T3 Connect CLI credential.";
203 }
205​
206export class CloudCliCredentialRefreshError extends Schema.TaggedError<CloudCliCredentialRefreshError>()(
207 "CloudCliCredentialRefreshError",
208 {
209 cause: Schema.Defect(),
210 status: Schema.optional(Schema.Number),
211 oauthErrorCode: Schema.optional(OAuthRefreshErrorCode),
212 },
213) {
214 get requiresLogin(): boolean {
215 return this.status !== undefined && isPermanentRefreshStatus(this.status);
216 }
217​
218 override get message(): string {
219 return this.requiresLogin
220 ? `Could not refresh the T3 Connect CLI credential${
221 this.oauthErrorCode === undefined ? "" : ` (OAuth error: ${this.oauthErrorCode})`
222 }. Run \`t3 connect login\` to authorize again.`
223 : "Could not refresh the T3 Connect CLI credential.";
224 }
226​
227export const isCloudCliCredentialRefreshError = Schema.is(CloudCliCredentialRefreshError);
228​
229export class CloudCliCredentialReadError extends Schema.TaggedError<CloudCliCredentialReadError>()(
230 "CloudCliCredentialReadError",
231 { cause: Schema.Defect() },
232) {
233 override get message(): string {
234 return "Could not read the stored T3 Connect CLI credential.";
235 }
237​
238export class CloudCliAuthorizationError extends Schema.TaggedError<CloudCliAuthorizationError>()(
239 "CloudCliAuthorizationError",
240 { cause: Schema.Defect() },
241) {
242 override get message(): string {
243 return "Could not authorize the T3 Connect CLI.";
244 }
246​
247export class CloudCliAuthorizationTimeoutError extends Schema.TaggedError<CloudCliAuthorizationTimeoutError>()(
248 "CloudCliAuthorizationTimeoutError",
249 { cause: Schema.Defect() },
250) {
251 override get message(): string {
252 return "Timed out waiting for T3 Connect authorization.";
253 }
255​
256export class CloudCliAuthorizationDeniedError extends Schema.TaggedError<CloudCliAuthorizationDeniedError>()(
257 "CloudCliAuthorizationDeniedError",
258 {},
259) {
260 override get message(): string {
261 return "T3 Connect authorization was denied in the browser.";
262 }
264​
265export const CloudCliTokenManagerError = Schema.Union([
266 CloudCliCredentialRemovalError,
267 CloudCliCredentialRefreshError,
268 CloudCliCredentialReadError,
269 CloudCliAuthorizationError,
270 CloudCliAuthorizationTimeoutError,
271 CloudCliAuthorizationDeniedError,
272]);
273export type CloudCliTokenManagerError = typeof CloudCliTokenManagerError.Type;
274​
275export class CloudCliTokenManager extends Context.Service<
276 CloudCliTokenManager,
277 {
278 readonly get: Effect.Effect<
279 | { readonly _tag: "Authorized"; readonly token: PersistedToken }
280 | { readonly _tag: "HeadlessRequested" },
281 CloudCliTokenManagerError | Terminal.QuitError
282 >;
283 readonly getExisting: Effect.Effect<Option.Option<PersistedToken>, CloudCliTokenManagerError>;
284 readonly hasCredential: Effect.Effect<boolean, CloudCliTokenManagerError>;
285 readonly store: (token: PersistedToken) => Effect.Effect<void, CloudCliTokenManagerError>;
286 readonly clear: Effect.Effect<void, CloudCliTokenManagerError>;
287 }
288>()("t3/cloud/CliTokenManager/CloudCliTokenManager") {}
289​
290function stringToBytes(value: string): Uint8Array {
291 return new TextEncoder().encode(value);
293​
294function bytesToString(value: Uint8Array): string {
295 return new TextDecoder().decode(value);
297​
298const readTokenResponse = Effect.fn("cloud.cli_token.read_token_response")(function* (
299 response: HttpClientResponse.HttpClientResponse,
300 params: Record<string, string>,
301) {
302 const body = yield* HttpClientResponse.schemaBodyJson(OAuthTokenResponse)(response);
303 const now = yield* Clock.currentTimeMillis;
304 const identity = idTokenIdentity(body.id_token);
305 return {
306 token: {
307 accessToken: body.access_token,
308 refreshToken: body.refresh_token ?? params.refresh_token ?? "",
309 expiresAtEpochMs: now + body.expires_in * 1_000,
310 ...(identity === null ? {} : { identity }),
311 } satisfies PersistedToken,
312 identity,
313 };
314});
315​
316const exchangeToken = Effect.fn("cloud.cli_token.exchange")(function* (
317 metadata: Pick<CloudCliOAuthConfig, "tokenEndpoint">,
318 params: Record<string, string>,
319) {
320 const httpClient = (yield* HttpClient.HttpClient).pipe(HttpClient.filterStatusOk);
321 const startedAt = yield* Clock.monotonicTimeNanos;
322 return yield* HttpClientRequest.post(metadata.tokenEndpoint).pipe(
323 HttpClientRequest.bodyUrlParams(params),
324 httpClient.execute,
325 Effect.flatMap((response) => readTokenResponse(response, params)),
326 Effect.timeout(OAUTH_REQUEST_TIMEOUT),
327 Effect.catchTags({
328 HttpClientError: (cause) =>
329 Effect.gen(function* () {
330 const reason = cause.reason;
331 if (
332 params.grant_type !== "refresh_token" ||
333 reason._tag !== "StatusCodeError" ||
334 !isPermanentRefreshStatus(reason.response.status)
335 ) {
336 return yield* cause;
337 }
338 // Reading a rejection body shares the exchange budget without losing
339 // the known status when the body stalls or cannot be decoded.
340 const elapsed = Duration.toMillis(
341 Duration.nanos((yield* Clock.monotonicTimeNanos) - startedAt),
342 );
343 const body = yield* reason.response.json.pipe(
344 Effect.timeout(Math.max(0, Duration.toMillis(OAUTH_REQUEST_TIMEOUT) - elapsed)),
345 Effect.mapError(
346 (cause) =>
347 new CloudCliCredentialRefreshError({
348 status: reason.response.status,
349 cause: new HttpClientError.HttpClientError({
350 reason: new HttpClientError.StatusCodeError({
351 request: reason.request,
352 response: reason.response,
353 cause,
354 }),
355 }),
356 }),
357 ),
358 );
359 const diagnostic = decodeOAuthRefreshErrorResponse(body);
360 return yield* new CloudCliCredentialRefreshError({
361 cause,
362 status: reason.response.status,
363 ...(Option.isSome(diagnostic) ? { oauthErrorCode: diagnostic.value.error } : {}),
364 });
365 }),
366 }),
367 );
368});
369​
370const makePkceRequest = Effect.gen(function* () {
371 const crypto = yield* Crypto.Crypto;
372 const verifier = Base64Url.encode(yield* crypto.randomBytes(32));
373 const challenge = Base64Url.encode(
374 yield* crypto.digest("SHA-256", new TextEncoder().encode(verifier)),
375 );
376 const state = Base64Url.encode(yield* crypto.randomBytes(16));
377 return { verifier, challenge, state };
378});
379​
380export interface DeviceAuthorizationPrompt {
381 readonly verificationUri: string;
382 readonly verificationUriComplete: string | undefined;
383 readonly userCode: string;
384 readonly expiresIn: Duration.Duration;
386​
387const isTransportError = (error: unknown) =>
388 HttpClientError.isHttpClientError(error) && error.reason._tag === "TransportError";
389​
390const pollDeviceToken = Effect.fn("cloud.cli_token.poll_device_token")(function* (
391 metadata: Pick<CloudCliOAuthConfig, "tokenEndpoint" | "clientId">,
392 deviceCode: string,
393 initialInterval: Duration.Duration,
394) {
395 const httpClient = yield* HttpClient.HttpClient;
396 const params = {
397 grant_type: DEVICE_CODE_GRANT_TYPE,
398 device_code: deviceCode,
399 client_id: metadata.clientId,
400 };
401 let interval = initialInterval;
402 while (true) {
403 yield* Effect.sleep(interval);
404 const response = yield* HttpClientRequest.post(metadata.tokenEndpoint).pipe(
405 HttpClientRequest.bodyUrlParams(params),
406 httpClient.execute,
407 Effect.asSome,
408 Effect.catchIf(isTransportError, () => Effect.succeedNone),
409 );
410 // Transport failures and upstream 5xx are transient while the device code
411 // is still valid. RFC 8628 §3.5 asks clients to back off before retrying,
412 // so widen the interval like slow_down; drain the body so the connection
413 // returns to the pool for the next poll.
414 if (Option.isNone(response) || response.value.status >= 500) {
415 if (Option.isSome(response)) yield* Effect.ignore(response.value.text);
416 interval = Duration.sum(interval, DEVICE_AUTHORIZATION_SLOW_DOWN_INCREMENT);
417 continue;
418 }
419 if (response.value.status >= 200 && response.value.status < 300) {
420 return yield* readTokenResponse(response.value, params);
421 }
422 const failure = yield* HttpClientResponse.schemaBodyJson(OAuthErrorResponse)(response.value);
423 switch (failure.error) {
424 case "authorization_pending":
425 continue;
426 case "slow_down":
427 interval = Duration.sum(interval, DEVICE_AUTHORIZATION_SLOW_DOWN_INCREMENT);
428 continue;
429 case "expired_token":
430 return yield* new CloudCliAuthorizationTimeoutError({ cause: failure });
431 case "access_denied":
432 return yield* new CloudCliAuthorizationDeniedError();
433 default:
434 return yield* new CloudCliAuthorizationError({
435 cause: failure.error_description ?? failure.error,
436 });
437 }
438 }
439});
440​
441export const deviceAuthorizationLogin = Effect.fn("cloud.cli_token.device_authorization_login")(
442 function* <E, R>(showPrompt: (prompt: DeviceAuthorizationPrompt) => Effect.Effect<void, E, R>) {
443 const metadata = yield* cloudCliOAuthConfig;
444 const httpClient = (yield* HttpClient.HttpClient).pipe(HttpClient.filterStatusOk);
445 const authorization = yield* HttpClientRequest.post(metadata.deviceAuthorizationEndpoint).pipe(
446 HttpClientRequest.bodyUrlParams({
447 client_id: metadata.clientId,
448 scope: metadata.scopes.join(" "),
449 }),
450 httpClient.execute,
451 Effect.flatMap(HttpClientResponse.schemaBodyJson(DeviceAuthorizationResponse)),
452 Effect.timeout(OAUTH_REQUEST_TIMEOUT),
453 );
454 const expiresIn = Duration.seconds(authorization.expires_in);
455 const interval =
456 authorization.interval === undefined
457 ? DEVICE_AUTHORIZATION_DEFAULT_INTERVAL
458 : Duration.seconds(authorization.interval);
459 yield* showPrompt({
460 verificationUri: authorization.verification_uri,
461 verificationUriComplete: authorization.verification_uri_complete,
462 userCode: authorization.user_code,
463 expiresIn,
464 });
465 return yield* pollDeviceToken(metadata, authorization.device_code, interval).pipe(
466 Effect.timeout(expiresIn),
467 Effect.catchTags({
468 TimeoutError: (cause) => Effect.fail(new CloudCliAuthorizationTimeoutError({ cause })),
469 }),
470 );
471 },
472);
473​
474/** @public Service construction is part of the canonical Effect module API. */
475export const make = Effect.gen(function* () {
476 const crypto = yield* Crypto.Crypto;
477 const httpClient = yield* HttpClient.HttpClient;
478 const services = Context.make(Crypto.Crypto, crypto).pipe(
479 Context.add(HttpClient.HttpClient, httpClient),
480 );
481 const secrets = yield* ServerSecretStore.ServerSecretStore;
482 const terminal = yield* Terminal.Terminal;
483 const externalLauncher = yield* ExternalLauncher.ExternalLauncher;
484 const semaphore = yield* Semaphore.make(1);
485 const persist = Effect.fn("cloud.cli_token.persist")(function* (token: PersistedToken) {
486 const encoded = yield* encodePersistedToken(token);
487 yield* secrets.set(CLOUD_CLI_OAUTH_TOKEN_SECRET, stringToBytes(encoded));
488 return token;
489 });
490​
491 const clear = secrets
492 .remove(CLOUD_CLI_OAUTH_TOKEN_SECRET)
493 .pipe(Effect.mapError((cause) => new CloudCliCredentialRemovalError({ cause })));
494​
495 const read = Effect.fn("cloud.cli_token.read")(function* () {
496 const encoded = yield* secrets.get(CLOUD_CLI_OAUTH_TOKEN_SECRET);
497 if (Option.isNone(encoded)) return Option.none<PersistedToken>();
498 return Option.some(yield* decodePersistedToken(bytesToString(encoded.value)));
499 });
500​
501 const refresh = Effect.fn("cloud.cli_token.refresh")(function* (token: PersistedToken) {
502 const metadata = yield* cloudCliOAuthConfig;
503 const { token: refreshed } = yield* exchangeToken(metadata, {
504 grant_type: "refresh_token",
505 refresh_token: token.refreshToken,
506 client_id: metadata.clientId,
507 });
508 return refreshed.identity === undefined && token.identity !== undefined
509 ? { ...refreshed, identity: token.identity }
510 : refreshed;
511 });
512​
513 const login = Effect.fn("cloud.cli_token.login")(function* () {
514 const metadata = yield* cloudCliOAuthConfig;
515 const hostedAppUrl = yield* hostedAppUrlConfig;
516 const { verifier, challenge, state } = yield* makePkceRequest;
517 const callback = yield* Deferred.make<string>();
518 const layerCallbackRoute = HttpRouter.add(
519 "GET",
520 "/callback",
521 Effect.gen(function* () {
522 const request = yield* HttpServerRequest.HttpServerRequest;
523 const url = new URL(request.originalUrl, metadata.redirectUri);
524 const code = url.searchParams.get("code");
525 if (url.searchParams.get("state") !== state || !code) {
526 return HttpServerResponse.text("Invalid T3 Connect authorization callback.", {
527 status: 400,
528 });
529 }
530 yield* Deferred.succeed(callback, code);
531 return HttpServerResponse.html(renderLoopbackAuthorizationCompleteHtml());
532 }),
533 );
534 yield* HttpRouter.serve(layerCallbackRoute, {
535 disableListenLog: true,
536 disableLogger: true,
537 }).pipe(
538 Layer.provide(
539 NodeHttpServer.layer(NodeHttp.createServer, {
540 host: "127.0.0.1",
541 port: metadata.loopbackPort,
542 disablePreemptiveShutdown: true,
543 }),
544 ),
545 Layer.build,
546 );
547 // The hosted /connect page establishes a Clerk session before forwarding
548 // the request to /oauth/authorize with the loopback redirect URI. Sending
549 // a signed-out browser to /oauth/authorize directly loses the authorize
550 // parameters across Clerk's sign-in redirect (#5051).
551 const authorizationUrl = buildConnectAuthorizeRequestUrl({
552 hostedAppUrl,
553 state,
554 challenge,
555 loopbackPort: metadata.loopbackPort,
556 });
557 yield* Console.log(formatLoopbackAuthorizationPrompt(authorizationUrl));
558 const authorization = yield* waitForLoopbackAuthorization({
559 authorizationUrl,
560 callback: Deferred.await(callback).pipe(
561 Effect.timeout(CLOUD_CLI_OAUTH_CALLBACK_TIMEOUT),
562 Effect.catchTags({
563 TimeoutError: (cause) => Effect.fail(new CloudCliAuthorizationTimeoutError({ cause })),
564 }),
565 ),
566 terminal,
567 launchBrowser: externalLauncher.launchBrowser,
568 });
569 if (authorization._tag === "HeadlessRequested") {
570 return authorization;
571 }
572 const { token } = yield* exchangeToken(metadata, {
573 grant_type: "authorization_code",
574 code: authorization.code,
575 redirect_uri: metadata.redirectUri,
576 client_id: metadata.clientId,
577 code_verifier: verifier,
578 });
579 return { _tag: "Authorized", token } as const;
580 });
581​
582 const getExistingNoLock = Effect.fn("cloud.cli_token.get_existing_no_lock")(function* () {
583 const token = yield* read();
584 if (Option.isNone(token)) return token;
585 const now = yield* Clock.currentTimeMillis;
586 if (token.value.expiresAtEpochMs - CLOUD_CLI_OAUTH_REFRESH_EARLY_MS > now) {
587 return token;
588 }
589 return Option.some(
590 // The endpoint can rotate the refresh token before shutdown interrupts us.
591 // Keep the lock through persistence; the exchange still times out internally.
592 yield* refresh(token.value).pipe(Effect.flatMap(persist), Effect.uninterruptible),
593 );
594 });
595​
596 const getExisting = semaphore.withPermits(1)(
597 getExistingNoLock().pipe(
598 Effect.mapError((cause) =>
599 isCloudCliCredentialRefreshError(cause)
600 ? cause
601 : new CloudCliCredentialRefreshError({
602 cause,
603 ...(HttpClientError.isHttpClientError(cause) &&
604 cause.reason._tag === "StatusCodeError"
605 ? { status: cause.reason.response.status }
606 : {}),
607 }),
608 ),
609 Effect.provide(services),
610 ),
611 );
612 const hasCredential = semaphore.withPermits(1)(
613 read().pipe(
614 Effect.map(Option.isSome),
615 Effect.mapError((cause) => new CloudCliCredentialReadError({ cause })),
616 ),
617 );
618 const get = semaphore.withPermits(1)(
619 Effect.gen(function* () {
620 const token = yield* getExistingNoLock().pipe(
621 Effect.orElseSucceed(() => Option.none<PersistedToken>()),
622 );
623 if (Option.isSome(token)) {
624 return { _tag: "Authorized", token: token.value } as const;
625 }
626 const authorization = yield* Effect.scoped(login());
627 return authorization._tag === "Authorized"
628 ? ({ _tag: "Authorized", token: yield* persist(authorization.token) } as const)
629 : authorization;
630 }).pipe(
631 Effect.mapError((cause) =>
632 Terminal.isQuitError(cause) ? cause : new CloudCliAuthorizationError({ cause }),
633 ),
634 Effect.provide(services),
635 ),
636 );
637 const store = Effect.fn("cloud.cli_token.store")(function* (token: PersistedToken) {
638 yield* semaphore.withPermits(1)(
639 persist(token).pipe(
640 Effect.asVoid,
641 Effect.mapError((cause) => new CloudCliAuthorizationError({ cause })),
642 ),
643 );
644 });
645​
646 return CloudCliTokenManager.of({ get, getExisting, hasCredential, store, clear });
647});
648​
649export const layer = Layer.effect(CloudCliTokenManager, make);