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