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