Open History to see the last commit
1import { EnvironmentId, type ExecutionEnvironmentDescriptor } from "@t3tools/contracts";
2import type { RelayManagedEndpoint } from "@t3tools/contracts/relay";
3import {
4 exchangeRemoteDpopAccessToken,
5 type RemoteEnvironmentAuthError,
6 resolveRemoteDpopWebSocketConnectionUrl,
7 resolveRemoteWebSocketConnectionUrl,
8} from "./remote.ts";
9import { environmentMismatchError, mapRemoteEnvironmentError } from "../connection/errors.ts";
10import { ConnectionBlockedError, type ConnectionAttemptError } from "../connection/model.ts";
11import { fetchRemoteEnvironmentDescriptor } from "../environment/descriptor.ts";
12import { environmentEndpointUrl } from "../environment/endpoint.ts";
13import * as ClientCapabilities from "../platform/capabilities.ts";
14import * as ManagedRelay from "../relay/managedRelay.ts";
15import * as TokenStore from "./tokenStore.ts";
16import * as Clock from "effect/Clock";
17import * as Context from "effect/Context";
18import * as Effect from "effect/Effect";
19import * as Layer from "effect/Layer";
20import * as Option from "effect/Option";
21import * as Ref from "effect/Ref";
22import * as Result from "effect/Result";
23import * as HttpClient from "effect/unstable/http/HttpClient";
24
25import type { PreparedHttpAuthorization } from "../connection/model.ts";
26
27export interface RelayEnvironmentAuthorization {
28 readonly environmentId: EnvironmentId;
29 readonly endpoint: RelayManagedEndpoint;
30 readonly credential: string;
31}
32
33export interface AuthorizedRemoteEnvironment {
34 readonly environmentId: EnvironmentId;
35 readonly label: string;
36 readonly httpBaseUrl: string;
37 readonly socketUrl: string;
38 readonly httpAuthorization: PreparedHttpAuthorization;
39}
40
41export class RemoteEnvironmentAuthorization extends Context.Service<
42 RemoteEnvironmentAuthorization,
43 {
44 readonly authorizeBearer: (input: {
45 readonly expectedEnvironmentId: EnvironmentId;
46 readonly httpBaseUrl: string;
47 readonly wsBaseUrl: string;
48 readonly bearerToken: string;
49 }) => Effect.Effect<AuthorizedRemoteEnvironment, ConnectionAttemptError>;
50 readonly authorizeDpop: (input: {
51 readonly expectedEnvironmentId: EnvironmentId;
52 readonly obtainBootstrap: Effect.Effect<
53 RelayEnvironmentAuthorization,
54 ConnectionAttemptError
55 >;
56 }) => Effect.Effect<AuthorizedRemoteEnvironment, ConnectionAttemptError>;
57 }
58>()("@t3tools/client-runtime/authorization/service/RemoteEnvironmentAuthorization") {}
59
60const TOKEN_EXPIRY_SAFETY_MARGIN_MS = 60_000;
61const CACHED_ENDPOINT_SOCKET_TIMEOUT_MS = 3_000;
62const BEARER_DESCRIPTOR_CACHE_TTL_MS = 10_000;
63
64function mapDpopSocketError(error: RemoteEnvironmentAuthError | ConnectionAttemptError) {
65 return error._tag === "ConnectionTransientError" || error._tag === "ConnectionBlockedError"
66 ? error
67 : mapRemoteEnvironmentError(error);
68}
69
70const fetchDescriptor = Effect.fn("clientRuntime.connection.remote.fetchDescriptor")(function* (
71 httpBaseUrl: string,
72) {
73 return yield* fetchRemoteEnvironmentDescriptor({ httpBaseUrl }).pipe(
74 Effect.mapError(mapRemoteEnvironmentError),
75 );
76});
77
78export const make = Effect.gen(function* () {
79 const signer = yield* ManagedRelay.ManagedRelayDpopSigner;
80 const presentation = yield* ClientCapabilities.ClientPresentation;
81 const tokenStore = yield* TokenStore.RemoteDpopAccessTokenStore;
82 const httpClient = yield* HttpClient.HttpClient;
83 const bearerDescriptors = yield* Ref.make<
84 ReadonlyMap<
85 EnvironmentId,
86 {
87 readonly httpBaseUrl: string;
88 readonly descriptor: ExecutionEnvironmentDescriptor;
89 readonly validatedAtEpochMs: number;
90 }
91 >
92 >(new Map());
93
94 const authorizeBearer = Effect.fn("clientRuntime.connection.remote.authorizeBearer")(
95 function* (input: {
96 readonly expectedEnvironmentId: Parameters<
97 RemoteEnvironmentAuthorization["Service"]["authorizeBearer"]
98 >[0]["expectedEnvironmentId"];
99 readonly httpBaseUrl: string;
100 readonly wsBaseUrl: string;
101 readonly bearerToken: string;
102 }) {
103 const now = yield* Clock.currentTimeMillis;
104 const cachedDescriptor = (yield* Ref.get(bearerDescriptors)).get(input.expectedEnvironmentId);
105 const canReuseDescriptor =
106 cachedDescriptor?.httpBaseUrl === input.httpBaseUrl &&
107 cachedDescriptor.validatedAtEpochMs + BEARER_DESCRIPTOR_CACHE_TTL_MS > now;
108 const descriptor = canReuseDescriptor
109 ? cachedDescriptor.descriptor
110 : yield* fetchDescriptor(input.httpBaseUrl).pipe(
111 Effect.provideService(HttpClient.HttpClient, httpClient),
112 );
113 if (descriptor.environmentId !== input.expectedEnvironmentId) {
114 return yield* environmentMismatchError({
115 expected: input.expectedEnvironmentId,
116 actual: descriptor.environmentId,
117 });
118 }
119 if (!canReuseDescriptor) {
120 yield* Ref.update(bearerDescriptors, (current) => {
121 const next = new Map(current);
122 next.set(input.expectedEnvironmentId, {
123 httpBaseUrl: input.httpBaseUrl,
124 descriptor,
125 validatedAtEpochMs: now,
126 });
127 return next;
128 });
129 }
130 const socketUrl = yield* resolveRemoteWebSocketConnectionUrl({
131 wsBaseUrl: input.wsBaseUrl,
132 httpBaseUrl: input.httpBaseUrl,
133 bearerToken: input.bearerToken,
134 }).pipe(
135 Effect.mapError(mapRemoteEnvironmentError),
136 Effect.provideService(HttpClient.HttpClient, httpClient),
137 );
138 return {
139 environmentId: descriptor.environmentId,
140 label: descriptor.label,
141 httpBaseUrl: input.httpBaseUrl,
142 socketUrl,
143 httpAuthorization: {
144 _tag: "Bearer" as const,
145 token: input.bearerToken,
146 },
147 };
148 },
149 );
150
151 const createDpopSocketUrl = Effect.fn("clientRuntime.connection.remote.createDpopSocketUrl")(
152 function* (token: TokenStore.RemoteDpopAccessToken, timeoutMs?: number) {
153 const ticketProof = yield* signer
154 .createProof({
155 method: "POST",
156 url: environmentEndpointUrl(token.endpoint.httpBaseUrl, "/api/auth/websocket-ticket"),
157 accessToken: token.accessToken,
158 })
159 .pipe(
160 Effect.mapError(
161 () =>
162 new ConnectionBlockedError({
163 reason: "configuration",
164 detail: "Could not create the websocket authorization proof.",
165 }),
166 ),
167 );
168 return yield* resolveRemoteDpopWebSocketConnectionUrl({
169 wsBaseUrl: token.endpoint.wsBaseUrl,
170 httpBaseUrl: token.endpoint.httpBaseUrl,
171 accessToken: token.accessToken,
172 dpopProof: ticketProof,
173 ...(timeoutMs === undefined ? {} : { timeoutMs }),
174 }).pipe(Effect.provideService(HttpClient.HttpClient, httpClient));
175 },
176 );
177
178 const authorizeDpop = Effect.fn("clientRuntime.connection.remote.authorizeDpop")(
179 function* (input: {
180 readonly expectedEnvironmentId: Parameters<
181 RemoteEnvironmentAuthorization["Service"]["authorizeDpop"]
182 >[0]["expectedEnvironmentId"];
183 readonly obtainBootstrap: Parameters<
184 RemoteEnvironmentAuthorization["Service"]["authorizeDpop"]
185 >[0]["obtainBootstrap"];
186 }) {
187 const thumbprint = yield* signer.thumbprint.pipe(
188 Effect.mapError(
189 () =>
190 new ConnectionBlockedError({
191 reason: "configuration",
192 detail: "Could not load the environment authorization key.",
193 }),
194 ),
195 Effect.withSpan("environment.authorization.dpopKey.resolve"),
196 );
197 const now = yield* Clock.currentTimeMillis;
198 const cached = yield* tokenStore
199 .get(input.expectedEnvironmentId)
200 .pipe(Effect.withSpan("environment.authorization.accessToken.cache"));
201 if (
202 Option.isSome(cached) &&
203 cached.value.environmentId === input.expectedEnvironmentId &&
204 cached.value.dpopThumbprint === thumbprint &&
205 cached.value.expiresAtEpochMs > now + TOKEN_EXPIRY_SAFETY_MARGIN_MS
206 ) {
207 yield* Effect.annotateCurrentSpan({
208 "connection.remote_token_cache": "hit",
209 });
210 const cachedSocket = yield* createDpopSocketUrl(
211 cached.value,
212 CACHED_ENDPOINT_SOCKET_TIMEOUT_MS,
213 ).pipe(Effect.result);
214 if (Result.isSuccess(cachedSocket)) {
215 return {
216 environmentId: cached.value.environmentId,
217 label: cached.value.label,
218 httpBaseUrl: cached.value.endpoint.httpBaseUrl,
219 socketUrl: cachedSocket.success,
220 httpAuthorization: {
221 _tag: "Dpop" as const,
222 accessToken: cached.value.accessToken,
223 },
224 };
225 }
226 if (cachedSocket.failure._tag === "ConnectionBlockedError") {
227 return yield* mapDpopSocketError(cachedSocket.failure);
228 }
229 yield* tokenStore
230 .remove(input.expectedEnvironmentId)
231 .pipe(Effect.withSpan("environment.authorization.accessToken.remove"));
232 }
233
234 yield* Effect.annotateCurrentSpan({
235 "connection.remote_token_cache": "miss",
236 });
237 const bootstrap = yield* input.obtainBootstrap;
238 const descriptor = yield* fetchDescriptor(bootstrap.endpoint.httpBaseUrl).pipe(
239 Effect.provideService(HttpClient.HttpClient, httpClient),
240 Effect.withSpan("environment.authorization.descriptor"),
241 );
242 if (descriptor.environmentId !== input.expectedEnvironmentId) {
243 return yield* environmentMismatchError({
244 expected: input.expectedEnvironmentId,
245 actual: descriptor.environmentId,
246 });
247 }
248 const bootstrapProof = yield* signer
249 .createProof({
250 method: "POST",
251 url: environmentEndpointUrl(bootstrap.endpoint.httpBaseUrl, "/oauth/token"),
252 })
253 .pipe(
254 Effect.mapError(
255 () =>
256 new ConnectionBlockedError({
257 reason: "configuration",
258 detail: "Could not create the environment authorization proof.",
259 }),
260 ),
261 );
262 const access = yield* exchangeRemoteDpopAccessToken({
263 httpBaseUrl: bootstrap.endpoint.httpBaseUrl,
264 credential: bootstrap.credential,
265 dpopProof: bootstrapProof,
266 scopes: presentation.scopes,
267 clientMetadata: presentation.metadata,
268 }).pipe(
269 Effect.mapError(mapRemoteEnvironmentError),
270 Effect.provideService(HttpClient.HttpClient, httpClient),
271 Effect.withSpan("environment.authorization.accessToken.exchange"),
272 );
273 const issuedAt = yield* Clock.currentTimeMillis;
274 const token = new TokenStore.RemoteDpopAccessToken({
275 environmentId: descriptor.environmentId,
276 label: descriptor.label,
277 endpoint: bootstrap.endpoint,
278 accessToken: access.access_token,
279 expiresAtEpochMs: issuedAt + access.expires_in * 1_000,
280 dpopThumbprint: thumbprint,
281 });
282 const socketUrl = yield* createDpopSocketUrl(token).pipe(Effect.mapError(mapDpopSocketError));
283 yield* tokenStore
284 .put(token)
285 .pipe(Effect.withSpan("environment.authorization.accessToken.persist"));
286 return {
287 environmentId: descriptor.environmentId,
288 label: descriptor.label,
289 httpBaseUrl: bootstrap.endpoint.httpBaseUrl,
290 socketUrl,
291 httpAuthorization: {
292 _tag: "Dpop" as const,
293 accessToken: token.accessToken,
294 },
295 };
296 },
297 );
298
299 return RemoteEnvironmentAuthorization.of({
300 authorizeBearer,
301 authorizeDpop: (input) =>
302 authorizeDpop(input).pipe(Effect.withSpan("environment.authorization")),
303 });
304});
305
306export const layer = Layer.effect(RemoteEnvironmentAuthorization, make);