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