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