Open History to see the last commit
1import {
2 RelayAccessTokenType,
3 RelayApi,
4 type RelayClientEnvironmentRecord,
5 type RelayClientDeviceRecord,
6 RelayConnectEnvironmentEndpoint,
7 type RelayDeviceRegistrationRequest,
8 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 RelayProtectedError,
27 type RelayProtectedError as RelayProtectedErrorType,
28 RelayUnregisterDeviceEndpoint,
29} from "@t3tools/contracts/relay";
30import { encodeOAuthScope, oauthScopeSetEquals } from "@t3tools/shared/oauthScope";
31import { decodeRelayJwt } from "@t3tools/shared/relayJwt";
32import { withRelayClientTracing } from "@t3tools/shared/relayTracing";
33import { normalizeSecureRelayUrl } from "@t3tools/shared/relayUrl";
34import * as Clock from "effect/Clock";
35import * as Context from "effect/Context";
36import * as Duration from "effect/Duration";
37import * as Effect from "effect/Effect";
38import * as Layer from "effect/Layer";
39import * as Option from "effect/Option";
40import * as Schema from "effect/Schema";
41import * as SynchronizedRef from "effect/SynchronizedRef";
42import * as HttpClientError from "effect/unstable/http/HttpClientError";
43import type * as HttpMethod from "effect/unstable/http/HttpMethod";
44import * as HttpApiClient from "effect/unstable/httpapi/HttpApiClient";
45
46export interface ManagedRelayDpopProofInput {
47 readonly method: HttpMethod.HttpMethod;
48 readonly url: string;
49 readonly accessToken?: string;
50}
51
52export class ManagedRelayDpopKeyLoadError extends Schema.TaggedErrorClass<ManagedRelayDpopKeyLoadError>()(
53 "ManagedRelayDpopKeyLoadError",
54 {
55 keyStore: Schema.Literals(["expo-secure-store", "indexed-db"]),
56 cause: Schema.Defect(),
57 },
58) {
59 override get message(): string {
60 return "Could not load relay DPoP proof key.";
61 }
62}
63
64export class ManagedRelayDpopProofCreationError extends Schema.TaggedErrorClass<ManagedRelayDpopProofCreationError>()(
65 "ManagedRelayDpopProofCreationError",
66 {
67 method: Schema.String,
68 url: Schema.String,
69 cause: Schema.Defect(),
70 },
71) {
72 override get message(): string {
73 return `Could not create the relay DPoP proof for ${this.method} ${this.url}.`;
74 }
75}
76
77export const ManagedRelayDpopSignerError = Schema.Union([
78 ManagedRelayDpopKeyLoadError,
79 ManagedRelayDpopProofCreationError,
80]);
81export type ManagedRelayDpopSignerError = typeof ManagedRelayDpopSignerError.Type;
82
83export const ManagedRelayRequestAction = Schema.Literals([
84 "exchange relay DPoP access token",
85 "list relay-managed environments",
86 "list relay client devices",
87 "create relay environment link challenge",
88 "link relay environment",
89 "unlink relay environment",
90 "get relay environment status",
91 "connect relay environment",
92 "register relay mobile device",
93 "unregister relay mobile device",
94 "register relay live activity",
95]);
96export type ManagedRelayRequestAction = typeof ManagedRelayRequestAction.Type;
97
98export const ManagedRelayRequestActivity = Schema.Literals([
99 "Relay DPoP access token exchange",
100 "Relay environment listing",
101 "Relay client device listing",
102 "Relay environment link challenge",
103 "Relay environment linking",
104 "Relay environment unlinking",
105 "Relay environment status request",
106 "Relay environment connection",
107 "Relay mobile device registration",
108 "Relay mobile device unregistration",
109 "Relay Live Activity registration",
110]);
111export type ManagedRelayRequestActivity = typeof ManagedRelayRequestActivity.Type;
112
113export class ManagedRelayRequestTimeoutError extends Schema.TaggedErrorClass<ManagedRelayRequestTimeoutError>()(
114 "ManagedRelayRequestTimeoutError",
115 {
116 activity: ManagedRelayRequestActivity,
117 timeoutMs: Schema.Number,
118 },
119) {
120 override get message(): string {
121 return `${this.activity} timed out.`;
122 }
123}
124
125export class ManagedRelayUrlInvalidError extends Schema.TaggedErrorClass<ManagedRelayUrlInvalidError>()(
126 "ManagedRelayUrlInvalidError",
127 {
128 relayUrl: Schema.String,
129 },
130) {
131 override get message(): string {
132 return "Relay URL must be a secure absolute HTTPS origin.";
133 }
134}
135
136export class ManagedRelayRequestFailedError extends Schema.TaggedErrorClass<ManagedRelayRequestFailedError>()(
137 "ManagedRelayRequestFailedError",
138 {
139 action: ManagedRelayRequestAction,
140 cause: Schema.Defect(),
141 relayError: Schema.optional(RelayProtectedError),
142 traceId: Schema.optional(Schema.String),
143 },
144) {
145 override get message(): string {
146 return `Could not ${this.action}.`;
147 }
148}
149
150export class ManagedRelayAccessTokenScopesUnexpectedError extends Schema.TaggedErrorClass<ManagedRelayAccessTokenScopesUnexpectedError>()(
151 "ManagedRelayAccessTokenScopesUnexpectedError",
152 {
153 requestedScopes: Schema.Array(RelayDpopAccessTokenScope),
154 grantedScope: Schema.String,
155 },
156) {
157 override get message(): string {
158 return "Relay granted unexpected DPoP access token scopes.";
159 }
160}
161
162export class ManagedRelayTokenProofCreationError extends Schema.TaggedErrorClass<ManagedRelayTokenProofCreationError>()(
163 "ManagedRelayTokenProofCreationError",
164 {
165 method: Schema.String,
166 url: Schema.String,
167 cause: Schema.Defect(),
168 },
169) {
170 override get message(): string {
171 return "Could not create relay token DPoP proof.";
172 }
173}
174
175export class ManagedRelayRequestProofCreationError extends Schema.TaggedErrorClass<ManagedRelayRequestProofCreationError>()(
176 "ManagedRelayRequestProofCreationError",
177 {
178 method: Schema.String,
179 url: Schema.String,
180 cause: Schema.Defect(),
181 },
182) {
183 override get message(): string {
184 return "Could not create relay request DPoP proof.";
185 }
186}
187
188export const ManagedRelayClientError = Schema.Union([
189 ManagedRelayUrlInvalidError,
190 ManagedRelayRequestFailedError,
191 ManagedRelayRequestTimeoutError,
192 ManagedRelayAccessTokenScopesUnexpectedError,
193 ManagedRelayDpopKeyLoadError,
194 ManagedRelayTokenProofCreationError,
195 ManagedRelayRequestProofCreationError,
196]);
197export type ManagedRelayClientError = typeof ManagedRelayClientError.Type;
198
199type RelayHttpRequestError =
200 | RelayProtectedErrorType
201 | HttpClientError.HttpClientError
202 | Schema.SchemaError;
203
204export class ManagedRelayDpopSigner extends Context.Service<
205 ManagedRelayDpopSigner,
206 {
207 readonly thumbprint: Effect.Effect<string, ManagedRelayDpopKeyLoadError>;
208 readonly createProof: (
209 input: ManagedRelayDpopProofInput,
210 ) => Effect.Effect<string, ManagedRelayDpopProofCreationError>;
211 }
212>()("@t3tools/client-runtime/relay/managedRelay/ManagedRelayDpopSigner") {}
213
214export const MANAGED_RELAY_REQUEST_TIMEOUT_MS = 10_000;
215
216export interface ManagedRelayAccessTokenCacheEntry {
217 readonly accountId: string;
218 readonly clientId: RelayPublicClientId;
219 readonly relayUrl: string;
220 readonly thumbprint: string;
221 readonly scopes: ReadonlyArray<RelayDpopAccessTokenScope>;
222 readonly accessToken: string;
223 readonly expiresAtMillis: number;
224}
225
226export interface ManagedRelayAccessTokenStore {
227 readonly load: Effect.Effect<ReadonlyArray<ManagedRelayAccessTokenCacheEntry>>;
228 readonly save: (entries: ReadonlyArray<ManagedRelayAccessTokenCacheEntry>) => Effect.Effect<void>;
229 readonly clear: Effect.Effect<void>;
230}
231
232export interface ManagedRelayAuthorization {
233 readonly accessToken: string;
234 readonly proof: string;
235 readonly thumbprint: string;
236}
237
238export interface ManagedRelayClientLayerOptions {
239 readonly relayUrl: string;
240 readonly clientId: RelayPublicClientId;
241 readonly accessTokenStore?: ManagedRelayAccessTokenStore;
242}
243
244export class ManagedRelayClient extends Context.Service<
245 ManagedRelayClient,
246 {
247 readonly relayUrl: string;
248 readonly listEnvironments: (input: {
249 readonly clerkToken: string;
250 }) => Effect.Effect<ReadonlyArray<RelayClientEnvironmentRecord>, ManagedRelayClientError>;
251 readonly listDevices: (input: {
252 readonly clerkToken: string;
253 }) => Effect.Effect<ReadonlyArray<RelayClientDeviceRecord>, ManagedRelayClientError>;
254 readonly createEnvironmentLinkChallenge: (input: {
255 readonly clerkToken: string;
256 readonly payload: RelayEnvironmentLinkChallengeRequest;
257 }) => Effect.Effect<RelayEnvironmentLinkChallengeResponse, ManagedRelayClientError>;
258 readonly linkEnvironment: (input: {
259 readonly clerkToken: string;
260 readonly payload: RelayEnvironmentLinkRequest;
261 }) => Effect.Effect<RelayEnvironmentLinkResponse, ManagedRelayClientError>;
262 readonly unlinkEnvironment: (input: {
263 readonly clerkToken: string;
264 readonly environmentId: RelayClientEnvironmentRecord["environmentId"];
265 }) => Effect.Effect<RelayOkResponse, ManagedRelayClientError>;
266 readonly getEnvironmentStatus: (input: {
267 readonly clerkToken: string;
268 readonly scopes: ReadonlyArray<RelayDpopAccessTokenScope>;
269 readonly environmentId: RelayClientEnvironmentRecord["environmentId"];
270 }) => Effect.Effect<RelayEnvironmentStatusResponse, ManagedRelayClientError>;
271 readonly connectEnvironment: (input: {
272 readonly clerkToken: string;
273 readonly scopes: ReadonlyArray<RelayDpopAccessTokenScope>;
274 readonly environmentId: RelayClientEnvironmentRecord["environmentId"];
275 readonly deviceId?: string;
276 }) => Effect.Effect<RelayEnvironmentConnectResponse, ManagedRelayClientError>;
277 readonly registerDevice: (input: {
278 readonly clerkToken: string;
279 readonly payload: RelayDeviceRegistrationRequest;
280 }) => Effect.Effect<RelayOkResponse, ManagedRelayClientError>;
281 readonly unregisterDevice: (input: {
282 readonly clerkToken: string;
283 readonly deviceId: string;
284 }) => Effect.Effect<RelayOkResponse, ManagedRelayClientError>;
285 readonly registerLiveActivity: (input: {
286 readonly clerkToken: string;
287 readonly payload: RelayLiveActivityRegistrationRequest;
288 }) => Effect.Effect<RelayOkResponse, ManagedRelayClientError>;
289 readonly resetTokenCache: Effect.Effect<void>;
290 }
291>()("@t3tools/client-runtime/relay/managedRelay/ManagedRelayClient") {}
292
293const isRelayProtectedError = Schema.is(RelayProtectedError);
294
295function relayRequestError(action: ManagedRelayRequestAction) {
296 return (cause: RelayHttpRequestError): ManagedRelayClientError =>
297 new ManagedRelayRequestFailedError({
298 action,
299 cause,
300 ...(isRelayProtectedError(cause) ? { relayError: cause, traceId: cause.traceId } : {}),
301 });
302}
303
304function proofCreationErrorFields(error: ManagedRelayDpopProofCreationError) {
305 return {
306 method: error.method,
307 url: error.url,
308 cause: error,
309 };
310}
311
312function isRejectedDpopAccessToken(error: ManagedRelayClientError): boolean {
313 return (
314 error._tag === "ManagedRelayRequestFailedError" &&
315 error.relayError?._tag === "RelayAuthInvalidError" &&
316 error.relayError.reason === "invalid_bearer"
317 );
318}
319
320function timeoutRelayRequest(activity: ManagedRelayRequestActivity) {
321 return <A, E, R>(
322 effect: Effect.Effect<A, E, R>,
323 ): Effect.Effect<A, E | ManagedRelayClientError, R> =>
324 effect.pipe(
325 Effect.timeoutOption(Duration.millis(MANAGED_RELAY_REQUEST_TIMEOUT_MS)),
326 Effect.flatMap(
327 Option.match({
328 onNone: () =>
329 Effect.fail(
330 new ManagedRelayRequestTimeoutError({
331 activity,
332 timeoutMs: MANAGED_RELAY_REQUEST_TIMEOUT_MS,
333 }),
334 ),
335 onSome: Effect.succeed,
336 }),
337 ),
338 );
339}
340
341function tokenMatches(
342 token: ManagedRelayAccessTokenCacheEntry,
343 input: {
344 readonly accountId: string;
345 readonly clientId: RelayPublicClientId;
346 readonly relayUrl: string;
347 readonly thumbprint: string;
348 readonly scopes: ReadonlyArray<RelayDpopAccessTokenScope>;
349 readonly nowMillis: number;
350 },
351): boolean {
352 return (
353 token.accountId === input.accountId &&
354 token.clientId === input.clientId &&
355 token.relayUrl === input.relayUrl &&
356 token.thumbprint === input.thumbprint &&
357 token.expiresAtMillis > input.nowMillis + 5_000 &&
358 input.scopes.every((scope) => token.scopes.includes(scope))
359 );
360}
361
362function relayAccountId(clerkToken: string): Option.Option<string> {
363 try {
364 return Option.fromNullishOr(decodeRelayJwt(clerkToken).sub).pipe(
365 Option.filter((subject) => subject.length > 0),
366 );
367 } catch {
368 return Option.none();
369 }
370}
371
372function bearerHeaders(clerkToken: string) {
373 return { authorization: `Bearer ${clerkToken}` };
374}
375
376function dpopHeaders(authorization: ManagedRelayAuthorization) {
377 return {
378 authorization: `DPoP ${authorization.accessToken}`,
379 dpop: authorization.proof,
380 };
381}
382
383function disabledManagedRelayClient(relayUrl: string): ManagedRelayClient["Service"] {
384 const unavailable = (spanName: string) =>
385 Effect.fn(spanName)(function* () {
386 return yield* new ManagedRelayUrlInvalidError({ relayUrl });
387 });
388 return ManagedRelayClient.of({
389 relayUrl,
390 listEnvironments: unavailable("clientRuntime.managedRelay.listEnvironments"),
391 listDevices: unavailable("clientRuntime.managedRelay.listDevices"),
392 createEnvironmentLinkChallenge: unavailable(
393 "clientRuntime.managedRelay.createEnvironmentLinkChallenge",
394 ),
395 linkEnvironment: unavailable("clientRuntime.managedRelay.linkEnvironment"),
396 unlinkEnvironment: unavailable("clientRuntime.managedRelay.unlinkEnvironment"),
397 getEnvironmentStatus: unavailable("clientRuntime.managedRelay.getEnvironmentStatus"),
398 connectEnvironment: unavailable("clientRuntime.managedRelay.connectEnvironment"),
399 registerDevice: unavailable("clientRuntime.managedRelay.registerDevice"),
400 unregisterDevice: unavailable("clientRuntime.managedRelay.unregisterDevice"),
401 registerLiveActivity: unavailable("clientRuntime.managedRelay.registerLiveActivity"),
402 resetTokenCache: Effect.void.pipe(
403 Effect.withSpan("clientRuntime.managedRelay.resetTokenCache"),
404 ),
405 });
406}
407
408export const make = Effect.fn("ManagedRelayClient.make")(function* (
409 options: ManagedRelayClientLayerOptions,
410) {
411 const relayUrl = normalizeSecureRelayUrl(options.relayUrl);
412 if (relayUrl === null) {
413 return disabledManagedRelayClient(options.relayUrl);
414 }
415 const signer = yield* ManagedRelayDpopSigner;
416 const client = yield* HttpApiClient.make(RelayApi, { baseUrl: relayUrl });
417 const initialTokens = options.accessTokenStore ? yield* options.accessTokenStore.load : [];
418 const cachedTokens = yield* SynchronizedRef.make<
419 ReadonlyArray<ManagedRelayAccessTokenCacheEntry>
420 >(initialTokens.filter((token) => token.clientId === options.clientId));
421 const urlBuilder = HttpApiClient.urlBuilder(RelayApi, { baseUrl: relayUrl });
422
423 type DpopProofTarget = Pick<ManagedRelayDpopProofInput, "method" | "url">;
424 const dpopProofTargets = {
425 exchangeAccessToken: (): DpopProofTarget => ({
426 method: RelayExchangeDpopAccessTokenEndpoint.method,
427 url: urlBuilder.token.exchangeDpopAccessToken(),
428 }),
429 getEnvironmentStatus: (
430 environmentId: RelayClientEnvironmentRecord["environmentId"],
431 ): DpopProofTarget => ({
432 method: RelayGetEnvironmentStatusEndpoint.method,
433 url: urlBuilder.dpopClient.getEnvironmentStatus({ params: { environmentId } }),
434 }),
435 connectEnvironment: (
436 environmentId: RelayClientEnvironmentRecord["environmentId"],
437 ): DpopProofTarget => ({
438 method: RelayConnectEnvironmentEndpoint.method,
439 url: urlBuilder.dpopClient.connectEnvironment({ params: { environmentId } }),
440 }),
441 registerDevice: (): DpopProofTarget => ({
442 method: RelayRegisterDeviceEndpoint.method,
443 url: urlBuilder.mobile.registerDevice(),
444 }),
445 unregisterDevice: (deviceId: string): DpopProofTarget => ({
446 method: RelayUnregisterDeviceEndpoint.method,
447 url: urlBuilder.mobile.unregisterDevice({ params: { deviceId } }),
448 }),
449 registerLiveActivity: (): DpopProofTarget => ({
450 method: RelayRegisterLiveActivityEndpoint.method,
451 url: urlBuilder.mobile.registerLiveActivity(),
452 }),
453 };
454
455 const exchangeAccessToken = Effect.fn("clientRuntime.managedRelay.exchangeAccessToken")(
456 function* (input: {
457 readonly clerkToken: string;
458 readonly scopes: ReadonlyArray<RelayDpopAccessTokenScope>;
459 }) {
460 yield* Effect.annotateCurrentSpan({
461 "relay.client_id": options.clientId,
462 "relay.scopes": input.scopes.join(" "),
463 });
464 const proof = yield* signer
465 .createProof(dpopProofTargets.exchangeAccessToken())
466 .pipe(
467 Effect.mapError(
468 (error) => new ManagedRelayTokenProofCreationError(proofCreationErrorFields(error)),
469 ),
470 );
471 const response = yield* client.token
472 .exchangeDpopAccessToken({
473 headers: { dpop: proof },
474 payload: {
475 grant_type: RelayDpopTokenExchangeGrantType,
476 subject_token: input.clerkToken,
477 subject_token_type: RelayJwtSubjectTokenType,
478 requested_token_type: RelayAccessTokenType,
479 resource: relayUrl,
480 scope: encodeOAuthScope(input.scopes),
481 client_id: options.clientId,
482 },
483 })
484 .pipe(
485 Effect.mapError(relayRequestError("exchange relay DPoP access token")),
486 timeoutRelayRequest("Relay DPoP access token exchange"),
487 );
488 if (!oauthScopeSetEquals(response.scope, input.scopes)) {
489 return yield* new ManagedRelayAccessTokenScopesUnexpectedError({
490 requestedScopes: input.scopes,
491 grantedScope: response.scope,
492 });
493 }
494 return response;
495 },
496 );
497
498 const obtainAccessToken = Effect.fn("clientRuntime.managedRelay.obtainAccessToken")(
499 function* (input: {
500 readonly clerkToken: string;
501 readonly scopes: ReadonlyArray<RelayDpopAccessTokenScope>;
502 readonly thumbprint: string;
503 }) {
504 yield* Effect.annotateCurrentSpan({
505 "relay.client_id": options.clientId,
506 "relay.scopes": input.scopes.join(" "),
507 });
508 const nowMillis = yield* Clock.currentTimeMillis;
509 const accountId = relayAccountId(input.clerkToken);
510 if (Option.isNone(accountId)) {
511 yield* Effect.annotateCurrentSpan({
512 "relay.token_cache.result": "bypass",
513 "relay.token_cache.bypass_reason": "invalid_subject_token",
514 });
515 const response = yield* exchangeAccessToken(input);
516 return {
517 accountId: "",
518 clientId: options.clientId,
519 relayUrl,
520 thumbprint: input.thumbprint,
521 scopes: input.scopes,
522 accessToken: response.access_token,
523 expiresAtMillis: nowMillis + response.expires_in * 1_000,
524 } satisfies ManagedRelayAccessTokenCacheEntry;
525 }
526 return yield* SynchronizedRef.modifyEffect(cachedTokens, (tokens) =>
527 Effect.gen(function* () {
528 const activeTokens = tokens.filter((token) => token.expiresAtMillis > nowMillis + 5_000);
529 const cached = activeTokens.find((token) =>
530 tokenMatches(token, {
531 accountId: accountId.value,
532 clientId: options.clientId,
533 relayUrl,
534 thumbprint: input.thumbprint,
535 scopes: input.scopes,
536 nowMillis,
537 }),
538 );
539 if (cached) {
540 yield* Effect.annotateCurrentSpan({
541 "relay.token_cache.result": "hit",
542 });
543 return [cached, activeTokens] as const;
544 }
545 yield* Effect.annotateCurrentSpan({
546 "relay.token_cache.result": "miss",
547 });
548 const response = yield* exchangeAccessToken(input);
549 const next: ManagedRelayAccessTokenCacheEntry = {
550 accountId: accountId.value,
551 clientId: options.clientId,
552 relayUrl,
553 thumbprint: input.thumbprint,
554 scopes: input.scopes,
555 accessToken: response.access_token,
556 expiresAtMillis: nowMillis + response.expires_in * 1_000,
557 };
558 const nextTokens = [...activeTokens, next];
559 if (options.accessTokenStore) {
560 yield* options.accessTokenStore.save(nextTokens);
561 }
562 return [next, nextTokens] as const;
563 }),
564 ).pipe(Effect.withSpan("clientRuntime.managedRelay.tokenCacheCriticalSection"));
565 },
566 );
567
568 const authorize = Effect.fn("clientRuntime.managedRelay.authorize")(function* (input: {
569 readonly clerkToken: string;
570 readonly scopes: ReadonlyArray<RelayDpopAccessTokenScope>;
571 readonly target: DpopProofTarget;
572 }) {
573 yield* Effect.annotateCurrentSpan({
574 "relay.client_id": options.clientId,
575 "relay.scopes": input.scopes.join(" "),
576 "http.request.method": input.target.method,
577 "url.full": input.target.url,
578 });
579 const thumbprint = yield* signer.thumbprint;
580 const token = yield* obtainAccessToken({
581 clerkToken: input.clerkToken,
582 scopes: input.scopes,
583 thumbprint,
584 });
585 const proof = yield* signer
586 .createProof({
587 ...input.target,
588 accessToken: token.accessToken,
589 })
590 .pipe(
591 Effect.mapError(
592 (error) => new ManagedRelayRequestProofCreationError(proofCreationErrorFields(error)),
593 ),
594 );
595 return { accessToken: token.accessToken, proof, thumbprint };
596 });
597
598 const invalidateAccessToken = Effect.fn("clientRuntime.managedRelay.invalidateAccessToken")(
599 function* (accessToken: string) {
600 return yield* SynchronizedRef.modifyEffect(cachedTokens, (tokens) => {
601 const nextTokens = tokens.filter((token) => token.accessToken !== accessToken);
602 if (nextTokens.length === tokens.length) {
603 return Effect.succeed([false, tokens] as const);
604 }
605 return (
606 options.accessTokenStore ? options.accessTokenStore.save(nextTokens) : Effect.void
607 ).pipe(Effect.as([true, nextTokens] as const));
608 });
609 },
610 );
611
612 const runDpopRequest = <A>(
613 input: {
614 readonly clerkToken: string;
615 readonly scopes: ReadonlyArray<RelayDpopAccessTokenScope>;
616 readonly target: DpopProofTarget;
617 },
618 request: (
619 authorization: ManagedRelayAuthorization,
620 ) => Effect.Effect<A, ManagedRelayClientError>,
621 ): Effect.Effect<A, ManagedRelayClientError> => {
622 const attempt = (refreshRejectedToken: boolean): Effect.Effect<A, ManagedRelayClientError> =>
623 authorize(input).pipe(
624 Effect.flatMap((authorization) =>
625 request(authorization).pipe(
626 Effect.catch((error) => {
627 if (!isRejectedDpopAccessToken(error)) {
628 return Effect.fail(error);
629 }
630 return invalidateAccessToken(authorization.accessToken).pipe(
631 Effect.tap((invalidated) =>
632 Effect.annotateCurrentSpan({
633 "relay.token_cache.invalidated": invalidated,
634 "relay.token_cache.invalidation_reason": "invalid_bearer",
635 "relay.token_cache.retry_after_invalidation": refreshRejectedToken,
636 }),
637 ),
638 Effect.tap((invalidated) =>
639 invalidated && refreshRejectedToken
640 ? Effect.logWarning(
641 "Relay rejected a cached DPoP access token; refreshing it once.",
642 )
643 : Effect.void,
644 ),
645 Effect.andThen(refreshRejectedToken ? attempt(false) : Effect.fail(error)),
646 );
647 }),
648 ),
649 ),
650 );
651 return attempt(true);
652 };
653
654 const mobileRegistrationRequest = <A>(
655 input: {
656 readonly clerkToken: string;
657 readonly target: DpopProofTarget;
658 },
659 request: (
660 authorization: ManagedRelayAuthorization,
661 ) => Effect.Effect<A, ManagedRelayClientError>,
662 ) =>
663 runDpopRequest(
664 {
665 ...input,
666 scopes: [RelayMobileRegistrationScope],
667 },
668 request,
669 );
670
671 return ManagedRelayClient.of({
672 relayUrl,
673 listEnvironments: Effect.fnUntraced(
674 function* (input) {
675 return yield* client.client
676 .listEnvironments({ headers: bearerHeaders(input.clerkToken) })
677 .pipe(
678 Effect.map((response) => response.environments),
679 Effect.mapError(relayRequestError("list relay-managed environments")),
680 timeoutRelayRequest("Relay environment listing"),
681 );
682 },
683 Effect.withSpan("clientRuntime.managedRelay.listEnvironments"),
684 withRelayClientTracing,
685 ),
686 listDevices: Effect.fnUntraced(
687 function* (input) {
688 return yield* client.client
689 .listDevices({
690 headers: bearerHeaders(input.clerkToken),
691 })
692 .pipe(
693 Effect.map((response) => response.devices),
694 Effect.mapError(relayRequestError("list relay client devices")),
695 timeoutRelayRequest("Relay client device listing"),
696 );
697 },
698 Effect.withSpan("clientRuntime.managedRelay.listDevices"),
699 withRelayClientTracing,
700 ),
701 createEnvironmentLinkChallenge: Effect.fnUntraced(
702 function* (input) {
703 return yield* client.client
704 .createEnvironmentLinkChallenge({
705 headers: bearerHeaders(input.clerkToken),
706 payload: input.payload,
707 })
708 .pipe(
709 Effect.mapError(relayRequestError("create relay environment link challenge")),
710 timeoutRelayRequest("Relay environment link challenge"),
711 );
712 },
713 Effect.withSpan("clientRuntime.managedRelay.createEnvironmentLinkChallenge"),
714 withRelayClientTracing,
715 ),
716 linkEnvironment: Effect.fnUntraced(
717 function* (input) {
718 return yield* client.client
719 .linkEnvironment({
720 headers: bearerHeaders(input.clerkToken),
721 payload: input.payload,
722 })
723 .pipe(
724 Effect.mapError(relayRequestError("link relay environment")),
725 timeoutRelayRequest("Relay environment linking"),
726 );
727 },
728 Effect.withSpan("clientRuntime.managedRelay.linkEnvironment"),
729 withRelayClientTracing,
730 ),
731 unlinkEnvironment: Effect.fnUntraced(
732 function* (input) {
733 return yield* client.client
734 .unlinkEnvironment({
735 headers: bearerHeaders(input.clerkToken),
736 params: { environmentId: input.environmentId },
737 })
738 .pipe(
739 Effect.mapError(relayRequestError("unlink relay environment")),
740 timeoutRelayRequest("Relay environment unlinking"),
741 );
742 },
743 Effect.withSpan("clientRuntime.managedRelay.unlinkEnvironment"),
744 withRelayClientTracing,
745 ),
746 getEnvironmentStatus: Effect.fnUntraced(
747 function* (input) {
748 yield* Effect.annotateCurrentSpan({
749 "environment.id": input.environmentId,
750 });
751 return yield* runDpopRequest(
752 {
753 clerkToken: input.clerkToken,
754 scopes: input.scopes,
755 target: dpopProofTargets.getEnvironmentStatus(input.environmentId),
756 },
757 (authorization) =>
758 client.dpopClient
759 .getEnvironmentStatus({
760 headers: dpopHeaders(authorization),
761 params: { environmentId: input.environmentId },
762 })
763 .pipe(
764 Effect.mapError(relayRequestError("get relay environment status")),
765 timeoutRelayRequest("Relay environment status request"),
766 ),
767 );
768 },
769 Effect.withSpan("clientRuntime.managedRelay.getEnvironmentStatus"),
770 withRelayClientTracing,
771 ),
772 connectEnvironment: Effect.fnUntraced(
773 function* (input) {
774 yield* Effect.annotateCurrentSpan({
775 "environment.id": input.environmentId,
776 });
777 return yield* runDpopRequest(
778 {
779 clerkToken: input.clerkToken,
780 scopes: input.scopes,
781 target: dpopProofTargets.connectEnvironment(input.environmentId),
782 },
783 (authorization) => {
784 const payload: RelayEnvironmentConnectRequest = {
785 ...(input.deviceId ? { deviceId: input.deviceId } : {}),
786 clientKeyThumbprint: authorization.thumbprint,
787 };
788 return client.dpopClient
789 .connectEnvironment({
790 headers: dpopHeaders(authorization),
791 params: { environmentId: input.environmentId },
792 payload,
793 })
794 .pipe(
795 Effect.mapError(relayRequestError("connect relay environment")),
796 timeoutRelayRequest("Relay environment connection"),
797 );
798 },
799 );
800 },
801 Effect.withSpan("clientRuntime.managedRelay.connectEnvironment"),
802 withRelayClientTracing,
803 ),
804 registerDevice: Effect.fnUntraced(
805 function* (input) {
806 return yield* mobileRegistrationRequest(
807 {
808 clerkToken: input.clerkToken,
809 target: dpopProofTargets.registerDevice(),
810 },
811 (authorization) =>
812 client.mobile
813 .registerDevice({
814 headers: dpopHeaders(authorization),
815 payload: input.payload,
816 })
817 .pipe(
818 Effect.mapError(relayRequestError("register relay mobile device")),
819 timeoutRelayRequest("Relay mobile device registration"),
820 ),
821 );
822 },
823 Effect.withSpan("clientRuntime.managedRelay.registerDevice"),
824 withRelayClientTracing,
825 ),
826 unregisterDevice: Effect.fnUntraced(
827 function* (input) {
828 return yield* mobileRegistrationRequest(
829 {
830 clerkToken: input.clerkToken,
831 target: dpopProofTargets.unregisterDevice(input.deviceId),
832 },
833 (authorization) =>
834 client.mobile
835 .unregisterDevice({
836 headers: dpopHeaders(authorization),
837 params: { deviceId: input.deviceId },
838 })
839 .pipe(
840 Effect.mapError(relayRequestError("unregister relay mobile device")),
841 timeoutRelayRequest("Relay mobile device unregistration"),
842 ),
843 );
844 },
845 Effect.withSpan("clientRuntime.managedRelay.unregisterDevice"),
846 withRelayClientTracing,
847 ),
848 registerLiveActivity: Effect.fnUntraced(
849 function* (input) {
850 return yield* mobileRegistrationRequest(
851 {
852 clerkToken: input.clerkToken,
853 target: dpopProofTargets.registerLiveActivity(),
854 },
855 (authorization) =>
856 client.mobile
857 .registerLiveActivity({
858 headers: dpopHeaders(authorization),
859 payload: input.payload,
860 })
861 .pipe(
862 Effect.mapError(relayRequestError("register relay live activity")),
863 timeoutRelayRequest("Relay Live Activity registration"),
864 ),
865 );
866 },
867 Effect.withSpan("clientRuntime.managedRelay.registerLiveActivity"),
868 withRelayClientTracing,
869 ),
870 resetTokenCache: SynchronizedRef.set(cachedTokens, []).pipe(
871 Effect.andThen(options.accessTokenStore ? options.accessTokenStore.clear : Effect.void),
872 Effect.withSpan("clientRuntime.managedRelay.resetTokenCache"),
873 withRelayClientTracing,
874 ),
875 });
876});
877
878export const layer = (options: ManagedRelayClientLayerOptions) =>
879 Layer.effect(ManagedRelayClient, make(options));