Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

managedRelay.ts

937 lines33.5 KB

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