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/unstable/http/HttpClientError";
45import type * as HttpMethod from "effect/unstable/http/HttpMethod";
46import * as HttpApiClient from "effect/unstable/httpapi/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.catch((error) => {
670 if (!isRejectedDpopAccessToken(error)) {
671 return Effect.fail(error);
672 }
673 return invalidateAccessToken(authorization.accessToken).pipe(
674 Effect.tap((invalidated) =>
675 Effect.annotateCurrentSpan({
676 "relay.token_cache.invalidated": invalidated,
677 "relay.token_cache.invalidation_reason": "invalid_bearer",
678 "relay.token_cache.retry_after_invalidation": refreshRejectedToken,
679 }),
680 ),
681 Effect.tap((invalidated) =>
682 invalidated && refreshRejectedToken
683 ? Effect.logWarning(
684 "Relay rejected a cached DPoP access token; refreshing it once.",
685 )
686 : Effect.void,
687 ),
688 Effect.andThen(refreshRejectedToken ? attempt(false) : Effect.fail(error)),
689 );
690 }),
691 ),
692 ),
693 );
694 return attempt(true);
695 };
696
697 const mobileRegistrationRequest = <A>(
698 input: {
699 readonly clerkToken: string;
700 readonly target: DpopProofTarget;
701 },
702 request: (
703 authorization: ManagedRelayAuthorization,
704 ) => Effect.Effect<A, ManagedRelayClientError>,
705 ) =>
706 runDpopRequest(
707 {
708 ...input,
709 scopes: [RelayMobileRegistrationScope],
710 },
711 request,
712 );
713
714 return ManagedRelayClient.of({
715 relayUrl,
716 listEnvironments: Effect.fnUntraced(
717 function* (input) {
718 return yield* client.client
719 .listEnvironments({ headers: bearerHeaders(input.clerkToken) })
720 .pipe(
721 Effect.map((response) => response.environments),
722 Effect.mapError(relayRequestError("list relay-managed environments")),
723 timeoutRelayRequest("Relay environment listing"),
724 );
725 },
726 Effect.withSpan("clientRuntime.managedRelay.listEnvironments"),
727 withRelayClientTracing,
728 ),
729 listDevices: Effect.fnUntraced(
730 function* (input) {
731 return yield* client.client
732 .listDevicesV2({
733 headers: bearerHeaders(input.clerkToken),
734 })
735 .pipe(
736 Effect.map((response) => response.devices),
737 Effect.mapError(relayRequestError("list relay client devices")),
738 timeoutRelayRequest("Relay client device listing"),
739 );
740 },
741 Effect.withSpan("clientRuntime.managedRelay.listDevices"),
742 withRelayClientTracing,
743 ),
744 createEnvironmentLinkChallenge: Effect.fnUntraced(
745 function* (input) {
746 return yield* client.client
747 .createEnvironmentLinkChallenge({
748 headers: bearerHeaders(input.clerkToken),
749 payload: input.payload,
750 })
751 .pipe(
752 Effect.mapError(relayRequestError("create relay environment link challenge")),
753 timeoutRelayRequest("Relay environment link challenge"),
754 );
755 },
756 Effect.withSpan("clientRuntime.managedRelay.createEnvironmentLinkChallenge"),
757 withRelayClientTracing,
758 ),
759 linkEnvironment: Effect.fnUntraced(
760 function* (input) {
761 return yield* client.client
762 .linkEnvironment({
763 headers: bearerHeaders(input.clerkToken),
764 payload: input.payload,
765 })
766 .pipe(
767 Effect.mapError(relayRequestError("link relay environment")),
768 timeoutRelayRequest("Relay environment linking"),
769 );
770 },
771 Effect.withSpan("clientRuntime.managedRelay.linkEnvironment"),
772 withRelayClientTracing,
773 ),
774 unlinkEnvironment: Effect.fnUntraced(
775 function* (input) {
776 return yield* client.client
777 .unlinkEnvironment({
778 headers: bearerHeaders(input.clerkToken),
779 params: { environmentId: input.environmentId },
780 })
781 .pipe(
782 Effect.mapError(relayRequestError("unlink relay environment")),
783 timeoutRelayRequest("Relay environment unlinking"),
784 );
785 },
786 Effect.withSpan("clientRuntime.managedRelay.unlinkEnvironment"),
787 withRelayClientTracing,
788 ),
789 getEnvironmentStatus: Effect.fnUntraced(
790 function* (input) {
791 yield* Effect.annotateCurrentSpan({
792 "environment.id": input.environmentId,
793 });
794 return yield* runDpopRequest(
795 {
796 clerkToken: input.clerkToken,
797 scopes: input.scopes,
798 target: dpopProofTargets.getEnvironmentStatus(input.environmentId),
799 },
800 (authorization) =>
801 client.dpopClient
802 .getEnvironmentStatus({
803 headers: dpopHeaders(authorization),
804 params: { environmentId: input.environmentId },
805 })
806 .pipe(
807 Effect.mapError(relayRequestError("get relay environment status")),
808 timeoutRelayRequest("Relay environment status request"),
809 ),
810 );
811 },
812 Effect.withSpan("clientRuntime.managedRelay.getEnvironmentStatus"),
813 withRelayClientTracing,
814 ),
815 connectEnvironment: Effect.fnUntraced(
816 function* (input) {
817 yield* Effect.annotateCurrentSpan({
818 "environment.id": input.environmentId,
819 });
820 return yield* runDpopRequest(
821 {
822 clerkToken: input.clerkToken,
823 scopes: input.scopes,
824 target: dpopProofTargets.connectEnvironment(input.environmentId),
825 },
826 (authorization) => {
827 const payload: RelayEnvironmentConnectRequest = {
828 ...(input.deviceId ? { deviceId: input.deviceId } : {}),
829 clientKeyThumbprint: authorization.thumbprint,
830 };
831 return client.dpopClient
832 .connectEnvironment({
833 headers: dpopHeaders(authorization),
834 params: { environmentId: input.environmentId },
835 payload,
836 })
837 .pipe(
838 Effect.mapError(relayRequestError("connect relay environment")),
839 timeoutRelayRequest("Relay environment connection"),
840 );
841 },
842 );
843 },
844 Effect.withSpan("clientRuntime.managedRelay.connectEnvironment"),
845 withRelayClientTracing,
846 ),
847 registerDevice: Effect.fnUntraced(
848 function* (input) {
849 return yield* mobileRegistrationRequest(
850 {
851 clerkToken: input.clerkToken,
852 target: dpopProofTargets.registerDevice(),
853 },
854 (authorization) =>
855 client.mobile
856 .registerDevice({
857 headers: dpopHeaders(authorization),
858 payload: input.payload,
859 })
860 .pipe(
861 Effect.mapError(relayRequestError("register relay mobile device")),
862 timeoutRelayRequest("Relay mobile device registration"),
863 ),
864 );
865 },
866 Effect.withSpan("clientRuntime.managedRelay.registerDevice"),
867 withRelayClientTracing,
868 ),
869 unregisterDevice: Effect.fnUntraced(
870 function* (input) {
871 return yield* mobileRegistrationRequest(
872 {
873 clerkToken: input.clerkToken,
874 target: dpopProofTargets.unregisterDevice(input.deviceId),
875 },
876 (authorization) =>
877 client.mobile
878 .unregisterDevice({
879 headers: dpopHeaders(authorization),
880 params: { deviceId: input.deviceId },
881 })
882 .pipe(
883 Effect.mapError(relayRequestError("unregister relay mobile device")),
884 timeoutRelayRequest("Relay mobile device unregistration"),
885 ),
886 );
887 },
888 Effect.withSpan("clientRuntime.managedRelay.unregisterDevice"),
889 withRelayClientTracing,
890 ),
891 getAgentActivitySnapshot: Effect.fnUntraced(
892 function* (input) {
893 return yield* mobileRegistrationRequest(
894 {
895 clerkToken: input.clerkToken,
896 target: dpopProofTargets.getAgentActivitySnapshot(),
897 },
898 (authorization) =>
899 client.mobile
900 .getAgentActivitySnapshot({
901 headers: dpopHeaders(authorization),
902 })
903 .pipe(
904 Effect.mapError(relayRequestError("read relay agent activity snapshot")),
905 timeoutRelayRequest("Relay agent activity snapshot"),
906 ),
907 );
908 },
909 Effect.withSpan("clientRuntime.managedRelay.getAgentActivitySnapshot"),
910 withRelayClientTracing,
911 ),
912 registerLiveActivity: Effect.fnUntraced(
913 function* (input) {
914 return yield* mobileRegistrationRequest(
915 {
916 clerkToken: input.clerkToken,
917 target: dpopProofTargets.registerLiveActivity(),
918 },
919 (authorization) =>
920 client.mobile
921 .registerLiveActivity({
922 headers: dpopHeaders(authorization),
923 payload: input.payload,
924 })
925 .pipe(
926 Effect.mapError(relayRequestError("register relay live activity")),
927 timeoutRelayRequest("Relay Live Activity registration"),
928 ),
929 );
930 },
931 Effect.withSpan("clientRuntime.managedRelay.registerLiveActivity"),
932 withRelayClientTracing,
933 ),
934 resetTokenCache: SynchronizedRef.set(cachedTokens, []).pipe(
935 Effect.andThen(options.accessTokenStore ? options.accessTokenStore.clear : Effect.void),
936 Effect.withSpan("clientRuntime.managedRelay.resetTokenCache"),
937 withRelayClientTracing,
938 ),
939 });
940});
941
942export const layer = (options: ManagedRelayClientLayerOptions) =>
943 Layer.effect(ManagedRelayClient, make(options));