Open History to see the last commit
1import {
2 connectDeviceVerificationCode,
3 type ClientConnectionMethod,
4 EnvironmentId,
5 type ExecutionEnvironmentDescriptor,
6} from "@t3tools/contracts";
7import { RelayEnvironmentConnectScope } from "@t3tools/contracts/relay";
8import { withRelayClientTracing } from "@t3tools/shared/relayTracing";
9import {
10 exchangeRemoteDpopAccessToken,
11 type RemoteEnvironmentAuthError,
12 resolveRemoteDpopWebSocketConnectionUrl,
13 resolveRemoteWebSocketConnectionUrl,
14} from "./remote.ts";
15import {
16 environmentMismatchError,
17 mapManagedRelayError,
18 mapRemoteDpopEnvironmentError,
19 mapRemoteEnvironmentError,
20} from "../connection/errors.ts";
21import {
22 ConnectionBlockedError,
23 ConnectionTransientError,
24 type ConnectionAttemptError,
25} from "../connection/model.ts";
26import { isNearbyAddress } from "../connection/routes.ts";
27import { fetchRemoteEnvironmentDescriptor } from "../environment/descriptor.ts";
28import { environmentEndpointUrl } from "../environment/endpoint.ts";
29import * as ClientCapabilities from "../platform/capabilities.ts";
30import * as ManagedRelay from "../relay/managedRelay.ts";
31import * as TokenStore from "./tokenStore.ts";
32import * as Clock from "effect/Clock";
33import * as Context from "effect/Context";
34import * as Effect from "effect/Effect";
35import * as Fiber from "effect/Fiber";
36import * as Layer from "effect/Layer";
37import * as Option from "effect/Option";
38import * as Result from "effect/Result";
39import * as Scope from "effect/Scope";
40import * as Semaphore from "effect/Semaphore";
41import * as HttpClient from "effect/http/HttpClient";
42
43import {
44 DPOP_ACCESS_TOKEN_REFRESH_SKEW_MS,
45 type PreparedHttpAuthorization,
46} from "../connection/model.ts";
47
48export interface AuthorizedRemoteEnvironment {
49 readonly environmentId: EnvironmentId;
50 readonly label: string;
51 readonly httpBaseUrl: string;
52 readonly socketUrl: string;
53 readonly httpAuthorization: PreparedHttpAuthorization;
54 readonly descriptor?: ExecutionEnvironmentDescriptor;
55}
56
57export interface AuthorizedRemoteHttpEnvironment {
58 readonly environmentId: EnvironmentId;
59 readonly label: string;
60 readonly httpBaseUrl: string;
61 readonly httpAuthorization: Extract<PreparedHttpAuthorization, { readonly _tag: "Dpop" }>;
62}
63
64export class RemoteEnvironmentAuthorization extends Context.Service<
65 RemoteEnvironmentAuthorization,
66 {
67 readonly authorizeBearer: (input: {
68 readonly expectedEnvironmentId: EnvironmentId;
69 readonly httpBaseUrl: string;
70 readonly wsBaseUrl: string;
71 readonly bearerToken: string;
72 readonly connectionMethod: ClientConnectionMethod;
73 }) => Effect.Effect<AuthorizedRemoteEnvironment, ConnectionAttemptError>;
74 readonly authorizeDpop: (input: {
75 readonly expectedEnvironmentId: EnvironmentId;
76 /**
77 * The access token is not bound to an origin, and each proof is minted
78 * for the URL it signs, so a token from the relay also works on the
79 * environment's LAN or tailnet address.
80 */
81 readonly directEndpoint?: { readonly httpBaseUrl: string; readonly wsBaseUrl: string };
82 }) => Effect.Effect<AuthorizedRemoteEnvironment, ConnectionAttemptError>;
83 readonly authorizeDpopHttp: (input: {
84 readonly expectedEnvironmentId: EnvironmentId;
85 readonly rejectedAccessToken?: string;
86 }) => Effect.Effect<AuthorizedRemoteHttpEnvironment, ConnectionAttemptError>;
87 /**
88 * Lets the next direct authorization of this address skip its own descriptor
89 * read. Kept only where the address reaches the same machine on every network.
90 */
91 readonly rememberCheckedDescriptor: (
92 httpBaseUrl: string,
93 descriptor: Option.Option<ExecutionEnvironmentDescriptor>,
94 keepsItsHost: boolean,
95 ) => Effect.Effect<void>;
96 /**
97 * Renews a live socket's token before it expires, so the server moves the
98 * socket to the new session instead of closing it. Runs until interrupted.
99 */
100 readonly renewDpopBeforeExpiry: (input: {
101 readonly expectedEnvironmentId: EnvironmentId;
102 readonly expiresAtEpochMs: number;
103 }) => Effect.Effect<void, ConnectionBlockedError>;
104 }
105>()("@t3tools/client-runtime/authorization/service/RemoteEnvironmentAuthorization") {}
106
107const CACHED_ENDPOINT_SOCKET_TIMEOUT_MS = 3_000;
108const DPOP_AUTHORIZATION_TIMEOUT_MS = 30_000;
109const CHECKED_DESCRIPTOR_TTL_NANOS = 5_000_000_000n;
110// A loopback or LAN host answers well inside this, so a dead one frees its attempt sooner.
111const NEARBY_DESCRIPTOR_TIMEOUT_MS = 3_000;
112
113/** A token with the descriptor its mint read. A cached token has none. */
114interface IssuedDpopToken {
115 readonly token: TokenStore.RemoteDpopAccessToken;
116 readonly descriptor?: ExecutionEnvironmentDescriptor;
117}
118
119function mapDpopSocketError(error: RemoteEnvironmentAuthError | ConnectionAttemptError) {
120 return error._tag === "ConnectionTransientError" || error._tag === "ConnectionBlockedError"
121 ? error
122 : mapRemoteDpopEnvironmentError(error);
123}
124
125function approvalPendingError(hostLabel: string, thumbprint: string, traceId: string) {
126 const verificationCode = connectDeviceVerificationCode(thumbprint);
127 return new ConnectionTransientError({
128 reason: "approval-pending",
129 detail: `Approve this device on ${hostLabel}. It shows code ${verificationCode}.`,
130 verificationCode,
131 traceId,
132 hop: "server",
133 via: "relay",
134 failureCause: "approval_pending",
135 });
136}
137
138const fetchDescriptor = Effect.fn("clientRuntime.connection.remote.fetchDescriptor")(function* (
139 httpBaseUrl: string,
140 connectionMethod: ClientConnectionMethod,
141 timeoutMs?: number,
142) {
143 return yield* fetchRemoteEnvironmentDescriptor({
144 httpBaseUrl,
145 ...(timeoutMs === undefined ? {} : { timeoutMs }),
146 }).pipe(Effect.mapError((error) => mapRemoteEnvironmentError(error, connectionMethod)));
147});
148
149export const make = Effect.gen(function* () {
150 const serviceScope = yield* Scope.Scope;
151 const signer = yield* ManagedRelay.ManagedRelayDpopSigner;
152 const relay = yield* ManagedRelay.ManagedRelayClient;
153 const cloudSession = yield* ClientCapabilities.CloudSession;
154 const deviceIdentity = yield* ClientCapabilities.RelayDeviceIdentity;
155 const presentation = yield* ClientCapabilities.ClientPresentation;
156 const tokenStore = yield* TokenStore.RemoteDpopAccessTokenStore;
157 const httpClient = yield* HttpClient.HttpClient;
158 const tokenLock = yield* Semaphore.make(1);
159 const tokenOwners = new Map<
160 EnvironmentId,
161 { readonly accessToken: string; readonly identity: ClientCapabilities.CloudSessionIdentity }
162 >();
163 const pendingTokens = new Map<
164 EnvironmentId,
165 {
166 readonly id: object;
167 readonly identity: ClientCapabilities.CloudSessionIdentity;
168 readonly thumbprint: string;
169 readonly issued: Effect.Effect<IssuedDpopToken, ConnectionAttemptError>;
170 }
171 >();
172
173 // A route or host check hands its descriptor to the connect it leads to, once,
174 // so the connect skips a round trip. Only over HTTPS or loopback: any other
175 // plain http address can belong to another machine after a network change.
176 const checkedDescriptors = new Map<
177 string,
178 { readonly descriptor: ExecutionEnvironmentDescriptor; readonly at: bigint }
179 >();
180
181 /**
182 * A saved LAN address can belong to another machine on a different network.
183 */
184 const verifyDirectEndpoint = Effect.fn("clientRuntime.connection.remote.verifyDirectEndpoint")(
185 function* (input: {
186 readonly expectedEnvironmentId: EnvironmentId;
187 readonly httpBaseUrl: string;
188 readonly connectionMethod: ClientConnectionMethod;
189 }) {
190 const checked = checkedDescriptors.get(input.httpBaseUrl);
191 checkedDescriptors.delete(input.httpBaseUrl);
192 // A remembered mismatch still reads again, so a host that answers for the
193 // right environment a moment later is not blocked.
194 const descriptor =
195 checked !== undefined &&
196 checked.descriptor.environmentId === input.expectedEnvironmentId &&
197 (yield* Clock.monotonicTimeNanos) - checked.at <= CHECKED_DESCRIPTOR_TTL_NANOS
198 ? checked.descriptor
199 : yield* fetchDescriptor(
200 input.httpBaseUrl,
201 input.connectionMethod,
202 // An SSH forward listens on loopback but reaches a remote host.
203 input.connectionMethod === "direct" && isNearbyAddress(input.httpBaseUrl)
204 ? NEARBY_DESCRIPTOR_TIMEOUT_MS
205 : undefined,
206 ).pipe(Effect.provideService(HttpClient.HttpClient, httpClient));
207 if (descriptor.environmentId !== input.expectedEnvironmentId) {
208 return yield* environmentMismatchError({
209 expected: input.expectedEnvironmentId,
210 actual: descriptor.environmentId,
211 });
212 }
213 return descriptor;
214 },
215 );
216
217 const authorizeBearer = Effect.fn("clientRuntime.connection.remote.authorizeBearer")(
218 function* (input: {
219 readonly expectedEnvironmentId: Parameters<
220 RemoteEnvironmentAuthorization["Service"]["authorizeBearer"]
221 >[0]["expectedEnvironmentId"];
222 readonly httpBaseUrl: string;
223 readonly wsBaseUrl: string;
224 readonly bearerToken: string;
225 readonly connectionMethod: ClientConnectionMethod;
226 }) {
227 const descriptor = yield* verifyDirectEndpoint(input);
228 const socketUrl = yield* resolveRemoteWebSocketConnectionUrl({
229 wsBaseUrl: input.wsBaseUrl,
230 httpBaseUrl: input.httpBaseUrl,
231 bearerToken: input.bearerToken,
232 clientMetadata: presentation.metadata,
233 connectionMethod: input.connectionMethod,
234 }).pipe(
235 Effect.mapError(mapRemoteEnvironmentError),
236 Effect.provideService(HttpClient.HttpClient, httpClient),
237 );
238 return {
239 environmentId: descriptor.environmentId,
240 label: descriptor.label,
241 httpBaseUrl: input.httpBaseUrl,
242 socketUrl,
243 descriptor,
244 httpAuthorization: {
245 _tag: "Bearer" as const,
246 token: input.bearerToken,
247 },
248 };
249 },
250 );
251
252 const createDpopSocketUrl = Effect.fn("clientRuntime.connection.remote.createDpopSocketUrl")(
253 function* (
254 token: TokenStore.RemoteDpopAccessToken,
255 timeoutMs?: number,
256 endpoint: { readonly httpBaseUrl: string; readonly wsBaseUrl: string } = token.endpoint,
257 ) {
258 return yield* resolveRemoteDpopWebSocketConnectionUrl({
259 wsBaseUrl: endpoint.wsBaseUrl,
260 httpBaseUrl: endpoint.httpBaseUrl,
261 accessToken: token.accessToken,
262 createProof: (proof) =>
263 signer.createProof(proof).pipe(
264 Effect.mapError(
265 () =>
266 new ConnectionBlockedError({
267 reason: "configuration",
268 detail: "Could not create the websocket authorization proof.",
269 }),
270 ),
271 ),
272 clientMetadata: presentation.metadata,
273 connectionMethod: "relay",
274 ...(timeoutMs === undefined ? {} : { timeoutMs }),
275 });
276 },
277 Effect.provideService(HttpClient.HttpClient, httpClient),
278 );
279
280 const sessionChanged = () =>
281 new ConnectionBlockedError({
282 reason: "authentication",
283 detail: "Your cloud sign-in changed. Sign in again to authorize the environment.",
284 });
285
286 // A missing identity before the attempt captures one means the cloud session
287 // is still loading, not a sign-out. Only a captured identity that goes away
288 // or changes is evidence of one.
289 const sessionPending = () =>
290 new ConnectionTransientError({
291 reason: "session-pending",
292 detail: "Waiting for the T3 Connect sign-in to load.",
293 });
294
295 const assertSession = Effect.fnUntraced(function* (
296 identity: ClientCapabilities.CloudSessionIdentity,
297 ) {
298 const current = yield* cloudSession.identity;
299 if (Option.isNone(current) || current.value !== identity) {
300 return yield* sessionChanged();
301 }
302 });
303
304 // Called under tokenLock so a late rejection cannot remove a newer credential.
305 const removeRejectedToken = Effect.fnUntraced(function* (
306 environmentId: EnvironmentId,
307 accessToken: string,
308 ) {
309 const cached = yield* tokenStore.get(environmentId);
310 if (Option.isSome(cached) && cached.value.accessToken === accessToken) {
311 yield* tokenStore.remove(environmentId);
312 tokenOwners.delete(environmentId);
313 }
314 });
315
316 const obtainBootstrap = Effect.fn("relay.connection.bootstrap.obtain")(function* (
317 environmentId: EnvironmentId,
318 identity: ClientCapabilities.CloudSessionIdentity,
319 ) {
320 yield* assertSession(identity);
321 const clerkToken = yield* cloudSession.clerkToken.pipe(
322 Effect.withSpan("relay.connection.cloudSessionToken.resolve"),
323 );
324 const deviceId = yield* deviceIdentity.deviceId.pipe(
325 Effect.withSpan("relay.connection.deviceIdentity.resolve"),
326 );
327 yield* assertSession(identity);
328 const connected = yield* relay
329 .connectEnvironment({
330 clerkToken,
331 scopes: [RelayEnvironmentConnectScope],
332 environmentId,
333 ...(Option.isSome(deviceId) ? { deviceId: deviceId.value } : {}),
334 })
335 .pipe(Effect.mapError(mapManagedRelayError));
336 if (connected.environmentId !== environmentId) {
337 return yield* environmentMismatchError({
338 expected: environmentId,
339 actual: connected.environmentId,
340 });
341 }
342 yield* assertSession(identity);
343 return connected;
344 });
345
346 const exchangeDpopToken = Effect.fn("clientRuntime.connection.remote.exchangeDpopToken")(
347 function* (
348 environmentId: EnvironmentId,
349 thumbprint: string,
350 identity: ClientCapabilities.CloudSessionIdentity,
351 ) {
352 const bootstrap = yield* obtainBootstrap(environmentId, identity);
353 const descriptor = yield* fetchDescriptor(bootstrap.endpoint.httpBaseUrl, "relay").pipe(
354 Effect.provideService(HttpClient.HttpClient, httpClient),
355 Effect.withSpan("environment.authorization.descriptor"),
356 );
357 if (descriptor.environmentId !== environmentId) {
358 return yield* environmentMismatchError({
359 expected: environmentId,
360 actual: descriptor.environmentId,
361 });
362 }
363 const bootstrapProof = yield* signer
364 .createProof({
365 method: "POST",
366 url: environmentEndpointUrl(bootstrap.endpoint.httpBaseUrl, "/oauth/token"),
367 })
368 .pipe(
369 Effect.mapError(
370 () =>
371 new ConnectionBlockedError({
372 reason: "configuration",
373 detail: "Could not create the environment authorization proof.",
374 }),
375 ),
376 );
377 yield* assertSession(identity);
378 const access = yield* exchangeRemoteDpopAccessToken({
379 httpBaseUrl: bootstrap.endpoint.httpBaseUrl,
380 credential: bootstrap.credential,
381 dpopProof: bootstrapProof,
382 clientMetadata: presentation.metadata,
383 }).pipe(
384 Effect.mapError((error) =>
385 error._tag === "EnvironmentConnectApprovalPendingError"
386 ? approvalPendingError(descriptor.label, thumbprint, error.traceId)
387 : mapRemoteDpopEnvironmentError(error),
388 ),
389 Effect.provideService(HttpClient.HttpClient, httpClient),
390 Effect.withSpan("environment.authorization.accessToken.exchange"),
391 );
392 const issuedAt = yield* Clock.currentTimeMillis;
393 const token = new TokenStore.RemoteDpopAccessToken({
394 environmentId: descriptor.environmentId,
395 accountId: identity.accountId,
396 label: descriptor.label,
397 endpoint: bootstrap.endpoint,
398 accessToken: access.access_token,
399 expiresAtEpochMs: issuedAt + access.expires_in * 1_000,
400 dpopThumbprint: thumbprint,
401 });
402 return { token, descriptor } satisfies IssuedDpopToken;
403 },
404 );
405
406 const getDpopToken = Effect.fn("clientRuntime.connection.remote.getDpopToken")(function* (
407 input: Parameters<RemoteEnvironmentAuthorization["Service"]["authorizeDpopHttp"]>[0],
408 ) {
409 const session = yield* cloudSession.identity;
410 if (Option.isNone(session)) {
411 return yield* sessionPending();
412 }
413 const identity = session.value;
414 const thumbprint = yield* signer.thumbprint.pipe(
415 Effect.mapError(
416 () =>
417 new ConnectionBlockedError({
418 reason: "configuration",
419 detail: "Could not load the environment authorization key.",
420 }),
421 ),
422 Effect.withSpan("environment.authorization.dpopKey.resolve"),
423 );
424 const selected = yield* tokenLock.withPermits(1)(
425 Effect.gen(function* () {
426 yield* assertSession(identity);
427 const now = yield* Clock.currentTimeMillis;
428 const cached = yield* tokenStore
429 .get(input.expectedEnvironmentId)
430 .pipe(Effect.withSpan("environment.authorization.accessToken.cache"));
431 const owner = tokenOwners.get(input.expectedEnvironmentId);
432 if (
433 Option.isSome(cached) &&
434 cached.value.environmentId === input.expectedEnvironmentId &&
435 cached.value.accountId === identity.accountId &&
436 cached.value.dpopThumbprint === thumbprint &&
437 cached.value.expiresAtEpochMs > now + DPOP_ACCESS_TOKEN_REFRESH_SKEW_MS &&
438 cached.value.accessToken !== input.rejectedAccessToken &&
439 (owner?.accessToken !== cached.value.accessToken || owner.identity === identity)
440 ) {
441 tokenOwners.set(input.expectedEnvironmentId, {
442 accessToken: cached.value.accessToken,
443 identity,
444 });
445 return {
446 issued: Effect.succeed<IssuedDpopToken>({ token: cached.value }),
447 fromCache: true,
448 };
449 }
450 if (input.rejectedAccessToken !== undefined) {
451 yield* removeRejectedToken(input.expectedEnvironmentId, input.rejectedAccessToken);
452 }
453 const pending = pendingTokens.get(input.expectedEnvironmentId);
454 if (pending?.identity === identity && pending.thumbprint === thumbprint) {
455 return { issued: pending.issued, fromCache: false };
456 }
457
458 const id = {};
459 const fiber = yield* exchangeDpopToken(
460 input.expectedEnvironmentId,
461 thumbprint,
462 identity,
463 ).pipe(
464 Effect.flatMap((issued) =>
465 tokenLock.withPermits(1)(
466 Effect.gen(function* () {
467 const { token } = issued;
468 yield* assertSession(identity);
469 yield* tokenStore
470 .put(token)
471 .pipe(Effect.withSpan("environment.authorization.accessToken.persist"));
472 const current = yield* cloudSession.identity;
473 if (Option.isNone(current) || current.value !== identity) {
474 yield* removeRejectedToken(input.expectedEnvironmentId, token.accessToken);
475 return yield* sessionChanged();
476 }
477 tokenOwners.set(input.expectedEnvironmentId, {
478 accessToken: token.accessToken,
479 identity,
480 });
481 if (pendingTokens.get(input.expectedEnvironmentId)?.id === id) {
482 pendingTokens.delete(input.expectedEnvironmentId);
483 }
484 return issued;
485 }),
486 ),
487 ),
488 Effect.timeoutOrElse({
489 duration: DPOP_AUTHORIZATION_TIMEOUT_MS,
490 orElse: () =>
491 Effect.fail(
492 new ConnectionTransientError({
493 reason: "timeout",
494 detail: "Timed out renewing the environment credential.",
495 }),
496 ),
497 }),
498 Effect.ensuring(
499 tokenLock.withPermits(1)(
500 Effect.sync(() => {
501 if (pendingTokens.get(input.expectedEnvironmentId)?.id === id) {
502 pendingTokens.delete(input.expectedEnvironmentId);
503 }
504 }),
505 ),
506 ),
507 // One caller's timeout must not cancel renewal for other HTTP requests.
508 Effect.forkIn(serviceScope),
509 );
510 const issued = Fiber.join(fiber);
511 pendingTokens.set(input.expectedEnvironmentId, { id, identity, thumbprint, issued });
512 return { issued, fromCache: false };
513 }),
514 );
515 yield* Effect.annotateCurrentSpan({
516 "connection.remote_token_cache": selected.fromCache ? "hit" : "miss",
517 });
518 const issued = yield* selected.issued;
519 yield* assertSession(identity);
520 return { ...issued, fromCache: selected.fromCache, identity };
521 });
522
523 const httpAuthorization = (
524 token: TokenStore.RemoteDpopAccessToken,
525 httpBaseUrl = token.endpoint.httpBaseUrl,
526 ): AuthorizedRemoteHttpEnvironment => ({
527 environmentId: token.environmentId,
528 label: token.label,
529 httpBaseUrl,
530 httpAuthorization: {
531 _tag: "Dpop",
532 accessToken: token.accessToken,
533 expiresAtEpochMs: token.expiresAtEpochMs,
534 },
535 });
536
537 const authorizeDpop = Effect.fn("clientRuntime.connection.remote.authorizeDpop")(function* (
538 input: Parameters<RemoteEnvironmentAuthorization["Service"]["authorizeDpop"]>[0],
539 ) {
540 const endpoint = input.directEndpoint;
541 const directDescriptor =
542 endpoint === undefined
543 ? undefined
544 : yield* verifyDirectEndpoint({
545 expectedEnvironmentId: input.expectedEnvironmentId,
546 httpBaseUrl: endpoint.httpBaseUrl,
547 connectionMethod: "direct",
548 });
549 const authorized = (
550 token: TokenStore.RemoteDpopAccessToken,
551 socketUrl: string,
552 descriptor: ExecutionEnvironmentDescriptor,
553 ) => ({ ...httpAuthorization(token, endpoint?.httpBaseUrl), socketUrl, descriptor });
554 // A cached token comes without a descriptor. That read needs no ticket, so
555 // it runs beside the ticket request, and a failed ticket abandons it.
556 const openSocket = Effect.fnUntraced(function* (issued: IssuedDpopToken, timeoutMs?: number) {
557 const socket = createDpopSocketUrl(issued.token, timeoutMs, endpoint).pipe(Effect.result);
558 const known = directDescriptor ?? issued.descriptor;
559 if (known !== undefined) {
560 return Result.map(yield* socket, (socketUrl) => authorized(issued.token, socketUrl, known));
561 }
562 const reading = yield* fetchDescriptor(issued.token.endpoint.httpBaseUrl, "relay").pipe(
563 Effect.provideService(HttpClient.HttpClient, httpClient),
564 Effect.forkChild,
565 );
566 const opened = yield* socket;
567 if (Result.isFailure(opened)) {
568 yield* Fiber.interrupt(reading);
569 return Result.fail(opened.failure);
570 }
571 return Result.succeed(authorized(issued.token, opened.success, yield* Fiber.join(reading)));
572 });
573 let selected = yield* getDpopToken(input);
574 if (selected.fromCache) {
575 const cachedSocket = yield* openSocket(selected, CACHED_ENDPOINT_SOCKET_TIMEOUT_MS);
576 if (Result.isSuccess(cachedSocket)) {
577 yield* assertSession(selected.identity);
578 return cachedSocket.success;
579 }
580 if (cachedSocket.failure._tag === "ConnectionBlockedError") {
581 return yield* mapDpopSocketError(cachedSocket.failure);
582 }
583 // An unreachable direct address says nothing about the token, so keep
584 // it for the T3 Connect route rather than forcing a relay round trip.
585 if (endpoint !== undefined && cachedSocket.failure._tag !== "EnvironmentAuthInvalidError") {
586 return yield* mapDpopSocketError(cachedSocket.failure);
587 }
588 yield* assertSession(selected.identity);
589 selected = yield* getDpopToken({
590 ...input,
591 rejectedAccessToken: selected.token.accessToken,
592 });
593 }
594 const socket = yield* openSocket(selected);
595 if (Result.isFailure(socket)) {
596 if (endpoint === undefined || socket.failure._tag === "ConnectionBlockedError") {
597 yield* tokenLock.withPermits(1)(
598 removeRejectedToken(input.expectedEnvironmentId, selected.token.accessToken),
599 );
600 }
601 return yield* mapDpopSocketError(socket.failure);
602 }
603 yield* assertSession(selected.identity);
604 return socket.success;
605 });
606
607 return RemoteEnvironmentAuthorization.of({
608 authorizeBearer,
609 // Untraced: it runs on every route and host check.
610 rememberCheckedDescriptor: Effect.fnUntraced(function* (httpBaseUrl, descriptor, keepsItsHost) {
611 if (Option.isNone(descriptor) || !keepsItsHost) {
612 checkedDescriptors.delete(httpBaseUrl);
613 return;
614 }
615 checkedDescriptors.set(httpBaseUrl, {
616 descriptor: descriptor.value,
617 at: yield* Clock.monotonicTimeNanos,
618 });
619 }),
620 authorizeDpop: Effect.fn("environment.authorization")(function (input) {
621 return authorizeDpop(input);
622 }),
623 // The relay tracer must wrap span creation, not just the token request.
624 authorizeDpopHttp: Effect.fnUntraced(function* (input) {
625 return yield* getDpopToken(input).pipe(
626 Effect.map(({ token }) => httpAuthorization(token)),
627 Effect.withSpan("environment.authorization.http"),
628 withRelayClientTracing,
629 );
630 }),
631 // Untraced: a span here would stay open for the socket's lifetime. Each renewal has its own.
632 renewDpopBeforeExpiry: Effect.fnUntraced(function* (input) {
633 let expiresAtEpochMs = input.expiresAtEpochMs;
634 let now = yield* Clock.currentTimeMillis;
635 // Past expiry the server has closed the socket.
636 while (now < expiresAtEpochMs) {
637 // getDpopToken reuses a cached token until it is within the skew of expiry.
638 // The floor spaces out retries and keeps a wall-clock jump from spinning.
639 yield* Effect.sleep(
640 Math.max(5_000, expiresAtEpochMs - DPOP_ACCESS_TOKEN_REFRESH_SKEW_MS - now),
641 );
642 const renewed = yield* getDpopToken({
643 expectedEnvironmentId: input.expectedEnvironmentId,
644 }).pipe(
645 Effect.map(({ token }) => token.expiresAtEpochMs),
646 Effect.withSpan("environment.authorization.renewSocket"),
647 withRelayClientTracing,
648 // A relay blip retries until expiry; a blocked credential ends the loop.
649 Effect.catchTags({ ConnectionTransientError: () => Effect.succeed(expiresAtEpochMs) }),
650 );
651 expiresAtEpochMs = Math.max(expiresAtEpochMs, renewed);
652 now = yield* Clock.currentTimeMillis;
653 }
654 }),
655 });
656});
657
658export const layer = Layer.effect(RemoteEnvironmentAuthorization, make);