Open History to see the last commit
1import { bootstrapRemoteBearerSession } from "@t3tools/client-runtime/authorization";
2import type { RemoteEnvironmentRequestError } from "@t3tools/client-runtime/rpc";
3import { PRIMARY_LOCAL_ENVIRONMENT_ID } from "@t3tools/contracts";
4import { currentDesktopBootstrapToken } from "@t3tools/shared/desktopBootstrapToken";
5import * as Clock from "effect/Clock";
6import * as Context from "effect/Context";
7import * as Duration from "effect/Duration";
8import * as Effect from "effect/Effect";
9import * as Layer from "effect/Layer";
10import * as Option from "effect/Option";
11import * as Ref from "effect/Ref";
12import * as Schedule from "effect/Schedule";
13import * as Schema from "effect/Schema";
14import * as Semaphore from "effect/Semaphore";
15import * as HttpClient from "effect/http/HttpClient";
16
17import * as DesktopBackendPool from "./DesktopBackendPool.ts";
18
19const BOOTSTRAP_TRANSIENT_RETRY_TIMEOUT = Duration.seconds(15);
20const BOOTSTRAP_TRANSIENT_RETRY_INTERVAL = Duration.millis(500);
21const TRANSIENT_BOOTSTRAP_STATUS_CODES = new Set([502, 503, 504]);
22
23const isTransientBearerBootstrapError = (error: RemoteEnvironmentRequestError): boolean => {
24 switch (error._tag) {
25 case "RemoteEnvironmentAuthFetchError":
26 case "RemoteEnvironmentAuthTimeoutError":
27 return true;
28 case "RemoteEnvironmentAuthUndeclaredStatusError":
29 return TRANSIENT_BOOTSTRAP_STATUS_CODES.has(error.status);
30 default:
31 return false;
32 }
33};
34
35export class DesktopLocalEnvironmentAuthBackendNotConfiguredError extends Schema.TaggedError<DesktopLocalEnvironmentAuthBackendNotConfiguredError>()(
36 "DesktopLocalEnvironmentAuthBackendNotConfiguredError",
37 {},
38) {
39 override get message(): string {
40 return "Local backend is not configured.";
41 }
42}
43
44export class DesktopLocalEnvironmentAuthSessionBootstrapError extends Schema.TaggedError<DesktopLocalEnvironmentAuthSessionBootstrapError>()(
45 "DesktopLocalEnvironmentAuthSessionBootstrapError",
46 { cause: Schema.Defect() },
47) {
48 override get message(): string {
49 return "Failed to create the local desktop bearer session.";
50 }
51}
52
53export const DesktopLocalEnvironmentAuthError = Schema.Union([
54 DesktopLocalEnvironmentAuthBackendNotConfiguredError,
55 DesktopLocalEnvironmentAuthSessionBootstrapError,
56]);
57export type DesktopLocalEnvironmentAuthError = typeof DesktopLocalEnvironmentAuthError.Type;
58
59export class DesktopLocalEnvironmentAuth extends Context.Service<
60 DesktopLocalEnvironmentAuth,
61 {
62 readonly getBearerToken: Effect.Effect<string, DesktopLocalEnvironmentAuthError>;
63 }
64>()("@t3tools/desktop/backend/DesktopLocalEnvironmentAuth") {}
65
66/** @public */
67export const make = Effect.gen(function* () {
68 const pool = yield* DesktopBackendPool.DesktopBackendPool;
69 const httpClient = yield* HttpClient.HttpClient;
70 const tokenRef = yield* Ref.make(Option.none<string>());
71 const mutex = yield* Semaphore.make(1);
72
73 const getBearerToken = mutex
74 .withPermits(1)(
75 Effect.gen(function* () {
76 const cached = yield* Ref.get(tokenRef);
77 if (Option.isSome(cached)) {
78 return cached.value;
79 }
80
81 const instances = yield* pool.list;
82 const primary = instances.find((instance) => instance.id === PRIMARY_LOCAL_ENVIRONMENT_ID);
83 if (primary === undefined || !(yield* primary.waitForReady(Duration.infinity))) {
84 return yield* new DesktopLocalEnvironmentAuthBackendNotConfiguredError();
85 }
86 const configOption = yield* primary.currentConfig;
87 if (Option.isNone(configOption)) {
88 return yield* new DesktopLocalEnvironmentAuthBackendNotConfiguredError();
89 }
90 const config = configOption.value;
91 // Secret-authenticated backends accept the current window token; the launch token may be stale.
92 const secret = config.bootstrap.desktopBootstrapSecret;
93 const credential =
94 secret === undefined
95 ? config.bootstrap.desktopBootstrapToken
96 : currentDesktopBootstrapToken(secret, yield* Clock.currentTimeMillis);
97 if (!credential) {
98 return yield* new DesktopLocalEnvironmentAuthBackendNotConfiguredError();
99 }
100 const session = yield* bootstrapRemoteBearerSession({
101 httpBaseUrl: config.httpBaseUrl.href,
102 credential,
103 clientMetadata: {
104 label: "T3 Code Desktop",
105 deviceType: "desktop",
106 },
107 }).pipe(
108 Effect.provideService(HttpClient.HttpClient, httpClient),
109 Effect.retry({
110 while: isTransientBearerBootstrapError,
111 schedule: Schedule.spaced(BOOTSTRAP_TRANSIENT_RETRY_INTERVAL),
112 }),
113 Effect.timeout(BOOTSTRAP_TRANSIENT_RETRY_TIMEOUT),
114 Effect.mapError(
115 (cause) =>
116 new DesktopLocalEnvironmentAuthSessionBootstrapError({
117 cause,
118 }),
119 ),
120 );
121 yield* Ref.set(tokenRef, Option.some(session.access_token));
122 return session.access_token;
123 }),
124 )
125 .pipe(Effect.withSpan("desktop.localEnvironmentAuth.getBearerToken"));
126
127 return DesktopLocalEnvironmentAuth.of({ getBearerToken });
128});
129
130export const layer = Layer.effect(DesktopLocalEnvironmentAuth, make);