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