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 clientMetadata: presentation.metadata,
135 }).pipe(
136 Effect.mapError(mapRemoteEnvironmentError),
137 Effect.provideService(HttpClient.HttpClient, httpClient),
138 );
139 return {
140 environmentId: descriptor.environmentId,
141 label: descriptor.label,
142 httpBaseUrl: input.httpBaseUrl,
143 socketUrl,
144 httpAuthorization: {
145 _tag: "Bearer" as const,
146 token: input.bearerToken,
147 },
148 };
149 },
150 );
151
152 const createDpopSocketUrl = Effect.fn("clientRuntime.connection.remote.createDpopSocketUrl")(
153 function* (token: TokenStore.RemoteDpopAccessToken, timeoutMs?: number) {
154 const ticketProof = yield* signer
155 .createProof({
156 method: "POST",
157 url: environmentEndpointUrl(token.endpoint.httpBaseUrl, "/api/auth/websocket-ticket"),
158 accessToken: token.accessToken,
159 })
160 .pipe(
161 Effect.mapError(
162 () =>
163 new ConnectionBlockedError({
164 reason: "configuration",
165 detail: "Could not create the websocket authorization proof.",
166 }),
167 ),
168 );
169 return yield* resolveRemoteDpopWebSocketConnectionUrl({
170 wsBaseUrl: token.endpoint.wsBaseUrl,
171 httpBaseUrl: token.endpoint.httpBaseUrl,
172 accessToken: token.accessToken,
173 dpopProof: ticketProof,
174 clientMetadata: presentation.metadata,
175 ...(timeoutMs === undefined ? {} : { timeoutMs }),
176 }).pipe(Effect.provideService(HttpClient.HttpClient, httpClient));
177 },
178 );
179
180 const authorizeDpop = Effect.fn("clientRuntime.connection.remote.authorizeDpop")(
181 function* (input: {
182 readonly expectedEnvironmentId: Parameters<
183 RemoteEnvironmentAuthorization["Service"]["authorizeDpop"]
184 >[0]["expectedEnvironmentId"];
185 readonly obtainBootstrap: Parameters<
186 RemoteEnvironmentAuthorization["Service"]["authorizeDpop"]
187 >[0]["obtainBootstrap"];
188 }) {
189 const thumbprint = yield* signer.thumbprint.pipe(
190 Effect.mapError(
191 () =>
192 new ConnectionBlockedError({
193 reason: "configuration",
194 detail: "Could not load the environment authorization key.",
195 }),
196 ),
197 Effect.withSpan("environment.authorization.dpopKey.resolve"),
198 );
199 const now = yield* Clock.currentTimeMillis;
200 const cached = yield* tokenStore
201 .get(input.expectedEnvironmentId)
202 .pipe(Effect.withSpan("environment.authorization.accessToken.cache"));
203 if (
204 Option.isSome(cached) &&
205 cached.value.environmentId === input.expectedEnvironmentId &&
206 cached.value.dpopThumbprint === thumbprint &&
207 cached.value.expiresAtEpochMs > now + TOKEN_EXPIRY_SAFETY_MARGIN_MS
208 ) {
209 yield* Effect.annotateCurrentSpan({
210 "connection.remote_token_cache": "hit",
211 });
212 const cachedSocket = yield* createDpopSocketUrl(
213 cached.value,
214 CACHED_ENDPOINT_SOCKET_TIMEOUT_MS,
215 ).pipe(Effect.result);
216 if (Result.isSuccess(cachedSocket)) {
217 return {
218 environmentId: cached.value.environmentId,
219 label: cached.value.label,
220 httpBaseUrl: cached.value.endpoint.httpBaseUrl,
221 socketUrl: cachedSocket.success,
222 httpAuthorization: {
223 _tag: "Dpop" as const,
224 accessToken: cached.value.accessToken,
225 },
226 };
227 }
228 if (cachedSocket.failure._tag === "ConnectionBlockedError") {
229 return yield* mapDpopSocketError(cachedSocket.failure);
230 }
231 yield* tokenStore
232 .remove(input.expectedEnvironmentId)
233 .pipe(Effect.withSpan("environment.authorization.accessToken.remove"));
234 }
235
236 yield* Effect.annotateCurrentSpan({
237 "connection.remote_token_cache": "miss",
238 });
239 const bootstrap = yield* input.obtainBootstrap;
240 const descriptor = yield* fetchDescriptor(bootstrap.endpoint.httpBaseUrl).pipe(
241 Effect.provideService(HttpClient.HttpClient, httpClient),
242 Effect.withSpan("environment.authorization.descriptor"),
243 );
244 if (descriptor.environmentId !== input.expectedEnvironmentId) {
245 return yield* environmentMismatchError({
246 expected: input.expectedEnvironmentId,
247 actual: descriptor.environmentId,
248 });
249 }
250 const bootstrapProof = yield* signer
251 .createProof({
252 method: "POST",
253 url: environmentEndpointUrl(bootstrap.endpoint.httpBaseUrl, "/oauth/token"),
254 })
255 .pipe(
256 Effect.mapError(
257 () =>
258 new ConnectionBlockedError({
259 reason: "configuration",
260 detail: "Could not create the environment authorization proof.",
261 }),
262 ),
263 );
264 const access = yield* exchangeRemoteDpopAccessToken({
265 httpBaseUrl: bootstrap.endpoint.httpBaseUrl,
266 credential: bootstrap.credential,
267 dpopProof: bootstrapProof,
268 scopes: presentation.scopes,
269 clientMetadata: presentation.metadata,
270 }).pipe(
271 Effect.mapError(mapRemoteEnvironmentError),
272 Effect.provideService(HttpClient.HttpClient, httpClient),
273 Effect.withSpan("environment.authorization.accessToken.exchange"),
274 );
275 const issuedAt = yield* Clock.currentTimeMillis;
276 const token = new TokenStore.RemoteDpopAccessToken({
277 environmentId: descriptor.environmentId,
278 label: descriptor.label,
279 endpoint: bootstrap.endpoint,
280 accessToken: access.access_token,
281 expiresAtEpochMs: issuedAt + access.expires_in * 1_000,
282 dpopThumbprint: thumbprint,
283 });
284 const socketUrl = yield* createDpopSocketUrl(token).pipe(Effect.mapError(mapDpopSocketError));
285 yield* tokenStore
286 .put(token)
287 .pipe(Effect.withSpan("environment.authorization.accessToken.persist"));
288 return {
289 environmentId: descriptor.environmentId,
290 label: descriptor.label,
291 httpBaseUrl: bootstrap.endpoint.httpBaseUrl,
292 socketUrl,
293 httpAuthorization: {
294 _tag: "Dpop" as const,
295 accessToken: token.accessToken,
296 },
297 };
298 },
299 );
300
301 return RemoteEnvironmentAuthorization.of({
302 authorizeBearer,
303 authorizeDpop: (input) =>
304 authorizeDpop(input).pipe(Effect.withSpan("environment.authorization")),
305 });
306});
307
308export const layer = Layer.effect(RemoteEnvironmentAuthorization, make);