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 Result from "effect/Result";
37import * as Scope from "effect/Scope";
38import * as Semaphore from "effect/Semaphore";
39import * as HttpClient from "effect/http/HttpClient";
40
41import {
42 DPOP_ACCESS_TOKEN_REFRESH_SKEW_MS,
43 type PreparedHttpAuthorization,
44} from "../connection/model.ts";
45
46export interface AuthorizedRemoteEnvironment {
47 readonly environmentId: EnvironmentId;
48 readonly label: string;
49 readonly httpBaseUrl: string;
50 readonly socketUrl: string;
51 readonly httpAuthorization: PreparedHttpAuthorization;
52 readonly descriptor?: ExecutionEnvironmentDescriptor;
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 /**
75 * The access token is not bound to an origin, and each proof is minted
76 * for the URL it signs, so a token from the relay also works on the
77 * environment's LAN or tailnet address.
78 */
79 readonly directEndpoint?: { readonly httpBaseUrl: string; readonly wsBaseUrl: string };
80 }) => Effect.Effect<AuthorizedRemoteEnvironment, ConnectionAttemptError>;
81 readonly authorizeDpopHttp: (input: {
82 readonly expectedEnvironmentId: EnvironmentId;
83 readonly rejectedAccessToken?: string;
84 }) => Effect.Effect<AuthorizedRemoteHttpEnvironment, ConnectionAttemptError>;
85 /**
86 * Renews a live socket's token before it expires, so the server moves the
87 * socket to the new session instead of closing it. Runs until interrupted.
88 */
89 readonly renewDpopBeforeExpiry: (input: {
90 readonly expectedEnvironmentId: EnvironmentId;
91 readonly expiresAtEpochMs: number;
92 }) => Effect.Effect<void, ConnectionBlockedError>;
93 }
94>()("@t3tools/client-runtime/authorization/service/RemoteEnvironmentAuthorization") {}
95
96const CACHED_ENDPOINT_SOCKET_TIMEOUT_MS = 3_000;
97const DPOP_AUTHORIZATION_TIMEOUT_MS = 30_000;
98
99function mapDpopSocketError(error: RemoteEnvironmentAuthError | ConnectionAttemptError) {
100 return error._tag === "ConnectionTransientError" || error._tag === "ConnectionBlockedError"
101 ? error
102 : mapRemoteDpopEnvironmentError(error);
103}
104
105const fetchDescriptor = Effect.fn("clientRuntime.connection.remote.fetchDescriptor")(function* (
106 httpBaseUrl: string,
107 connectionMethod: ClientConnectionMethod,
108) {
109 return yield* fetchRemoteEnvironmentDescriptor({ httpBaseUrl }).pipe(
110 Effect.mapError((error) => mapRemoteEnvironmentError(error, connectionMethod)),
111 );
112});
113
114export const make = Effect.gen(function* () {
115 const serviceScope = yield* Scope.Scope;
116 const signer = yield* ManagedRelay.ManagedRelayDpopSigner;
117 const relay = yield* ManagedRelay.ManagedRelayClient;
118 const cloudSession = yield* ClientCapabilities.CloudSession;
119 const deviceIdentity = yield* ClientCapabilities.RelayDeviceIdentity;
120 const presentation = yield* ClientCapabilities.ClientPresentation;
121 const tokenStore = yield* TokenStore.RemoteDpopAccessTokenStore;
122 const httpClient = yield* HttpClient.HttpClient;
123 const tokenLock = yield* Semaphore.make(1);
124 const tokenOwners = new Map<
125 EnvironmentId,
126 { readonly accessToken: string; readonly identity: ClientCapabilities.CloudSessionIdentity }
127 >();
128 const pendingTokens = new Map<
129 EnvironmentId,
130 {
131 readonly id: object;
132 readonly identity: ClientCapabilities.CloudSessionIdentity;
133 readonly thumbprint: string;
134 readonly token: Effect.Effect<TokenStore.RemoteDpopAccessToken, ConnectionAttemptError>;
135 }
136 >();
137
138 /**
139 * A saved LAN address can belong to another machine on a different network.
140 */
141 const verifyDirectEndpoint = Effect.fn("clientRuntime.connection.remote.verifyDirectEndpoint")(
142 function* (input: {
143 readonly expectedEnvironmentId: EnvironmentId;
144 readonly httpBaseUrl: string;
145 readonly connectionMethod: ClientConnectionMethod;
146 }) {
147 const descriptor = yield* fetchDescriptor(input.httpBaseUrl, input.connectionMethod).pipe(
148 Effect.provideService(HttpClient.HttpClient, httpClient),
149 );
150 if (descriptor.environmentId !== input.expectedEnvironmentId) {
151 return yield* environmentMismatchError({
152 expected: input.expectedEnvironmentId,
153 actual: descriptor.environmentId,
154 });
155 }
156 return descriptor;
157 },
158 );
159
160 const authorizeBearer = Effect.fn("clientRuntime.connection.remote.authorizeBearer")(
161 function* (input: {
162 readonly expectedEnvironmentId: Parameters<
163 RemoteEnvironmentAuthorization["Service"]["authorizeBearer"]
164 >[0]["expectedEnvironmentId"];
165 readonly httpBaseUrl: string;
166 readonly wsBaseUrl: string;
167 readonly bearerToken: string;
168 readonly connectionMethod: ClientConnectionMethod;
169 }) {
170 const descriptor = yield* verifyDirectEndpoint(input);
171 const socketUrl = yield* resolveRemoteWebSocketConnectionUrl({
172 wsBaseUrl: input.wsBaseUrl,
173 httpBaseUrl: input.httpBaseUrl,
174 bearerToken: input.bearerToken,
175 clientMetadata: presentation.metadata,
176 connectionMethod: input.connectionMethod,
177 }).pipe(
178 Effect.mapError(mapRemoteEnvironmentError),
179 Effect.provideService(HttpClient.HttpClient, httpClient),
180 );
181 return {
182 environmentId: descriptor.environmentId,
183 label: descriptor.label,
184 httpBaseUrl: input.httpBaseUrl,
185 socketUrl,
186 descriptor,
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* (
197 token: TokenStore.RemoteDpopAccessToken,
198 timeoutMs?: number,
199 endpoint: { readonly httpBaseUrl: string; readonly wsBaseUrl: string } = token.endpoint,
200 ) {
201 return yield* resolveRemoteDpopWebSocketConnectionUrl({
202 wsBaseUrl: endpoint.wsBaseUrl,
203 httpBaseUrl: endpoint.httpBaseUrl,
204 accessToken: token.accessToken,
205 createProof: (proof) =>
206 signer.createProof(proof).pipe(
207 Effect.mapError(
208 () =>
209 new ConnectionBlockedError({
210 reason: "configuration",
211 detail: "Could not create the websocket authorization proof.",
212 }),
213 ),
214 ),
215 clientMetadata: presentation.metadata,
216 connectionMethod: "relay",
217 ...(timeoutMs === undefined ? {} : { timeoutMs }),
218 });
219 },
220 Effect.provideService(HttpClient.HttpClient, httpClient),
221 );
222
223 const sessionChanged = () =>
224 new ConnectionBlockedError({
225 reason: "authentication",
226 detail: "Your cloud sign-in changed. Sign in again to authorize the environment.",
227 });
228
229 // A missing identity before the attempt captures one means the cloud session
230 // is still loading, not a sign-out. Only a captured identity that goes away
231 // or changes is evidence of one.
232 const sessionPending = () =>
233 new ConnectionTransientError({
234 reason: "session-pending",
235 detail: "Waiting for the T3 Connect sign-in to load.",
236 });
237
238 const assertSession = Effect.fnUntraced(function* (
239 identity: ClientCapabilities.CloudSessionIdentity,
240 ) {
241 const current = yield* cloudSession.identity;
242 if (Option.isNone(current) || current.value !== identity) {
243 return yield* sessionChanged();
244 }
245 });
246
247 // Called under tokenLock so a late rejection cannot remove a newer credential.
248 const removeRejectedToken = Effect.fnUntraced(function* (
249 environmentId: EnvironmentId,
250 accessToken: string,
251 ) {
252 const cached = yield* tokenStore.get(environmentId);
253 if (Option.isSome(cached) && cached.value.accessToken === accessToken) {
254 yield* tokenStore.remove(environmentId);
255 tokenOwners.delete(environmentId);
256 }
257 });
258
259 const obtainBootstrap = Effect.fn("relay.connection.bootstrap.obtain")(function* (
260 environmentId: EnvironmentId,
261 identity: ClientCapabilities.CloudSessionIdentity,
262 ) {
263 yield* assertSession(identity);
264 const clerkToken = yield* cloudSession.clerkToken.pipe(
265 Effect.withSpan("relay.connection.cloudSessionToken.resolve"),
266 );
267 const deviceId = yield* deviceIdentity.deviceId.pipe(
268 Effect.withSpan("relay.connection.deviceIdentity.resolve"),
269 );
270 yield* assertSession(identity);
271 const connected = yield* relay
272 .connectEnvironment({
273 clerkToken,
274 scopes: [RelayEnvironmentConnectScope],
275 environmentId,
276 ...(Option.isSome(deviceId) ? { deviceId: deviceId.value } : {}),
277 })
278 .pipe(Effect.mapError(mapManagedRelayError));
279 if (connected.environmentId !== environmentId) {
280 return yield* environmentMismatchError({
281 expected: environmentId,
282 actual: connected.environmentId,
283 });
284 }
285 yield* assertSession(identity);
286 return connected;
287 });
288
289 const exchangeDpopToken = Effect.fn("clientRuntime.connection.remote.exchangeDpopToken")(
290 function* (
291 environmentId: EnvironmentId,
292 thumbprint: string,
293 identity: ClientCapabilities.CloudSessionIdentity,
294 ) {
295 const bootstrap = yield* obtainBootstrap(environmentId, identity);
296 const descriptor = yield* fetchDescriptor(bootstrap.endpoint.httpBaseUrl, "relay").pipe(
297 Effect.provideService(HttpClient.HttpClient, httpClient),
298 Effect.withSpan("environment.authorization.descriptor"),
299 );
300 if (descriptor.environmentId !== environmentId) {
301 return yield* environmentMismatchError({
302 expected: environmentId,
303 actual: descriptor.environmentId,
304 });
305 }
306 const bootstrapProof = yield* signer
307 .createProof({
308 method: "POST",
309 url: environmentEndpointUrl(bootstrap.endpoint.httpBaseUrl, "/oauth/token"),
310 })
311 .pipe(
312 Effect.mapError(
313 () =>
314 new ConnectionBlockedError({
315 reason: "configuration",
316 detail: "Could not create the environment authorization proof.",
317 }),
318 ),
319 );
320 yield* assertSession(identity);
321 const access = yield* exchangeRemoteDpopAccessToken({
322 httpBaseUrl: bootstrap.endpoint.httpBaseUrl,
323 credential: bootstrap.credential,
324 dpopProof: bootstrapProof,
325 clientMetadata: presentation.metadata,
326 }).pipe(
327 Effect.mapError(mapRemoteDpopEnvironmentError),
328 Effect.provideService(HttpClient.HttpClient, httpClient),
329 Effect.withSpan("environment.authorization.accessToken.exchange"),
330 );
331 const issuedAt = yield* Clock.currentTimeMillis;
332 return new TokenStore.RemoteDpopAccessToken({
333 environmentId: descriptor.environmentId,
334 accountId: identity.accountId,
335 label: descriptor.label,
336 endpoint: bootstrap.endpoint,
337 accessToken: access.access_token,
338 expiresAtEpochMs: issuedAt + access.expires_in * 1_000,
339 dpopThumbprint: thumbprint,
340 });
341 },
342 );
343
344 const getDpopToken = Effect.fn("clientRuntime.connection.remote.getDpopToken")(function* (
345 input: Parameters<RemoteEnvironmentAuthorization["Service"]["authorizeDpopHttp"]>[0],
346 ) {
347 const session = yield* cloudSession.identity;
348 if (Option.isNone(session)) {
349 return yield* sessionPending();
350 }
351 const identity = session.value;
352 const thumbprint = yield* signer.thumbprint.pipe(
353 Effect.mapError(
354 () =>
355 new ConnectionBlockedError({
356 reason: "configuration",
357 detail: "Could not load the environment authorization key.",
358 }),
359 ),
360 Effect.withSpan("environment.authorization.dpopKey.resolve"),
361 );
362 const selected = yield* tokenLock.withPermits(1)(
363 Effect.gen(function* () {
364 yield* assertSession(identity);
365 const now = yield* Clock.currentTimeMillis;
366 const cached = yield* tokenStore
367 .get(input.expectedEnvironmentId)
368 .pipe(Effect.withSpan("environment.authorization.accessToken.cache"));
369 const owner = tokenOwners.get(input.expectedEnvironmentId);
370 if (
371 Option.isSome(cached) &&
372 cached.value.environmentId === input.expectedEnvironmentId &&
373 cached.value.accountId === identity.accountId &&
374 cached.value.dpopThumbprint === thumbprint &&
375 cached.value.expiresAtEpochMs > now + DPOP_ACCESS_TOKEN_REFRESH_SKEW_MS &&
376 cached.value.accessToken !== input.rejectedAccessToken &&
377 (owner?.accessToken !== cached.value.accessToken || owner.identity === identity)
378 ) {
379 tokenOwners.set(input.expectedEnvironmentId, {
380 accessToken: cached.value.accessToken,
381 identity,
382 });
383 return { token: Effect.succeed(cached.value), fromCache: true };
384 }
385 if (input.rejectedAccessToken !== undefined) {
386 yield* removeRejectedToken(input.expectedEnvironmentId, input.rejectedAccessToken);
387 }
388 const pending = pendingTokens.get(input.expectedEnvironmentId);
389 if (pending?.identity === identity && pending.thumbprint === thumbprint) {
390 return { token: pending.token, fromCache: false };
391 }
392
393 const id = {};
394 const fiber = yield* exchangeDpopToken(
395 input.expectedEnvironmentId,
396 thumbprint,
397 identity,
398 ).pipe(
399 Effect.flatMap((token) =>
400 tokenLock.withPermits(1)(
401 Effect.gen(function* () {
402 yield* assertSession(identity);
403 yield* tokenStore
404 .put(token)
405 .pipe(Effect.withSpan("environment.authorization.accessToken.persist"));
406 const current = yield* cloudSession.identity;
407 if (Option.isNone(current) || current.value !== identity) {
408 yield* removeRejectedToken(input.expectedEnvironmentId, token.accessToken);
409 return yield* sessionChanged();
410 }
411 tokenOwners.set(input.expectedEnvironmentId, {
412 accessToken: token.accessToken,
413 identity,
414 });
415 if (pendingTokens.get(input.expectedEnvironmentId)?.id === id) {
416 pendingTokens.delete(input.expectedEnvironmentId);
417 }
418 return token;
419 }),
420 ),
421 ),
422 Effect.timeoutOrElse({
423 duration: DPOP_AUTHORIZATION_TIMEOUT_MS,
424 orElse: () =>
425 Effect.fail(
426 new ConnectionTransientError({
427 reason: "timeout",
428 detail: "Timed out renewing the environment credential.",
429 }),
430 ),
431 }),
432 Effect.ensuring(
433 tokenLock.withPermits(1)(
434 Effect.sync(() => {
435 if (pendingTokens.get(input.expectedEnvironmentId)?.id === id) {
436 pendingTokens.delete(input.expectedEnvironmentId);
437 }
438 }),
439 ),
440 ),
441 // One caller's timeout must not cancel renewal for other HTTP requests.
442 Effect.forkIn(serviceScope),
443 );
444 const token = Fiber.join(fiber);
445 pendingTokens.set(input.expectedEnvironmentId, { id, identity, thumbprint, token });
446 return { token, fromCache: false };
447 }),
448 );
449 yield* Effect.annotateCurrentSpan({
450 "connection.remote_token_cache": selected.fromCache ? "hit" : "miss",
451 });
452 const token = yield* selected.token;
453 yield* assertSession(identity);
454 return { token, fromCache: selected.fromCache, identity };
455 });
456
457 const httpAuthorization = (
458 token: TokenStore.RemoteDpopAccessToken,
459 httpBaseUrl = token.endpoint.httpBaseUrl,
460 ): AuthorizedRemoteHttpEnvironment => ({
461 environmentId: token.environmentId,
462 label: token.label,
463 httpBaseUrl,
464 httpAuthorization: {
465 _tag: "Dpop",
466 accessToken: token.accessToken,
467 expiresAtEpochMs: token.expiresAtEpochMs,
468 },
469 });
470
471 const authorizeDpop = Effect.fn("clientRuntime.connection.remote.authorizeDpop")(function* (
472 input: Parameters<RemoteEnvironmentAuthorization["Service"]["authorizeDpop"]>[0],
473 ) {
474 const endpoint = input.directEndpoint;
475 const descriptor =
476 endpoint === undefined
477 ? undefined
478 : yield* verifyDirectEndpoint({
479 expectedEnvironmentId: input.expectedEnvironmentId,
480 httpBaseUrl: endpoint.httpBaseUrl,
481 connectionMethod: "direct",
482 });
483 const authorized = (token: TokenStore.RemoteDpopAccessToken, socketUrl: string) => ({
484 ...httpAuthorization(token, endpoint?.httpBaseUrl),
485 socketUrl,
486 ...(descriptor === undefined ? {} : { descriptor }),
487 });
488 let selected = yield* getDpopToken(input);
489 if (selected.fromCache) {
490 const cachedSocket = yield* createDpopSocketUrl(
491 selected.token,
492 CACHED_ENDPOINT_SOCKET_TIMEOUT_MS,
493 endpoint,
494 ).pipe(Effect.result);
495 if (Result.isSuccess(cachedSocket)) {
496 yield* assertSession(selected.identity);
497 return authorized(selected.token, cachedSocket.success);
498 }
499 if (cachedSocket.failure._tag === "ConnectionBlockedError") {
500 return yield* mapDpopSocketError(cachedSocket.failure);
501 }
502 // An unreachable direct address says nothing about the token, so keep
503 // it for the T3 Connect route rather than forcing a relay round trip.
504 if (endpoint !== undefined && cachedSocket.failure._tag !== "EnvironmentAuthInvalidError") {
505 return yield* mapDpopSocketError(cachedSocket.failure);
506 }
507 yield* assertSession(selected.identity);
508 selected = yield* getDpopToken({
509 ...input,
510 rejectedAccessToken: selected.token.accessToken,
511 });
512 }
513 const socket = yield* createDpopSocketUrl(selected.token, undefined, endpoint).pipe(
514 Effect.result,
515 );
516 if (Result.isFailure(socket)) {
517 if (endpoint === undefined || socket.failure._tag === "ConnectionBlockedError") {
518 yield* tokenLock.withPermits(1)(
519 removeRejectedToken(input.expectedEnvironmentId, selected.token.accessToken),
520 );
521 }
522 return yield* mapDpopSocketError(socket.failure);
523 }
524 yield* assertSession(selected.identity);
525 return authorized(selected.token, socket.success);
526 });
527
528 return RemoteEnvironmentAuthorization.of({
529 authorizeBearer,
530 authorizeDpop: Effect.fn("environment.authorization")(function (input) {
531 return authorizeDpop(input);
532 }),
533 // The relay tracer must wrap span creation, not just the token request.
534 authorizeDpopHttp: Effect.fnUntraced(function* (input) {
535 return yield* getDpopToken(input).pipe(
536 Effect.map(({ token }) => httpAuthorization(token)),
537 Effect.withSpan("environment.authorization.http"),
538 withRelayClientTracing,
539 );
540 }),
541 // Untraced: a span here would stay open for the socket's lifetime. Each renewal has its own.
542 renewDpopBeforeExpiry: Effect.fnUntraced(function* (input) {
543 let expiresAtEpochMs = input.expiresAtEpochMs;
544 let now = yield* Clock.currentTimeMillis;
545 // Past expiry the server has closed the socket.
546 while (now < expiresAtEpochMs) {
547 // getDpopToken reuses a cached token until it is within the skew of expiry.
548 // The floor spaces out retries and keeps a wall-clock jump from spinning.
549 yield* Effect.sleep(
550 Math.max(5_000, expiresAtEpochMs - DPOP_ACCESS_TOKEN_REFRESH_SKEW_MS - now),
551 );
552 const renewed = yield* getDpopToken({
553 expectedEnvironmentId: input.expectedEnvironmentId,
554 }).pipe(
555 Effect.map(({ token }) => token.expiresAtEpochMs),
556 Effect.withSpan("environment.authorization.renewSocket"),
557 withRelayClientTracing,
558 // A relay blip retries until expiry; a blocked credential ends the loop.
559 Effect.catchTags({ ConnectionTransientError: () => Effect.succeed(expiresAtEpochMs) }),
560 );
561 expiresAtEpochMs = Math.max(expiresAtEpochMs, renewed);
562 now = yield* Clock.currentTimeMillis;
563 }
564 }),
565 });
566});
567
568export const layer = Layer.effect(RemoteEnvironmentAuthorization, make);