Open History to see the last commit
1import {
2 type ClientConnectionMethod,
3 EnvironmentId,
4 type ExecutionEnvironmentDescriptor,
5} from "@t3tools/contracts";
6import { RelayEnvironmentConnectScope } from "@t3tools/contracts/relay";
7import { withRelayClientTracing } from "@t3tools/shared/relayTracing";
8import {
9 exchangeRemoteDpopAccessToken,
10 type RemoteEnvironmentAuthError,
11 resolveRemoteDpopWebSocketConnectionUrl,
12 resolveRemoteWebSocketConnectionUrl,
13} from "./remote.ts";
14import {
15 environmentMismatchError,
16 mapManagedRelayError,
17 mapRemoteDpopEnvironmentError,
18 mapRemoteEnvironmentError,
19} from "../connection/errors.ts";
20import {
21 ConnectionBlockedError,
22 ConnectionTransientError,
23 type ConnectionAttemptError,
24} from "../connection/model.ts";
25import { fetchRemoteEnvironmentDescriptor } from "../environment/descriptor.ts";
26import { environmentEndpointUrl } from "../environment/endpoint.ts";
27import * as ClientCapabilities from "../platform/capabilities.ts";
28import * as ManagedRelay from "../relay/managedRelay.ts";
29import * as TokenStore from "./tokenStore.ts";
30import * as Clock from "effect/Clock";
31import * as Context from "effect/Context";
32import * as Effect from "effect/Effect";
33import * as Fiber from "effect/Fiber";
34import * as Layer from "effect/Layer";
35import * as Option from "effect/Option";
36import * as Ref from "effect/Ref";
37import * as Result from "effect/Result";
38import * as Scope from "effect/Scope";
39import * as Semaphore from "effect/Semaphore";
40import * as HttpClient from "effect/unstable/http/HttpClient";
41
42import {
43 DPOP_ACCESS_TOKEN_REFRESH_SKEW_MS,
44 type PreparedHttpAuthorization,
45} from "../connection/model.ts";
46
47export interface AuthorizedRemoteEnvironment {
48 readonly environmentId: EnvironmentId;
49 readonly label: string;
50 readonly httpBaseUrl: string;
51 readonly socketUrl: string;
52 readonly httpAuthorization: PreparedHttpAuthorization;
53}
54
55export interface AuthorizedRemoteHttpEnvironment {
56 readonly environmentId: EnvironmentId;
57 readonly label: string;
58 readonly httpBaseUrl: string;
59 readonly httpAuthorization: Extract<PreparedHttpAuthorization, { readonly _tag: "Dpop" }>;
60}
61
62export class RemoteEnvironmentAuthorization extends Context.Service<
63 RemoteEnvironmentAuthorization,
64 {
65 readonly authorizeBearer: (input: {
66 readonly expectedEnvironmentId: EnvironmentId;
67 readonly httpBaseUrl: string;
68 readonly wsBaseUrl: string;
69 readonly bearerToken: string;
70 readonly connectionMethod: ClientConnectionMethod;
71 }) => Effect.Effect<AuthorizedRemoteEnvironment, ConnectionAttemptError>;
72 readonly authorizeDpop: (input: {
73 readonly expectedEnvironmentId: EnvironmentId;
74 }) => Effect.Effect<AuthorizedRemoteEnvironment, ConnectionAttemptError>;
75 readonly authorizeDpopHttp: (input: {
76 readonly expectedEnvironmentId: EnvironmentId;
77 readonly rejectedAccessToken?: string;
78 }) => Effect.Effect<AuthorizedRemoteHttpEnvironment, ConnectionAttemptError>;
79 }
80>()("@t3tools/client-runtime/authorization/service/RemoteEnvironmentAuthorization") {}
81
82const CACHED_ENDPOINT_SOCKET_TIMEOUT_MS = 3_000;
83const BEARER_DESCRIPTOR_CACHE_TTL_MS = 10_000;
84const DPOP_AUTHORIZATION_TIMEOUT_MS = 30_000;
85
86function mapDpopSocketError(error: RemoteEnvironmentAuthError | ConnectionAttemptError) {
87 return error._tag === "ConnectionTransientError" || error._tag === "ConnectionBlockedError"
88 ? error
89 : mapRemoteDpopEnvironmentError(error);
90}
91
92const fetchDescriptor = Effect.fn("clientRuntime.connection.remote.fetchDescriptor")(function* (
93 httpBaseUrl: string,
94 connectionMethod: ClientConnectionMethod,
95) {
96 return yield* fetchRemoteEnvironmentDescriptor({ httpBaseUrl }).pipe(
97 Effect.mapError((error) => mapRemoteEnvironmentError(error, connectionMethod)),
98 );
99});
100
101export const make = Effect.gen(function* () {
102 const serviceScope = yield* Scope.Scope;
103 const signer = yield* ManagedRelay.ManagedRelayDpopSigner;
104 const relay = yield* ManagedRelay.ManagedRelayClient;
105 const cloudSession = yield* ClientCapabilities.CloudSession;
106 const deviceIdentity = yield* ClientCapabilities.RelayDeviceIdentity;
107 const presentation = yield* ClientCapabilities.ClientPresentation;
108 const tokenStore = yield* TokenStore.RemoteDpopAccessTokenStore;
109 const httpClient = yield* HttpClient.HttpClient;
110 const tokenLock = yield* Semaphore.make(1);
111 const tokenOwners = new Map<
112 EnvironmentId,
113 { readonly accessToken: string; readonly identity: ClientCapabilities.CloudSessionIdentity }
114 >();
115 const pendingTokens = new Map<
116 EnvironmentId,
117 {
118 readonly id: object;
119 readonly identity: ClientCapabilities.CloudSessionIdentity;
120 readonly thumbprint: string;
121 readonly token: Effect.Effect<TokenStore.RemoteDpopAccessToken, ConnectionAttemptError>;
122 }
123 >();
124 const bearerDescriptors = yield* Ref.make<
125 ReadonlyMap<
126 EnvironmentId,
127 {
128 readonly httpBaseUrl: string;
129 readonly descriptor: ExecutionEnvironmentDescriptor;
130 readonly validatedAtEpochMs: number;
131 }
132 >
133 >(new Map());
134
135 const authorizeBearer = Effect.fn("clientRuntime.connection.remote.authorizeBearer")(
136 function* (input: {
137 readonly expectedEnvironmentId: Parameters<
138 RemoteEnvironmentAuthorization["Service"]["authorizeBearer"]
139 >[0]["expectedEnvironmentId"];
140 readonly httpBaseUrl: string;
141 readonly wsBaseUrl: string;
142 readonly bearerToken: string;
143 readonly connectionMethod: ClientConnectionMethod;
144 }) {
145 const now = yield* Clock.currentTimeMillis;
146 const cachedDescriptor = (yield* Ref.get(bearerDescriptors)).get(input.expectedEnvironmentId);
147 const canReuseDescriptor =
148 cachedDescriptor?.httpBaseUrl === input.httpBaseUrl &&
149 cachedDescriptor.validatedAtEpochMs + BEARER_DESCRIPTOR_CACHE_TTL_MS > now;
150 const descriptor = canReuseDescriptor
151 ? cachedDescriptor.descriptor
152 : yield* fetchDescriptor(input.httpBaseUrl, input.connectionMethod).pipe(
153 Effect.provideService(HttpClient.HttpClient, httpClient),
154 );
155 if (descriptor.environmentId !== input.expectedEnvironmentId) {
156 return yield* environmentMismatchError({
157 expected: input.expectedEnvironmentId,
158 actual: descriptor.environmentId,
159 });
160 }
161 if (!canReuseDescriptor) {
162 yield* Ref.update(bearerDescriptors, (current) => {
163 const next = new Map(current);
164 next.set(input.expectedEnvironmentId, {
165 httpBaseUrl: input.httpBaseUrl,
166 descriptor,
167 validatedAtEpochMs: now,
168 });
169 return next;
170 });
171 }
172 const socketUrl = yield* resolveRemoteWebSocketConnectionUrl({
173 wsBaseUrl: input.wsBaseUrl,
174 httpBaseUrl: input.httpBaseUrl,
175 bearerToken: input.bearerToken,
176 clientMetadata: presentation.metadata,
177 connectionMethod: input.connectionMethod,
178 }).pipe(
179 Effect.mapError(mapRemoteEnvironmentError),
180 Effect.provideService(HttpClient.HttpClient, httpClient),
181 );
182 return {
183 environmentId: descriptor.environmentId,
184 label: descriptor.label,
185 httpBaseUrl: input.httpBaseUrl,
186 socketUrl,
187 httpAuthorization: {
188 _tag: "Bearer" as const,
189 token: input.bearerToken,
190 },
191 };
192 },
193 );
194
195 const createDpopSocketUrl = Effect.fn("clientRuntime.connection.remote.createDpopSocketUrl")(
196 function* (token: TokenStore.RemoteDpopAccessToken, timeoutMs?: number) {
197 const ticketProof = yield* signer
198 .createProof({
199 method: "POST",
200 url: environmentEndpointUrl(token.endpoint.httpBaseUrl, "/api/auth/websocket-ticket"),
201 accessToken: token.accessToken,
202 })
203 .pipe(
204 Effect.mapError(
205 () =>
206 new ConnectionBlockedError({
207 reason: "configuration",
208 detail: "Could not create the websocket authorization proof.",
209 }),
210 ),
211 );
212 return yield* resolveRemoteDpopWebSocketConnectionUrl({
213 wsBaseUrl: token.endpoint.wsBaseUrl,
214 httpBaseUrl: token.endpoint.httpBaseUrl,
215 accessToken: token.accessToken,
216 dpopProof: ticketProof,
217 clientMetadata: presentation.metadata,
218 connectionMethod: "relay",
219 ...(timeoutMs === undefined ? {} : { timeoutMs }),
220 }).pipe(Effect.provideService(HttpClient.HttpClient, httpClient));
221 },
222 );
223
224 const sessionChanged = () =>
225 new ConnectionBlockedError({
226 reason: "authentication",
227 detail: "Your cloud sign-in changed. Sign in again to authorize the environment.",
228 });
229
230 const assertSession = Effect.fnUntraced(function* (
231 identity: ClientCapabilities.CloudSessionIdentity,
232 ) {
233 const current = yield* cloudSession.identity;
234 if (Option.isNone(current) || current.value !== identity) {
235 return yield* sessionChanged();
236 }
237 });
238
239 // Called under tokenLock so a late rejection cannot remove a newer credential.
240 const removeRejectedToken = Effect.fnUntraced(function* (
241 environmentId: EnvironmentId,
242 accessToken: string,
243 ) {
244 const cached = yield* tokenStore.get(environmentId);
245 if (Option.isSome(cached) && cached.value.accessToken === accessToken) {
246 yield* tokenStore.remove(environmentId);
247 tokenOwners.delete(environmentId);
248 }
249 });
250
251 const obtainBootstrap = Effect.fn("relay.connection.bootstrap.obtain")(function* (
252 environmentId: EnvironmentId,
253 identity: ClientCapabilities.CloudSessionIdentity,
254 ) {
255 yield* assertSession(identity);
256 const clerkToken = yield* cloudSession.clerkToken.pipe(
257 Effect.withSpan("relay.connection.cloudSessionToken.resolve"),
258 );
259 const deviceId = yield* deviceIdentity.deviceId.pipe(
260 Effect.withSpan("relay.connection.deviceIdentity.resolve"),
261 );
262 yield* assertSession(identity);
263 const connected = yield* relay
264 .connectEnvironment({
265 clerkToken,
266 scopes: [RelayEnvironmentConnectScope],
267 environmentId,
268 ...(Option.isSome(deviceId) ? { deviceId: deviceId.value } : {}),
269 })
270 .pipe(Effect.mapError(mapManagedRelayError));
271 if (connected.environmentId !== environmentId) {
272 return yield* environmentMismatchError({
273 expected: environmentId,
274 actual: connected.environmentId,
275 });
276 }
277 yield* assertSession(identity);
278 return connected;
279 });
280
281 const exchangeDpopToken = Effect.fn("clientRuntime.connection.remote.exchangeDpopToken")(
282 function* (
283 environmentId: EnvironmentId,
284 thumbprint: string,
285 identity: ClientCapabilities.CloudSessionIdentity,
286 ) {
287 const bootstrap = yield* obtainBootstrap(environmentId, identity);
288 const descriptor = yield* fetchDescriptor(bootstrap.endpoint.httpBaseUrl, "relay").pipe(
289 Effect.provideService(HttpClient.HttpClient, httpClient),
290 Effect.withSpan("environment.authorization.descriptor"),
291 );
292 if (descriptor.environmentId !== environmentId) {
293 return yield* environmentMismatchError({
294 expected: environmentId,
295 actual: descriptor.environmentId,
296 });
297 }
298 const bootstrapProof = yield* signer
299 .createProof({
300 method: "POST",
301 url: environmentEndpointUrl(bootstrap.endpoint.httpBaseUrl, "/oauth/token"),
302 })
303 .pipe(
304 Effect.mapError(
305 () =>
306 new ConnectionBlockedError({
307 reason: "configuration",
308 detail: "Could not create the environment authorization proof.",
309 }),
310 ),
311 );
312 yield* assertSession(identity);
313 const access = yield* exchangeRemoteDpopAccessToken({
314 httpBaseUrl: bootstrap.endpoint.httpBaseUrl,
315 credential: bootstrap.credential,
316 dpopProof: bootstrapProof,
317 scopes: presentation.scopes,
318 clientMetadata: presentation.metadata,
319 }).pipe(
320 Effect.mapError(mapRemoteDpopEnvironmentError),
321 Effect.provideService(HttpClient.HttpClient, httpClient),
322 Effect.withSpan("environment.authorization.accessToken.exchange"),
323 );
324 const issuedAt = yield* Clock.currentTimeMillis;
325 return new TokenStore.RemoteDpopAccessToken({
326 environmentId: descriptor.environmentId,
327 accountId: identity.accountId,
328 label: descriptor.label,
329 endpoint: bootstrap.endpoint,
330 accessToken: access.access_token,
331 expiresAtEpochMs: issuedAt + access.expires_in * 1_000,
332 dpopThumbprint: thumbprint,
333 });
334 },
335 );
336
337 const getDpopToken = Effect.fn("clientRuntime.connection.remote.getDpopToken")(function* (
338 input: Parameters<RemoteEnvironmentAuthorization["Service"]["authorizeDpopHttp"]>[0],
339 ) {
340 const session = yield* cloudSession.identity;
341 if (Option.isNone(session)) {
342 return yield* sessionChanged();
343 }
344 const identity = session.value;
345 const thumbprint = yield* signer.thumbprint.pipe(
346 Effect.mapError(
347 () =>
348 new ConnectionBlockedError({
349 reason: "configuration",
350 detail: "Could not load the environment authorization key.",
351 }),
352 ),
353 Effect.withSpan("environment.authorization.dpopKey.resolve"),
354 );
355 const selected = yield* tokenLock.withPermits(1)(
356 Effect.gen(function* () {
357 yield* assertSession(identity);
358 const now = yield* Clock.currentTimeMillis;
359 const cached = yield* tokenStore
360 .get(input.expectedEnvironmentId)
361 .pipe(Effect.withSpan("environment.authorization.accessToken.cache"));
362 const owner = tokenOwners.get(input.expectedEnvironmentId);
363 if (
364 Option.isSome(cached) &&
365 cached.value.environmentId === input.expectedEnvironmentId &&
366 cached.value.accountId === identity.accountId &&
367 cached.value.dpopThumbprint === thumbprint &&
368 cached.value.expiresAtEpochMs > now + DPOP_ACCESS_TOKEN_REFRESH_SKEW_MS &&
369 cached.value.accessToken !== input.rejectedAccessToken &&
370 (owner?.accessToken !== cached.value.accessToken || owner.identity === identity)
371 ) {
372 tokenOwners.set(input.expectedEnvironmentId, {
373 accessToken: cached.value.accessToken,
374 identity,
375 });
376 return { token: Effect.succeed(cached.value), fromCache: true };
377 }
378 if (input.rejectedAccessToken !== undefined) {
379 yield* removeRejectedToken(input.expectedEnvironmentId, input.rejectedAccessToken);
380 }
381 const pending = pendingTokens.get(input.expectedEnvironmentId);
382 if (pending?.identity === identity && pending.thumbprint === thumbprint) {
383 return { token: pending.token, fromCache: false };
384 }
385
386 const id = {};
387 const fiber = yield* exchangeDpopToken(
388 input.expectedEnvironmentId,
389 thumbprint,
390 identity,
391 ).pipe(
392 Effect.flatMap((token) =>
393 tokenLock.withPermits(1)(
394 Effect.gen(function* () {
395 yield* assertSession(identity);
396 yield* tokenStore
397 .put(token)
398 .pipe(Effect.withSpan("environment.authorization.accessToken.persist"));
399 const current = yield* cloudSession.identity;
400 if (Option.isNone(current) || current.value !== identity) {
401 yield* removeRejectedToken(input.expectedEnvironmentId, token.accessToken);
402 return yield* sessionChanged();
403 }
404 tokenOwners.set(input.expectedEnvironmentId, {
405 accessToken: token.accessToken,
406 identity,
407 });
408 if (pendingTokens.get(input.expectedEnvironmentId)?.id === id) {
409 pendingTokens.delete(input.expectedEnvironmentId);
410 }
411 return token;
412 }),
413 ),
414 ),
415 Effect.timeoutOrElse({
416 duration: DPOP_AUTHORIZATION_TIMEOUT_MS,
417 orElse: () =>
418 Effect.fail(
419 new ConnectionTransientError({
420 reason: "timeout",
421 detail: "Timed out renewing the environment credential.",
422 }),
423 ),
424 }),
425 Effect.ensuring(
426 tokenLock.withPermits(1)(
427 Effect.sync(() => {
428 if (pendingTokens.get(input.expectedEnvironmentId)?.id === id) {
429 pendingTokens.delete(input.expectedEnvironmentId);
430 }
431 }),
432 ),
433 ),
434 // One caller's timeout must not cancel renewal for other HTTP requests.
435 Effect.forkIn(serviceScope),
436 );
437 const token = Fiber.join(fiber);
438 pendingTokens.set(input.expectedEnvironmentId, { id, identity, thumbprint, token });
439 return { token, fromCache: false };
440 }),
441 );
442 yield* Effect.annotateCurrentSpan({
443 "connection.remote_token_cache": selected.fromCache ? "hit" : "miss",
444 });
445 const token = yield* selected.token;
446 yield* assertSession(identity);
447 return { token, fromCache: selected.fromCache, identity };
448 });
449
450 const httpAuthorization = (
451 token: TokenStore.RemoteDpopAccessToken,
452 ): AuthorizedRemoteHttpEnvironment => ({
453 environmentId: token.environmentId,
454 label: token.label,
455 httpBaseUrl: token.endpoint.httpBaseUrl,
456 httpAuthorization: {
457 _tag: "Dpop",
458 accessToken: token.accessToken,
459 expiresAtEpochMs: token.expiresAtEpochMs,
460 },
461 });
462
463 const authorizeDpop = Effect.fn("clientRuntime.connection.remote.authorizeDpop")(function* (
464 input: Parameters<RemoteEnvironmentAuthorization["Service"]["authorizeDpop"]>[0],
465 ) {
466 let selected = yield* getDpopToken(input);
467 if (selected.fromCache) {
468 const cachedSocket = yield* createDpopSocketUrl(
469 selected.token,
470 CACHED_ENDPOINT_SOCKET_TIMEOUT_MS,
471 ).pipe(Effect.result);
472 if (Result.isSuccess(cachedSocket)) {
473 yield* assertSession(selected.identity);
474 return { ...httpAuthorization(selected.token), socketUrl: cachedSocket.success };
475 }
476 if (cachedSocket.failure._tag === "ConnectionBlockedError") {
477 return yield* mapDpopSocketError(cachedSocket.failure);
478 }
479 selected = yield* getDpopToken({
480 ...input,
481 rejectedAccessToken: selected.token.accessToken,
482 });
483 }
484 const socket = yield* createDpopSocketUrl(selected.token).pipe(Effect.result);
485 if (Result.isFailure(socket)) {
486 yield* tokenLock.withPermits(1)(
487 removeRejectedToken(input.expectedEnvironmentId, selected.token.accessToken),
488 );
489 return yield* mapDpopSocketError(socket.failure);
490 }
491 yield* assertSession(selected.identity);
492 return { ...httpAuthorization(selected.token), socketUrl: socket.success };
493 });
494
495 return RemoteEnvironmentAuthorization.of({
496 authorizeBearer,
497 authorizeDpop: (input) =>
498 authorizeDpop(input).pipe(Effect.withSpan("environment.authorization")),
499 authorizeDpopHttp: (input) =>
500 getDpopToken(input).pipe(
501 Effect.map(({ token }) => httpAuthorization(token)),
502 Effect.withSpan("environment.authorization.http"),
503 withRelayClientTracing,
504 ),
505 });
506});
507
508export const layer = Layer.effect(RemoteEnvironmentAuthorization, make);