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.TaggedErrorClass<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.TaggedErrorClass<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.TaggedErrorClass<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.TaggedErrorClass<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.TaggedErrorClass<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.TaggedErrorClass<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.TaggedErrorClass<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.TaggedErrorClass<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
432export const make = Effect.fn("ManagedRelayClient.make")(function* (
433 options: ManagedRelayClientLayerOptions,
434) {
435 const relayUrl = normalizeSecureRelayUrl(options.relayUrl);
436 if (relayUrl === null) {
437 return disabledManagedRelayClient(options.relayUrl);
438 }
439 const signer = yield* ManagedRelayDpopSigner;
440 const client = yield* HttpApiClient.make(RelayApi, { baseUrl: relayUrl });
441 const initialTokens = options.accessTokenStore ? yield* options.accessTokenStore.load : [];
442 const cachedTokens = yield* SynchronizedRef.make<
443 ReadonlyArray<ManagedRelayAccessTokenCacheEntry>
444 >(initialTokens.filter((token) => token.clientId === options.clientId));
445 const urlBuilder = HttpApiClient.urlBuilder(RelayApi, { baseUrl: relayUrl });
446
447 type DpopProofTarget = Pick<ManagedRelayDpopProofInput, "method" | "url">;
448 const dpopProofTargets = {
449 exchangeAccessToken: (): DpopProofTarget => ({
450 method: RelayExchangeDpopAccessTokenEndpoint.method,
451 url: urlBuilder.token.exchangeDpopAccessToken(),
452 }),
453 getEnvironmentStatus: (
454 environmentId: RelayClientEnvironmentRecord["environmentId"],
455 ): DpopProofTarget => ({
456 method: RelayGetEnvironmentStatusEndpoint.method,
457 url: urlBuilder.dpopClient.getEnvironmentStatus({ params: { environmentId } }),
458 }),
459 connectEnvironment: (
460 environmentId: RelayClientEnvironmentRecord["environmentId"],
461 ): DpopProofTarget => ({
462 method: RelayConnectEnvironmentEndpoint.method,
463 url: urlBuilder.dpopClient.connectEnvironment({ params: { environmentId } }),
464 }),
465 registerDevice: (): DpopProofTarget => ({
466 method: RelayRegisterDeviceEndpoint.method,
467 url: urlBuilder.mobile.registerDevice(),
468 }),
469 unregisterDevice: (deviceId: string): DpopProofTarget => ({
470 method: RelayUnregisterDeviceEndpoint.method,
471 url: urlBuilder.mobile.unregisterDevice({ params: { deviceId } }),
472 }),
473 getAgentActivitySnapshot: (): DpopProofTarget => ({
474 method: RelayAgentActivitySnapshotEndpoint.method,
475 url: urlBuilder.mobile.getAgentActivitySnapshot(),
476 }),
477 registerLiveActivity: (): DpopProofTarget => ({
478 method: RelayRegisterLiveActivityEndpoint.method,
479 url: urlBuilder.mobile.registerLiveActivity(),
480 }),
481 };
482
483 const exchangeAccessToken = Effect.fn("clientRuntime.managedRelay.exchangeAccessToken")(
484 function* (input: {
485 readonly clerkToken: string;
486 readonly scopes: ReadonlyArray<RelayDpopAccessTokenScope>;
487 }) {
488 yield* Effect.annotateCurrentSpan({
489 "relay.client_id": options.clientId,
490 "relay.scopes": input.scopes.join(" "),
491 });
492 const proof = yield* signer
493 .createProof(dpopProofTargets.exchangeAccessToken())
494 .pipe(
495 Effect.mapError(
496 (error) => new ManagedRelayTokenProofCreationError(proofCreationErrorFields(error)),
497 ),
498 );
499 const response = yield* client.token
500 .exchangeDpopAccessToken({
501 headers: { dpop: proof },
502 payload: {
503 grant_type: RelayDpopTokenExchangeGrantType,
504 subject_token: input.clerkToken,
505 subject_token_type: RelayJwtSubjectTokenType,
506 requested_token_type: RelayAccessTokenType,
507 resource: relayUrl,
508 scope: encodeOAuthScope(input.scopes),
509 client_id: options.clientId,
510 },
511 })
512 .pipe(
513 Effect.mapError(relayRequestError("exchange relay DPoP access token")),
514 timeoutRelayRequest("Relay DPoP access token exchange"),
515 );
516 if (!oauthScopeSetEquals(response.scope, input.scopes)) {
517 return yield* new ManagedRelayAccessTokenScopesUnexpectedError({
518 requestedScopes: input.scopes,
519 grantedScope: response.scope,
520 });
521 }
522 return response;
523 },
524 );
525
526 const obtainAccessToken = Effect.fn("clientRuntime.managedRelay.obtainAccessToken")(
527 function* (input: {
528 readonly clerkToken: string;
529 readonly scopes: ReadonlyArray<RelayDpopAccessTokenScope>;
530 readonly thumbprint: string;
531 }) {
532 yield* Effect.annotateCurrentSpan({
533 "relay.client_id": options.clientId,
534 "relay.scopes": input.scopes.join(" "),
535 });
536 const nowMillis = yield* Clock.currentTimeMillis;
537 const accountId = relayAccountId(input.clerkToken);
538 if (Option.isNone(accountId)) {
539 yield* Effect.annotateCurrentSpan({
540 "relay.token_cache.result": "bypass",
541 "relay.token_cache.bypass_reason": "invalid_subject_token",
542 });
543 const response = yield* exchangeAccessToken(input);
544 return {
545 accountId: "",
546 clientId: options.clientId,
547 relayUrl,
548 thumbprint: input.thumbprint,
549 scopes: input.scopes,
550 accessToken: response.access_token,
551 expiresAtMillis: nowMillis + response.expires_in * 1_000,
552 } satisfies ManagedRelayAccessTokenCacheEntry;
553 }
554 const match = {
555 accountId: accountId.value,
556 clientId: options.clientId,
557 relayUrl,
558 thumbprint: input.thumbprint,
559 scopes: input.scopes,
560 nowMillis,
561 };
562 // Cache hits do not need to wait for an unrelated exchange or store write.
563 const cached = (yield* SynchronizedRef.get(cachedTokens)).find((token) =>
564 tokenMatches(token, match),
565 );
566 if (cached) {
567 yield* Effect.annotateCurrentSpan({
568 "relay.token_cache.result": "hit",
569 });
570 return cached;
571 }
572 return yield* SynchronizedRef.modifyEffect(cachedTokens, (tokens) =>
573 Effect.gen(function* () {
574 const lookupMillis = yield* Clock.currentTimeMillis;
575 const activeTokens = tokens.filter(
576 (token) => token.expiresAtMillis > lookupMillis + 5_000,
577 );
578 const cached = activeTokens.find((token) =>
579 tokenMatches(token, { ...match, nowMillis: lookupMillis }),
580 );
581 if (cached) {
582 yield* Effect.annotateCurrentSpan({
583 "relay.token_cache.result": "hit",
584 });
585 return [cached, activeTokens] as const;
586 }
587 yield* Effect.annotateCurrentSpan({
588 "relay.token_cache.result": "miss",
589 });
590 const response = yield* exchangeAccessToken(input);
591 const next: ManagedRelayAccessTokenCacheEntry = {
592 accountId: accountId.value,
593 clientId: options.clientId,
594 relayUrl,
595 thumbprint: input.thumbprint,
596 scopes: input.scopes,
597 accessToken: response.access_token,
598 expiresAtMillis: lookupMillis + response.expires_in * 1_000,
599 };
600 const nextTokens = [...activeTokens, next];
601 if (options.accessTokenStore) {
602 yield* options.accessTokenStore.save(nextTokens);
603 }
604 return [next, nextTokens] as const;
605 }),
606 ).pipe(Effect.withSpan("clientRuntime.managedRelay.tokenCacheCriticalSection"));
607 },
608 );
609
610 const authorize = Effect.fn("clientRuntime.managedRelay.authorize")(function* (input: {
611 readonly clerkToken: string;
612 readonly scopes: ReadonlyArray<RelayDpopAccessTokenScope>;
613 readonly target: DpopProofTarget;
614 }) {
615 yield* Effect.annotateCurrentSpan({
616 "relay.client_id": options.clientId,
617 "relay.scopes": input.scopes.join(" "),
618 "http.request.method": input.target.method,
619 "url.full": input.target.url,
620 });
621 const thumbprint = yield* signer.thumbprint;
622 const token = yield* obtainAccessToken({
623 clerkToken: input.clerkToken,
624 scopes: input.scopes,
625 thumbprint,
626 });
627 const proof = yield* signer
628 .createProof({
629 ...input.target,
630 accessToken: token.accessToken,
631 })
632 .pipe(
633 Effect.mapError(
634 (error) => new ManagedRelayRequestProofCreationError(proofCreationErrorFields(error)),
635 ),
636 );
637 return { accessToken: token.accessToken, proof, thumbprint };
638 });
639
640 const invalidateAccessToken = Effect.fn("clientRuntime.managedRelay.invalidateAccessToken")(
641 function* (accessToken: string) {
642 return yield* SynchronizedRef.modifyEffect(cachedTokens, (tokens) => {
643 const nextTokens = tokens.filter((token) => token.accessToken !== accessToken);
644 if (nextTokens.length === tokens.length) {
645 return Effect.succeed([false, tokens] as const);
646 }
647 return (
648 options.accessTokenStore ? options.accessTokenStore.save(nextTokens) : Effect.void
649 ).pipe(Effect.as([true, nextTokens] as const));
650 });
651 },
652 );
653
654 const runDpopRequest = <A>(
655 input: {
656 readonly clerkToken: string;
657 readonly scopes: ReadonlyArray<RelayDpopAccessTokenScope>;
658 readonly target: DpopProofTarget;
659 },
660 request: (
661 authorization: ManagedRelayAuthorization,
662 ) => Effect.Effect<A, ManagedRelayClientError>,
663 ): Effect.Effect<A, ManagedRelayClientError> => {
664 const attempt = (refreshRejectedToken: boolean): Effect.Effect<A, ManagedRelayClientError> =>
665 authorize(input).pipe(
666 Effect.flatMap((authorization) =>
667 request(authorization).pipe(
668 Effect.catch((error) => {
669 if (!isRejectedDpopAccessToken(error)) {
670 return Effect.fail(error);
671 }
672 return invalidateAccessToken(authorization.accessToken).pipe(
673 Effect.tap((invalidated) =>
674 Effect.annotateCurrentSpan({
675 "relay.token_cache.invalidated": invalidated,
676 "relay.token_cache.invalidation_reason": "invalid_bearer",
677 "relay.token_cache.retry_after_invalidation": refreshRejectedToken,
678 }),
679 ),
680 Effect.tap((invalidated) =>
681 invalidated && refreshRejectedToken
682 ? Effect.logWarning(
683 "Relay rejected a cached DPoP access token; refreshing it once.",
684 )
685 : Effect.void,
686 ),
687 Effect.andThen(refreshRejectedToken ? attempt(false) : Effect.fail(error)),
688 );
689 }),
690 ),
691 ),
692 );
693 return attempt(true);
694 };
695
696 const mobileRegistrationRequest = <A>(
697 input: {
698 readonly clerkToken: string;
699 readonly target: DpopProofTarget;
700 },
701 request: (
702 authorization: ManagedRelayAuthorization,
703 ) => Effect.Effect<A, ManagedRelayClientError>,
704 ) =>
705 runDpopRequest(
706 {
707 ...input,
708 scopes: [RelayMobileRegistrationScope],
709 },
710 request,
711 );
712
713 return ManagedRelayClient.of({
714 relayUrl,
715 listEnvironments: Effect.fnUntraced(
716 function* (input) {
717 return yield* client.client
718 .listEnvironments({ headers: bearerHeaders(input.clerkToken) })
719 .pipe(
720 Effect.map((response) => response.environments),
721 Effect.mapError(relayRequestError("list relay-managed environments")),
722 timeoutRelayRequest("Relay environment listing"),
723 );
724 },
725 Effect.withSpan("clientRuntime.managedRelay.listEnvironments"),
726 withRelayClientTracing,
727 ),
728 listDevices: Effect.fnUntraced(
729 function* (input) {
730 return yield* client.client
731 .listDevices({
732 headers: bearerHeaders(input.clerkToken),
733 })
734 .pipe(
735 Effect.map((response) => response.devices),
736 Effect.mapError(relayRequestError("list relay client devices")),
737 timeoutRelayRequest("Relay client device listing"),
738 );
739 },
740 Effect.withSpan("clientRuntime.managedRelay.listDevices"),
741 withRelayClientTracing,
742 ),
743 createEnvironmentLinkChallenge: Effect.fnUntraced(
744 function* (input) {
745 return yield* client.client
746 .createEnvironmentLinkChallenge({
747 headers: bearerHeaders(input.clerkToken),
748 payload: input.payload,
749 })
750 .pipe(
751 Effect.mapError(relayRequestError("create relay environment link challenge")),
752 timeoutRelayRequest("Relay environment link challenge"),
753 );
754 },
755 Effect.withSpan("clientRuntime.managedRelay.createEnvironmentLinkChallenge"),
756 withRelayClientTracing,
757 ),
758 linkEnvironment: Effect.fnUntraced(
759 function* (input) {
760 return yield* client.client
761 .linkEnvironment({
762 headers: bearerHeaders(input.clerkToken),
763 payload: input.payload,
764 })
765 .pipe(
766 Effect.mapError(relayRequestError("link relay environment")),
767 timeoutRelayRequest("Relay environment linking"),
768 );
769 },
770 Effect.withSpan("clientRuntime.managedRelay.linkEnvironment"),
771 withRelayClientTracing,
772 ),
773 unlinkEnvironment: Effect.fnUntraced(
774 function* (input) {
775 return yield* client.client
776 .unlinkEnvironment({
777 headers: bearerHeaders(input.clerkToken),
778 params: { environmentId: input.environmentId },
779 })
780 .pipe(
781 Effect.mapError(relayRequestError("unlink relay environment")),
782 timeoutRelayRequest("Relay environment unlinking"),
783 );
784 },
785 Effect.withSpan("clientRuntime.managedRelay.unlinkEnvironment"),
786 withRelayClientTracing,
787 ),
788 getEnvironmentStatus: Effect.fnUntraced(
789 function* (input) {
790 yield* Effect.annotateCurrentSpan({
791 "environment.id": input.environmentId,
792 });
793 return yield* runDpopRequest(
794 {
795 clerkToken: input.clerkToken,
796 scopes: input.scopes,
797 target: dpopProofTargets.getEnvironmentStatus(input.environmentId),
798 },
799 (authorization) =>
800 client.dpopClient
801 .getEnvironmentStatus({
802 headers: dpopHeaders(authorization),
803 params: { environmentId: input.environmentId },
804 })
805 .pipe(
806 Effect.mapError(relayRequestError("get relay environment status")),
807 timeoutRelayRequest("Relay environment status request"),
808 ),
809 );
810 },
811 Effect.withSpan("clientRuntime.managedRelay.getEnvironmentStatus"),
812 withRelayClientTracing,
813 ),
814 connectEnvironment: Effect.fnUntraced(
815 function* (input) {
816 yield* Effect.annotateCurrentSpan({
817 "environment.id": input.environmentId,
818 });
819 return yield* runDpopRequest(
820 {
821 clerkToken: input.clerkToken,
822 scopes: input.scopes,
823 target: dpopProofTargets.connectEnvironment(input.environmentId),
824 },
825 (authorization) => {
826 const payload: RelayEnvironmentConnectRequest = {
827 ...(input.deviceId ? { deviceId: input.deviceId } : {}),
828 clientKeyThumbprint: authorization.thumbprint,
829 };
830 return client.dpopClient
831 .connectEnvironment({
832 headers: dpopHeaders(authorization),
833 params: { environmentId: input.environmentId },
834 payload,
835 })
836 .pipe(
837 Effect.mapError(relayRequestError("connect relay environment")),
838 timeoutRelayRequest("Relay environment connection"),
839 );
840 },
841 );
842 },
843 Effect.withSpan("clientRuntime.managedRelay.connectEnvironment"),
844 withRelayClientTracing,
845 ),
846 registerDevice: Effect.fnUntraced(
847 function* (input) {
848 return yield* mobileRegistrationRequest(
849 {
850 clerkToken: input.clerkToken,
851 target: dpopProofTargets.registerDevice(),
852 },
853 (authorization) =>
854 client.mobile
855 .registerDevice({
856 headers: dpopHeaders(authorization),
857 payload: input.payload,
858 })
859 .pipe(
860 Effect.mapError(relayRequestError("register relay mobile device")),
861 timeoutRelayRequest("Relay mobile device registration"),
862 ),
863 );
864 },
865 Effect.withSpan("clientRuntime.managedRelay.registerDevice"),
866 withRelayClientTracing,
867 ),
868 unregisterDevice: Effect.fnUntraced(
869 function* (input) {
870 return yield* mobileRegistrationRequest(
871 {
872 clerkToken: input.clerkToken,
873 target: dpopProofTargets.unregisterDevice(input.deviceId),
874 },
875 (authorization) =>
876 client.mobile
877 .unregisterDevice({
878 headers: dpopHeaders(authorization),
879 params: { deviceId: input.deviceId },
880 })
881 .pipe(
882 Effect.mapError(relayRequestError("unregister relay mobile device")),
883 timeoutRelayRequest("Relay mobile device unregistration"),
884 ),
885 );
886 },
887 Effect.withSpan("clientRuntime.managedRelay.unregisterDevice"),
888 withRelayClientTracing,
889 ),
890 getAgentActivitySnapshot: Effect.fnUntraced(
891 function* (input) {
892 return yield* mobileRegistrationRequest(
893 {
894 clerkToken: input.clerkToken,
895 target: dpopProofTargets.getAgentActivitySnapshot(),
896 },
897 (authorization) =>
898 client.mobile
899 .getAgentActivitySnapshot({
900 headers: dpopHeaders(authorization),
901 })
902 .pipe(
903 Effect.mapError(relayRequestError("read relay agent activity snapshot")),
904 timeoutRelayRequest("Relay agent activity snapshot"),
905 ),
906 );
907 },
908 Effect.withSpan("clientRuntime.managedRelay.getAgentActivitySnapshot"),
909 withRelayClientTracing,
910 ),
911 registerLiveActivity: Effect.fnUntraced(
912 function* (input) {
913 return yield* mobileRegistrationRequest(
914 {
915 clerkToken: input.clerkToken,
916 target: dpopProofTargets.registerLiveActivity(),
917 },
918 (authorization) =>
919 client.mobile
920 .registerLiveActivity({
921 headers: dpopHeaders(authorization),
922 payload: input.payload,
923 })
924 .pipe(
925 Effect.mapError(relayRequestError("register relay live activity")),
926 timeoutRelayRequest("Relay Live Activity registration"),
927 ),
928 );
929 },
930 Effect.withSpan("clientRuntime.managedRelay.registerLiveActivity"),
931 withRelayClientTracing,
932 ),
933 resetTokenCache: SynchronizedRef.set(cachedTokens, []).pipe(
934 Effect.andThen(options.accessTokenStore ? options.accessTokenStore.clear : Effect.void),
935 Effect.withSpan("clientRuntime.managedRelay.resetTokenCache"),
936 withRelayClientTracing,
937 ),
938 });
939});
940
941export const layer = (options: ManagedRelayClientLayerOptions) =>
942 Layer.effect(ManagedRelayClient, make(options));