Open History to see the last commit
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// A stalled OAuth request holds the semaphore and blocks all credential calls.
48const OAUTH_REQUEST_TIMEOUT = Duration.seconds(10);
49const boldTerminalText = (value: string): string => `\u001b[1m${value}\u001b[22m`;
50
51function formatLoopbackAuthorizationPrompt(authorizationUrl: string): string {
52 return [
53 "Open this URL to authorize T3 Connect:",
54 ` ${authorizationUrl}`,
55 "",
56 `Press ${boldTerminalText("Enter")} to open it in your browser.`,
57 `No browser on this device? Press ${boldTerminalText("H")} to switch to headless mode.`,
58 ].join("\n");
59}
60
61export type LoopbackAuthorizationResult =
62 | { readonly _tag: "AuthorizationCode"; readonly code: string }
63 | { readonly _tag: "HeadlessRequested" };
64
65const readLoopbackAuthorizationAction = Effect.fn(
66 "cloud.cli_token.read_loopback_authorization_action",
67)(function* (input: Queue.Dequeue<Terminal.UserInput, Cause.Done>) {
68 while (true) {
69 const event = yield* Queue.take(input).pipe(Effect.mapError(() => new Terminal.QuitError({})));
70 const keyName = event.key.name.toLowerCase();
71 if (!event.key.ctrl && !event.key.meta && keyName === "h") {
72 return "headless" as const;
73 }
74 if (keyName === "enter" || keyName === "return") {
75 return "open-browser" as const;
76 }
77 }
78});
79
80const waitForLoopbackAuthorization = Effect.fn("cloud.cli_token.wait_for_loopback_authorization")(
81 function* <E, R>(input: {
82 readonly authorizationUrl: string;
83 readonly callback: Effect.Effect<string, E, R>;
84 readonly terminal: Terminal.Terminal;
85 readonly launchBrowser: (
86 url: string,
87 ) => Effect.Effect<void, ExternalLauncher.ExternalLauncherError>;
88 }) {
89 return yield* Effect.scoped(
90 Effect.gen(function* () {
91 const terminalInput = yield* input.terminal.readInput;
92 while (true) {
93 const result = yield* Effect.raceFirst(
94 input.callback.pipe(
95 Effect.map((code): LoopbackAuthorizationResult => ({
96 _tag: "AuthorizationCode",
97 code,
98 })),
99 ),
100 readLoopbackAuthorizationAction(terminalInput),
101 );
102 if (typeof result !== "string") {
103 return result;
104 }
105 if (result === "headless") {
106 return { _tag: "HeadlessRequested" } as const;
107 }
108 yield* input
109 .launchBrowser(input.authorizationUrl)
110 .pipe(
111 Effect.catch(() =>
112 Console.warn(
113 `Could not open a browser on this device. Open the URL above manually, or press ${boldTerminalText("H")} to switch to headless mode.`,
114 ),
115 ),
116 );
117 }
118 }),
119 );
120 },
121);
122
123const PersistedToken = Schema.Struct({
124 accessToken: Schema.String,
125 refreshToken: Schema.String,
126 expiresAtEpochMs: Schema.Number,
127 identity: Schema.optional(Schema.String),
128});
129export type PersistedToken = typeof PersistedToken.Type;
130
131const PersistedTokenJson = Schema.fromJsonString(PersistedToken);
132const decodePersistedToken = Schema.decodeUnknownEffect(PersistedTokenJson);
133const encodePersistedToken = Schema.encodeEffect(PersistedTokenJson);
134
135const OAuthTokenResponse = Schema.Struct({
136 access_token: Schema.String,
137 refresh_token: Schema.optional(Schema.String),
138 id_token: Schema.optional(Schema.String),
139 expires_in: Schema.Number,
140 token_type: Schema.String,
141});
142
143const OAuthErrorResponse = Schema.Struct({
144 error: Schema.String,
145 error_description: Schema.optional(Schema.String),
146});
147const OAuthRefreshErrorCode = Schema.Literals([
148 "invalid_grant",
149 "invalid_client",
150 "unauthorized_client",
151 "unsupported_grant_type",
152 "invalid_request",
153 "invalid_scope",
154 "access_denied",
155]);
156const decodeOAuthRefreshErrorResponse = Schema.decodeUnknownOption(
157 Schema.Struct({ error: OAuthRefreshErrorCode }),
158);
159
160const isPermanentRefreshStatus = (status: number): boolean =>
161 status >= 400 && status < 500 && status !== 408 && status !== 429;
162
163const DeviceAuthorizationResponse = Schema.Struct({
164 device_code: Schema.String,
165 user_code: Schema.String,
166 verification_uri: Schema.String,
167 verification_uri_complete: Schema.optional(Schema.String),
168 expires_in: Schema.Number,
169 interval: Schema.optional(Schema.Number),
170});
171
172const OidcIdentityClaimsJson = Schema.fromJsonString(
173 Schema.Struct({
174 email: Schema.optional(Schema.String),
175 preferred_username: Schema.optional(Schema.String),
176 sub: Schema.optional(Schema.String),
177 }),
178);
179const decodeOidcIdentityClaimsJson = Schema.decodeUnknownOption(OidcIdentityClaimsJson);
180
181function idTokenIdentity(idToken: string | undefined): string | null {
182 if (!idToken) return null;
183 const payload = idToken.split(".")[1];
184 if (!payload) return null;
185 const decoded = Base64Url.decodeString(payload);
186 if (decoded._tag !== "Success") return null;
187 const claims = decodeOidcIdentityClaimsJson(decoded.success);
188 if (Option.isNone(claims)) return null;
189 for (const value of [claims.value.email, claims.value.preferred_username, claims.value.sub]) {
190 if (typeof value === "string" && value.length > 0) return value;
191 }
192 return null;
193}
194
195export class CloudCliCredentialRemovalError extends Schema.TaggedError<CloudCliCredentialRemovalError>()(
196 "CloudCliCredentialRemovalError",
197 { cause: Schema.Defect() },
198) {
199 override get message(): string {
200 return "Could not remove the stored T3 Connect CLI credential.";
201 }
202}
203
204export class CloudCliCredentialRefreshError extends Schema.TaggedError<CloudCliCredentialRefreshError>()(
205 "CloudCliCredentialRefreshError",
206 {
207 cause: Schema.Defect(),
208 status: Schema.optional(Schema.Number),
209 oauthErrorCode: Schema.optional(OAuthRefreshErrorCode),
210 },
211) {
212 get requiresLogin(): boolean {
213 return this.status !== undefined && isPermanentRefreshStatus(this.status);
214 }
215
216 override get message(): string {
217 return this.requiresLogin
218 ? `Could not refresh the T3 Connect CLI credential${
219 this.oauthErrorCode === undefined ? "" : ` (OAuth error: ${this.oauthErrorCode})`
220 }. Run \`t3 connect login\` to authorize again.`
221 : "Could not refresh the T3 Connect CLI credential.";
222 }
223}
224
225export const isCloudCliCredentialRefreshError = Schema.is(CloudCliCredentialRefreshError);
226
227export class CloudCliCredentialReadError extends Schema.TaggedError<CloudCliCredentialReadError>()(
228 "CloudCliCredentialReadError",
229 { cause: Schema.Defect() },
230) {
231 override get message(): string {
232 return "Could not read the stored T3 Connect CLI credential.";
233 }
234}
235
236export class CloudCliAuthorizationError extends Schema.TaggedError<CloudCliAuthorizationError>()(
237 "CloudCliAuthorizationError",
238 { cause: Schema.Defect() },
239) {
240 override get message(): string {
241 return "Could not authorize the T3 Connect CLI.";
242 }
243}
244
245export class CloudCliAuthorizationTimeoutError extends Schema.TaggedError<CloudCliAuthorizationTimeoutError>()(
246 "CloudCliAuthorizationTimeoutError",
247 { cause: Schema.Defect() },
248) {
249 override get message(): string {
250 return "Timed out waiting for T3 Connect authorization.";
251 }
252}
253
254export class CloudCliAuthorizationDeniedError extends Schema.TaggedError<CloudCliAuthorizationDeniedError>()(
255 "CloudCliAuthorizationDeniedError",
256 {},
257) {
258 override get message(): string {
259 return "T3 Connect authorization was denied in the browser.";
260 }
261}
262
263export const CloudCliTokenManagerError = Schema.Union([
264 CloudCliCredentialRemovalError,
265 CloudCliCredentialRefreshError,
266 CloudCliCredentialReadError,
267 CloudCliAuthorizationError,
268 CloudCliAuthorizationTimeoutError,
269 CloudCliAuthorizationDeniedError,
270]);
271export type CloudCliTokenManagerError = typeof CloudCliTokenManagerError.Type;
272
273export class CloudCliTokenManager extends Context.Service<
274 CloudCliTokenManager,
275 {
276 readonly get: Effect.Effect<
277 | { readonly _tag: "Authorized"; readonly token: PersistedToken }
278 | { readonly _tag: "HeadlessRequested" },
279 CloudCliTokenManagerError | Terminal.QuitError
280 >;
281 readonly getExisting: Effect.Effect<Option.Option<PersistedToken>, CloudCliTokenManagerError>;
282 readonly hasCredential: Effect.Effect<boolean, CloudCliTokenManagerError>;
283 readonly store: (token: PersistedToken) => Effect.Effect<void, CloudCliTokenManagerError>;
284 readonly clear: Effect.Effect<void, CloudCliTokenManagerError>;
285 }
286>()("t3/cloud/CliTokenManager/CloudCliTokenManager") {}
287
288function stringToBytes(value: string): Uint8Array {
289 return new TextEncoder().encode(value);
290}
291
292function bytesToString(value: Uint8Array): string {
293 return new TextDecoder().decode(value);
294}
295
296const readTokenResponse = Effect.fn("cloud.cli_token.read_token_response")(function* (
297 response: HttpClientResponse.HttpClientResponse,
298 params: Record<string, string>,
299) {
300 const body = yield* HttpClientResponse.schemaBodyJson(OAuthTokenResponse)(response);
301 const now = yield* Clock.currentTimeMillis;
302 const identity = idTokenIdentity(body.id_token);
303 return {
304 token: {
305 accessToken: body.access_token,
306 refreshToken: body.refresh_token ?? params.refresh_token ?? "",
307 expiresAtEpochMs: now + body.expires_in * 1_000,
308 ...(identity === null ? {} : { identity }),
309 } satisfies PersistedToken,
310 identity,
311 };
312});
313
314const exchangeToken = Effect.fn("cloud.cli_token.exchange")(function* (
315 metadata: Pick<CloudCliOAuthConfig, "tokenEndpoint">,
316 params: Record<string, string>,
317) {
318 const httpClient = (yield* HttpClient.HttpClient).pipe(HttpClient.filterStatusOk);
319 const startedAt = yield* Clock.monotonicTimeNanos;
320 return yield* HttpClientRequest.post(metadata.tokenEndpoint).pipe(
321 HttpClientRequest.bodyUrlParams(params),
322 httpClient.execute,
323 Effect.flatMap((response) => readTokenResponse(response, params)),
324 Effect.timeout(OAUTH_REQUEST_TIMEOUT),
325 Effect.catchTags({
326 // The enclosing operation owns the span for this inline handler.
327 HttpClientError: Effect.fnUntraced(function* (cause) {
328 const reason = cause.reason;
329 if (
330 params.grant_type !== "refresh_token" ||
331 reason._tag !== "StatusCodeError" ||
332 !isPermanentRefreshStatus(reason.response.status)
333 ) {
334 return yield* cause;
335 }
336 // Reading a rejection body shares the exchange budget without losing
337 // the known status when the body stalls or cannot be decoded.
338 const elapsed = Duration.toMillis(
339 Duration.nanos((yield* Clock.monotonicTimeNanos) - startedAt),
340 );
341 const body = yield* reason.response.json.pipe(
342 Effect.timeout(Math.max(0, Duration.toMillis(OAUTH_REQUEST_TIMEOUT) - elapsed)),
343 Effect.mapError(
344 (cause) =>
345 new CloudCliCredentialRefreshError({
346 status: reason.response.status,
347 cause: new HttpClientError.HttpClientError({
348 reason: new HttpClientError.StatusCodeError({
349 request: reason.request,
350 response: reason.response,
351 cause,
352 }),
353 }),
354 }),
355 ),
356 );
357 const diagnostic = decodeOAuthRefreshErrorResponse(body);
358 return yield* new CloudCliCredentialRefreshError({
359 cause,
360 status: reason.response.status,
361 ...(Option.isSome(diagnostic) ? { oauthErrorCode: diagnostic.value.error } : {}),
362 });
363 }),
364 }),
365 );
366});
367
368const makePkceRequest = Effect.gen(function* () {
369 const crypto = yield* Crypto.Crypto;
370 const verifier = Base64Url.encode(yield* crypto.randomBytes(32));
371 const challenge = Base64Url.encode(
372 yield* crypto.digest("SHA-256", new TextEncoder().encode(verifier)),
373 );
374 const state = Base64Url.encode(yield* crypto.randomBytes(16));
375 return { verifier, challenge, state };
376});
377
378export interface DeviceAuthorizationPrompt {
379 readonly verificationUri: string;
380 readonly verificationUriComplete: string | undefined;
381 readonly userCode: string;
382 readonly expiresIn: Duration.Duration;
383}
384
385const isTransportError = (error: unknown) =>
386 HttpClientError.isHttpClientError(error) && error.reason._tag === "TransportError";
387
388const pollDeviceToken = Effect.fn("cloud.cli_token.poll_device_token")(function* (
389 metadata: Pick<CloudCliOAuthConfig, "tokenEndpoint" | "clientId">,
390 deviceCode: string,
391 initialInterval: Duration.Duration,
392) {
393 const httpClient = yield* HttpClient.HttpClient;
394 const params = {
395 grant_type: DEVICE_CODE_GRANT_TYPE,
396 device_code: deviceCode,
397 client_id: metadata.clientId,
398 };
399 let interval = initialInterval;
400 while (true) {
401 yield* Effect.sleep(interval);
402 const response = yield* HttpClientRequest.post(metadata.tokenEndpoint).pipe(
403 HttpClientRequest.bodyUrlParams(params),
404 httpClient.execute,
405 Effect.asSome,
406 Effect.catchIf(isTransportError, () => Effect.succeedNone),
407 );
408 // Retry transport errors and 5xx while the device code is valid, backing off per RFC 8628 §3.5. Drain bodies to reuse connections.
409 if (Option.isNone(response) || response.value.status >= 500) {
410 if (Option.isSome(response)) yield* Effect.ignore(response.value.text);
411 interval = Duration.sum(interval, DEVICE_AUTHORIZATION_SLOW_DOWN_INCREMENT);
412 continue;
413 }
414 if (response.value.status >= 200 && response.value.status < 300) {
415 return yield* readTokenResponse(response.value, params);
416 }
417 const failure = yield* HttpClientResponse.schemaBodyJson(OAuthErrorResponse)(response.value);
418 switch (failure.error) {
419 case "authorization_pending":
420 continue;
421 case "slow_down":
422 interval = Duration.sum(interval, DEVICE_AUTHORIZATION_SLOW_DOWN_INCREMENT);
423 continue;
424 case "expired_token":
425 return yield* new CloudCliAuthorizationTimeoutError({ cause: failure });
426 case "access_denied":
427 return yield* new CloudCliAuthorizationDeniedError();
428 default:
429 return yield* new CloudCliAuthorizationError({
430 cause: failure.error_description ?? failure.error,
431 });
432 }
433 }
434});
435
436export const deviceAuthorizationLogin = Effect.fn("cloud.cli_token.device_authorization_login")(
437 function* <E, R>(showPrompt: (prompt: DeviceAuthorizationPrompt) => Effect.Effect<void, E, R>) {
438 const metadata = yield* cloudCliOAuthConfig;
439 const httpClient = (yield* HttpClient.HttpClient).pipe(HttpClient.filterStatusOk);
440 const authorization = yield* HttpClientRequest.post(metadata.deviceAuthorizationEndpoint).pipe(
441 HttpClientRequest.bodyUrlParams({
442 client_id: metadata.clientId,
443 scope: metadata.scopes.join(" "),
444 }),
445 httpClient.execute,
446 Effect.flatMap(HttpClientResponse.schemaBodyJson(DeviceAuthorizationResponse)),
447 Effect.timeout(OAUTH_REQUEST_TIMEOUT),
448 );
449 const expiresIn = Duration.seconds(authorization.expires_in);
450 const interval =
451 authorization.interval === undefined
452 ? DEVICE_AUTHORIZATION_DEFAULT_INTERVAL
453 : Duration.seconds(authorization.interval);
454 yield* showPrompt({
455 verificationUri: authorization.verification_uri,
456 verificationUriComplete: authorization.verification_uri_complete,
457 userCode: authorization.user_code,
458 expiresIn,
459 });
460 return yield* pollDeviceToken(metadata, authorization.device_code, interval).pipe(
461 Effect.timeout(expiresIn),
462 Effect.catchTags({
463 TimeoutError: (cause) => Effect.fail(new CloudCliAuthorizationTimeoutError({ cause })),
464 }),
465 );
466 },
467);
468
469/** @public */
470export const make = Effect.gen(function* () {
471 const crypto = yield* Crypto.Crypto;
472 const httpClient = yield* HttpClient.HttpClient;
473 const services = Context.make(Crypto.Crypto, crypto).pipe(
474 Context.add(HttpClient.HttpClient, httpClient),
475 );
476 const secrets = yield* ServerSecretStore.ServerSecretStore;
477 const terminal = yield* Terminal.Terminal;
478 const externalLauncher = yield* ExternalLauncher.ExternalLauncher;
479 const semaphore = yield* Semaphore.make(1);
480 const persist = Effect.fn("cloud.cli_token.persist")(function* (token: PersistedToken) {
481 const encoded = yield* encodePersistedToken(token);
482 yield* secrets.set(CLOUD_CLI_OAUTH_TOKEN_SECRET, stringToBytes(encoded));
483 return token;
484 });
485
486 const clear = secrets
487 .remove(CLOUD_CLI_OAUTH_TOKEN_SECRET)
488 .pipe(Effect.mapError((cause) => new CloudCliCredentialRemovalError({ cause })));
489
490 const read = Effect.fn("cloud.cli_token.read")(function* () {
491 const encoded = yield* secrets.get(CLOUD_CLI_OAUTH_TOKEN_SECRET);
492 if (Option.isNone(encoded)) return Option.none<PersistedToken>();
493 return Option.some(yield* decodePersistedToken(bytesToString(encoded.value)));
494 });
495
496 const refresh = Effect.fn("cloud.cli_token.refresh")(function* (token: PersistedToken) {
497 const metadata = yield* cloudCliOAuthConfig;
498 const { token: refreshed } = yield* exchangeToken(metadata, {
499 grant_type: "refresh_token",
500 refresh_token: token.refreshToken,
501 client_id: metadata.clientId,
502 });
503 return refreshed.identity === undefined && token.identity !== undefined
504 ? { ...refreshed, identity: token.identity }
505 : refreshed;
506 });
507
508 const login = Effect.fn("cloud.cli_token.login")(function* () {
509 const metadata = yield* cloudCliOAuthConfig;
510 const hostedAppUrl = yield* hostedAppUrlConfig;
511 const { verifier, challenge, state } = yield* makePkceRequest;
512 const callback = yield* Deferred.make<string>();
513 const layerCallbackRoute = HttpRouter.add(
514 "GET",
515 "/callback",
516 Effect.gen(function* () {
517 const request = yield* HttpServerRequest.HttpServerRequest;
518 const url = new URL(request.originalUrl, metadata.redirectUri);
519 const code = url.searchParams.get("code");
520 if (url.searchParams.get("state") !== state || !code) {
521 return HttpServerResponse.text("Invalid T3 Connect authorization callback.", {
522 status: 400,
523 });
524 }
525 yield* Deferred.succeed(callback, code);
526 return HttpServerResponse.html(renderLoopbackAuthorizationCompleteHtml());
527 }),
528 );
529 yield* HttpRouter.serve(layerCallbackRoute, {
530 disableListenLog: true,
531 disableLogger: true,
532 }).pipe(
533 Layer.provide(
534 NodeHttpServer.layer(NodeHttp.createServer, {
535 host: "127.0.0.1",
536 port: metadata.loopbackPort,
537 disablePreemptiveShutdown: true,
538 }),
539 ),
540 Layer.build,
541 );
542 // /connect establishes a Clerk session first; /oauth/authorize loses parameters across sign-in.
543 const authorizationUrl = buildConnectAuthorizeRequestUrl({
544 hostedAppUrl,
545 state,
546 challenge,
547 loopbackPort: metadata.loopbackPort,
548 });
549 yield* Console.log(formatLoopbackAuthorizationPrompt(authorizationUrl));
550 const authorization = yield* waitForLoopbackAuthorization({
551 authorizationUrl,
552 callback: Deferred.await(callback).pipe(
553 Effect.timeout(CLOUD_CLI_OAUTH_CALLBACK_TIMEOUT),
554 Effect.catchTags({
555 TimeoutError: (cause) => Effect.fail(new CloudCliAuthorizationTimeoutError({ cause })),
556 }),
557 ),
558 terminal,
559 launchBrowser: externalLauncher.launchBrowser,
560 });
561 if (authorization._tag === "HeadlessRequested") {
562 return authorization;
563 }
564 const { token } = yield* exchangeToken(metadata, {
565 grant_type: "authorization_code",
566 code: authorization.code,
567 redirect_uri: metadata.redirectUri,
568 client_id: metadata.clientId,
569 code_verifier: verifier,
570 });
571 return { _tag: "Authorized", token } as const;
572 });
573
574 const getExistingNoLock = Effect.fn("cloud.cli_token.get_existing_no_lock")(function* () {
575 const token = yield* read();
576 if (Option.isNone(token)) return token;
577 const now = yield* Clock.currentTimeMillis;
578 if (token.value.expiresAtEpochMs - CLOUD_CLI_OAUTH_REFRESH_EARLY_MS > now) {
579 return token;
580 }
581 return Option.some(
582 // The endpoint can rotate the refresh token before shutdown interrupts us.
583 // Keep the lock through persistence; the exchange still times out internally.
584 yield* refresh(token.value).pipe(Effect.flatMap(persist), Effect.uninterruptible),
585 );
586 });
587
588 const getExisting = semaphore.withPermits(1)(
589 getExistingNoLock().pipe(
590 Effect.mapError((cause) =>
591 isCloudCliCredentialRefreshError(cause)
592 ? cause
593 : new CloudCliCredentialRefreshError({
594 cause,
595 ...(HttpClientError.isHttpClientError(cause) &&
596 cause.reason._tag === "StatusCodeError"
597 ? { status: cause.reason.response.status }
598 : {}),
599 }),
600 ),
601 Effect.provide(services),
602 ),
603 );
604 const hasCredential = semaphore.withPermits(1)(
605 read().pipe(
606 Effect.map(Option.isSome),
607 Effect.mapError((cause) => new CloudCliCredentialReadError({ cause })),
608 ),
609 );
610 const get = semaphore.withPermits(1)(
611 Effect.gen(function* () {
612 const token = yield* getExistingNoLock().pipe(
613 Effect.orElseSucceed(() => Option.none<PersistedToken>()),
614 );
615 if (Option.isSome(token)) {
616 return { _tag: "Authorized", token: token.value } as const;
617 }
618 const authorization = yield* Effect.scoped(login());
619 return authorization._tag === "Authorized"
620 ? ({ _tag: "Authorized", token: yield* persist(authorization.token) } as const)
621 : authorization;
622 }).pipe(
623 Effect.mapError((cause) =>
624 Terminal.isQuitError(cause) ? cause : new CloudCliAuthorizationError({ cause }),
625 ),
626 Effect.provide(services),
627 ),
628 );
629 const store = Effect.fn("cloud.cli_token.store")(function* (token: PersistedToken) {
630 yield* semaphore.withPermits(1)(
631 persist(token).pipe(
632 Effect.asVoid,
633 Effect.mapError((cause) => new CloudCliAuthorizationError({ cause })),
634 ),
635 );
636 });
637
638 return CloudCliTokenManager.of({ get, getExisting, hasCredential, store, clear });
639});
640
641export const layer = Layer.effect(CloudCliTokenManager, make);