Open History to see the last commit
1import {
2 RelayAccessTokenType,
3 RelayApi,
4 type RelayClientEnvironmentRecord,
5 type RelayClientDeviceRecord,
6 RelayConnectEnvironmentEndpoint,
7 type RelayDeviceRegistrationRequest,
8 type RelayDpopAccessTokenScope,
9 RelayDpopTokenExchangeGrantType,
10 type RelayEnvironmentConnectRequest,
11 type RelayEnvironmentConnectResponse,
12 type RelayEnvironmentLinkChallengeRequest,
13 type RelayEnvironmentLinkChallengeResponse,
14 type RelayEnvironmentLinkRequest,
15 type RelayEnvironmentLinkResponse,
16 type RelayEnvironmentStatusResponse,
17 RelayExchangeDpopAccessTokenEndpoint,
18 RelayGetEnvironmentStatusEndpoint,
19 RelayJwtSubjectTokenType,
20 type RelayLiveActivityRegistrationRequest,
21 RelayMobileRegistrationScope,
22 type RelayOkResponse,
23 type RelayPublicClientId,
24 RelayRegisterDeviceEndpoint,
25 RelayRegisterLiveActivityEndpoint,
26 RelayUnregisterDeviceEndpoint,
27} from "@t3tools/contracts/relay";
28import { encodeOAuthScope, oauthScopeSetEquals } from "@t3tools/shared/oauthScope";
29import { normalizeSecureRelayUrl } from "@t3tools/shared/relayUrl";
30import * as Clock from "effect/Clock";
31import * as Context from "effect/Context";
32import * as Data from "effect/Data";
33import * as Duration from "effect/Duration";
34import * as Effect from "effect/Effect";
35import * as Layer from "effect/Layer";
36import * as Option from "effect/Option";
37import * as SynchronizedRef from "effect/SynchronizedRef";
38import type { HttpMethod } from "effect/unstable/http/HttpMethod";
39import * as HttpApiClient from "effect/unstable/httpapi/HttpApiClient";
40
41export interface ManagedRelayDpopProofInput {
42 readonly method: HttpMethod;
43 readonly url: string;
44 readonly accessToken?: string;
45}
46
47export class ManagedRelayDpopSignerError extends Data.TaggedError("ManagedRelayDpopSignerError")<{
48 readonly cause: unknown;
49}> {}
50
51export interface ManagedRelayDpopSignerShape {
52 readonly thumbprint: Effect.Effect<string, ManagedRelayDpopSignerError>;
53 readonly createProof: (
54 input: ManagedRelayDpopProofInput,
55 ) => Effect.Effect<string, ManagedRelayDpopSignerError>;
56}
57
58export class ManagedRelayDpopSigner extends Context.Service<
59 ManagedRelayDpopSigner,
60 ManagedRelayDpopSignerShape
61>()("@t3tools/client-runtime/managedRelay/ManagedRelayDpopSigner") {}
62
63export class ManagedRelayClientError extends Data.TaggedError("ManagedRelayClientError")<{
64 readonly message: string;
65 readonly cause?: unknown;
66}> {}
67
68export const MANAGED_RELAY_REQUEST_TIMEOUT_MS = 10_000;
69
70interface CachedRelayAccessToken {
71 readonly clerkToken: string;
72 readonly thumbprint: string;
73 readonly scopes: ReadonlyArray<RelayDpopAccessTokenScope>;
74 readonly accessToken: string;
75 readonly expiresAtMillis: number;
76}
77
78export interface ManagedRelayAuthorization {
79 readonly accessToken: string;
80 readonly proof: string;
81 readonly thumbprint: string;
82}
83
84export interface ManagedRelayClientLayerOptions {
85 readonly relayUrl: string;
86 readonly clientId: RelayPublicClientId;
87}
88
89export interface ManagedRelayClientShape {
90 readonly relayUrl: string;
91 readonly listEnvironments: (input: {
92 readonly clerkToken: string;
93 }) => Effect.Effect<ReadonlyArray<RelayClientEnvironmentRecord>, ManagedRelayClientError>;
94 readonly listDevices: (input: {
95 readonly clerkToken: string;
96 }) => Effect.Effect<ReadonlyArray<RelayClientDeviceRecord>, ManagedRelayClientError>;
97 readonly createEnvironmentLinkChallenge: (input: {
98 readonly clerkToken: string;
99 readonly payload: RelayEnvironmentLinkChallengeRequest;
100 }) => Effect.Effect<RelayEnvironmentLinkChallengeResponse, ManagedRelayClientError>;
101 readonly linkEnvironment: (input: {
102 readonly clerkToken: string;
103 readonly payload: RelayEnvironmentLinkRequest;
104 }) => Effect.Effect<RelayEnvironmentLinkResponse, ManagedRelayClientError>;
105 readonly unlinkEnvironment: (input: {
106 readonly clerkToken: string;
107 readonly environmentId: RelayClientEnvironmentRecord["environmentId"];
108 }) => Effect.Effect<RelayOkResponse, ManagedRelayClientError>;
109 readonly getEnvironmentStatus: (input: {
110 readonly clerkToken: string;
111 readonly scopes: ReadonlyArray<RelayDpopAccessTokenScope>;
112 readonly environmentId: RelayClientEnvironmentRecord["environmentId"];
113 }) => Effect.Effect<RelayEnvironmentStatusResponse, ManagedRelayClientError>;
114 readonly connectEnvironment: (input: {
115 readonly clerkToken: string;
116 readonly scopes: ReadonlyArray<RelayDpopAccessTokenScope>;
117 readonly environmentId: RelayClientEnvironmentRecord["environmentId"];
118 readonly deviceId?: string;
119 }) => Effect.Effect<RelayEnvironmentConnectResponse, ManagedRelayClientError>;
120 readonly registerDevice: (input: {
121 readonly clerkToken: string;
122 readonly payload: RelayDeviceRegistrationRequest;
123 }) => Effect.Effect<RelayOkResponse, ManagedRelayClientError>;
124 readonly unregisterDevice: (input: {
125 readonly clerkToken: string;
126 readonly deviceId: string;
127 }) => Effect.Effect<RelayOkResponse, ManagedRelayClientError>;
128 readonly registerLiveActivity: (input: {
129 readonly clerkToken: string;
130 readonly payload: RelayLiveActivityRegistrationRequest;
131 }) => Effect.Effect<RelayOkResponse, ManagedRelayClientError>;
132 readonly resetTokenCache: Effect.Effect<void>;
133}
134
135export class ManagedRelayClient extends Context.Service<
136 ManagedRelayClient,
137 ManagedRelayClientShape
138>()("@t3tools/client-runtime/managedRelay/ManagedRelayClient") {}
139
140function relayClientError(message: string, cause?: unknown): ManagedRelayClientError {
141 return new ManagedRelayClientError({ message, ...(cause === undefined ? {} : { cause }) });
142}
143
144function timeoutRelayRequest(message: string) {
145 return <A, E, R>(
146 request: Effect.Effect<A, E, R>,
147 ): Effect.Effect<A, E | ManagedRelayClientError, R> =>
148 request.pipe(
149 Effect.timeoutOption(Duration.millis(MANAGED_RELAY_REQUEST_TIMEOUT_MS)),
150 Effect.flatMap(
151 Option.match({
152 onNone: () => Effect.fail(relayClientError(message)),
153 onSome: Effect.succeed,
154 }),
155 ),
156 );
157}
158
159function tokenMatches(
160 token: CachedRelayAccessToken,
161 input: {
162 readonly clerkToken: string;
163 readonly thumbprint: string;
164 readonly scopes: ReadonlyArray<RelayDpopAccessTokenScope>;
165 readonly nowMillis: number;
166 },
167): boolean {
168 return (
169 token.clerkToken === input.clerkToken &&
170 token.thumbprint === input.thumbprint &&
171 token.expiresAtMillis > input.nowMillis + 5_000 &&
172 input.scopes.every((scope) => token.scopes.includes(scope))
173 );
174}
175
176function bearerHeaders(clerkToken: string) {
177 return { authorization: `Bearer ${clerkToken}` };
178}
179
180function dpopHeaders(authorization: ManagedRelayAuthorization) {
181 return {
182 authorization: `DPoP ${authorization.accessToken}`,
183 dpop: authorization.proof,
184 };
185}
186
187function disabledManagedRelayClient(relayUrl: string): ManagedRelayClientShape {
188 const unavailable = () =>
189 Effect.fail(relayClientError("Relay URL must be a secure absolute HTTPS origin."));
190 return ManagedRelayClient.of({
191 relayUrl,
192 listEnvironments: unavailable,
193 listDevices: unavailable,
194 createEnvironmentLinkChallenge: unavailable,
195 linkEnvironment: unavailable,
196 unlinkEnvironment: unavailable,
197 getEnvironmentStatus: unavailable,
198 connectEnvironment: unavailable,
199 registerDevice: unavailable,
200 unregisterDevice: unavailable,
201 registerLiveActivity: unavailable,
202 resetTokenCache: Effect.void,
203 });
204}
205
206export function managedRelayClientLayer(options: ManagedRelayClientLayerOptions) {
207 return Layer.effect(
208 ManagedRelayClient,
209 Effect.gen(function* () {
210 const relayUrl = normalizeSecureRelayUrl(options.relayUrl);
211 if (relayUrl === null) {
212 return disabledManagedRelayClient(options.relayUrl);
213 }
214 const signer = yield* ManagedRelayDpopSigner;
215 const client = yield* HttpApiClient.make(RelayApi, { baseUrl: relayUrl });
216 const cachedTokens = yield* SynchronizedRef.make<ReadonlyArray<CachedRelayAccessToken>>([]);
217 const urlBuilder = HttpApiClient.urlBuilder(RelayApi, { baseUrl: relayUrl });
218
219 type DpopProofTarget = Pick<ManagedRelayDpopProofInput, "method" | "url">;
220 const dpopProofTargets = {
221 exchangeAccessToken: (): DpopProofTarget => ({
222 method: RelayExchangeDpopAccessTokenEndpoint.method,
223 url: urlBuilder.token.exchangeDpopAccessToken(),
224 }),
225 getEnvironmentStatus: (
226 environmentId: RelayClientEnvironmentRecord["environmentId"],
227 ): DpopProofTarget => ({
228 method: RelayGetEnvironmentStatusEndpoint.method,
229 url: urlBuilder.dpopClient.getEnvironmentStatus({ params: { environmentId } }),
230 }),
231 connectEnvironment: (
232 environmentId: RelayClientEnvironmentRecord["environmentId"],
233 ): DpopProofTarget => ({
234 method: RelayConnectEnvironmentEndpoint.method,
235 url: urlBuilder.dpopClient.connectEnvironment({ params: { environmentId } }),
236 }),
237 registerDevice: (): DpopProofTarget => ({
238 method: RelayRegisterDeviceEndpoint.method,
239 url: urlBuilder.mobile.registerDevice(),
240 }),
241 unregisterDevice: (deviceId: string): DpopProofTarget => ({
242 method: RelayUnregisterDeviceEndpoint.method,
243 url: urlBuilder.mobile.unregisterDevice({ params: { deviceId } }),
244 }),
245 registerLiveActivity: (): DpopProofTarget => ({
246 method: RelayRegisterLiveActivityEndpoint.method,
247 url: urlBuilder.mobile.registerLiveActivity(),
248 }),
249 };
250
251 const obtainAccessToken = Effect.fn("clientRuntime.managedRelay.obtainAccessToken")(
252 function* (input: {
253 readonly clerkToken: string;
254 readonly scopes: ReadonlyArray<RelayDpopAccessTokenScope>;
255 readonly thumbprint: string;
256 }) {
257 const nowMillis = yield* Clock.currentTimeMillis;
258 return yield* SynchronizedRef.modifyEffect(cachedTokens, (tokens) => {
259 const activeTokens = tokens.filter(
260 (token) => token.expiresAtMillis > nowMillis + 5_000,
261 );
262 const cached = activeTokens.find((token) =>
263 tokenMatches(token, { ...input, nowMillis }),
264 );
265 if (cached) {
266 return Effect.succeed([cached, activeTokens] as const);
267 }
268 return Effect.gen(function* () {
269 const proof = yield* signer
270 .createProof(dpopProofTargets.exchangeAccessToken())
271 .pipe(
272 Effect.mapError((cause) =>
273 relayClientError("Could not create relay token DPoP proof.", cause),
274 ),
275 );
276 const response = yield* client.token
277 .exchangeDpopAccessToken({
278 headers: { dpop: proof },
279 payload: {
280 grant_type: RelayDpopTokenExchangeGrantType,
281 subject_token: input.clerkToken,
282 subject_token_type: RelayJwtSubjectTokenType,
283 requested_token_type: RelayAccessTokenType,
284 resource: relayUrl,
285 scope: encodeOAuthScope(input.scopes),
286 client_id: options.clientId,
287 },
288 })
289 .pipe(
290 Effect.mapError((cause) =>
291 relayClientError("Could not exchange relay DPoP access token.", cause),
292 ),
293 timeoutRelayRequest("Relay DPoP access token exchange timed out."),
294 );
295 if (!oauthScopeSetEquals(response.scope, input.scopes)) {
296 return yield* relayClientError(
297 "Relay granted unexpected DPoP access token scopes.",
298 );
299 }
300 const next: CachedRelayAccessToken = {
301 clerkToken: input.clerkToken,
302 thumbprint: input.thumbprint,
303 scopes: input.scopes,
304 accessToken: response.access_token,
305 expiresAtMillis: nowMillis + response.expires_in * 1_000,
306 };
307 return [next, [...activeTokens, next]] as const;
308 });
309 });
310 },
311 );
312
313 const authorize = (input: {
314 readonly clerkToken: string;
315 readonly scopes: ReadonlyArray<RelayDpopAccessTokenScope>;
316 readonly target: DpopProofTarget;
317 }) =>
318 Effect.gen(function* () {
319 const thumbprint = yield* signer.thumbprint.pipe(
320 Effect.mapError((cause) =>
321 relayClientError("Could not load relay DPoP proof key.", cause),
322 ),
323 );
324 const token = yield* obtainAccessToken({
325 clerkToken: input.clerkToken,
326 scopes: input.scopes,
327 thumbprint,
328 });
329 const proof = yield* signer
330 .createProof({
331 ...input.target,
332 accessToken: token.accessToken,
333 })
334 .pipe(
335 Effect.mapError((cause) =>
336 relayClientError("Could not create relay request DPoP proof.", cause),
337 ),
338 );
339 return { accessToken: token.accessToken, proof, thumbprint };
340 });
341
342 const authorizeMobileRegistration = (input: {
343 readonly clerkToken: string;
344 readonly target: DpopProofTarget;
345 }) =>
346 authorize({
347 ...input,
348 scopes: [RelayMobileRegistrationScope],
349 });
350
351 return ManagedRelayClient.of({
352 relayUrl,
353 listEnvironments: (input) =>
354 client.client.listEnvironments({ headers: bearerHeaders(input.clerkToken) }).pipe(
355 Effect.map((response) => response.environments),
356 Effect.mapError((cause) =>
357 relayClientError("Could not list relay-managed environments.", cause),
358 ),
359 timeoutRelayRequest("Relay environment listing timed out."),
360 ),
361 listDevices: (input) =>
362 client.client
363 .listDevices({
364 headers: bearerHeaders(input.clerkToken),
365 })
366 .pipe(
367 Effect.map((response) => response.devices),
368 Effect.mapError((cause) =>
369 relayClientError("Could not list relay client devices.", cause),
370 ),
371 timeoutRelayRequest("Relay client device listing timed out."),
372 ),
373 createEnvironmentLinkChallenge: (input) =>
374 client.client
375 .createEnvironmentLinkChallenge({
376 headers: bearerHeaders(input.clerkToken),
377 payload: input.payload,
378 })
379 .pipe(
380 Effect.mapError((cause) =>
381 relayClientError("Could not create relay environment link challenge.", cause),
382 ),
383 timeoutRelayRequest("Relay environment link challenge timed out."),
384 ),
385 linkEnvironment: (input) =>
386 client.client
387 .linkEnvironment({
388 headers: bearerHeaders(input.clerkToken),
389 payload: input.payload,
390 })
391 .pipe(
392 Effect.mapError((cause) =>
393 relayClientError("Could not link relay environment.", cause),
394 ),
395 timeoutRelayRequest("Relay environment linking timed out."),
396 ),
397 unlinkEnvironment: (input) =>
398 client.client
399 .unlinkEnvironment({
400 headers: bearerHeaders(input.clerkToken),
401 params: { environmentId: input.environmentId },
402 })
403 .pipe(
404 Effect.mapError((cause) =>
405 relayClientError("Could not unlink relay environment.", cause),
406 ),
407 timeoutRelayRequest("Relay environment unlinking timed out."),
408 ),
409 getEnvironmentStatus: (input) =>
410 Effect.gen(function* () {
411 const authorization = yield* authorize({
412 clerkToken: input.clerkToken,
413 scopes: input.scopes,
414 target: dpopProofTargets.getEnvironmentStatus(input.environmentId),
415 });
416 return yield* client.dpopClient
417 .getEnvironmentStatus({
418 headers: dpopHeaders(authorization),
419 params: { environmentId: input.environmentId },
420 })
421 .pipe(
422 Effect.mapError((cause) =>
423 relayClientError("Could not get relay environment status.", cause),
424 ),
425 timeoutRelayRequest("Relay environment status request timed out."),
426 );
427 }),
428 connectEnvironment: (input) =>
429 Effect.gen(function* () {
430 const authorization = yield* authorize({
431 clerkToken: input.clerkToken,
432 scopes: input.scopes,
433 target: dpopProofTargets.connectEnvironment(input.environmentId),
434 });
435 const payload: RelayEnvironmentConnectRequest = {
436 ...(input.deviceId ? { deviceId: input.deviceId } : {}),
437 clientKeyThumbprint: authorization.thumbprint,
438 };
439 return yield* client.dpopClient
440 .connectEnvironment({
441 headers: dpopHeaders(authorization),
442 params: { environmentId: input.environmentId },
443 payload,
444 })
445 .pipe(
446 Effect.mapError((cause) =>
447 relayClientError("Could not connect relay environment.", cause),
448 ),
449 timeoutRelayRequest("Relay environment connection timed out."),
450 );
451 }),
452 registerDevice: (input) =>
453 Effect.gen(function* () {
454 const authorization = yield* authorizeMobileRegistration({
455 clerkToken: input.clerkToken,
456 target: dpopProofTargets.registerDevice(),
457 });
458 return yield* client.mobile
459 .registerDevice({
460 headers: dpopHeaders(authorization),
461 payload: input.payload,
462 })
463 .pipe(
464 Effect.mapError((cause) =>
465 relayClientError("Could not register relay mobile device.", cause),
466 ),
467 timeoutRelayRequest("Relay mobile device registration timed out."),
468 );
469 }),
470 unregisterDevice: (input) =>
471 Effect.gen(function* () {
472 const authorization = yield* authorizeMobileRegistration({
473 clerkToken: input.clerkToken,
474 target: dpopProofTargets.unregisterDevice(input.deviceId),
475 });
476 return yield* client.mobile
477 .unregisterDevice({
478 headers: dpopHeaders(authorization),
479 params: { deviceId: input.deviceId },
480 })
481 .pipe(
482 Effect.mapError((cause) =>
483 relayClientError("Could not unregister relay mobile device.", cause),
484 ),
485 timeoutRelayRequest("Relay mobile device unregistration timed out."),
486 );
487 }),
488 registerLiveActivity: (input) =>
489 Effect.gen(function* () {
490 const authorization = yield* authorizeMobileRegistration({
491 clerkToken: input.clerkToken,
492 target: dpopProofTargets.registerLiveActivity(),
493 });
494 return yield* client.mobile
495 .registerLiveActivity({
496 headers: dpopHeaders(authorization),
497 payload: input.payload,
498 })
499 .pipe(
500 Effect.mapError((cause) =>
501 relayClientError("Could not register relay live activity.", cause),
502 ),
503 timeoutRelayRequest("Relay Live Activity registration timed out."),
504 );
505 }),
506 resetTokenCache: SynchronizedRef.set(cachedTokens, []),
507 });
508 }),
509 );
510}