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 Service construction is part of the canonical Effect module API. */
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 const configOption = primary === undefined ? Option.none() : yield* primary.currentConfig;
84 if (Option.isNone(configOption)) {
85 return yield* new DesktopLocalEnvironmentAuthBackendNotConfiguredError();
86 }
87 const config = configOption.value;
88 // A backend launched with the desktop secret accepts the current
89 // window's token, not the one frozen into its launch config; this
90 // exchange can run long after launch (e.g. after a suspend).
91 const secret = config.bootstrap.desktopBootstrapSecret;
92 const credential =
93 secret === undefined
94 ? config.bootstrap.desktopBootstrapToken
95 : currentDesktopBootstrapToken(secret, yield* Clock.currentTimeMillis);
96 if (!credential) {
97 return yield* new DesktopLocalEnvironmentAuthBackendNotConfiguredError();
98 }
99 const session = yield* bootstrapRemoteBearerSession({
100 httpBaseUrl: config.httpBaseUrl.href,
101 credential,
102 clientMetadata: {
103 label: "T3 Code Desktop",
104 deviceType: "desktop",
105 },
106 }).pipe(
107 Effect.provideService(HttpClient.HttpClient, httpClient),
108 Effect.retry({
109 while: isTransientBearerBootstrapError,
110 schedule: Schedule.spaced(BOOTSTRAP_TRANSIENT_RETRY_INTERVAL),
111 }),
112 Effect.timeout(BOOTSTRAP_TRANSIENT_RETRY_TIMEOUT),
113 Effect.mapError(
114 (cause) =>
115 new DesktopLocalEnvironmentAuthSessionBootstrapError({
116 cause,
117 }),
118 ),
119 );
120 yield* Ref.set(tokenRef, Option.some(session.access_token));
121 return session.access_token;
122 }),
123 )
124 .pipe(Effect.withSpan("desktop.localEnvironmentAuth.getBearerToken"));
125
126 return DesktopLocalEnvironmentAuth.of({ getBearerToken });
127});
128
129export const layer = Layer.effect(DesktopLocalEnvironmentAuth, make);