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

CliTokenManager.ts

648 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 Digest from "effect/crypto/Digest";
10import * as SecureRandom from "effect/crypto/SecureRandom";
11import * as Deferred from "effect/Deferred";
12import * as Duration from "effect/Duration";
13import * as Effect from "effect/Effect";
14import * as Base64Url from "effect/encoding/Base64Url";
15import * as Layer from "effect/Layer";
16import * as Option from "effect/Option";
17import * as Queue from "effect/Queue";
18import * as Schema from "effect/Schema";
19import * as Semaphore from "effect/Semaphore";
20import * as Terminal from "effect/Terminal";
21import * as HttpClient from "effect/http/HttpClient";
22import * as HttpClientError from "effect/http/HttpClientError";
23import * as HttpClientRequest from "effect/http/HttpClientRequest";
24import * as HttpClientResponse from "effect/http/HttpClientResponse";
25import * as HttpRouter from "effect/http/HttpRouter";
26import * as HttpServerRequest from "effect/http/HttpServerRequest";
27import * as HttpServerResponse from "effect/http/HttpServerResponse";
28​
29import { buildConnectAuthorizeRequestUrl } from "@t3tools/shared/connectAuth";
30​
31import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
32import * as ExternalLauncher from "../process/externalLauncher.ts";
33import {
34 cloudCliOAuthConfig,
35 hostedAppUrlConfig,
36 type CloudCliOAuthConfig,
37} from "./publicConfig.ts";
38import { renderLoopbackAuthorizationCompleteHtml } from "./cliAuthHtml.ts";
39​
40const CLOUD_CLI_OAUTH_TOKEN_SECRET = "cloud-cli-oauth-token";
41const CLOUD_CLI_OAUTH_CALLBACK_TIMEOUT = Duration.minutes(10);
42const CLOUD_CLI_OAUTH_REFRESH_EARLY_MS = Duration.toMillis(Duration.minutes(5));
43const DEVICE_CODE_GRANT_TYPE = "urn:ietf:params:oauth:grant-type:device_code";
44// RFC 8628 defaults, used only when Clerk omits the field.
45const DEVICE_AUTHORIZATION_DEFAULT_INTERVAL = Duration.seconds(5);
46// RFC 8628 §3.5: a slow_down response means "add 5 seconds to the interval".
47const DEVICE_AUTHORIZATION_SLOW_DOWN_INCREMENT = Duration.seconds(5);
48// A stalled OAuth request holds the semaphore and blocks all credential calls.
49const OAUTH_REQUEST_TIMEOUT = Duration.seconds(10);
50const boldTerminalText = (value: string): string => `\u001b[1m${value}\u001b[22m`;
51​
52function formatLoopbackAuthorizationPrompt(authorizationUrl: string): string {
53 return [
54 "Open this URL to authorize T3 Connect:",
55 ` ${authorizationUrl}`,
56 "",
57 `Press ${boldTerminalText("Enter")} to open it in your browser.`,
58 `No browser on this device? Press ${boldTerminalText("H")} to switch to headless mode.`,
59 ].join("\n");
61​
62export type LoopbackAuthorizationResult =
63 | { readonly _tag: "AuthorizationCode"; readonly code: string }
64 | { readonly _tag: "HeadlessRequested" };
65​
66const readLoopbackAuthorizationAction = Effect.fn(
67 "cloud.cli_token.read_loopback_authorization_action",
68)(function* (input: Queue.Dequeue<Terminal.UserInput, Cause.Done>) {
69 while (true) {
70 const event = yield* Queue.take(input).pipe(Effect.mapError(() => new Terminal.QuitError({})));
71 const keyName = event.key.name.toLowerCase();
72 if (!event.key.ctrl && !event.key.meta && keyName === "h") {
73 return "headless" as const;
74 }
75 if (keyName === "enter" || keyName === "return") {
76 return "open-browser" as const;
77 }
78 }
79});
80​
81const waitForLoopbackAuthorization = Effect.fn("cloud.cli_token.wait_for_loopback_authorization")(
82 function* <E, R>(input: {
83 readonly authorizationUrl: string;
84 readonly callback: Effect.Effect<string, E, R>;
85 readonly terminal: Terminal.Terminal;
86 readonly launchBrowser: (
87 url: string,
88 ) => Effect.Effect<void, ExternalLauncher.ExternalLauncherError>;
89 }) {
90 return yield* Effect.scoped(
91 Effect.gen(function* () {
92 const terminalInput = yield* input.terminal.readInput;
93 while (true) {
94 const result = yield* Effect.raceFirst(
95 input.callback.pipe(
96 Effect.map((code): LoopbackAuthorizationResult => ({
97 _tag: "AuthorizationCode",
98 code,
99 })),
100 ),
101 readLoopbackAuthorizationAction(terminalInput),
102 );
103 if (typeof result !== "string") {
104 return result;
105 }
106 if (result === "headless") {
107 return { _tag: "HeadlessRequested" } as const;
108 }
109 yield* input
110 .launchBrowser(input.authorizationUrl)
111 .pipe(
112 Effect.catch(() =>
113 Console.warn(
114 `Could not open a browser on this device. Open the URL above manually, or press ${boldTerminalText("H")} to switch to headless mode.`,
115 ),
116 ),
117 );
118 }
119 }),
120 );
121 },
122);
123​
124const PersistedToken = Schema.Struct({
125 accessToken: Schema.String,
126 refreshToken: Schema.String,
127 expiresAtEpochMs: Schema.Number,
128 identity: Schema.optional(Schema.String),
129});
130export type PersistedToken = typeof PersistedToken.Type;
131​
132const PersistedTokenJson = Schema.fromJsonString(PersistedToken);
133const decodePersistedToken = Schema.decodeUnknownEffect(PersistedTokenJson);
134const encodePersistedToken = Schema.encodeEffect(PersistedTokenJson);
135​
136const OAuthTokenResponse = Schema.Struct({
137 access_token: Schema.String,
138 refresh_token: Schema.optional(Schema.String),
139 id_token: Schema.optional(Schema.String),
140 expires_in: Schema.Number,
141 token_type: Schema.String,
142});
143​
144const OAuthErrorResponse = Schema.Struct({
145 error: Schema.String,
146 error_description: Schema.optional(Schema.String),
147});
148const OAuthRefreshErrorCode = Schema.Literals([
149 "invalid_grant",
150 "invalid_client",
151 "unauthorized_client",
152 "unsupported_grant_type",
153 "invalid_request",
154 "invalid_scope",
155 "access_denied",
156]);
157const decodeOAuthRefreshErrorResponse = Schema.decodeUnknownOption(
158 Schema.Struct({ error: OAuthRefreshErrorCode }),
159);
160​
161const isPermanentRefreshStatus = (status: number): boolean =>
162 status >= 400 && status < 500 && status !== 408 && status !== 429;
163​
164const DeviceAuthorizationResponse = Schema.Struct({
165 device_code: Schema.String,
166 user_code: Schema.String,
167 verification_uri: Schema.String,
168 verification_uri_complete: Schema.optional(Schema.String),
169 expires_in: Schema.Number,
170 interval: Schema.optional(Schema.Number),
171});
172​
173const OidcIdentityClaimsJson = Schema.fromJsonString(
174 Schema.Struct({
175 email: Schema.optional(Schema.String),
176 preferred_username: Schema.optional(Schema.String),
177 sub: Schema.optional(Schema.String),
178 }),
179);
180const decodeOidcIdentityClaimsJson = Schema.decodeUnknownOption(OidcIdentityClaimsJson);
181​
182function idTokenIdentity(idToken: string | undefined): string | null {
183 if (!idToken) return null;
184 const payload = idToken.split(".")[1];
185 if (!payload) return null;
186 const decoded = Base64Url.decodeString(payload);
187 if (decoded._tag !== "Success") return null;
188 const claims = decodeOidcIdentityClaimsJson(decoded.success);
189 if (Option.isNone(claims)) return null;
190 for (const value of [claims.value.email, claims.value.preferred_username, claims.value.sub]) {
191 if (typeof value === "string" && value.length > 0) return value;
192 }
193 return null;
195​
196export class CloudCliCredentialRemovalError extends Schema.TaggedError<CloudCliCredentialRemovalError>()(
197 "CloudCliCredentialRemovalError",
198 { cause: Schema.Defect() },
199) {
200 override get message(): string {
201 return "Could not remove the stored T3 Connect CLI credential.";
202 }
204​
205export class CloudCliCredentialRefreshError extends Schema.TaggedError<CloudCliCredentialRefreshError>()(
206 "CloudCliCredentialRefreshError",
207 {
208 cause: Schema.Defect(),
209 status: Schema.optional(Schema.Number),
210 oauthErrorCode: Schema.optional(OAuthRefreshErrorCode),
211 },
212) {
213 get requiresLogin(): boolean {
214 return this.status !== undefined && isPermanentRefreshStatus(this.status);
215 }
216​
217 override get message(): string {
218 return this.requiresLogin
219 ? `Could not refresh the T3 Connect CLI credential${
220 this.oauthErrorCode === undefined ? "" : ` (OAuth error: ${this.oauthErrorCode})`
221 }. Run \`t3 connect login\` to authorize again.`
222 : "Could not refresh the T3 Connect CLI credential.";
223 }
225​
226export const isCloudCliCredentialRefreshError = Schema.is(CloudCliCredentialRefreshError);
227​
228export class CloudCliCredentialReadError extends Schema.TaggedError<CloudCliCredentialReadError>()(
229 "CloudCliCredentialReadError",
230 { cause: Schema.Defect() },
231) {
232 override get message(): string {
233 return "Could not read the stored T3 Connect CLI credential.";
234 }
236​
237export class CloudCliAuthorizationError extends Schema.TaggedError<CloudCliAuthorizationError>()(
238 "CloudCliAuthorizationError",
239 { cause: Schema.Defect() },
240) {
241 override get message(): string {
242 return "Could not authorize the T3 Connect CLI.";
243 }
245​
246export class CloudCliAuthorizationTimeoutError extends Schema.TaggedError<CloudCliAuthorizationTimeoutError>()(
247 "CloudCliAuthorizationTimeoutError",
248 { cause: Schema.Defect() },
249) {
250 override get message(): string {
251 return "Timed out waiting for T3 Connect authorization.";
252 }
254​
255export class CloudCliAuthorizationDeniedError extends Schema.TaggedError<CloudCliAuthorizationDeniedError>()(
256 "CloudCliAuthorizationDeniedError",
257 {},
258) {
259 override get message(): string {
260 return "T3 Connect authorization was denied in the browser.";
261 }
263​
264export const CloudCliTokenManagerError = Schema.Union([
265 CloudCliCredentialRemovalError,
266 CloudCliCredentialRefreshError,
267 CloudCliCredentialReadError,
268 CloudCliAuthorizationError,
269 CloudCliAuthorizationTimeoutError,
270 CloudCliAuthorizationDeniedError,
271]);
272export type CloudCliTokenManagerError = typeof CloudCliTokenManagerError.Type;
273export const isCloudCliTokenManagerError = Schema.is(CloudCliTokenManagerError);
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 // The enclosing operation owns the span for this inline handler.
329 HttpClientError: Effect.fnUntraced(function* (cause) {
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 random = yield* SecureRandom.SecureRandom;
372 const digest = yield* Digest.Digest;
373 const verifier = Base64Url.encode(yield* random.randomBytes(32));
374 const challenge = Base64Url.encode(
375 yield* digest.digest(Digest.sha256, new TextEncoder().encode(verifier)),
376 );
377 const state = Base64Url.encode(yield* random.randomBytes(16));
378 return { verifier, challenge, state };
379});
380​
381export interface DeviceAuthorizationPrompt {
382 readonly verificationUri: string;
383 readonly verificationUriComplete: string | undefined;
384 readonly userCode: string;
385 readonly expiresIn: Duration.Duration;
387​
388const isTransportError = (error: unknown) =>
389 HttpClientError.isHttpClientError(error) && error.reason._tag === "TransportError";
390​
391const pollDeviceToken = Effect.fn("cloud.cli_token.poll_device_token")(function* (
392 metadata: Pick<CloudCliOAuthConfig, "tokenEndpoint" | "clientId">,
393 deviceCode: string,
394 initialInterval: Duration.Duration,
395) {
396 const httpClient = yield* HttpClient.HttpClient;
397 const params = {
398 grant_type: DEVICE_CODE_GRANT_TYPE,
399 device_code: deviceCode,
400 client_id: metadata.clientId,
401 };
402 let interval = initialInterval;
403 while (true) {
404 yield* Effect.sleep(interval);
405 const response = yield* HttpClientRequest.post(metadata.tokenEndpoint).pipe(
406 HttpClientRequest.bodyUrlParams(params),
407 httpClient.execute,
408 Effect.timeoutOption(OAUTH_REQUEST_TIMEOUT),
409 Effect.catchIf(isTransportError, () => Effect.succeedNone),
410 );
411 // Retry transport errors, timeouts and 5xx while the device code is valid, backing off per RFC 8628 §3.5. Drain bodies to reuse connections.
412 if (Option.isNone(response) || response.value.status >= 500) {
413 if (Option.isSome(response)) yield* Effect.ignore(response.value.text);
414 interval = Duration.sum(interval, DEVICE_AUTHORIZATION_SLOW_DOWN_INCREMENT);
415 continue;
416 }
417 if (response.value.status >= 200 && response.value.status < 300) {
418 return yield* readTokenResponse(response.value, params);
419 }
420 const failure = yield* HttpClientResponse.schemaBodyJson(OAuthErrorResponse)(response.value);
421 switch (failure.error) {
422 case "authorization_pending":
423 continue;
424 case "slow_down":
425 interval = Duration.sum(interval, DEVICE_AUTHORIZATION_SLOW_DOWN_INCREMENT);
426 continue;
427 case "expired_token":
428 return yield* new CloudCliAuthorizationTimeoutError({ cause: failure });
429 case "access_denied":
430 return yield* new CloudCliAuthorizationDeniedError();
431 default:
432 return yield* new CloudCliAuthorizationError({
433 cause: failure.error_description ?? failure.error,
434 });
435 }
436 }
437});
438​
439export const deviceAuthorizationLogin = Effect.fn("cloud.cli_token.device_authorization_login")(
440 function* <E, R>(showPrompt: (prompt: DeviceAuthorizationPrompt) => Effect.Effect<void, E, R>) {
441 const metadata = yield* cloudCliOAuthConfig;
442 const httpClient = (yield* HttpClient.HttpClient).pipe(HttpClient.filterStatusOk);
443 const authorization = yield* HttpClientRequest.post(metadata.deviceAuthorizationEndpoint).pipe(
444 HttpClientRequest.bodyUrlParams({
445 client_id: metadata.clientId,
446 scope: metadata.scopes.join(" "),
447 }),
448 httpClient.execute,
449 Effect.flatMap(HttpClientResponse.schemaBodyJson(DeviceAuthorizationResponse)),
450 Effect.timeout(OAUTH_REQUEST_TIMEOUT),
451 );
452 const expiresIn = Duration.seconds(authorization.expires_in);
453 const interval =
454 authorization.interval === undefined
455 ? DEVICE_AUTHORIZATION_DEFAULT_INTERVAL
456 : Duration.seconds(authorization.interval);
457 yield* showPrompt({
458 verificationUri: authorization.verification_uri,
459 verificationUriComplete: authorization.verification_uri_complete,
460 userCode: authorization.user_code,
461 expiresIn,
462 });
463 return yield* pollDeviceToken(metadata, authorization.device_code, interval).pipe(
464 Effect.timeout(expiresIn),
465 Effect.catchTags({
466 TimeoutError: (cause) => Effect.fail(new CloudCliAuthorizationTimeoutError({ cause })),
467 }),
468 );
469 },
470);
471​
472/** @public */
473export const make = Effect.gen(function* () {
474 const random = yield* SecureRandom.SecureRandom;
475 const digest = yield* Digest.Digest;
476 const httpClient = yield* HttpClient.HttpClient;
477 const services = Context.make(SecureRandom.SecureRandom, random).pipe(
478 Context.add(Digest.Digest, digest),
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 // /connect establishes a Clerk session first; /oauth/authorize loses parameters across sign-in.
548 const authorizationUrl = buildConnectAuthorizeRequestUrl({
549 hostedAppUrl,
550 state,
551 challenge,
552 loopbackPort: metadata.loopbackPort,
553 });
554 yield* Console.log(formatLoopbackAuthorizationPrompt(authorizationUrl));
555 const authorization = yield* waitForLoopbackAuthorization({
556 authorizationUrl,
557 callback: Deferred.await(callback).pipe(
558 Effect.timeout(CLOUD_CLI_OAUTH_CALLBACK_TIMEOUT),
559 Effect.catchTags({
560 TimeoutError: (cause) => Effect.fail(new CloudCliAuthorizationTimeoutError({ cause })),
561 }),
562 ),
563 terminal,
564 launchBrowser: externalLauncher.launchBrowser,
565 });
566 if (authorization._tag === "HeadlessRequested") {
567 return authorization;
568 }
569 const { token } = yield* exchangeToken(metadata, {
570 grant_type: "authorization_code",
571 code: authorization.code,
572 redirect_uri: metadata.redirectUri,
573 client_id: metadata.clientId,
574 code_verifier: verifier,
575 });
576 return { _tag: "Authorized", token } as const;
577 });
578​
579 const getExistingNoLock = Effect.fn("cloud.cli_token.get_existing_no_lock")(function* () {
580 const token = yield* read();
581 if (Option.isNone(token)) return token;
582 const now = yield* Clock.currentTimeMillis;
583 if (token.value.expiresAtEpochMs - CLOUD_CLI_OAUTH_REFRESH_EARLY_MS > now) {
584 return token;
585 }
586 return Option.some(
587 // The endpoint can rotate the refresh token before shutdown interrupts us.
588 // Keep the lock through persistence; the exchange still times out internally.
589 yield* refresh(token.value).pipe(Effect.flatMap(persist), Effect.uninterruptible),
590 );
591 });
592​
593 const getExisting = semaphore.withPermits(1)(
594 getExistingNoLock().pipe(
595 Effect.mapError((cause) =>
596 isCloudCliCredentialRefreshError(cause)
597 ? cause
598 : new CloudCliCredentialRefreshError({
599 cause,
600 ...(HttpClientError.isHttpClientError(cause) &&
601 cause.reason._tag === "StatusCodeError"
602 ? { status: cause.reason.response.status }
603 : {}),
604 }),
605 ),
606 Effect.provide(services),
607 ),
608 );
609 const hasCredential = semaphore.withPermits(1)(
610 read().pipe(
611 Effect.map(Option.isSome),
612 Effect.mapError((cause) => new CloudCliCredentialReadError({ cause })),
613 ),
614 );
615 const get = semaphore.withPermits(1)(
616 Effect.gen(function* () {
617 const token = yield* getExistingNoLock().pipe(
618 Effect.orElseSucceed(() => Option.none<PersistedToken>()),
619 );
620 if (Option.isSome(token)) {
621 return { _tag: "Authorized", token: token.value } as const;
622 }
623 const authorization = yield* Effect.scoped(login());
624 return authorization._tag === "Authorized"
625 ? ({ _tag: "Authorized", token: yield* persist(authorization.token) } as const)
626 : authorization;
627 }).pipe(
628 Effect.mapError((cause) =>
629 Terminal.isQuitError(cause) || isCloudCliTokenManagerError(cause)
630 ? cause
631 : new CloudCliAuthorizationError({ cause }),
632 ),
633 Effect.provide(services),
634 ),
635 );
636 const store = Effect.fn("cloud.cli_token.store")(function* (token: PersistedToken) {
637 yield* semaphore.withPermits(1)(
638 persist(token).pipe(
639 Effect.asVoid,
640 Effect.mapError((cause) => new CloudCliAuthorizationError({ cause })),
641 ),
642 );
643 });
644​
645 return CloudCliTokenManager.of({ get, getExisting, hasCredential, store, clear });
646});
647​
648export const layer = Layer.effect(CloudCliTokenManager, make);