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